@rizom/brain 0.2.0-alpha.404 → 0.2.0-alpha.405
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 +227 -227
- package/dist/chunks/{app-afye8rgv.js → app-3z7kg4n4.js} +2 -2
- package/dist/chunks/{blog-post-adapter-wxf0f0rf.js → blog-post-adapter-vn4bvezs.js} +2 -2
- package/dist/chunks/{index-97j4t44j.js → index-03cfb3s4.js} +2 -2
- package/dist/chunks/{index-hp3ma2a0.js → index-aft95ek4.js} +26 -26
- package/dist/chunks/{index-hp3ma2a0.js.map → index-aft95ek4.js.map} +3 -3
- package/dist/chunks/{index-02vqvq05.js → index-e0rx633y.js} +3 -3
- package/dist/chunks/{index-02vqvq05.js.map → index-e0rx633y.js.map} +1 -1
- package/dist/chunks/{index-wqbddw4c.js → index-pkcefcbr.js} +2 -2
- package/dist/chunks/{index-122t0n9j.js → index-t1p3qrrm.js} +2 -2
- package/dist/chunks/{index-7q5j58p2.js → index-zghffskf.js} +3 -3
- package/dist/chunks/linkedin-template-mra3dywt.js +5 -0
- package/dist/chunks/{rss-datasource-ftkdarkw.js → rss-datasource-meq425kx.js} +2 -2
- package/dist/entities.js +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.js +38 -38
- package/dist/model.js.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/services.js +1 -1
- package/dist/ui/studio-chunks/main-s1ykse8z.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/linkedin-template-jj13p2ah.js +0 -5
- /package/dist/chunks/{app-afye8rgv.js.map → app-3z7kg4n4.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-wxf0f0rf.js.map → blog-post-adapter-vn4bvezs.js.map} +0 -0
- /package/dist/chunks/{index-97j4t44j.js.map → index-03cfb3s4.js.map} +0 -0
- /package/dist/chunks/{index-wqbddw4c.js.map → index-pkcefcbr.js.map} +0 -0
- /package/dist/chunks/{index-122t0n9j.js.map → index-t1p3qrrm.js.map} +0 -0
- /package/dist/chunks/{index-7q5j58p2.js.map → index-zghffskf.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-jj13p2ah.js.map → linkedin-template-mra3dywt.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-ftkdarkw.js.map → rss-datasource-meq425kx.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a as z,b as f}from"./index-1en0tvp6.js";import{d as c,e as l}from"./index-5w0615mb.js";import{sa as D}from"./index-48ksf4j5.js";import{Ah as M,Hg as I,Ig as A,Jg as P,Kg as T,Lg as R,Mg as S,Pg as L,Wg as w,ih as B,kg as x}from"./index-
|
|
2
|
+
import{a as z,b as f}from"./index-1en0tvp6.js";import{d as c,e as l}from"./index-5w0615mb.js";import{sa as D}from"./index-48ksf4j5.js";import{Ah as M,Hg as I,Ig as A,Jg as P,Kg as T,Lg as R,Mg as S,Pg as L,Wg as w,ih as B,kg as x}from"./index-aft95ek4.js";import"./index-3rzkj0kw.js";import"./index-3w748142.js";import{Ni as k,Yh as d}from"./index-18h53jey.js";import{Sj as h}from"./index-j1kv20z9.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 y={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.405",dependencies:{"@brains/job-queue":"workspace:*","@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 j={completed:"\u2713",declined:"\u25CB",failed:"\u2717"},Z={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",y,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-4ps3ngse.js"),import("react"),import("./EnhancedApp-2y67m71j.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,Z))}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 q({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",b=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:[b>0&&p(c,{children:[a(l,{color:"green",children:"\u2713 "}),p(l,{color:"gray",children:[b," 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{q as BatchProgress,E as CLIInterface,f as ProgressBar,m as cliConfigSchema};
|
|
17
17
|
|
|
18
|
-
//# debugId=
|
|
19
|
-
//# sourceMappingURL=index-
|
|
18
|
+
//# debugId=3C4D1C587DAB400464756E2164756E21
|
|
19
|
+
//# sourceMappingURL=index-e0rx633y.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/job-queue\";\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": "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",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "3C4D1C587DAB400464756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S as c,T as y}from"./index-
|
|
2
|
+
import{S as c,T as y}from"./index-zghffskf.js";import{Bb as R,Db as z,Kf as a}from"./index-aft95ek4.js";import{Dh as i}from"./index-3rzkj0kw.js";import{Fj as l,Gj as h,Hj as C,Yh as e}from"./index-18h53jey.js";function _(t,n={}){if(!a(t))throw Error("use() expects a package definition returned by a @rizom/brain define helper");return Object.freeze({kind:"rizom-configured-plugin",definition:t,config:Object.freeze({...n})})}function O(t){if(t===null||typeof t!=="object")return!1;return Reflect.get(t,"kind")==="rizom-configured-plugin"&&a(Reflect.get(t,"definition"))&&typeof Reflect.get(t,"config")==="object"}var Ee=e.array(e.string()),Ie=e.record(e.string(),e.unknown()),Ae=e.unknown();var Be=e.enum(["eval"]),p=e.enum(["person","team","organization"]);function K(t){if(t.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");return t}function f(t){if(Array.isArray(t))return t.map((n)=>f(n));if(i(t))return Object.fromEntries(Object.entries(t).map(([n,o])=>[n,f(o)]));return t}function u(t){return f(t)}var r=e.string().min(1),V=e.strictObject({member:r,value:e.record(e.string(),e.unknown()),overrides:r.optional()}),G=e.custom(i,{message:"Expected an opaque permission config object"}),q=e.strictObject({member:r,config:G,overrides:r.optional()}),U=e.strictObject({id:r,members:e.array(r),config:e.array(V).optional(),permissions:e.array(q).optional(),agentInstructions:e.array(e.string().min(1)).optional(),evalDisable:e.array(r).optional()});function E(t,n,o,Z){let w=new Set;for(let[j,g]of t.entries()){if(w.has(g))Z.addIssue({code:e.ZodIssueCode.custom,message:`Duplicate ${n} "${g}"`,path:[o,j]});w.add(g)}}var H=U.superRefine((t,n)=>{E(t.members,"member","members",n),E(t.evalDisable??[],"eval exclusion","evalDisable",n)});function I(t){return u(H.parse(t))}function J(t){if(t===void 0)return[];return Array.isArray(t)?t:[t]}var W=e.record(e.string(),e.unknown()),ut=e.record(e.string(),e.unknown()),Y=e.enum(["eval"]),Q=l,s=h,X=e.strictObject({create:s.optional(),update:s.optional(),delete:s.optional(),extract:s.optional(),publish:s.optional()}),ee=e.record(e.string(),X),A=W.superRefine((t,n)=>{if(typeof t.package!=="string")return;n.addIssue({code:"custom",message:'"package" uses the removed alpha external-plugin contract. Default-export a declarative package definition from a @rizom/brain define helper and compose it with use() in defineBrain().'})}),mt=e.strictObject({brain:e.string().optional(),bundleContract:e.string().trim().min(1).optional(),anchor:p.optional(),site:e.object({package:e.string().optional(),variant:e.string().optional(),theme:e.string().optional(),themeOverride:e.string().optional()}).optional(),name:e.string().optional(),kind:e.string().trim().min(1).optional(),logLevel:c.optional(),logFile:e.string().optional(),port:e.number().optional(),domain:e.string().optional(),database:e.string().optional(),embedding:e.strictObject({enabled:e.boolean().optional()}).optional(),model:e.string().optional(),reasoningEffort:y.optional(),bundles:e.array(e.string().min(1)).optional(),mode:Y.optional(),add:e.array(e.string()).optional(),remove:e.array(e.string()).optional(),admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),spaces:e.array(e.string()).optional(),plugins:e.record(e.string(),A).optional(),permissions:e.object({admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),rules:e.array(e.object({pattern:e.string(),level:Q})).optional(),entityActions:ee.optional()}).optional()});var Pt=e.record(e.string(),e.unknown());var ne=e.strictObject({pattern:e.string(),level:l}),Et=e.strictObject({admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),rules:e.array(ne).optional(),entityActions:C.optional()});var D=`/* ============================================
|
|
3
3
|
THEME BASE - Shared utilities for all themes
|
|
4
4
|
============================================
|
|
5
5
|
This file contains CSS that is IDENTICAL across all themes.
|
|
@@ -528,4 +528,4 @@ import{S as c,T as y}from"./index-7q5j58p2.js";import{Bb as R,Db as z,Kf as a}fr
|
|
|
528
528
|
`+t}var B=e.custom((t)=>z.safeParse(t).success),se=e.custom((t)=>{if(!i(t))return!1;let{plugin:n,...o}=t;if(n!==void 0&&typeof n!=="function")return!1;return R.safeParse(o).success});var ce=e.looseObject({id:e.string().min(1)}),de=e.looseObject({label:e.string().min(1)}),ge=e.custom((t)=>typeof t==="function"),pe=e.looseObject({layouts:e.record(e.string(),e.unknown()).optional(),plugin:ge.optional(),pluginConfig:e.record(e.string(),e.unknown()).optional(),routes:e.array(ce).optional(),entityDisplay:e.record(e.string(),de).optional(),content:e.unknown().optional(),themeOverride:e.string().optional(),headScripts:e.array(e.string()).optional(),staticAssets:e.record(e.string(),e.string()).optional()}),Ut=e.custom((t)=>pe.safeParse(t).success);var En=e.looseObject({name:e.string().min(1),version:e.string().min(1),dependencies:e.record(e.string(),e.string()).optional(),peerDependencies:e.record(e.string(),e.string()).optional()});export{_ as M,O as N,K as O,I as P,J as Q,re as R};
|
|
529
529
|
|
|
530
530
|
//# debugId=8EE7646B735574C264756E2164756E21
|
|
531
|
-
//# sourceMappingURL=index-
|
|
531
|
+
//# sourceMappingURL=index-pkcefcbr.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{F as o,G as n}from"./index-
|
|
2
|
+
import{F as o,G as n}from"./index-03cfb3s4.js";import{He as a,ob as s}from"./index-aft95ek4.js";class l extends a{constructor(){super({entityType:"post",purpose:"A long-form published article, essay, or blog post written for an audience.",schema:n,frontmatterSchema:o,supportsCoverImage:!0})}toMarkdown(t){let e=this.extractBody(t.content);try{let r=this.parseFrontMatter(t.content,o),i={...r,slug:r.slug??t.metadata.slug};return this.buildMarkdown(e,i)}catch{return e}}fromMarkdown(t){let e=this.parseFrontMatter(t,o),r=e.slug??s(e.title);return{content:t,entityType:"post",metadata:{title:e.title,slug:r,status:e.status,publishedAt:e.publishedAt,seriesName:e.seriesName,seriesIndex:e.seriesIndex}}}parsePostFrontmatter(t){return this.parseFrontMatter(t.content,o)}createPostContent(t,e){return this.buildMarkdown(e,t)}buildStub(t){let e={title:t.title,slug:t.id,status:"generating",excerpt:"",author:"AI"};return{content:this.buildMarkdown("",e),metadata:{title:t.title,slug:t.id,status:"generating"}}}}var p=new l;
|
|
3
3
|
export{l as B,p as C};
|
|
4
4
|
|
|
5
5
|
//# debugId=216F2C4A0B20933164756E2164756E21
|
|
6
|
-
//# sourceMappingURL=index-
|
|
6
|
+
//# sourceMappingURL=index-t1p3qrrm.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pa as hR,qa as CR,ra as kR}from"./index-cmhbf9f7.js";import{sa as pp}from"./index-48ksf4j5.js";import{$d as ar,Ab as xp,Ac as de,Ad as Ex,Bc as vs,Bg as PT,Bh as OT,Cb as yr,Cc as vd,Cf as Qs,Dc as Xr,Df as CT,Dg as MT,Eb as XT,Ed as xC,Fc as _n,Fe as yT,Ff as SC,Gc as oT,Ge as DT,Gf as kT,Gg as hx,Hb as Nd,Hc as iT,Hf as RT,Ib as Fx,Ic as aT,Ie as zT,If as ET,Jb as ir,Je as AI,Kc as mC,Lb as zo,Lc as gC,Le as QI,Mc as fC,Me as vT,Nb as Gx,Oc as yn,Od as IC,Pd as CC,Pe as Dr,Qc as mt,Qd as kC,Qe as Tp,Rd as RC,Re as ga,Sd as EC,Se as eI,Td as AC,Te as bC,Ud as PC,Ue as kx,Vb as Bx,Vd as MC,Ve as ST,Wc as gx,Wd as jC,Xd as da,Xe as HT,Yb as Od,Yd as pI,Ye as Gd,Zb as ks,Zd as KI,_b as Dx,_f as lI,ac as zx,ae as Gs,af as ZT,be as Bd,cb as VI,cc as qx,ce as jI,de as qI,fc as $x,gb as ZI,gc as Wx,gf as _C,he as Bs,ib as FI,ic as xn,if as wT,jb as GI,jc as Tn,jf as xT,kc as NC,lc as DC,mc as VT,nc as Ox,ob as Yr,qc as Ds,qg as oI,qh as qT,rc as nT,rg as iI,rh as Xx,sc as Kx,sg as pa,tc as Uw,td as qC,uc as rt,ud as $C,uh as $T,vc as or,vd as LC,ve as vC,vh as eT,wc as hT,we as Px,wf as TT,wh as jT,xc as tt,xh as tT,yc as Xe,yd as xI,yf as IT,zc as Ki,zd as tp,zf as $s}from"./index-
|
|
2
|
+
import{pa as hR,qa as CR,ra as kR}from"./index-cmhbf9f7.js";import{sa as pp}from"./index-48ksf4j5.js";import{$d as ar,Ab as xp,Ac as de,Ad as Ex,Bc as vs,Bg as PT,Bh as OT,Cb as yr,Cc as vd,Cf as Qs,Dc as Xr,Df as CT,Dg as MT,Eb as XT,Ed as xC,Fc as _n,Fe as yT,Ff as SC,Gc as oT,Ge as DT,Gf as kT,Gg as hx,Hb as Nd,Hc as iT,Hf as RT,Ib as Fx,Ic as aT,Ie as zT,If as ET,Jb as ir,Je as AI,Kc as mC,Lb as zo,Lc as gC,Le as QI,Mc as fC,Me as vT,Nb as Gx,Oc as yn,Od as IC,Pd as CC,Pe as Dr,Qc as mt,Qd as kC,Qe as Tp,Rd as RC,Re as ga,Sd as EC,Se as eI,Td as AC,Te as bC,Ud as PC,Ue as kx,Vb as Bx,Vd as MC,Ve as ST,Wc as gx,Wd as jC,Xd as da,Xe as HT,Yb as Od,Yd as pI,Ye as Gd,Zb as ks,Zd as KI,_b as Dx,_f as lI,ac as zx,ae as Gs,af as ZT,be as Bd,cb as VI,cc as qx,ce as jI,de as qI,fc as $x,gb as ZI,gc as Wx,gf as _C,he as Bs,ib as FI,ic as xn,if as wT,jb as GI,jc as Tn,jf as xT,kc as NC,lc as DC,mc as VT,nc as Ox,ob as Yr,qc as Ds,qg as oI,qh as qT,rc as nT,rg as iI,rh as Xx,sc as Kx,sg as pa,tc as Uw,td as qC,uc as rt,ud as $C,uh as $T,vc as or,vd as LC,ve as vC,vh as eT,wc as hT,we as Px,wf as TT,wh as jT,xc as tt,xh as tT,yc as Xe,yd as xI,yf as IT,zc as Ki,zd as tp,zf as $s}from"./index-aft95ek4.js";import{Dh as Td,Fh as dC,Gh as _s,Hh as Kw,Ih as Ss,Jh as Qw,Kh as AT,Oh as wn,Sh as en}from"./index-3rzkj0kw.js";import{Th as qt,Uh as vr}from"./index-3w748142.js";import{Ai as Cx,Dj as bT,Ii as ea,Ij as wI,Jj as bs,Kj as _T,Li as Qn,Ni as Ae,Oi as ta,Qi as wx,Wh as Bm,Xh as Jm,Xi as Ps,Yh as r,ai as ap,bj as Vd,ci as ia,cj as WT,dj as uC,ii as gt,mi as Zw,qi as Qx,rj as sI,si as Yx,ti as vx,uj as yC,vj as Fd,wi as ys,yi as Ix,yj as uT}from"./index-18h53jey.js";import{Pj as Nn,Qj as ye,Sj as Al}from"./index-j1kv20z9.js";var El=ye(function(DW,gg){var{defineProperty:Rl,getOwnPropertyDescriptor:cR,getOwnPropertyNames:uR}=Object,dR=Object.prototype.hasOwnProperty,pR=(e,t)=>{for(var n in t)Rl(e,n,{get:t[n],enumerable:!0})},mR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of uR(t))if(!dR.call(e,i)&&i!==n)Rl(e,i,{get:()=>t[i],enumerable:!(o=cR(t,i))||o.enumerable})}return e},gR=(e)=>mR(Rl({},"__esModule",{value:!0}),e),pg={};pR(pg,{SYMBOL_FOR_REQ_CONTEXT:()=>mg,getContext:()=>fR});gg.exports=gR(pg);var mg=Symbol.for("@vercel/request-context");function fR(){return globalThis[mg]?.get?.()??{}}});var yg=ye(function(zW,hg){var{defineProperty:Ml,getOwnPropertyDescriptor:yR,getOwnPropertyNames:vR}=Object,bR=Object.prototype.hasOwnProperty,_R=(e,t)=>{for(var n in t)Ml(e,n,{get:t[n],enumerable:!0})},SR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of vR(t))if(!bR.call(e,i)&&i!==n)Ml(e,i,{get:()=>t[i],enumerable:!(o=yR(t,i))||o.enumerable})}return e},wR=(e)=>SR(Ml({},"__esModule",{value:!0}),e),fg={};_R(fg,{getVercelOidcToken:()=>IR,getVercelOidcTokenSync:()=>Pl});hg.exports=wR(fg);var xR=El(),TR=hR();async function IR(e){let t="",n;try{t=Pl()}catch(o){n=o}try{let[{getTokenPayload:o,isExpired:i},{refreshToken:a}]=await Promise.all([await import("./token-util-bc9s3zxm.js").then((m)=>Nn(m.default)),await import("./token-9y4fbccb.js").then((m)=>Nn(m.default))]);if(!t||i(o(t),e?.expirationBufferMs))await a(e),t=Pl()}catch(o){let i=n instanceof Error?n.message:"";if(o instanceof Error)i=`${i}
|
|
3
3
|
${o.message}`;if(i)throw new TR.VercelOidcTokenError(i);throw o}return t}function Pl(){let e=(0,xR.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return e}});var Ol=ye(function(qW,Sg){var{defineProperty:jl,getOwnPropertyDescriptor:RR,getOwnPropertyNames:ER}=Object,AR=Object.prototype.hasOwnProperty,PR=(e,t)=>{for(var n in t)jl(e,n,{get:t[n],enumerable:!0})},MR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of ER(t))if(!AR.call(e,i)&&i!==n)jl(e,i,{get:()=>t[i],enumerable:!(o=RR(t,i))||o.enumerable})}return e},jR=(e)=>MR(jl({},"__esModule",{value:!0}),e),_g={};PR(_g,{AccessTokenMissingError:()=>bg.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>bg.RefreshAccessTokenFailedError,getContext:()=>OR.getContext,getVercelOidcToken:()=>vg.getVercelOidcToken,getVercelOidcTokenSync:()=>vg.getVercelOidcTokenSync,getVercelToken:()=>NR.getVercelToken});Sg.exports=jR(_g);var vg=yg(),OR=El(),bg=CR(),NR=kR()});var zl=ye(function(yf){Object.defineProperty(yf,"__esModule",{value:!0});yf.VERSION=void 0;yf.VERSION="1.9.1"});var xf=ye(function(Sf){Object.defineProperty(Sf,"__esModule",{value:!0});Sf.isCompatible=Sf._makeCompatibilityCheck=void 0;var YE=zl(),bf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _f(e){let t=new Set([e]),n=new Set,o=e.match(bf);if(!o)return()=>!1;let i={major:+o[1],minor:+o[2],patch:+o[3],prerelease:o[4]};if(i.prerelease!=null)return function(c){return c===e};function a(l){return n.add(l),!1}function s(l){return t.add(l),!0}return function(c){if(t.has(c))return!0;if(n.has(c))return!1;let u=c.match(bf);if(!u)return a(c);let d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};if(d.prerelease!=null)return a(c);if(i.major!==d.major)return a(c);if(i.major===0){if(i.minor===d.minor&&i.patch<=d.patch)return s(c);return a(c)}if(i.minor<=d.minor)return s(c);return a(c)}}Sf._makeCompatibilityCheck=_f;Sf.isCompatible=_f(YE.VERSION)});var Dn=ye(function(Tf){Object.defineProperty(Tf,"__esModule",{value:!0});Tf.unregisterGlobal=Tf.getGlobal=Tf.registerGlobal=void 0;var uo=zl(),eA=xf(),tA=uo.VERSION.split(".")[0],bi=Symbol.for(`opentelemetry.js.api.${tA}`),_i=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function rA(e,t,n,o=!1){var i;let a=_i[bi]=(i=_i[bi])!==null&&i!==void 0?i:{version:uo.VERSION};if(!o&&a[e]){let s=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return n.error(s.stack||s.message),!1}if(a.version!==uo.VERSION){let s=Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${uo.VERSION}`);return n.error(s.stack||s.message),!1}return a[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${uo.VERSION}.`),!0}Tf.registerGlobal=rA;function nA(e){var t,n;let o=(t=_i[bi])===null||t===void 0?void 0:t.version;if(!o||!(0,eA.isCompatible)(o))return;return(n=_i[bi])===null||n===void 0?void 0:n[e]}Tf.getGlobal=nA;function oA(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${uo.VERSION}.`);let n=_i[bi];if(n)delete n[e]}Tf.unregisterGlobal=oA});var Ef=ye(function(kf){Object.defineProperty(kf,"__esModule",{value:!0});kf.DiagComponentLogger=void 0;var sA=Dn();class Cf{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return Si("debug",this._namespace,e)}error(...e){return Si("error",this._namespace,e)}info(...e){return Si("info",this._namespace,e)}warn(...e){return Si("warn",this._namespace,e)}verbose(...e){return Si("verbose",this._namespace,e)}}kf.DiagComponentLogger=Cf;function Si(e,t,n){let o=(0,sA.getGlobal)("diag");if(!o)return;return o[e](t,...n)}});var za=ye(function(Af){Object.defineProperty(Af,"__esModule",{value:!0});Af.DiagLogLevel=void 0;var lA;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(lA=Af.DiagLogLevel||(Af.DiagLogLevel={}))});var jf=ye(function(Pf){Object.defineProperty(Pf,"__esModule",{value:!0});Pf.createLogLevelDiagLogger=void 0;var Hr=za();function cA(e,t){if(e<Hr.DiagLogLevel.NONE)e=Hr.DiagLogLevel.NONE;else if(e>Hr.DiagLogLevel.ALL)e=Hr.DiagLogLevel.ALL;t=t||{};function n(o,i){let a=t[o];if(typeof a==="function"&&e>=i)return a.bind(t);return function(){}}return{error:n("error",Hr.DiagLogLevel.ERROR),warn:n("warn",Hr.DiagLogLevel.WARN),info:n("info",Hr.DiagLogLevel.INFO),debug:n("debug",Hr.DiagLogLevel.DEBUG),verbose:n("verbose",Hr.DiagLogLevel.VERBOSE)}}Pf.createLogLevelDiagLogger=cA});var zn=ye(function(Nf){Object.defineProperty(Nf,"__esModule",{value:!0});Nf.DiagAPI=void 0;var uA=Ef(),dA=jf(),Of=za(),qa=Dn(),pA="diag";class $l{static instance(){if(!this._instance)this._instance=new $l;return this._instance}constructor(){function e(o){return function(...i){let a=(0,qa.getGlobal)("diag");if(!a)return;return a[o](...i)}}let t=this,n=(o,i={logLevel:Of.DiagLogLevel.INFO})=>{var a,s,l;if(o===t){let d=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=d.stack)!==null&&a!==void 0?a:d.message),!1}if(typeof i==="number")i={logLevel:i};let c=(0,qa.getGlobal)("diag"),u=(0,dA.createLogLevelDiagLogger)((s=i.logLevel)!==null&&s!==void 0?s:Of.DiagLogLevel.INFO,o);if(c&&!i.suppressOverrideMessage){let d=(l=Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${d}`),u.warn(`Current logger will overwrite one already registered from ${d}`)}return(0,qa.registerGlobal)("diag",u,t,!0)};t.setLogger=n,t.disable=()=>{(0,qa.unregisterGlobal)(pA,t)},t.createComponentLogger=(o)=>new uA.DiagComponentLogger(o),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}Nf.DiagAPI=$l});var $f=ye(function(zf){Object.defineProperty(zf,"__esModule",{value:!0});zf.BaggageImpl=void 0;class po{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let t=this._entries.get(e);if(!t)return;return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){let n=new po(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new po(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new po(this._entries);for(let n of e)t._entries.delete(n);return t}clear(){return new po}}zf.BaggageImpl=po});var Ff=ye(function(Lf){Object.defineProperty(Lf,"__esModule",{value:!0});Lf.baggageEntryMetadataSymbol=void 0;Lf.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var Ll=ye(function(Gf){Object.defineProperty(Gf,"__esModule",{value:!0});Gf.baggageEntryMetadataFromString=Gf.createBaggage=void 0;var mA=zn(),gA=$f(),fA=Ff(),hA=mA.DiagAPI.instance();function yA(e={}){return new gA.BaggageImpl(new Map(Object.entries(e)))}Gf.createBaggage=yA;function vA(e){if(typeof e!=="string")hA.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:fA.baggageEntryMetadataSymbol,toString(){return e}}}Gf.baggageEntryMetadataFromString=vA});var wi=ye(function(Jf){Object.defineProperty(Jf,"__esModule",{value:!0});Jf.ROOT_CONTEXT=Jf.createContextKey=void 0;function _A(e){return Symbol.for(e)}Jf.createContextKey=_A;class $a{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=(n)=>t._currentContext.get(n),t.setValue=(n,o)=>{let i=new $a(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=(n)=>{let o=new $a(t._currentContext);return o._currentContext.delete(n),o}}}Jf.ROOT_CONTEXT=new $a});var Kf=ye(function(Vf){Object.defineProperty(Vf,"__esModule",{value:!0});Vf.DiagConsoleLogger=Vf._originalConsoleMethods=void 0;var Ul=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];Vf._originalConsoleMethods={};if(typeof console<"u"){let e=["error","warn","info","debug","trace","log"];for(let t of e)if(typeof console[t]==="function")Vf._originalConsoleMethods[t]=console[t]}class Hf{constructor(){function e(t){return function(...n){let o=Vf._originalConsoleMethods[t];if(typeof o!=="function")o=Vf._originalConsoleMethods.log;if(typeof o!=="function"&&console){if(o=console[t],typeof o!=="function")o=console.log}if(typeof o==="function")return o.apply(console,n)}}for(let t=0;t<Ul.length;t++)this[Ul[t].n]=e(Ul[t].c)}}Vf.DiagConsoleLogger=Hf});var Kl=ye(function(Qf){Object.defineProperty(Qf,"__esModule",{value:!0});Qf.createNoopMeter=Qf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=Qf.NOOP_OBSERVABLE_GAUGE_METRIC=Qf.NOOP_OBSERVABLE_COUNTER_METRIC=Qf.NOOP_UP_DOWN_COUNTER_METRIC=Qf.NOOP_HISTOGRAM_METRIC=Qf.NOOP_GAUGE_METRIC=Qf.NOOP_COUNTER_METRIC=Qf.NOOP_METER=Qf.NoopObservableUpDownCounterMetric=Qf.NoopObservableGaugeMetric=Qf.NoopObservableCounterMetric=Qf.NoopObservableMetric=Qf.NoopHistogramMetric=Qf.NoopGaugeMetric=Qf.NoopUpDownCounterMetric=Qf.NoopCounterMetric=Qf.NoopMetric=Qf.NoopMeter=void 0;class Fl{constructor(){}createGauge(e,t){return Qf.NOOP_GAUGE_METRIC}createHistogram(e,t){return Qf.NOOP_HISTOGRAM_METRIC}createCounter(e,t){return Qf.NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return Qf.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return Qf.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return Qf.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return Qf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}Qf.NoopMeter=Fl;class mo{}Qf.NoopMetric=mo;class Gl extends mo{add(e,t){}}Qf.NoopCounterMetric=Gl;class Bl extends mo{add(e,t){}}Qf.NoopUpDownCounterMetric=Bl;class Jl extends mo{record(e,t){}}Qf.NoopGaugeMetric=Jl;class Wl extends mo{record(e,t){}}Qf.NoopHistogramMetric=Wl;class xi{addCallback(e){}removeCallback(e){}}Qf.NoopObservableMetric=xi;class Hl extends xi{}Qf.NoopObservableCounterMetric=Hl;class Vl extends xi{}Qf.NoopObservableGaugeMetric=Vl;class Zl extends xi{}Qf.NoopObservableUpDownCounterMetric=Zl;Qf.NOOP_METER=new Fl;Qf.NOOP_COUNTER_METRIC=new Gl;Qf.NOOP_GAUGE_METRIC=new Jl;Qf.NOOP_HISTOGRAM_METRIC=new Wl;Qf.NOOP_UP_DOWN_COUNTER_METRIC=new Bl;Qf.NOOP_OBSERVABLE_COUNTER_METRIC=new Hl;Qf.NOOP_OBSERVABLE_GAUGE_METRIC=new Vl;Qf.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new Zl;function wA(){return Qf.NOOP_METER}Qf.createNoopMeter=wA});var lh=ye(function(sh){Object.defineProperty(sh,"__esModule",{value:!0});sh.ValueType=void 0;var jA;(function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"})(jA=sh.ValueType||(sh.ValueType={}))});var Yl=ye(function(ch){Object.defineProperty(ch,"__esModule",{value:!0});ch.defaultTextMapSetter=ch.defaultTextMapGetter=void 0;ch.defaultTextMapGetter={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}};ch.defaultTextMapSetter={set(e,t,n){if(e==null)return;e[t]=n}}});var gh=ye(function(ph){Object.defineProperty(ph,"__esModule",{value:!0});ph.NoopContextManager=void 0;var NA=wi();class dh{active(){return NA.ROOT_CONTEXT}with(e,t,n,...o){return t.call(n,...o)}bind(e,t){return t}enable(){return this}disable(){return this}}ph.NoopContextManager=dh});var Ti=ye(function(hh){Object.defineProperty(hh,"__esModule",{value:!0});hh.ContextAPI=void 0;var DA=gh(),Xl=Dn(),fh=zn(),ec="context",zA=new DA.NoopContextManager;class tc{constructor(){}static getInstance(){if(!this._instance)this._instance=new tc;return this._instance}setGlobalContextManager(e){return(0,Xl.registerGlobal)(ec,e,fh.DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,n,...o){return this._getContextManager().with(e,t,n,...o)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return(0,Xl.getGlobal)(ec)||zA}disable(){this._getContextManager().disable(),(0,Xl.unregisterGlobal)(ec,fh.DiagAPI.instance())}}hh.ContextAPI=tc});var nc=ye(function(vh){Object.defineProperty(vh,"__esModule",{value:!0});vh.TraceFlags=void 0;var qA;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(qA=vh.TraceFlags||(vh.TraceFlags={}))});var Ua=ye(function(bh){Object.defineProperty(bh,"__esModule",{value:!0});bh.INVALID_SPAN_CONTEXT=bh.INVALID_TRACEID=bh.INVALID_SPANID=void 0;var $A=nc();bh.INVALID_SPANID="0000000000000000";bh.INVALID_TRACEID="00000000000000000000000000000000";bh.INVALID_SPAN_CONTEXT={traceId:bh.INVALID_TRACEID,spanId:bh.INVALID_SPANID,traceFlags:$A.TraceFlags.NONE}});var Fa=ye(function(Th){Object.defineProperty(Th,"__esModule",{value:!0});Th.NonRecordingSpan=void 0;var LA=Ua();class xh{constructor(e=LA.INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}Th.NonRecordingSpan=xh});var ac=ye(function(kh){Object.defineProperty(kh,"__esModule",{value:!0});kh.getSpanContext=kh.setSpanContext=kh.deleteSpan=kh.setSpan=kh.getActiveSpan=kh.getSpan=void 0;var UA=wi(),FA=Fa(),GA=Ti(),oc=(0,UA.createContextKey)("OpenTelemetry Context Key SPAN");function ic(e){return e.getValue(oc)||void 0}kh.getSpan=ic;function BA(){return ic(GA.ContextAPI.getInstance().active())}kh.getActiveSpan=BA;function Ch(e,t){return e.setValue(oc,t)}kh.setSpan=Ch;function JA(e){return e.deleteValue(oc)}kh.deleteSpan=JA;function WA(e,t){return Ch(e,new FA.NonRecordingSpan(t))}kh.setSpanContext=WA;function HA(e){var t;return(t=ic(e))===null||t===void 0?void 0:t.spanContext()}kh.getSpanContext=HA});var Ba=ye(function(jh){Object.defineProperty(jh,"__esModule",{value:!0});jh.wrapSpanContext=jh.isSpanContextValid=jh.isValidSpanId=jh.isValidTraceId=void 0;var Eh=Ua(),XA=Fa(),Ga=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Ah(e,t){if(typeof e!=="string"||e.length!==t)return!1;let n=0;for(let o=0;o<e.length;o+=4)n+=(Ga[e.charCodeAt(o)]|0)+(Ga[e.charCodeAt(o+1)]|0)+(Ga[e.charCodeAt(o+2)]|0)+(Ga[e.charCodeAt(o+3)]|0);return n===t}function Ph(e){return Ah(e,32)&&e!==Eh.INVALID_TRACEID}jh.isValidTraceId=Ph;function Mh(e){return Ah(e,16)&&e!==Eh.INVALID_SPANID}jh.isValidSpanId=Mh;function eP(e){return Ph(e.traceId)&&Mh(e.spanId)}jh.isSpanContextValid=eP;function tP(e){return new XA.NonRecordingSpan(e)}jh.wrapSpanContext=tP});var cc=ye(function(zh){Object.defineProperty(zh,"__esModule",{value:!0});zh.NoopTracer=void 0;var iP=Ti(),Nh=ac(),sc=Fa(),aP=Ba(),lc=iP.ContextAPI.getInstance();class Dh{startSpan(e,t,n=lc.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new sc.NonRecordingSpan;let i=n&&(0,Nh.getSpanContext)(n);if(sP(i)&&(0,aP.isSpanContextValid)(i))return new sc.NonRecordingSpan(i);else return new sc.NonRecordingSpan}startActiveSpan(e,t,n,o){let i,a,s;if(arguments.length<2)return;else if(arguments.length===2)s=t;else if(arguments.length===3)i=t,s=n;else i=t,a=n,s=o;let l=a!==null&&a!==void 0?a:lc.active(),c=this.startSpan(e,i,l),u=(0,Nh.setSpan)(l,c);return lc.with(u,s,void 0,c)}}zh.NoopTracer=Dh;function sP(e){return e!==null&&typeof e==="object"&&"spanId"in e&&typeof e.spanId==="string"&&"traceId"in e&&typeof e.traceId==="string"&&"traceFlags"in e&&typeof e.traceFlags==="number"}});var uc=ye(function(Lh){Object.defineProperty(Lh,"__esModule",{value:!0});Lh.ProxyTracer=void 0;var lP=cc(),cP=new lP.NoopTracer;class $h{constructor(e,t,n,o){this._provider=e,this.name=t,this.version=n,this.options=o}startSpan(e,t,n){return this._getTracer().startSpan(e,t,n)}startActiveSpan(e,t,n,o){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!e)return cP;return this._delegate=e,this._delegate}}Lh.ProxyTracer=$h});var Jh=ye(function(Gh){Object.defineProperty(Gh,"__esModule",{value:!0});Gh.NoopTracerProvider=void 0;var uP=cc();class Fh{getTracer(e,t,n){return new uP.NoopTracer}}Gh.NoopTracerProvider=Fh});var dc=ye(function(Hh){Object.defineProperty(Hh,"__esModule",{value:!0});Hh.ProxyTracerProvider=void 0;var dP=uc(),pP=Jh(),mP=new pP.NoopTracerProvider;class Wh{getTracer(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new dP.ProxyTracer(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:mP}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,t,n)}}Hh.ProxyTracerProvider=Wh});var Kh=ye(function(Zh){Object.defineProperty(Zh,"__esModule",{value:!0});Zh.SamplingDecision=void 0;var gP;(function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(gP=Zh.SamplingDecision||(Zh.SamplingDecision={}))});var Yh=ye(function(Qh){Object.defineProperty(Qh,"__esModule",{value:!0});Qh.SpanKind=void 0;var fP;(function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"})(fP=Qh.SpanKind||(Qh.SpanKind={}))});var ey=ye(function(Xh){Object.defineProperty(Xh,"__esModule",{value:!0});Xh.SpanStatusCode=void 0;var hP;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(hP=Xh.SpanStatusCode||(Xh.SpanStatusCode={}))});var ny=ye(function(ty){Object.defineProperty(ty,"__esModule",{value:!0});ty.validateValue=ty.validateKey=void 0;var fc="[_0-9a-z-*/]",yP=`[a-z]${fc}{0,255}`,vP=`[a-z0-9]${fc}{0,240}@[a-z]${fc}{0,13}`,bP=new RegExp(`^(?:${yP}|${vP})$`),_P=/^[ -~]{0,255}[!-~]$/,SP=/,|=/;function wP(e){return bP.test(e)}ty.validateKey=wP;function xP(e){return _P.test(e)&&!SP.test(e)}ty.validateValue=xP});var uy=ye(function(ly){Object.defineProperty(ly,"__esModule",{value:!0});ly.TraceStateImpl=void 0;var oy=ny(),iy=32,IP=512,ay=",",sy="=";class hc{constructor(e){if(this._internalState=new Map,e)this._parse(e)}set(e,t){let n=this._clone();if(n._internalState.has(e))n._internalState.delete(e);return n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,t)=>(e.push(t+sy+this.get(t)),e),[]).join(ay)}_parse(e){if(e.length>IP)return;if(this._internalState=e.split(ay).reduceRight((t,n)=>{let o=n.trim(),i=o.indexOf(sy);if(i!==-1){let a=o.slice(0,i),s=o.slice(i+1,n.length);if((0,oy.validateKey)(a)&&(0,oy.validateValue)(s))t.set(a,s)}return t},new Map),this._internalState.size>iy)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,iy))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new hc;return e._internalState=new Map(this._internalState),e}}ly.TraceStateImpl=hc});var my=ye(function(dy){Object.defineProperty(dy,"__esModule",{value:!0});dy.createTraceState=void 0;var CP=uy();function kP(e){return new CP.TraceStateImpl(e)}dy.createTraceState=kP});var hy=ye(function(gy){Object.defineProperty(gy,"__esModule",{value:!0});gy.context=void 0;var RP=Ti();gy.context=RP.ContextAPI.getInstance()});var by=ye(function(yy){Object.defineProperty(yy,"__esModule",{value:!0});yy.diag=void 0;var EP=zn();yy.diag=EP.DiagAPI.instance()});var wy=ye(function(_y){Object.defineProperty(_y,"__esModule",{value:!0});_y.NOOP_METER_PROVIDER=_y.NoopMeterProvider=void 0;var AP=Kl();class yc{getMeter(e,t,n){return AP.NOOP_METER}}_y.NoopMeterProvider=yc;_y.NOOP_METER_PROVIDER=new yc});var Cy=ye(function(Ty){Object.defineProperty(Ty,"__esModule",{value:!0});Ty.MetricsAPI=void 0;var MP=wy(),vc=Dn(),xy=zn(),bc="metrics";class _c{constructor(){}static getInstance(){if(!this._instance)this._instance=new _c;return this._instance}setGlobalMeterProvider(e){return(0,vc.registerGlobal)(bc,e,xy.DiagAPI.instance())}getMeterProvider(){return(0,vc.getGlobal)(bc)||MP.NOOP_METER_PROVIDER}getMeter(e,t,n){return this.getMeterProvider().getMeter(e,t,n)}disable(){(0,vc.unregisterGlobal)(bc,xy.DiagAPI.instance())}}Ty.MetricsAPI=_c});var Ey=ye(function(ky){Object.defineProperty(ky,"__esModule",{value:!0});ky.metrics=void 0;var jP=Cy();ky.metrics=jP.MetricsAPI.getInstance()});var jy=ye(function(Py){Object.defineProperty(Py,"__esModule",{value:!0});Py.NoopTextMapPropagator=void 0;class Ay{inject(e,t){}extract(e,t){return e}fields(){return[]}}Py.NoopTextMapPropagator=Ay});var zy=ye(function(Ny){Object.defineProperty(Ny,"__esModule",{value:!0});Ny.deleteBaggage=Ny.setBaggage=Ny.getActiveBaggage=Ny.getBaggage=void 0;var OP=Ti(),NP=wi(),Sc=(0,NP.createContextKey)("OpenTelemetry Baggage Key");function Oy(e){return e.getValue(Sc)||void 0}Ny.getBaggage=Oy;function DP(){return Oy(OP.ContextAPI.getInstance().active())}Ny.getActiveBaggage=DP;function zP(e,t){return e.setValue(Sc,t)}Ny.setBaggage=zP;function qP(e){return e.deleteValue(Sc)}Ny.deleteBaggage=qP});var Fy=ye(function(Ly){Object.defineProperty(Ly,"__esModule",{value:!0});Ly.PropagationAPI=void 0;var wc=Dn(),FP=jy(),qy=Yl(),Ja=zy(),GP=Ll(),$y=zn(),xc="propagation",BP=new FP.NoopTextMapPropagator;class Tc{constructor(){this.createBaggage=GP.createBaggage,this.getBaggage=Ja.getBaggage,this.getActiveBaggage=Ja.getActiveBaggage,this.setBaggage=Ja.setBaggage,this.deleteBaggage=Ja.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Tc;return this._instance}setGlobalPropagator(e){return(0,wc.registerGlobal)(xc,e,$y.DiagAPI.instance())}inject(e,t,n=qy.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,n)}extract(e,t,n=qy.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,n)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,wc.unregisterGlobal)(xc,$y.DiagAPI.instance())}_getGlobalPropagator(){return(0,wc.getGlobal)(xc)||BP}}Ly.PropagationAPI=Tc});var Jy=ye(function(Gy){Object.defineProperty(Gy,"__esModule",{value:!0});Gy.propagation=void 0;var JP=Fy();Gy.propagation=JP.PropagationAPI.getInstance()});var Qy=ye(function(Zy){Object.defineProperty(Zy,"__esModule",{value:!0});Zy.TraceAPI=void 0;var Ic=Dn(),Wy=dc(),Hy=Ba(),go=ac(),Vy=zn(),Cc="trace";class kc{constructor(){this._proxyTracerProvider=new Wy.ProxyTracerProvider,this.wrapSpanContext=Hy.wrapSpanContext,this.isSpanContextValid=Hy.isSpanContextValid,this.deleteSpan=go.deleteSpan,this.getSpan=go.getSpan,this.getActiveSpan=go.getActiveSpan,this.getSpanContext=go.getSpanContext,this.setSpan=go.setSpan,this.setSpanContext=go.setSpanContext}static getInstance(){if(!this._instance)this._instance=new kc;return this._instance}setGlobalTracerProvider(e){let t=(0,Ic.registerGlobal)(Cc,this._proxyTracerProvider,Vy.DiagAPI.instance());if(t)this._proxyTracerProvider.setDelegate(e);return t}getTracerProvider(){return(0,Ic.getGlobal)(Cc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,Ic.unregisterGlobal)(Cc,Vy.DiagAPI.instance()),this._proxyTracerProvider=new Wy.ProxyTracerProvider}}Zy.TraceAPI=kc});var ev=ye(function(Yy){Object.defineProperty(Yy,"__esModule",{value:!0});Yy.trace=void 0;var WP=Qy();Yy.trace=WP.TraceAPI.getInstance()});var Ac=ye(function(Ze){Object.defineProperty(Ze,"__esModule",{value:!0});Ze.trace=Ze.propagation=Ze.metrics=Ze.diag=Ze.context=Ze.INVALID_SPAN_CONTEXT=Ze.INVALID_TRACEID=Ze.INVALID_SPANID=Ze.isValidSpanId=Ze.isValidTraceId=Ze.isSpanContextValid=Ze.createTraceState=Ze.TraceFlags=Ze.SpanStatusCode=Ze.SpanKind=Ze.SamplingDecision=Ze.ProxyTracerProvider=Ze.ProxyTracer=Ze.defaultTextMapSetter=Ze.defaultTextMapGetter=Ze.ValueType=Ze.createNoopMeter=Ze.DiagLogLevel=Ze.DiagConsoleLogger=Ze.ROOT_CONTEXT=Ze.createContextKey=Ze.baggageEntryMetadataFromString=void 0;var HP=Ll();Object.defineProperty(Ze,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return HP.baggageEntryMetadataFromString}});var tv=wi();Object.defineProperty(Ze,"createContextKey",{enumerable:!0,get:function(){return tv.createContextKey}});Object.defineProperty(Ze,"ROOT_CONTEXT",{enumerable:!0,get:function(){return tv.ROOT_CONTEXT}});var VP=Kf();Object.defineProperty(Ze,"DiagConsoleLogger",{enumerable:!0,get:function(){return VP.DiagConsoleLogger}});var ZP=za();Object.defineProperty(Ze,"DiagLogLevel",{enumerable:!0,get:function(){return ZP.DiagLogLevel}});var KP=Kl();Object.defineProperty(Ze,"createNoopMeter",{enumerable:!0,get:function(){return KP.createNoopMeter}});var QP=lh();Object.defineProperty(Ze,"ValueType",{enumerable:!0,get:function(){return QP.ValueType}});var rv=Yl();Object.defineProperty(Ze,"defaultTextMapGetter",{enumerable:!0,get:function(){return rv.defaultTextMapGetter}});Object.defineProperty(Ze,"defaultTextMapSetter",{enumerable:!0,get:function(){return rv.defaultTextMapSetter}});var YP=uc();Object.defineProperty(Ze,"ProxyTracer",{enumerable:!0,get:function(){return YP.ProxyTracer}});var XP=dc();Object.defineProperty(Ze,"ProxyTracerProvider",{enumerable:!0,get:function(){return XP.ProxyTracerProvider}});var eM=Kh();Object.defineProperty(Ze,"SamplingDecision",{enumerable:!0,get:function(){return eM.SamplingDecision}});var tM=Yh();Object.defineProperty(Ze,"SpanKind",{enumerable:!0,get:function(){return tM.SpanKind}});var rM=ey();Object.defineProperty(Ze,"SpanStatusCode",{enumerable:!0,get:function(){return rM.SpanStatusCode}});var nM=nc();Object.defineProperty(Ze,"TraceFlags",{enumerable:!0,get:function(){return nM.TraceFlags}});var oM=my();Object.defineProperty(Ze,"createTraceState",{enumerable:!0,get:function(){return oM.createTraceState}});var Rc=Ba();Object.defineProperty(Ze,"isSpanContextValid",{enumerable:!0,get:function(){return Rc.isSpanContextValid}});Object.defineProperty(Ze,"isValidTraceId",{enumerable:!0,get:function(){return Rc.isValidTraceId}});Object.defineProperty(Ze,"isValidSpanId",{enumerable:!0,get:function(){return Rc.isValidSpanId}});var Ec=Ua();Object.defineProperty(Ze,"INVALID_SPANID",{enumerable:!0,get:function(){return Ec.INVALID_SPANID}});Object.defineProperty(Ze,"INVALID_TRACEID",{enumerable:!0,get:function(){return Ec.INVALID_TRACEID}});Object.defineProperty(Ze,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Ec.INVALID_SPAN_CONTEXT}});var nv=hy();Object.defineProperty(Ze,"context",{enumerable:!0,get:function(){return nv.context}});var ov=by();Object.defineProperty(Ze,"diag",{enumerable:!0,get:function(){return ov.diag}});var iv=Ey();Object.defineProperty(Ze,"metrics",{enumerable:!0,get:function(){return iv.metrics}});var av=Jy();Object.defineProperty(Ze,"propagation",{enumerable:!0,get:function(){return av.propagation}});var sv=ev();Object.defineProperty(Ze,"trace",{enumerable:!0,get:function(){return sv.trace}});Ze.default={context:nv.context,diag:ov.diag,metrics:iv.metrics,propagation:av.propagation,trace:sv.trace}});var ss=ye(function(LS){Object.defineProperty(LS,"__esModule",{value:!0});function qS(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function $S(){let e=qS();if(e.__xstate__)return e.__xstate__;return}function xz(e){if(typeof window>"u")return;let t=$S();if(t)t.register(e)}var Tz=(e)=>{if(typeof window>"u")return;let t=$S();if(t)t.register(e)};LS.devToolsAdapter=Tz;LS.getGlobal=qS;LS.registerService=xz});var Eo=ye(function(jq){var Rz=ss();class Pu{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){if(this._current)this._current.next=null,this._last=this._current}enqueue(e){let t={value:e,next:null};if(this._current){this._last.next=t,this._last=t;return}if(this._current=t,this._last=t,this._active)this.flush()}flush(){while(this._current){let e=this._current;this._process(e.value),this._current=e.next}this._last=null}}var WS=".",Ez="",HS="",Az="#",Mu="*",VS="xstate.init",Pz="xstate.error",ls="xstate.stop";function Mz(e,t){return{type:`xstate.after.${e}.${t}`}}function ju(e,t){return{type:`xstate.done.state.${e}`,output:t}}function jz(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function ZS(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function KS(e){return{type:VS,input:e}}function Mr(e){setTimeout(()=>{throw e})}var Oz=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function zu(e,t){let n=US(e),o=US(t);if(typeof o==="string"){if(typeof n==="string")return o===n;return!1}if(typeof n==="string")return n in o;return Object.keys(n).every((i)=>{if(!(i in o))return!1;return zu(n[i],o[i])})}function qu(e){if(XS(e))return e;let t=[],n="";for(let o=0;o<e.length;o++){switch(e.charCodeAt(o)){case 92:n+=e[o+1],o++;continue;case 46:t.push(n),n="";continue}n+=e[o]}return t.push(n),t}function US(e){if(yw(e))return e.value;if(typeof e!=="string")return e;let t=qu(e);return QS(t)}function QS(e){if(e.length===1)return e[0];let t={},n=t;for(let o=0;o<e.length-1;o++)if(o===e.length-2)n[e[o]]=e[o+1];else{let i=n;n={},i[e[o]]=n}return t}function Nz(e,t){let n={},o=Object.keys(e);for(let i=0;i<o.length;i++){let a=o[i];n[a]=t(e[a],a,e,i)}return n}function YS(e){if(XS(e))return e;return[e]}function Bi(e){if(e===void 0)return[];return YS(e)}function Ou(e,t,n,o){if(typeof e==="function")return e({context:t,event:n,self:o});if(!!e&&typeof e==="object"&&Object.values(e).some((i)=>typeof i==="function"))console.warn(`Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.
|
|
4
4
|
Found object containing properties whose values are possibly mapping functions: ${Object.entries(e).filter(([,i])=>typeof i==="function").map(([i,a])=>`
|
|
5
5
|
- ${i}: ${a.toString().replace(/\n\s*/g,"")}`).join("")}`);return e}function XS(e){return Array.isArray(e)}function Dz(e){return e.type.startsWith("xstate.error.actor")}function wo(e){return YS(e).map((t)=>{if(typeof t>"u"||typeof t==="string")return{target:t};return t})}function ew(e){if(e===void 0||e===Ez)return;return Bi(e)}function Fi(e,t,n){let o=typeof e==="object",i=o?e:void 0;return{next:(o?e.next:e)?.bind(i),error:(o?e.error:t)?.bind(i),complete:(o?e.complete:n)?.bind(i)}}function zz(e,t){return`${t}.${e}`}function tw(e,t){let n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];let[,o,i]=n,s=e.getStateNodeById(i).config.invoke;return(Array.isArray(s)?s[o]:s).src}function qz(e){return[...new Set([...e._nodes.flatMap((t)=>t.ownEvents)])]}function rw(e,t){if(t===e)return!0;if(t===Mu)return!0;if(!t.endsWith(".*"))return!1;if(/.*\*.+/.test(t))console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${t}" event.`);let n=t.split("."),o=e.split(".");for(let i=0;i<n.length;i++){let a=n[i],s=o[i];if(a==="*"){let l=i===n.length-1;if(!l)console.warn(`Infix wildcards in transition events are not allowed. Check the "${t}" transition.`);return l}if(a!==s)return!1}return!0}function FS(e,t){return`${e.sessionId}.${t}`}var $z=0;function nw(e,t){let n=new Map,o=new Map,i=new WeakMap,a=new Set,s={},{clock:l,logger:c}=t,u={schedule:(p,f,g,h,v=Math.random().toString(36).slice(2))=>{let x={source:p,target:f,event:g,delay:h,id:v,startedAt:Date.now()},S=FS(p,v);m._snapshot._scheduledEvents[S]=x;let y=l.setTimeout(()=>{delete s[S],delete m._snapshot._scheduledEvents[S],m._relay(p,f,g)},h);s[S]=y},cancel:(p,f)=>{let g=FS(p,f),h=s[g];if(delete s[g],delete m._snapshot._scheduledEvents[g],h!==void 0)l.clearTimeout(h)},cancelAll:(p)=>{for(let f in m._snapshot._scheduledEvents){let g=m._snapshot._scheduledEvents[f];if(g.source===p)u.cancel(p,g.id)}}},d=(p)=>{if(!a.size)return;let f={...p,rootId:e.sessionId};a.forEach((g)=>g.next?.(f))},m={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${$z++}`,_register:(p,f)=>(n.set(p,f),p),_unregister:(p)=>{n.delete(p.sessionId);let f=i.get(p);if(f!==void 0)o.delete(f),i.delete(p)},get:(p)=>o.get(p),getAll:()=>Object.fromEntries(o.entries()),_set:(p,f)=>{let g=o.get(p);if(g&&g!==f)throw Error(`Actor with system ID '${p}' already exists.`);o.set(p,f),i.set(f,p)},inspect:(p)=>{let f=Fi(p);return a.add(f),{unsubscribe(){a.delete(f)}}},_sendInspectionEvent:d,_relay:(p,f,g)=>{m._sendInspectionEvent({type:"@xstate.event",sourceRef:p,actorRef:f,event:g}),f._send(g)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...m._snapshot._scheduledEvents}}),start:()=>{let p=m._snapshot._scheduledEvents;m._snapshot._scheduledEvents={};for(let f in p){let{source:g,target:h,event:v,delay:x,id:S}=p[f];u.schedule(g,h,v,x,S)}},_clock:l,_logger:c};return m}jq.executingCustomAction=!1;var $u=1,Wt=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({}),Lz={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Lu{constructor(e,t){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Pu(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Wt.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let n={...Lz,...t},{clock:o,logger:i,parent:a,syncSnapshot:s,id:l,systemId:c,inspect:u}=n;if(this.system=a?a.system:nw(this,{clock:o,logger:i}),u&&!a)this.system.inspect(Fi(u));if(this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=t?.logger??this.system._logger,this.clock=t?.clock??this.system._clock,this._parent=a,this._syncSnapshot=s,this.options=n,this.src=n.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:(d)=>{this._deferred.push(d)},system:this.system,stopChild:(d)=>{if(d._parent!==this)throw Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:(d)=>{let m=this.eventListeners.get(d.type),p=this.eventListeners.get("*");if(!m&&!p)return;let f=[...m?m.values():[],...p?p.values():[]];for(let g of f)try{g(d)}catch(h){Mr(h)}},actionExecutor:(d)=>{let m=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:d.type,params:d.params}}),!d.exec)return;let p=jq.executingCustomAction;try{jq.executingCustomAction=!0,d.exec(d.info,d.params)}finally{jq.executingCustomAction=p}};if(this._processingStatus===Wt.Running)m();else this._deferred.push(m)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),c)this.systemId=c,this.system._set(c,this);if(this._initState(t?.snapshot??t?.state),c&&this._snapshot.status!=="active")this.system._unregister(this)}_initState(e){try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(e,t){this._snapshot=e;let n;while(n=this._deferred.shift())try{n()}catch(o){this._deferred.length=0,this._snapshot={...e,status:"error",error:o}}switch(this._snapshot.status){case"active":for(let o of this.observers)try{o.next?.(e)}catch(i){Mr(i)}break;case"done":for(let o of this.observers)try{o.next?.(e)}catch(i){Mr(i)}if(this._stopProcedure(),this._complete(),this._doneEvent=jz(this.id,this._snapshot.output),this._parent)this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:t,snapshot:e})}subscribe(e,t,n){let o=Fi(e,t,n);if(this._processingStatus!==Wt.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{o.complete?.()}catch(i){Mr(i)}break;case"error":{let i=this._snapshot.error;if(!o.error)Mr(i);else try{o.error(i)}catch(a){Mr(a)}break}}return{unsubscribe:()=>{this.observers.delete(o)}}}on(e,t){let n=this.eventListeners.get(e);if(!n)n=new Set,this.eventListeners.set(e,n);let o=t.bind(void 0);return n.add(o),{unsubscribe:()=>{n.delete(o)}}}select(e,t=Object.is){return{subscribe:(n)=>{let o=Fi(n),i=this.getSnapshot(),a=e(i);return this.subscribe((s)=>{let l=e(s);if(!t(a,l))a=l,o.next?.(l)})},get:()=>e(this.getSnapshot())}}start(){if(this._processingStatus===Wt.Running)return this;if(this._syncSnapshot)this.subscribe({next:(n)=>{if(n.status==="active")this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:n})},error:()=>{}});if(this.system._register(this.sessionId,this),this.systemId)this.system._set(this.systemId,this);this._processingStatus=Wt.Running;let e=KS(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case"done":return this.update(this._snapshot,e),this;case"error":return this._error(this._snapshot.error),this}if(!this._parent)this.system.start();if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(n){return this._snapshot={...this._snapshot,status:"error",error:n},this._error(n),this}if(this.update(this._snapshot,e),this.options.devTools)this.attachDevTools();return this.mailbox.start(),this}_process(e){let t,n;try{t=this.logic.transition(this._snapshot,e,this._actorScope)}catch(o){n={err:o}}if(n){let{err:o}=n;this._snapshot={...this._snapshot,status:"error",error:o},this._error(o);return}if(this.update(t,e),e.type===ls)this._stopProcedure(),this._complete()}_stop(){if(this._processingStatus===Wt.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===Wt.NotStarted)return this._processingStatus=Wt.Stopped,this;return this.mailbox.enqueue({type:ls}),this}stop(){if(this._parent)throw Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(let e of this.observers)try{e.complete?.()}catch(t){Mr(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){if(!this._parent)Mr(e);this.eventListeners.clear();return}let t=!1;for(let n of this.observers){let o=n.error;t||=!o;try{o?.(e)}catch(i){Mr(i)}}if(this.observers.clear(),this.eventListeners.clear(),t)Mr(e)}_error(e){if(this._stopProcedure(),this._reportError(e),this._parent)this.system._relay(this,this._parent,ZS(this.id,e))}_stopProcedure(){if(this._processingStatus!==Wt.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Pu(this._process.bind(this)),this._processingStatus=Wt.Stopped,this.system._unregister(this),this}_send(e){if(this._processingStatus===Wt.Stopped){{let t=JSON.stringify(e);console.warn(`Event "${e.type}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.
|
|
@@ -179,9 +179,9 @@ ${a}`:"")}function wd(e,t,n,o){let i=n.actor??{kind:"agent",agentId:"brain-agent
|
|
|
179
179
|
`),s=[];for(let l=0;l<Math.max(i.length,a.length);l++)if((i[l]??"")!==(a[l]??"")){if(i[l])s.push(`- ${i[l]}`);if(a[l])s.push(`+ ${a[l]}`)}return s.join(`
|
|
180
180
|
`)}function XI(e){let{entityService:t,logger:n,entityRegistry:o}=e,i=en({label:"update",requestNoun:"the update"});return Nr("update","Update an entity's fields or content. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. For direct requests that provide exact IDs to set an existing image as an entity cover, call this tool on the target entity with fields.coverImageId set to the image ID; do not stop after lookup.",vI,async(a,s)=>{let l=ar(s.userPermissionLevel),c=await Dr(t,a.entityType,a.id,n,void 0,l);if(!c.ok)return{success:!1,error:c.error};let{entity:u}=c,d=II({...a.fields!==void 0?{fields:a.fields}:{},...a.content!==void 0?{content:a.content}:{}}),m=d.content?.trim().length===0&&d.fields===void 0,p=u.metadata.status,f=!1;if(a.confirmed&&u.entityType==="agent"&&(p==="discovered"||p==="approved")&&(!d.content&&!d.fields||m)){let R=UB.safeParse(i.takePending(a.confirmationToken));if(!R.success||R.data.id!==u.id)return{success:!1,error:"No pending update confirmation found for this agent. Please request the update again and confirm the new approval."};d={fields:{status:"approved"}},f=!0}if(d.content&&d.fields)return{success:!1,error:"Provide either 'content' or 'fields', not both"};if(!d.content&&!d.fields)return{success:!1,error:"Provide 'content' (full replacement) or 'fields' (partial update)"};let g=GB(u.entityType,d);if(g)return g;let h=WB(u,d,o,t);if(h)return h;let v=HB(u.entityType,d,o);if(v)return v;let x=VB(u.entityType,d,o);if(x)return x;let S=u.metadata.status,y=ZB(u,d,o),_=QI(u.entityType,S,y,o)==="non-publish"?"update":"publish",C=Or(e,a.entityType,_,s);if(C)return C;if(a.confirmed){if(!f){let q=i.validateConfirmed(a.confirmationToken,a);if(q)return q}if(a.contentHash&&u.contentHash!==a.contentHash)return{success:!1,error:"Entity was modified since you reviewed the changes. Please try again."};let R=d.content!==void 0?{...u,content:d.content,visibility:Bs(d.content)??u.visibility}:YI(u,d.fields??{},o);if(R.visibility!==u.visibility&&!Gs(s.userPermissionLevel,R.visibility))return{success:!1,error:`Cannot set entity visibility to "${R.visibility}" \u2014 caller permission "${s.userPermissionLevel??"public"}" is not allowed to write at that level.`};try{let q=Lo(s);await t.updateEntity({entity:R,...q?{options:{eventContext:q}}:{}})}catch(q){return{success:!1,error:Ae(q,"Failed to update entity")}}return{success:!0,data:{updated:u.id}}}let I=Fs(u),b=KB(u,d,o);return{needsConfirmation:!0,toolName:"system_update",summary:`Update "${I}"?`,completionSummary:`Updated ${CI(u.entityType)}.`,preview:b,args:i.buildArgs((R)=>({...a,...d,id:u.id,confirmed:!0,confirmationToken:R,contentHash:u.contentHash}))}},{visibility:"trusted",sideEffects:"writes"})}function eC(e){return[EI(e),PI(e),MI(e),XI(e)]}function Zs(e){if(e.interfaceType!==mt){if(e.guestExecution!==void 0)throw Error("Guest execution scope mismatch");return{}}let t=yn.safeParse(e.guestExecution);if(!t.success||e.userPermissionLevel!=="public"||e.isAnchor||!(e.signal instanceof AbortSignal))throw Error("Guest execution denied");return e.signal.throwIfAborted(),{readBudget:t.data.limits.retrieval,signal:e.signal,queryEmbedding:e.guestQueryEmbedding??(async()=>{throw Error("Guest query embedding unavailable")})}}var QB=0.5;function tC(e){let{entityService:t,logger:n}=e;return[wn("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. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. Search results include each matched entity's content. 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.",mI,async(o,i)=>{let a=Zs(i),s=ar(i.userPermissionLevel);return{success:!0,data:{results:(await t.search({query:o.query,options:{limit:o.limit??e.searchLimit,...o.scope.kind==="type"&&{types:[o.scope.entityType]},minScore:o.minScore??QB,...o.includeUngenerated!==void 0&&{includeUngenerated:o.includeUngenerated},visibilityScope:s,...a}})).map((l)=>({...l,entity:ep(l.entity)}))}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),wn("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.",gI,async(o,i)=>{let a=Zs(i);if(!a.readBudget&&!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let s=ar(i.userPermissionLevel),l=await Dr(t,o.entityType,o.id,n,void 0,s,a);if(!l.ok)return{success:!1,error:l.error};return{success:!0,data:{entity:ep(l.entity)}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),wn("system","list","List entities by a known entity type. Returns metadata only \u2014 use system_get for full content. Use system_search, not system_list, for broad or vague lookup requests. 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.",fI,async(o,i)=>{let a=Zs(i);if(!a.readBudget&&!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let l={visibilityScope:ar(i.userPermissionLevel)};if(o.status&&o.status!=="any")l.metadata={status:o.status};let u=(await t.listEntities({entityType:o.entityType,options:{limit:o.limit??20,filter:l,...a}})).map(({content:d,contentHash:m,...p})=>p);if(o.entityType==="post")u.sort((d,m)=>{let p=d.metadata.publishedAt,f=m.metadata.publishedAt,g=typeof p==="string"?Date.parse(p):0;return(typeof f==="string"?Date.parse(f):0)-g});return{success:!0,data:{entities:u,count:u.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function rC(e){let{entityService:t}=e;return[wn("system","insights",`Get aggregate content insights and analytics only. For a general overview of actual content, use system_list instead. Available types: ${e.insights.getTypes().join(", ")}.`,SI,async(n,o)=>{let i=ar(o.userPermissionLevel);return{success:!0,data:await e.insights.get(n.type,t,i)}},{visibility:"public",sideEffects:"none"})]}function nC(e){let{jobs:t}=e;return[Nr("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.",_I,async(n)=>{if(n.batchId){let a=await t.getBatchStatus(n.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${n.batchId}`};let s=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:n.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:s},currentOperation:a.currentOperation,errors:a.errors}}}let o=await t.getActiveJobs(n.jobTypes),i=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:i.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:i.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,errors:a.status.errors}))}}},{visibility:"public",sideEffects:"none"})]}function YB(e){let{entityCounts:t,daemons:n,endpoints:o,interactions:i,...a}=e;return a}function oC(e){return[wn("system","status","Get system status including model, version, interfaces, and tools",r.object({}),async()=>({success:!0,data:YB(await e.getAppInfo())}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function iC(e){return[...tC(e),...nC(e),...oC(e),...eC(e),...rC(e)]}function aC(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(`
|
|
181
181
|
`)}]})},{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 sC(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((o)=>({uri:`entity://${o}`,name:`${o} entities`})),complete:{type:async()=>t.getEntityTypes()},handler:async({type:n})=>{let o=t.getEntityTypes();if(!o.includes(n))throw Error(`Unknown entity type: ${n}. Available: ${o.join(", ")}`);let a=(await t.listEntities({entityType:n})).map((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.updated}));return{contents:[{uri:`entity://${n}`,mimeType:"application/json",text:JSON.stringify(a,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(n)=>{let o=t.getEntityTypes();return n?o.filter((i)=>i.startsWith(n)):o},id:async()=>[]},handler:async({type:n,id:o})=>{let i=await t.getEntity({entityType:n,id:o});if(!i)throw Error(`Entity not found: ${n}/${o}`);return{contents:[{uri:`entity://${n}/${o}`,mimeType:"text/markdown",text:i.content}]}}}]}function lC(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:n,type:o})=>({messages:[{role:"user",content:{type:"text",text:n?`Create a new ${o} about: ${n}`:`Create a new ${o}. 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:n,topic:o})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${n} about: ${o}`}}]})},{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:n,id:o})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${n} "${o}". 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:n,id:o})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${n} "${o}". 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:n})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${n}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function cC(e){let t=e.entityService.getEntityTypes(),n=t.map((o)=>`- ${o}: ${e.entityRegistry.getAdapter(o).purpose}`);return["## Entity CRUD","","Use these system tools for ALL entity operations:","","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.","",`- **system_create**: Create an entity from existing/concrete material. Requires confirmation before persisting; call system_create without \`confirmed\` to request that confirmation, and never pass \`confirmed: true\` on the initial user request. Use the typed \`visibility\` field instead of rewriting exact source text: omit it for public content, use \`shared\` for team/collaborator content, and use \`restricted\` for private/admin-only content. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three levels. If the user only says 'not public' without clarifying team/shared versus private/admin-only, ask which scope they mean. Required \`source\` union: \`{ kind: "text", content }\` stores exact/direct content; \`{ kind: "url", url }\` creates URL/domain-backed records such as links (preserve bare domains as bare domains); \`{ kind: "upload", upload, transform: "extract-markdown" }\` imports extractable upload bytes as a markdown note; \`{ kind: "upload", upload, transform: "preserve" }\` preserves raw uploaded bytes as their durable file entity; \`{ kind: "prior-response", messageId? }\` saves a previous assistant answer/summary by reference without copying or paraphrasing it. If a direct save request includes the content in the same message, that content is sufficient, even if it is a short sentence or fragment after a colon or embedded in the request phrase (for example, "Save this memo about the launch timeline"); call system_create instead of asking the user to paste it again. If the immediate context is an assistant summary/answer about an upload and the user asks to save it/that/this/summary, create a note with \`source.kind: "prior-response"\`; do this even when the prior answer says there was limited readable content. Do not ask whether they meant the summary or the file after you just summarized/answered about the upload: save the visible prior response as a note. Do not treat a bare upload receipt like "I got filename. What would you like me to do?" as a summary/answer; if the user then says "save it", preserve the latest uploaded file itself with upload \`preserve\` (image uploads as entityType image, PDFs/documents as their file entity type). Only use \`source.kind: "upload"\` when the runtime supplies an actual upload reference/attachment; if the message contains a pasted uploaded-file transcript with readable content (for example, \`User uploaded a file "name.md": ...\`), save the visible transcript content as \`source.kind: "text"\`. Only use upload \`preserve\` otherwise when they explicitly want to save the uploaded file/document itself. Use system_generate, not system_create, for AI generation, generated images, cover images, and source-derived artifacts. Available entity types: ${t.join(", ")}.`,'- **system_generate**: Generate a new durable entity or deterministic artifact. Requires confirmation before queueing generation; call system_generate without `confirmed` to request that confirmation, and never pass `confirmed: true` on the initial user request. When the user asks you to create, write, draft, or generate new durable content and has not supplied final exact content to store, call system_generate instead of drafting the content in chat or asking for separate prose approval first. An underspecified generation request still supplies a usable prompt: preserve the user\'s wording and call system_generate rather than stopping to ask what details to highlight. If generation depends on an existing source entity (for example, a newsletter from a blog post), resolve the source with read/search/list tools first unless the user gives an exact entity id in quotes, then call system_generate with `operation.kind: "prompt-from-source"` in the same turn when a clear source is found. If you identify the latest source entity, do not stop after saying you found it or can generate from it; call system_generate immediately. If no existing durable source entity is resolved, use `operation.kind: "prompt"` in the same turn, including after an optional search returns no source; never invent source IDs, use upload IDs/filenames as entity refs, use profile/brain-character as a generic source, or create placeholder source refs. For broad topical prompts like \'about AI\' or \'about continuous learning\', use `operation.kind: "prompt"`. If the user asks for the latest published/blog source, use system_list for that entity type (for blog posts, entityType post) to inspect publishedAt dates; do not rely on semantic search result order. Choose the newest matching candidate by publishedAt (not updated/created order) and proceed with system_generate rather than asking for separate prose approval; do not say \'if that is the one you mean\' when a newest dated candidate is visible. Do not say \'I can generate it if you want\' or \'I need to queue it first\'; calling system_generate without `confirmed` is the confirmation request. Required `operation` union: `{ kind: "prompt", entityType, prompt }` generates a new non-image durable entity from a broad prompt with no source; `{ kind: "prompt-from-source", entityType, source: { entityType, entityId }, prompt }` generates from an existing resolved entity, such as a newsletter from a blog post. `{ kind: "standalone-image", prompt }` generates an unattached image; `{ kind: "cover-image", target: { entityType, entityId }, prompt }` generates an image and attaches it to an existing canonical entity as `coverImageId`; `{ kind: "attachment", source: { entityType, entityId }, attachmentType }` renders a deterministic artifact from an existing entity attachment provider. For save/render/regenerate/replace requests for source-derived artifacts, call `system_generate` with `operation.kind: "attachment"` immediately; do not say you can queue it later. Use `replace: true` when the user says regenerate, replace, refresh, or update an existing artifact. For OG/social preview renders, use `attachmentType: "og-image"`; the provider derives the output image and updates `ogImageId`. For deck carousel PDFs use `attachmentType: "carousel"`; for printable post/project PDFs use `attachmentType: "printable"`. If the user asks to attach a generated artifact to another entity, generate the artifact first in the same turn; do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer`. Update the target only after the real artifact ID exists. To create an entity and a cover image, first create/generate only the entity, then after confirmation and after the real canonical entity ID is known call system_generate with operation.kind cover-image. When the user asks to create/regenerate a cover for an existing entity and search/get resolves a clear target, call system_generate with operation.kind cover-image in the same turn; do not stop after saying you found it. In a single initial request for \'a post with a cover image\', do not also call standalone-image; never guess a future target ID, and do not generate a standalone image as a substitute for a requested cover image.','- **system_update**: Modify an entity\'s fields or content. Use `fields` for title, status, coverImageId, ogImageId, and other frontmatter/metadata changes. To remove or clear a cover image, set `fields.coverImageId` to null, not an empty string. Use system_update for coverImageId when an existing image entity id is known; if the user says to set an existing image as a cover, update `coverImageId` even when `ogImageId` already points at that image. To generate a new cover image for an existing entity, use system_generate with operation.kind cover-image. Agent approval/archive is a status field update on `entityType: "agent"`. Cover images use `coverImageId`; OG/social previews use `ogImageId`; do not treat them as interchangeable. Requires confirmation before applying changes; call system_update without `confirmed` to request that confirmation, rather than asking for prose approval. For explicit publish requests, use the publishing tool if available instead of changing status with system_update; follow-up pronouns like \'publish it\' should target the entity just read or updated in the conversation.',"- **system_delete**: Admin-only entity removal. Requires confirmation before deleting. Never pass `confirmed: true` on the initial user request; call without `confirmed` so the confirmation flow can ask an administrator first. If system_delete is not available in the current tool surface, say deletion requires Admin access; do not imply a confirmation flow is available. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.","- **system_get**: Retrieve a specific entity by type and ID/slug/title.","- **system_list**: List entities by type with optional filters. For simple list/show-all/summary requests that name or browse a known type or synonym (for example essays/articles/blog posts => post), use system_list with that entity type instead of semantic search. For 'summarize my blog posts' or similar whole-type summaries, first call system_list for entityType post, then summarize those returned entities. For 'latest' requests, use system_list metadata dates such as publishedAt to choose the newest candidate.","- **system_search**: Semantic search across all entities. Search results include matched entity content; when relevant results already provide the complete evidence needed, answer from them instead of redundantly calling system_list or system_get for those same entities. 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 search results or memory; this includes analysis phrasing such as 'How do I discuss X in my writing?' even if prior turns searched related topics.","","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 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:",...n].join(`
|
|
182
|
-
`)}var Uo="system",XB=r.object({toolName:r.string(),args:r.unknown(),...dC.partial().shape});function Ks(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function pC(e,t,n,o){let i=iC(e);Ks(i,(d)=>t.registerTool(Uo,d),(d)=>d.name,"tool",o);let a=n.subscribe(uC.toolExecute(Uo),async(d)=>{let m=XB.safeParse(d.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:p,args:f,interfaceType:g,actor:h,conversationId:v,channelId:x,userPermissionLevel:S}=m.data,y=i.find((C)=>C.name===p);if(!y)return{success:!1,error:`System tool not found: ${p}`};let w={interfaceType:g??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(x)w.channelId=x;if(S)w.userPermissionLevel=S;return{success:!0,data:await y.handler(f,w)}});o.debug(`Registered ${i.length} system tools`);let s=aC(e);Ks(s,(d)=>t.registerResource(Uo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=sC(e);Ks(l,(d)=>t.registerResourceTemplate(Uo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=lC(e);Ks(c,(d)=>t.registerPrompt(Uo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=cC(e);try{t.registerInstructions(Uo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function hC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=pC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:mC(s,"system",!1),enqueueBatch:gC(n,"system"),registerHandler:fC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Qs(t.attachmentRegistry),logger:l,query:i,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:a,searchLimit:10,insights:o,permissionService:t.permissionService},t.mcpService,t.messageBus,l);t.disposables.push(c)}class lp{scope;closePromise=null;closed=!1;constructor(){this.scope=de.runSync(Xe.make())}buildLayer(e){this.assertOpen();let t=de.runSyncExit(Xr.buildWithScope(e,this.scope));if(tt.isFailure(t))throw or.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),de.runSync(Xe.addFinalizer(this.scope,de.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),de.runSync(Xe.addFinalizer(this.scope,de.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await jr(de.forkIn(e,this.scope))}close(e=tt.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=jr(Xe.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,de.runSync(Xe.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class aa{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;insightsRegistry;bootTime=Date.now();endpointRegistry=new Qd;interactionRegistry=new Yd;httpRouteRegistry=Ls.createFresh();jobs;static createFresh(e,t,n){return new aa(ma(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new lp,_C(this,()=>this.httpRouteRegistry.getSnapshot());let o=t?.logger??vr.getInstance(),i=zs.createFresh(o,this.config,n?.processRole);try{this.services=i.initializeServices(this.lifecycle,t),this.jobs=aI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=rI(),this.bootloader=new Zd(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Ip(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(cI(this.services.pluginManager))},registerSystemCapabilities:()=>hC({services:this.services,jobs:this.jobs,insights:this.insightsRegistry,query:(a,s)=>this.query(a,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(a,s)=>ga(this.services.entityService,a,s),appInfo:()=>this.getAppInfo(),identityInput:()=>{let a=this.getIdentity(),s=this.getProfile();return vC.parse({brainName:a.name,role:a.role,purpose:a.purpose,values:a.values,profileName:s.name,...s.description!==void 0?{profileDescription:s.description}:{},...s.organization!==void 0?{profileOrganization:s.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:bC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),dI(this.lifecycle,this.services)}catch(a){try{this.lifecycle.closeSync(tt.fail(a))}catch(s){o.error("Failed to roll back Shell service construction",s)}throw a}}getInsightsRegistry(){return this.insightsRegistry}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:$s.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(tt.fail(t))}catch(n){this.services.logger.error("Failed to clean up Shell after initialization failure",n)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[n,o]of Object.entries(e))this.registerTemplate(n,o,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){return this.requireInitialized("Shell content generation"),Cp(this.services,e)}async query(e,t){this.requireInitialized("Shell query");let n=await this.getAppInfo(),o={...t,appInfo:n,timestamp:new Date().toISOString()},{conversationHistory:i,...a}=o;return yC.parse(await this.generateContent({prompt:e,templateName:Yo.KNOWLEDGE_QUERY,...i&&{conversationHistory:i},data:a,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,n){this.requireInitialized("Shell generateObject");let{object:o}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,n);return{object:o}}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}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return Qs(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return SC(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:n})=>({name:n.name,description:n.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let n of t)try{this.services.mcpService.registerTool(e,n)}catch(o){this.services.logger.error(`Failed to register tool ${n.name} from ${e}:`,o)}}registerResources(e,t){for(let n of t)try{this.services.mcpService.registerResource(e,n)}catch(o){this.services.logger.error(`Failed to register resource ${n.name} from ${e}:`,o)}}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 n of this.services.templateRegistry.getNames())if(n.startsWith(`${e}:`))this.services.templateRegistry.unregister(n);let t=this.config.evalHandlerRegistry;if(t){for(let n of t.list())if(n.pluginId===e)t.unregister(e,n.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,n){this.services.daemonRegistry.register(e,t,n)}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,n){let o=n?`${n}:${e}`:`shell:${e}`;this.services.templateRegistry.register(o,t),this.services.logger.debug(`Registered template: ${o}`)}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}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}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,n){this.config.evalHandlerRegistry?.register(e,t,n)}async getAppInfo(){return vp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Sp(this.services)}}var wC={kind:"service",serviceId:"brain-cli"},cp=`${wC.kind}:${wC.serviceId}`;var e4=r.object({provider:r.enum(["hetzner","docker"]).default("hetzner"),serverSize:r.string().default("cx33"),location:r.string().default("fsn1"),domain:r.string().optional(),docker:r.object({enabled:r.boolean().default(!0),image:r.string().optional()}).prefault({}),ports:r.object({default:r.number().default(3333),preview:r.number().default(4321),production:r.number().default(8080)}).prefault({}),cdn:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),dns:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),paths:r.object({install:r.string().optional(),data:r.string().optional()}).prefault({})}),TC=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:r.string().optional(),aiApiKey:r.string().optional(),aiImageKey:r.string().optional(),aiModel:r.string().optional(),aiReasoningEffort:Xn.optional(),logLevel:Yn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(pa).default([]),spaces:r.array(r.string()).default([]),identity:xC.optional(),agentInstructions:r.array(r.string()).optional(),deployment:e4.prefault({})});async function OC(e,t){await xn({label:"entity",config:e,schema:{assets:CC,entities:IC,projectionDirtyInputs:kC,projectionWaves:RC,projectionIncidents:EC,projectionWaveInputs:AC,projectionWaveRules:PC,projectionRuleMemos:MC},migrationsFolder:Tn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:jC})}async function zC(e,t){await xn({label:"job-queue",config:e,schema:{jobQueue:NC,jobWorkerSessions:DC},migrationsFolder:Tn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function UC(e,t){await xn({label:"conversation",config:e,schema:{conversations:qC,messages:$C,summaryTracking:LC},migrationsFolder:Tn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function FC(e,t){await xn({label:"runtime-state",config:e,schema:{runtimeStateRecords:Ue},migrationsFolder:Tn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as up}from"fs/promises";import{isAbsolute as t4}from"path";function GC(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function BC(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!t4(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function JC(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let n=107;if(Buffer.byteLength(t)>n)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${n} bytes): ${t}`);return t}function WC(e=process.env){return kn(GC(e))}async function HC(e=process.env){let t=GC(e);try{await up(t.dataDir,{recursive:!0}),await up(t.cacheDir,{recursive:!0}),await up(t.distDir,{recursive:!0})}catch(n){let o=n instanceof Error&&n.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: ${Ae(n)}`;throw Error(o,{cause:n})}return kn(t)}class dp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>HC(),migrateEntities:OC,migrateJobQueue:zC,migrateConversations:UC,migrateRuntimeState:FC}}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 r4="NODE_ENV";function n4(){return process.env[r4]}function VC(){return n4()!=="production"}var o4="startup-check";function i4(e){let n={...TC.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function a4(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return s4(n),l4(e,n),c4(e,n,t),u4(e,n),d4(e,n),p4(e,n),m4(e,n),g4(e,n),f4(e,n),n}function s4(e){let t=WC();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??=JC(),e.gitBrokerCheckout??=BC()}function l4(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function c4(e,t,n){let o=n?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!o)return;t.ai={...t.ai,...o&&!t.ai?.apiKey&&{apiKey:o4},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function u4(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 d4(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===cp)?n:[{pattern:cp,level:"admin"},...n]}}function p4(e,t){if(e.spaces)t.spaces=e.spaces}function m4(e,t){if(e.identity)t.identity=e.identity}function g4(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function f4(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=VC()}class mp{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new mp(i4(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=vr.getInstance();await new dp(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,t){this.shell=aa.createFresh(a4(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-02vqvq05.js"),n=new t(this.config.cliConfig);e.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t?.processRole)}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 n={debug:qt.DEBUG,info:qt.INFO,warn:qt.WARN,error:qt.ERROR}[this.config.logLevel??"info"]??qt.INFO,o=vr.createFresh({level:n,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)vr.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(i){o.error(`\u274C Failed to start ${this.config.name}:`,i),process.exit(1)}}static async run(e,t,n){await mp.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=de.runSync(Xe.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},o=pp(["SIGINT"],t),i=pp(["SIGTERM"],n);de.runSync(Xe.addFinalizer(e,de.sync(()=>{i(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=vr.getInstance();t.info(`
|
|
182
|
+
`)}var Uo="system",XB=r.object({toolName:r.string(),args:r.unknown(),...dC.partial().shape});function Ks(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function pC(e,t,n,o){let i=iC(e);Ks(i,(d)=>t.registerTool(Uo,d),(d)=>d.name,"tool",o);let a=n.subscribe(uC.toolExecute(Uo),async(d)=>{let m=XB.safeParse(d.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:p,args:f,interfaceType:g,actor:h,conversationId:v,channelId:x,userPermissionLevel:S}=m.data,y=i.find((C)=>C.name===p);if(!y)return{success:!1,error:`System tool not found: ${p}`};let w={interfaceType:g??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(x)w.channelId=x;if(S)w.userPermissionLevel=S;return{success:!0,data:await y.handler(f,w)}});o.debug(`Registered ${i.length} system tools`);let s=aC(e);Ks(s,(d)=>t.registerResource(Uo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=sC(e);Ks(l,(d)=>t.registerResourceTemplate(Uo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=lC(e);Ks(c,(d)=>t.registerPrompt(Uo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=cC(e);try{t.registerInstructions(Uo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function hC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=pC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:mC(s,"system",!1),enqueueBatch:gC(n,"system"),registerHandler:fC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Qs(t.attachmentRegistry),logger:l,query:i,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:a,searchLimit:10,insights:o,permissionService:t.permissionService},t.mcpService,t.messageBus,l);t.disposables.push(c)}class lp{scope;closePromise=null;closed=!1;constructor(){this.scope=de.runSync(Xe.make())}buildLayer(e){this.assertOpen();let t=de.runSyncExit(Xr.buildWithScope(e,this.scope));if(tt.isFailure(t))throw or.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),de.runSync(Xe.addFinalizer(this.scope,de.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),de.runSync(Xe.addFinalizer(this.scope,de.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await jr(de.forkIn(e,this.scope))}close(e=tt.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=jr(Xe.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,de.runSync(Xe.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class aa{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;insightsRegistry;bootTime=Date.now();endpointRegistry=new Qd;interactionRegistry=new Yd;httpRouteRegistry=Ls.createFresh();jobs;static createFresh(e,t,n){return new aa(ma(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new lp,_C(this,()=>this.httpRouteRegistry.getSnapshot());let o=t?.logger??vr.getInstance(),i=zs.createFresh(o,this.config,n?.processRole);try{this.services=i.initializeServices(this.lifecycle,t),this.jobs=aI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=rI(),this.bootloader=new Zd(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Ip(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(cI(this.services.pluginManager))},registerSystemCapabilities:()=>hC({services:this.services,jobs:this.jobs,insights:this.insightsRegistry,query:(a,s)=>this.query(a,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(a,s)=>ga(this.services.entityService,a,s),appInfo:()=>this.getAppInfo(),identityInput:()=>{let a=this.getIdentity(),s=this.getProfile();return vC.parse({brainName:a.name,role:a.role,purpose:a.purpose,values:a.values,profileName:s.name,...s.description!==void 0?{profileDescription:s.description}:{},...s.organization!==void 0?{profileOrganization:s.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:bC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),dI(this.lifecycle,this.services)}catch(a){try{this.lifecycle.closeSync(tt.fail(a))}catch(s){o.error("Failed to roll back Shell service construction",s)}throw a}}getInsightsRegistry(){return this.insightsRegistry}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:$s.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(tt.fail(t))}catch(n){this.services.logger.error("Failed to clean up Shell after initialization failure",n)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[n,o]of Object.entries(e))this.registerTemplate(n,o,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){return this.requireInitialized("Shell content generation"),Cp(this.services,e)}async query(e,t){this.requireInitialized("Shell query");let n=await this.getAppInfo(),o={...t,appInfo:n,timestamp:new Date().toISOString()},{conversationHistory:i,...a}=o;return yC.parse(await this.generateContent({prompt:e,templateName:Yo.KNOWLEDGE_QUERY,...i&&{conversationHistory:i},data:a,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,n){this.requireInitialized("Shell generateObject");let{object:o}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,n);return{object:o}}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}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return Qs(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return SC(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:n})=>({name:n.name,description:n.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let n of t)try{this.services.mcpService.registerTool(e,n)}catch(o){this.services.logger.error(`Failed to register tool ${n.name} from ${e}:`,o)}}registerResources(e,t){for(let n of t)try{this.services.mcpService.registerResource(e,n)}catch(o){this.services.logger.error(`Failed to register resource ${n.name} from ${e}:`,o)}}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 n of this.services.templateRegistry.getNames())if(n.startsWith(`${e}:`))this.services.templateRegistry.unregister(n);let t=this.config.evalHandlerRegistry;if(t){for(let n of t.list())if(n.pluginId===e)t.unregister(e,n.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,n){this.services.daemonRegistry.register(e,t,n)}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,n){let o=n?`${n}:${e}`:`shell:${e}`;this.services.templateRegistry.register(o,t),this.services.logger.debug(`Registered template: ${o}`)}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}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}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,n){this.config.evalHandlerRegistry?.register(e,t,n)}async getAppInfo(){return vp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Sp(this.services)}}var wC={kind:"service",serviceId:"brain-cli"},cp=`${wC.kind}:${wC.serviceId}`;var e4=r.object({provider:r.enum(["hetzner","docker"]).default("hetzner"),serverSize:r.string().default("cx33"),location:r.string().default("fsn1"),domain:r.string().optional(),docker:r.object({enabled:r.boolean().default(!0),image:r.string().optional()}).prefault({}),ports:r.object({default:r.number().default(3333),preview:r.number().default(4321),production:r.number().default(8080)}).prefault({}),cdn:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),dns:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),paths:r.object({install:r.string().optional(),data:r.string().optional()}).prefault({})}),TC=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:r.string().optional(),aiApiKey:r.string().optional(),aiImageKey:r.string().optional(),aiModel:r.string().optional(),aiReasoningEffort:Xn.optional(),logLevel:Yn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(pa).default([]),spaces:r.array(r.string()).default([]),identity:xC.optional(),agentInstructions:r.array(r.string()).optional(),deployment:e4.prefault({})});async function OC(e,t){await xn({label:"entity",config:e,schema:{assets:CC,entities:IC,projectionDirtyInputs:kC,projectionWaves:RC,projectionIncidents:EC,projectionWaveInputs:AC,projectionWaveRules:PC,projectionRuleMemos:MC},migrationsFolder:Tn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:jC})}async function zC(e,t){await xn({label:"job-queue",config:e,schema:{jobQueue:NC,jobWorkerSessions:DC},migrationsFolder:Tn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function UC(e,t){await xn({label:"conversation",config:e,schema:{conversations:qC,messages:$C,summaryTracking:LC},migrationsFolder:Tn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function FC(e,t){await xn({label:"runtime-state",config:e,schema:{runtimeStateRecords:Ue},migrationsFolder:Tn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as up}from"fs/promises";import{isAbsolute as t4}from"path";function GC(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function BC(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!t4(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function JC(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let n=107;if(Buffer.byteLength(t)>n)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${n} bytes): ${t}`);return t}function WC(e=process.env){return kn(GC(e))}async function HC(e=process.env){let t=GC(e);try{await up(t.dataDir,{recursive:!0}),await up(t.cacheDir,{recursive:!0}),await up(t.distDir,{recursive:!0})}catch(n){let o=n instanceof Error&&n.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: ${Ae(n)}`;throw Error(o,{cause:n})}return kn(t)}class dp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>HC(),migrateEntities:OC,migrateJobQueue:zC,migrateConversations:UC,migrateRuntimeState:FC}}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 r4="NODE_ENV";function n4(){return process.env[r4]}function VC(){return n4()!=="production"}var o4="startup-check";function i4(e){let n={...TC.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function a4(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return s4(n),l4(e,n),c4(e,n,t),u4(e,n),d4(e,n),p4(e,n),m4(e,n),g4(e,n),f4(e,n),n}function s4(e){let t=WC();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??=JC(),e.gitBrokerCheckout??=BC()}function l4(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function c4(e,t,n){let o=n?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!o)return;t.ai={...t.ai,...o&&!t.ai?.apiKey&&{apiKey:o4},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function u4(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 d4(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===cp)?n:[{pattern:cp,level:"admin"},...n]}}function p4(e,t){if(e.spaces)t.spaces=e.spaces}function m4(e,t){if(e.identity)t.identity=e.identity}function g4(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function f4(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=VC()}class mp{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new mp(i4(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=vr.getInstance();await new dp(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,t){this.shell=aa.createFresh(a4(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-e0rx633y.js"),n=new t(this.config.cliConfig);e.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t?.processRole)}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 n={debug:qt.DEBUG,info:qt.INFO,warn:qt.WARN,error:qt.ERROR}[this.config.logLevel??"info"]??qt.INFO,o=vr.createFresh({level:n,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)vr.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(i){o.error(`\u274C Failed to start ${this.config.name}:`,i),process.exit(1)}}static async run(e,t,n){await mp.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=de.runSync(Xe.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},o=pp(["SIGINT"],t),i=pp(["SIGTERM"],n);de.runSync(Xe.addFinalizer(e,de.sync(()=>{i(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=vr.getInstance();t.info(`
|
|
183
183
|
Received ${e}, shutting down gracefully...`);let n=de.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(de.match({onFailure:(o)=>{t.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=de.runFork(n)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await de.runPromise(Xe.close(e,tt.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
|
|
184
184
|
export{Yn as S,Xn as T,Jj as U,n6 as V,ce as W,oa as X,DI as Y,$I as Z,Ws as _,PB as $,rp as aa,jB as ba,Hs as ca,OB as da,yee as ea,HI as fa,zB as ga,op as ha,ip as ia,qB as ja,LB as ka,o4 as la,i4 as ma,a4 as na,mp as oa};
|
|
185
185
|
|
|
186
186
|
//# debugId=FE56983AFBACC99D64756E2164756E21
|
|
187
|
-
//# sourceMappingURL=index-
|
|
187
|
+
//# sourceMappingURL=index-zghffskf.js.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{I as a,J as b}from"./index-kt2v9nw1.js";import"./index-aft95ek4.js";import"./index-3rzkj0kw.js";import"./index-3w748142.js";import"./index-18h53jey.js";import"./index-j1kv20z9.js";export{a as linkedinPostSchema,b as linkedinTemplate};
|
|
3
|
+
|
|
4
|
+
//# debugId=4DB900F63898B70564756E2164756E21
|
|
5
|
+
//# sourceMappingURL=linkedin-template-mra3dywt.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{D as g}from"./index-058stchf.js";import{F as n,G as l}from"./index-
|
|
2
|
+
import{D as g}from"./index-058stchf.js";import{F as n,G as l}from"./index-03cfb3s4.js";import{ge as i}from"./index-aft95ek4.js";import"./index-3rzkj0kw.js";import"./index-3w748142.js";import{Yh as t}from"./index-18h53jey.js";import"./index-j1kv20z9.js";var S=t.object({siteUrl:t.url(),title:t.string(),description:t.string(),language:t.string().optional(),copyright:t.string().optional()});class d{logger;id="blog:rss";name="Blog RSS Feed DataSource";description="Generates RSS 2.0 feed XML from published blog posts";constructor(r){this.logger=r,this.logger.debug("RSSDataSource initialized")}async fetch(r,c,p){let e=S.parse(r),a=(await p.entityService.listEntities({entityType:"post",options:{limit:1000}},l)).filter((o)=>o.metadata.status==="published"&&o.metadata.publishedAt).map((o)=>{let s=i(o.content,n);return{...o,frontmatter:s.metadata,body:s.content}});this.logger.debug(`Generating RSS feed with ${a.length} posts`);let m={title:e.title,description:e.description,link:e.siteUrl,language:e.language??"en-us",...e.copyright&&{copyright:e.copyright}},u={xml:g(a,m)};return c.parse(u)}}export{d as RSSDataSource};
|
|
3
3
|
|
|
4
4
|
//# debugId=0E3D0EE8F0347FE264756E2164756E21
|
|
5
|
-
//# sourceMappingURL=rss-datasource-
|
|
5
|
+
//# sourceMappingURL=rss-datasource-meq425kx.js.map
|
package/dist/entities.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Lf as n,Mf as i,Nf as e}from"./chunks/index-
|
|
2
|
+
import{Lf as n,Mf as i,Nf as e}from"./chunks/index-aft95ek4.js";import"./chunks/index-3rzkj0kw.js";import"./chunks/index-3w748142.js";import{Yh as t}from"./chunks/index-18h53jey.js";import"./chunks/index-j1kv20z9.js";export{n as defineEntity,e as defineEntityPackage,i as defineProjection,t as z};
|
|
3
3
|
|
|
4
4
|
//# debugId=3A1FF81CECBBE40964756E2164756E21
|
|
5
5
|
//# sourceMappingURL=entities.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{M as d,N as t}from"./chunks/index-
|
|
2
|
+
import{M as d,N as t}from"./chunks/index-pkcefcbr.js";import"./chunks/index-zghffskf.js";import"./chunks/index-cmhbf9f7.js";import"./chunks/index-48ksf4j5.js";import{Jf as a}from"./chunks/index-aft95ek4.js";import"./chunks/index-3rzkj0kw.js";import"./chunks/index-3w748142.js";import"./chunks/index-18h53jey.js";import"./chunks/index-j1kv20z9.js";function s(e,i){let o=new Set,n=new Set;for(let r of e){if(!t(r))throw Error(`${i} contains a value that was not returned by use()`);if(o.has(r.definition))throw Error(`${i} contains duplicate plugin definition "${r.definition.id}"; include each configured definition only once`);if(n.has(r.definition.id))throw Error(`${i} contains duplicate local plugin id "${r.definition.id}"; give each package definition a unique local id before composing it`);o.add(r.definition),n.add(r.definition.id)}}function l(e){a(e.id,"Bundle id"),s(e.members,`Bundle "${e.id}"`);for(let i of e.config??[])if(!t(i.member))throw Error(`Bundle "${e.id}" config contains a value that was not returned by use()`);for(let i of e.permissions??[])if(!t(i.member))throw Error(`Bundle "${e.id}" permissions contains a value that was not returned by use()`);for(let i of e.evalDisable??[])if(!t(i))throw Error(`Bundle "${e.id}" evalDisable contains a value that was not returned by use()`);return Object.freeze({...e,members:Object.freeze([...e.members]),...e.config?{config:Object.freeze([...e.config])}:{},...e.permissions?{permissions:Object.freeze([...e.permissions])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}function u(e){if(!e.name.trim())throw Error("Brain name must not be empty");if(e.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");s(e.plugins,`Brain "${e.name}"`);let i=new Set(e.plugins),o=new Set;for(let n of e.bundles??[]){if(o.has(n.id))throw Error(`Brain "${e.name}" has duplicate bundle "${n.id}"`);o.add(n.id);for(let r of n.members)if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" references a plugin outside its catalog`);for(let r of n.config??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" config references a plugin outside its catalog`);for(let r of n.permissions??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" permissions reference a plugin outside its catalog`);for(let r of n.evalDisable??[])if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" evalDisable references a plugin outside its catalog`)}for(let n of e.evalDisable??[])if(!i.has(n))throw Error(`Brain "${e.name}" evalDisable references a plugin outside its catalog`);return Object.freeze({...e,plugins:Object.freeze([...e.plugins]),...e.bundles?{bundles:Object.freeze([...e.bundles])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}export{u as defineBrain,l as defineBundle,d as use};
|
|
3
3
|
|
|
4
4
|
//# debugId=A5E1772512D3D25C64756E2164756E21
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/dist/interfaces.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Yf as n,lg as i,mg as o,ng as r,og as s,pg as f}from"./chunks/index-
|
|
2
|
+
import{Yf as n,lg as i,mg as o,ng as r,og as s,pg as f}from"./chunks/index-aft95ek4.js";import"./chunks/index-3rzkj0kw.js";import"./chunks/index-3w748142.js";import{Fj as t,Yh as e}from"./chunks/index-18h53jey.js";import"./chunks/index-j1kv20z9.js";export{t as UserPermissionLevelSchema,n as defineAccountSettings,r as defineDaemon,s as defineInterface,f as defineMessageInterface,o as defineRoute,i as protocol,e as z};
|
|
3
3
|
|
|
4
4
|
//# debugId=3E9721711B1236A664756E2164756E21
|
|
5
5
|
//# sourceMappingURL=interfaces.js.map
|