@rizom/brain 0.2.0-alpha.92 → 0.2.0-alpha.93
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 +47 -35
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/site.js +4 -4
- package/dist/site.js.map +1 -1
- package/package.json +1 -1
package/dist/brain.js
CHANGED
|
@@ -511,7 +511,7 @@ ${Z}`,args:{...$,...W,id:X.id,confirmed:!0,contentHash:X.contentHash}}},{visibil
|
|
|
511
511
|
hash text NOT NULL,
|
|
512
512
|
created_at numeric
|
|
513
513
|
)
|
|
514
|
-
`;await A.session.run($);let D=(await A.values(SA`SELECT id, hash, created_at FROM ${SA.identifier(w)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,Y=[];for(let X of B)if(!D||Number(D[2])<X.folderMillis){for(let W of X.sql)Y.push(A.run(SA.raw(W)));Y.push(A.run(SA`INSERT INTO ${SA.identifier(w)} ("hash", "created_at") VALUES(${X.hash}, ${X.folderMillis})`))}await A.session.migrate(Y)}var Vo=l(()=>{L40();u5()});async function E40(A,Q){let B=Q?.child("entity-migrate")??W2.getInstance().child("entity-migrate"),{db:w,client:$,url:I}=od(A);B.debug("Running entity database migrations...");try{await sd($,I);let Y=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await cO(w,{migrationsFolder:Y}),await ad($),B.debug("Entity database migrations completed successfully")}catch(D){throw B.error("Entity database migration failed:",D),D}finally{$.close()}}var V40=l(()=>{Vo();N4A();fA()});async function M40(A,Q){let B=Q?.child("job-queue-migrate")??W2.getInstance().child("job-queue-migrate"),{db:w,client:$,url:I}=dd(A);B.debug("Running job queue migrations...");try{await rd($,I);let Y=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await cO(w,{migrationsFolder:Y}),B.debug("Job queue migrations completed successfully")}catch(D){throw B.error("Job queue migration failed:",D),D}finally{$.close()}}var C40=l(()=>{Vo();X4A();fA()});async function O40(A,Q){let B=Q?.child("conversation-migrate")??W2.getInstance().child("conversation-migrate"),{db:w,client:$,url:I}=Yr(A);B.debug("Running conversation database migrations...");try{if(I.startsWith("file:"))await $.execute("PRAGMA journal_mode = WAL");let Y=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await cO(w,{migrationsFolder:Y}),B.debug("Conversation database migrations completed successfully")}catch(D){throw B.error("Conversation database migration failed:",D),D}finally{$.close()}}var R40=l(()=>{Vo();QIA();fA()});class sy{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:Lx,migrateEntities:E40,migrateJobQueue:M40,migrateConversations:O40}}async runAllMigrations(A){this.logger.debug("Running database migrations...");let Q=await this.migrations.getStandardConfigWithDirectories();if(A?.database)Q.database.url=A.database;if(A?.jobQueueDatabase)Q.jobQueueDatabase.url=A.jobQueueDatabase;if(A?.conversationDatabase)Q.conversationDatabase.url=A.conversationDatabase;await this.migrateEntityDatabase(Q),await this.migrateJobQueueDatabase(Q),await this.migrateConversationDatabase(Q),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(A){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:A.database.url,...A.database.authToken&&{authToken:A.database.authToken}},this.logger)}async migrateJobQueueDatabase(A){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:A.jobQueueDatabase.url,...A.jobQueueDatabase.authToken&&{authToken:A.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(A){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:A.conversationDatabase.url,...A.conversationDatabase.authToken&&{authToken:A.conversationDatabase.authToken}},this.logger)}}var ZGA=l(()=>{Lo();V40();C40();R40()});function Hs1(){return process.env[Ws1]}function b40(){return Hs1()!=="production"}var Ws1="NODE_ENV";var Mo;var zGA=l(()=>{fA();Mo=f.object({theme:f.object({primaryColor:f.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:f.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})})});var j40;var P40=l(()=>{j40={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.92",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{dev:"tsc --watch",typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/plugins":"workspace:*",chalk:"^5.4.1",ink:"^6.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^12.0.0",react:"^19.2.6"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/react":"^19.0.3",typescript:"^5.3.3"}}});var n2=v((Js1,Co)=>{(function(){function A(wA,TA){Object.defineProperty(w.prototype,wA,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",TA[0],TA[1])}})}function Q(wA){if(wA===null||typeof wA!=="object")return null;return wA=lA&&wA[lA]||wA["@@iterator"],typeof wA==="function"?wA:null}function B(wA,TA){wA=(wA=wA.constructor)&&(wA.displayName||wA.name)||"ReactClass";var bA=wA+"."+TA;FA[bA]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",TA,wA),FA[bA]=!0)}function w(wA,TA,bA){this.props=wA,this.context=TA,this.refs=rA,this.updater=bA||CA}function $(){}function I(wA,TA,bA){this.props=wA,this.context=TA,this.refs=rA,this.updater=bA||CA}function D(){}function Y(wA){return""+wA}function X(wA){try{Y(wA);var TA=!1}catch(G0){TA=!0}if(TA){TA=console;var bA=TA.error,mA=typeof Symbol==="function"&&Symbol.toStringTag&&wA[Symbol.toStringTag]||wA.constructor.name||"Object";return bA.call(TA,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",mA),Y(wA)}}function W(wA){if(wA==null)return null;if(typeof wA==="function")return wA.$$typeof===W0?null:wA.displayName||wA.name||null;if(typeof wA==="string")return wA;switch(wA){case AA:return"Fragment";case UA:return"Profiler";case o:return"StrictMode";case K0:return"Suspense";case KA:return"SuspenseList";case NA:return"Activity"}if(typeof wA==="object")switch(typeof wA.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),wA.$$typeof){case u:return"Portal";case IA:return wA.displayName||"Context";case LA:return(wA._context.displayName||"Context")+".Consumer";case B0:var TA=wA.render;return wA=wA.displayName,wA||(wA=TA.displayName||TA.name||"",wA=wA!==""?"ForwardRef("+wA+")":"ForwardRef"),wA;case Z0:return TA=wA.displayName||null,TA!==null?TA:W(wA.type)||"Memo";case I0:TA=wA._payload,wA=wA._init;try{return W(wA(TA))}catch(bA){}}return null}function U(wA){if(wA===AA)return"<>";if(typeof wA==="object"&&wA!==null&&wA.$$typeof===I0)return"<...>";try{var TA=W(wA);return TA?"<"+TA+">":"<...>"}catch(bA){return"<...>"}}function K(){var wA=w0.A;return wA===null?null:wA.getOwner()}function F(){return Error("react-stack-top-frame")}function Z(wA){if(RA.call(wA,"key")){var TA=Object.getOwnPropertyDescriptor(wA,"key").get;if(TA&&TA.isReactWarning)return!1}return wA.key!==void 0}function q(wA,TA){function bA(){$A||($A=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",TA))}bA.isReactWarning=!0,Object.defineProperty(wA,"key",{get:bA,configurable:!0})}function E(){var wA=W(this.type);return e0[wA]||(e0[wA]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),wA=this.props.ref,wA!==void 0?wA:null}function L(wA,TA,bA,mA,G0,M0){var aA=bA.ref;return wA={$$typeof:i,type:wA,key:TA,props:bA,_owner:mA},(aA!==void 0?aA:null)!==null?Object.defineProperty(wA,"ref",{enumerable:!1,get:E}):Object.defineProperty(wA,"ref",{enumerable:!1,value:null}),wA._store={},Object.defineProperty(wA._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(wA,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(wA,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:G0}),Object.defineProperty(wA,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:M0}),Object.freeze&&(Object.freeze(wA.props),Object.freeze(wA)),wA}function R(wA,TA){return TA=L(wA.type,TA,wA.props,wA._owner,wA._debugStack,wA._debugTask),wA._store&&(TA._store.validated=wA._store.validated),TA}function _(wA){O(wA)?wA._store&&(wA._store.validated=1):typeof wA==="object"&&wA!==null&&wA.$$typeof===I0&&(wA._payload.status==="fulfilled"?O(wA._payload.value)&&wA._payload.value._store&&(wA._payload.value._store.validated=1):wA._store&&(wA._store.validated=1))}function O(wA){return typeof wA==="object"&&wA!==null&&wA.$$typeof===i}function r(wA){var TA={"=":"=0",":":"=2"};return"$"+wA.replace(/[=:]/g,function(bA){return TA[bA]})}function n(wA,TA){return typeof wA==="object"&&wA!==null&&wA.key!=null?(X(wA.key),r(""+wA.key)):TA.toString(36)}function S(wA){switch(wA.status){case"fulfilled":return wA.value;case"rejected":throw wA.reason;default:switch(typeof wA.status==="string"?wA.then(D,D):(wA.status="pending",wA.then(function(TA){wA.status==="pending"&&(wA.status="fulfilled",wA.value=TA)},function(TA){wA.status==="pending"&&(wA.status="rejected",wA.reason=TA)})),wA.status){case"fulfilled":return wA.value;case"rejected":throw wA.reason}}throw wA}function x(wA,TA,bA,mA,G0){var M0=typeof wA;if(M0==="undefined"||M0==="boolean")wA=null;var aA=!1;if(wA===null)aA=!0;else switch(M0){case"bigint":case"string":case"number":aA=!0;break;case"object":switch(wA.$$typeof){case i:case u:aA=!0;break;case I0:return aA=wA._init,x(aA(wA._payload),TA,bA,mA,G0)}}if(aA){aA=wA,G0=G0(aA);var a0=mA===""?"."+n(aA,0):mA;return k0(G0)?(bA="",a0!=null&&(bA=a0.replace(_A,"$&/")+"/"),x(G0,TA,bA,"",function(g1){return g1})):G0!=null&&(O(G0)&&(G0.key!=null&&(aA&&aA.key===G0.key||X(G0.key)),bA=R(G0,bA+(G0.key==null||aA&&aA.key===G0.key?"":(""+G0.key).replace(_A,"$&/")+"/")+a0),mA!==""&&aA!=null&&O(aA)&&aA.key==null&&aA._store&&!aA._store.validated&&(bA._store.validated=2),G0=bA),TA.push(G0)),1}if(aA=0,a0=mA===""?".":mA+":",k0(wA))for(var g0=0;g0<wA.length;g0++)mA=wA[g0],M0=a0+n(mA,g0),aA+=x(mA,TA,bA,M0,G0);else if(g0=Q(wA),typeof g0==="function")for(g0===wA.entries&&(cA||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),cA=!0),wA=g0.call(wA),g0=0;!(mA=wA.next()).done;)mA=mA.value,M0=a0+n(mA,g0++),aA+=x(mA,TA,bA,M0,G0);else if(M0==="object"){if(typeof wA.then==="function")return x(S(wA),TA,bA,mA,G0);throw TA=String(wA),Error("Objects are not valid as a React child (found: "+(TA==="[object Object]"?"object with keys {"+Object.keys(wA).join(", ")+"}":TA)+"). If you meant to render a collection of children, use an array instead.")}return aA}function T(wA,TA,bA){if(wA==null)return wA;var mA=[],G0=0;return x(wA,mA,"","",function(M0){return TA.call(bA,M0,G0++)}),mA}function g(wA){if(wA._status===-1){var TA=wA._ioInfo;TA!=null&&(TA.start=TA.end=performance.now()),TA=wA._result;var bA=TA();if(bA.then(function(G0){if(wA._status===0||wA._status===-1){wA._status=1,wA._result=G0;var M0=wA._ioInfo;M0!=null&&(M0.end=performance.now()),bA.status===void 0&&(bA.status="fulfilled",bA.value=G0)}},function(G0){if(wA._status===0||wA._status===-1){wA._status=2,wA._result=G0;var M0=wA._ioInfo;M0!=null&&(M0.end=performance.now()),bA.status===void 0&&(bA.status="rejected",bA.reason=G0)}}),TA=wA._ioInfo,TA!=null){TA.value=bA;var mA=bA.displayName;typeof mA==="string"&&(TA.name=mA)}wA._status===-1&&(wA._status=0,wA._result=bA)}if(wA._status===1)return TA=wA._result,TA===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
514
|
+
`;await A.session.run($);let D=(await A.values(SA`SELECT id, hash, created_at FROM ${SA.identifier(w)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,Y=[];for(let X of B)if(!D||Number(D[2])<X.folderMillis){for(let W of X.sql)Y.push(A.run(SA.raw(W)));Y.push(A.run(SA`INSERT INTO ${SA.identifier(w)} ("hash", "created_at") VALUES(${X.hash}, ${X.folderMillis})`))}await A.session.migrate(Y)}var Vo=l(()=>{L40();u5()});async function E40(A,Q){let B=Q?.child("entity-migrate")??W2.getInstance().child("entity-migrate"),{db:w,client:$,url:I}=od(A);B.debug("Running entity database migrations...");try{await sd($,I);let Y=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await cO(w,{migrationsFolder:Y}),await ad($),B.debug("Entity database migrations completed successfully")}catch(D){throw B.error("Entity database migration failed:",D),D}finally{$.close()}}var V40=l(()=>{Vo();N4A();fA()});async function M40(A,Q){let B=Q?.child("job-queue-migrate")??W2.getInstance().child("job-queue-migrate"),{db:w,client:$,url:I}=dd(A);B.debug("Running job queue migrations...");try{await rd($,I);let Y=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await cO(w,{migrationsFolder:Y}),B.debug("Job queue migrations completed successfully")}catch(D){throw B.error("Job queue migration failed:",D),D}finally{$.close()}}var C40=l(()=>{Vo();X4A();fA()});async function O40(A,Q){let B=Q?.child("conversation-migrate")??W2.getInstance().child("conversation-migrate"),{db:w,client:$,url:I}=Yr(A);B.debug("Running conversation database migrations...");try{if(I.startsWith("file:"))await $.execute("PRAGMA journal_mode = WAL");let Y=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await cO(w,{migrationsFolder:Y}),B.debug("Conversation database migrations completed successfully")}catch(D){throw B.error("Conversation database migration failed:",D),D}finally{$.close()}}var R40=l(()=>{Vo();QIA();fA()});class sy{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:Lx,migrateEntities:E40,migrateJobQueue:M40,migrateConversations:O40}}async runAllMigrations(A){this.logger.debug("Running database migrations...");let Q=await this.migrations.getStandardConfigWithDirectories();if(A?.database)Q.database.url=A.database;if(A?.jobQueueDatabase)Q.jobQueueDatabase.url=A.jobQueueDatabase;if(A?.conversationDatabase)Q.conversationDatabase.url=A.conversationDatabase;await this.migrateEntityDatabase(Q),await this.migrateJobQueueDatabase(Q),await this.migrateConversationDatabase(Q),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(A){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:A.database.url,...A.database.authToken&&{authToken:A.database.authToken}},this.logger)}async migrateJobQueueDatabase(A){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:A.jobQueueDatabase.url,...A.jobQueueDatabase.authToken&&{authToken:A.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(A){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:A.conversationDatabase.url,...A.conversationDatabase.authToken&&{authToken:A.conversationDatabase.authToken}},this.logger)}}var ZGA=l(()=>{Lo();V40();C40();R40()});function Hs1(){return process.env[Ws1]}function b40(){return Hs1()!=="production"}var Ws1="NODE_ENV";var Mo;var zGA=l(()=>{fA();Mo=f.object({theme:f.object({primaryColor:f.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:f.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})})});var j40;var P40=l(()=>{j40={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.93",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{dev:"tsc --watch",typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/plugins":"workspace:*",chalk:"^5.4.1",ink:"^6.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^12.0.0",react:"^19.2.6"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/react":"^19.0.3",typescript:"^5.3.3"}}});var n2=v((Js1,Co)=>{(function(){function A(wA,TA){Object.defineProperty(w.prototype,wA,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",TA[0],TA[1])}})}function Q(wA){if(wA===null||typeof wA!=="object")return null;return wA=lA&&wA[lA]||wA["@@iterator"],typeof wA==="function"?wA:null}function B(wA,TA){wA=(wA=wA.constructor)&&(wA.displayName||wA.name)||"ReactClass";var bA=wA+"."+TA;FA[bA]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",TA,wA),FA[bA]=!0)}function w(wA,TA,bA){this.props=wA,this.context=TA,this.refs=rA,this.updater=bA||CA}function $(){}function I(wA,TA,bA){this.props=wA,this.context=TA,this.refs=rA,this.updater=bA||CA}function D(){}function Y(wA){return""+wA}function X(wA){try{Y(wA);var TA=!1}catch(G0){TA=!0}if(TA){TA=console;var bA=TA.error,mA=typeof Symbol==="function"&&Symbol.toStringTag&&wA[Symbol.toStringTag]||wA.constructor.name||"Object";return bA.call(TA,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",mA),Y(wA)}}function W(wA){if(wA==null)return null;if(typeof wA==="function")return wA.$$typeof===W0?null:wA.displayName||wA.name||null;if(typeof wA==="string")return wA;switch(wA){case AA:return"Fragment";case UA:return"Profiler";case o:return"StrictMode";case K0:return"Suspense";case KA:return"SuspenseList";case NA:return"Activity"}if(typeof wA==="object")switch(typeof wA.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),wA.$$typeof){case u:return"Portal";case IA:return wA.displayName||"Context";case LA:return(wA._context.displayName||"Context")+".Consumer";case B0:var TA=wA.render;return wA=wA.displayName,wA||(wA=TA.displayName||TA.name||"",wA=wA!==""?"ForwardRef("+wA+")":"ForwardRef"),wA;case Z0:return TA=wA.displayName||null,TA!==null?TA:W(wA.type)||"Memo";case I0:TA=wA._payload,wA=wA._init;try{return W(wA(TA))}catch(bA){}}return null}function U(wA){if(wA===AA)return"<>";if(typeof wA==="object"&&wA!==null&&wA.$$typeof===I0)return"<...>";try{var TA=W(wA);return TA?"<"+TA+">":"<...>"}catch(bA){return"<...>"}}function K(){var wA=w0.A;return wA===null?null:wA.getOwner()}function F(){return Error("react-stack-top-frame")}function Z(wA){if(RA.call(wA,"key")){var TA=Object.getOwnPropertyDescriptor(wA,"key").get;if(TA&&TA.isReactWarning)return!1}return wA.key!==void 0}function q(wA,TA){function bA(){$A||($A=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",TA))}bA.isReactWarning=!0,Object.defineProperty(wA,"key",{get:bA,configurable:!0})}function E(){var wA=W(this.type);return e0[wA]||(e0[wA]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),wA=this.props.ref,wA!==void 0?wA:null}function L(wA,TA,bA,mA,G0,M0){var aA=bA.ref;return wA={$$typeof:i,type:wA,key:TA,props:bA,_owner:mA},(aA!==void 0?aA:null)!==null?Object.defineProperty(wA,"ref",{enumerable:!1,get:E}):Object.defineProperty(wA,"ref",{enumerable:!1,value:null}),wA._store={},Object.defineProperty(wA._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(wA,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(wA,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:G0}),Object.defineProperty(wA,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:M0}),Object.freeze&&(Object.freeze(wA.props),Object.freeze(wA)),wA}function R(wA,TA){return TA=L(wA.type,TA,wA.props,wA._owner,wA._debugStack,wA._debugTask),wA._store&&(TA._store.validated=wA._store.validated),TA}function _(wA){O(wA)?wA._store&&(wA._store.validated=1):typeof wA==="object"&&wA!==null&&wA.$$typeof===I0&&(wA._payload.status==="fulfilled"?O(wA._payload.value)&&wA._payload.value._store&&(wA._payload.value._store.validated=1):wA._store&&(wA._store.validated=1))}function O(wA){return typeof wA==="object"&&wA!==null&&wA.$$typeof===i}function r(wA){var TA={"=":"=0",":":"=2"};return"$"+wA.replace(/[=:]/g,function(bA){return TA[bA]})}function n(wA,TA){return typeof wA==="object"&&wA!==null&&wA.key!=null?(X(wA.key),r(""+wA.key)):TA.toString(36)}function S(wA){switch(wA.status){case"fulfilled":return wA.value;case"rejected":throw wA.reason;default:switch(typeof wA.status==="string"?wA.then(D,D):(wA.status="pending",wA.then(function(TA){wA.status==="pending"&&(wA.status="fulfilled",wA.value=TA)},function(TA){wA.status==="pending"&&(wA.status="rejected",wA.reason=TA)})),wA.status){case"fulfilled":return wA.value;case"rejected":throw wA.reason}}throw wA}function x(wA,TA,bA,mA,G0){var M0=typeof wA;if(M0==="undefined"||M0==="boolean")wA=null;var aA=!1;if(wA===null)aA=!0;else switch(M0){case"bigint":case"string":case"number":aA=!0;break;case"object":switch(wA.$$typeof){case i:case u:aA=!0;break;case I0:return aA=wA._init,x(aA(wA._payload),TA,bA,mA,G0)}}if(aA){aA=wA,G0=G0(aA);var a0=mA===""?"."+n(aA,0):mA;return k0(G0)?(bA="",a0!=null&&(bA=a0.replace(_A,"$&/")+"/"),x(G0,TA,bA,"",function(g1){return g1})):G0!=null&&(O(G0)&&(G0.key!=null&&(aA&&aA.key===G0.key||X(G0.key)),bA=R(G0,bA+(G0.key==null||aA&&aA.key===G0.key?"":(""+G0.key).replace(_A,"$&/")+"/")+a0),mA!==""&&aA!=null&&O(aA)&&aA.key==null&&aA._store&&!aA._store.validated&&(bA._store.validated=2),G0=bA),TA.push(G0)),1}if(aA=0,a0=mA===""?".":mA+":",k0(wA))for(var g0=0;g0<wA.length;g0++)mA=wA[g0],M0=a0+n(mA,g0),aA+=x(mA,TA,bA,M0,G0);else if(g0=Q(wA),typeof g0==="function")for(g0===wA.entries&&(cA||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),cA=!0),wA=g0.call(wA),g0=0;!(mA=wA.next()).done;)mA=mA.value,M0=a0+n(mA,g0++),aA+=x(mA,TA,bA,M0,G0);else if(M0==="object"){if(typeof wA.then==="function")return x(S(wA),TA,bA,mA,G0);throw TA=String(wA),Error("Objects are not valid as a React child (found: "+(TA==="[object Object]"?"object with keys {"+Object.keys(wA).join(", ")+"}":TA)+"). If you meant to render a collection of children, use an array instead.")}return aA}function T(wA,TA,bA){if(wA==null)return wA;var mA=[],G0=0;return x(wA,mA,"","",function(M0){return TA.call(bA,M0,G0++)}),mA}function g(wA){if(wA._status===-1){var TA=wA._ioInfo;TA!=null&&(TA.start=TA.end=performance.now()),TA=wA._result;var bA=TA();if(bA.then(function(G0){if(wA._status===0||wA._status===-1){wA._status=1,wA._result=G0;var M0=wA._ioInfo;M0!=null&&(M0.end=performance.now()),bA.status===void 0&&(bA.status="fulfilled",bA.value=G0)}},function(G0){if(wA._status===0||wA._status===-1){wA._status=2,wA._result=G0;var M0=wA._ioInfo;M0!=null&&(M0.end=performance.now()),bA.status===void 0&&(bA.status="rejected",bA.reason=G0)}}),TA=wA._ioInfo,TA!=null){TA.value=bA;var mA=bA.displayName;typeof mA==="string"&&(TA.name=mA)}wA._status===-1&&(wA._status=0,wA._result=bA)}if(wA._status===1)return TA=wA._result,TA===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
515
515
|
|
|
516
516
|
Your code should look like:
|
|
517
517
|
const MyComponent = lazy(() => import('./MyComponent'))
|
|
@@ -1737,7 +1737,7 @@ Example bad output: "A dreamlike crystal formation glowing with ethereal light i
|
|
|
1737
1737
|
Title: "${A.entityTitle??Y}"
|
|
1738
1738
|
|
|
1739
1739
|
Content:
|
|
1740
|
-
${A.entityContent}`,h1Q);X=`${w.trim()} ${R.imagePrompt}`}catch(R){this.logger.warn("AI prompt distillation failed, using fallback",{error:S0(R)})}}await this.reportProgress(B,{progress:u2.PROCESS,message:"Generating image"});let W=this.context.identity.get(),U=this.context.identity.getProfile(),F=tW0(W,U)+X,Z;try{Z=await this.context.ai.generateImage(F,{...$&&{aspectRatio:$}})}catch(R){return this.logger.error("Image generation failed",{jobId:Q,error:S0(R)}),d$.failure(R)}await this.reportProgress(B,{progress:u2.GENERATE,message:"Creating image entity"});let q=XQ(Y),E=YZ.createImageEntity({dataUrl:Z.dataUrl,title:Y});if(await this.context.entityService.getEntity({entityType:"image",id:q}))this.logger.debug("Deleting existing image for regeneration",{imageId:q}),await this.context.entityService.deleteEntity({entityType:"image",id:q});if(await this.context.entityService.createEntity({entity:{...E,id:q}}),this.logger.debug("Created image entity",{imageId:q}),I&&D){await this.reportProgress(B,{progress:u2.SAVE,message:`Updating ${I} with cover image`});let R=await wr(this.context.entityService,I,D,this.logger);if(!R)return d$.failure(Error(`Target entity not found: ${I}/${D}`));let _=oy(R,q);await this.context.entities.update(_),this.logger.debug("Updated target entity with cover image",{targetEntityType:I,targetEntityId:D,imageId:q})}return await this.reportProgress(B,{progress:u2.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:q,targetEntityType:I,targetEntityId:D}),{success:!0,imageId:q}}catch(X){return this.logger.error("Image generation job failed",{jobId:Q,error:S0(X)}),d$.failure(X)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}var eW0={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.92",description:"Plugin for AI-powered image generation and management",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var c1Q=f.object({defaultAspectRatio:f.enum(["1:1","16:9","9:16","4:3","3:4"]).default("16:9").describe("Default aspect ratio for generated images")});class vfA extends V2{entityType=YZ.entityType;schema=ry;adapter=YZ;constructor(A={}){super("image",eW0,A,c1Q)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,B){if(!A.targetEntityType||!A.targetEntityId)return{kind:"continue",input:A};let w=await XY(B.entityService,A.targetEntityType,A.targetEntityId,this.logger,"Target entity");if(!w.ok)return{kind:"handled",result:{success:!1,error:w.error}};return{kind:"continue",input:{...A,targetEntityId:w.entity.id}}}createGenerationHandler(A){return new is(A,this.logger)}async onRegister(A){let Q=new is(A,this.logger);A.jobs.registerHandler("image-generate",Q)}}function dT(A){return new vfA(A)}eA();import{StdioServerTransport as p1Q}from"@modelcontextprotocol/sdk/server/stdio.js";function AH0(){return{info:(A,...Q)=>console.error(`[STDIO MCP] ${A}`,...Q),debug:(A,...Q)=>console.error(`[STDIO MCP DEBUG] ${A}`,...Q),error:(A,...Q)=>console.error(`[STDIO MCP ERROR] ${A}`,...Q),warn:(A,...Q)=>console.error(`[STDIO MCP WARN] ${A}`,...Q)}}function xfA(){return{info:(A,...Q)=>console.log(`[HTTP MCP] ${A}`,...Q),debug:(A,...Q)=>console.debug(`[HTTP MCP DEBUG] ${A}`,...Q),error:(A,...Q)=>console.error(`[HTTP MCP ERROR] ${A}`,...Q),warn:(A,...Q)=>console.warn(`[HTTP MCP WARN] ${A}`,...Q)}}function ds(A){if(A&&typeof A==="object"&&"info"in A&&"debug"in A&&"error"in A&&"warn"in A){let Q=A;return{info:(B,...w)=>Q.info(B,...w),debug:(B,...w)=>Q.debug(B,...w),error:(B,...w)=>Q.error(B,...w),warn:(B,...w)=>Q.warn(B,...w)}}return xfA()}class HW{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return HW.instance??=new HW(A),HW.instance}static resetInstance(){if(HW.instance)HW.instance.stop(),HW.instance=null}static createFresh(A){return new HW(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?ds(this.config.logger):AH0()}connectMCPServer(A){this.mcpServer=A,this.logger.debug("MCP server connected to stdio transport")}async start(){if(!this.mcpServer)throw Error("MCP server not connected. Call connectMCPServer() first.");if(this.transport)throw Error("Server is already running");this.logger.info("Starting stdio transport"),this.transport=new p1Q,await this.mcpServer.connect(this.transport),this.logger.info("Stdio transport started successfully")}stop(){if(this.logger.info("Stopping stdio transport"),this.transport)this.transport=null;this.logger.info("Stdio transport stopped")}isRunning(){return this.transport!==null}}import{randomUUID as QH0}from"crypto";import{WebStandardStreamableHTTPServerTransport as l1Q}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as i1Q}from"@modelcontextprotocol/sdk/types.js";var d1Q={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Session-Id, MCP-Protocol-Version, Last-Event-ID","Access-Control-Allow-Private-Network":"true","X-Content-Type-Options":"nosniff"};function r1Q(A){let Q=new URL(A.url),w=A.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),$=A.headers.get("x-forwarded-host")??A.headers.get("host");if(!$)return Q.origin;return`${w??Q.protocol.replace(":","")}://${$}`}class aG{static instance=null;transports={};mcpServer=null;mcpTransport=null;agentService=null;server=null;boundPort=null;config;logger;authConfig;constructor(A={}){if(this.config=A,this.logger=this.config.logger?ds(this.config.logger):xfA(),this.authConfig=A.auth??{},!this.authConfig.disabled&&!this.authConfig.token&&!this.authConfig.verifyBearerToken)throw Error("MCP HTTP transport requires an auth token or bearer token verifier. Set MCP_AUTH_TOKEN, configure OAuth verification, or pass auth: { disabled: true } for local dev.")}static getInstance(A){return aG.instance??=new aG(A),aG.instance}static resetInstance(){aG.instance=null}static createFresh(A){return new aG(A)}withCors(A){let Q=new Headers(A.headers);for(let[B,w]of Object.entries(d1Q))Q.set(B,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}createJsonResponse(A,Q=200){return this.withCors(new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json"}}))}createTextResponse(A,Q=200){return this.withCors(new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8"}}))}getAuthErrorResponse(A,Q=401,B){let w=this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},Q);if(!B)return w;let $=new Headers(w.headers);return $.set("WWW-Authenticate",B),new Response(w.body,{status:w.status,statusText:w.statusText,headers:$})}getBearerChallenge(A,Q={}){let w={resource_metadata:`${r1Q(A)}/.well-known/oauth-protected-resource`,...Q};return`Bearer ${Object.entries(w).map(([I,D])=>`${I}="${n1Q(D)}"`).join(", ")}`}async authenticate(A){let Q=new URL(A.url).pathname;if(Q==="/health"||Q==="/status"||Q==="/mcp"&&A.method==="OPTIONS")return null;if(this.authConfig.disabled)return null;let B=A.headers.get("authorization");if(!B?.startsWith("Bearer "))return this.logger.warn("Authentication failed: Missing Bearer token"),this.getAuthErrorResponse("Unauthorized: Bearer token required",401,this.getBearerChallenge(A,{realm:"mcp"}));if(this.authConfig.token){if(B.substring(7)!==this.authConfig.token)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));return this.logger.debug("Authentication successful"),null}try{let w=await this.authConfig.verifyBearerToken?.(A);if(!w)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));let $=this.authConfig.requiredScopes??[],I=$.filter((D)=>!w.scope?.includes(D));if(I.length>0)return this.logger.warn(`Authentication failed: Missing required scope(s): ${I.join(", ")}`),this.getAuthErrorResponse("Forbidden: Missing required scope",403,this.getBearerChallenge(A,{error:"insufficient_scope",scope:$.join(" ")}));return this.logger.debug("Authentication successful"),null}catch(w){return this.logger.warn("Authentication failed: Invalid token",w),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}))}}async handleMcpRequest(A){let Q=A.headers.get("mcp-session-id")??void 0;if(A.method==="GET"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.debug(`GET /mcp - SSE stream for session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="DELETE"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.info(`DELETE /mcp - Terminating session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="OPTIONS")return this.withCors(new Response(null,{status:204}));if(A.method!=="POST")return this.createTextResponse("Method Not Allowed",405);if(!this.mcpServer)return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Service Unavailable: MCP server not connected"},id:null},503);let B=await A.json();this.logger.debug(`POST /mcp - Session: ${Q??"new"}`);try{let w;if(Q&&this.transports[Q])w=this.transports[Q];else if(!Q&&i1Q(B))w=new l1Q({sessionIdGenerator:()=>QH0(),onsessioninitialized:(I)=>{this.logger.info(`Session initialized: ${I}`),this.transports[I]=w},onsessionclosed:(I)=>{this.logger.info(`Session closed: ${I}`),delete this.transports[I]}}),await(this.mcpTransport?this.mcpTransport.createMcpServer():this.mcpServer).connect(w);else return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32000,message:"Bad Request: Server not initialized"},id:null},400);return this.withCors(await w.handleRequest(A,{parsedBody:B}))}catch(w){return this.logger.error("MCP transport error:",w),this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}},500)}}async handleAgentChatRequest(A){if(!this.agentService)return this.createJsonResponse({error:"Agent service not connected"},503);let{message:Q,conversationId:B}=await A.json();if(!Q||typeof Q!=="string")return this.createJsonResponse({error:"Missing or invalid 'message' field"},400);let w=B??QH0();this.logger.debug(`POST /api/chat - conversation: ${w}`);try{let $=await this.agentService.chat(Q,w);return this.createJsonResponse($)}catch($){return this.logger.error("Agent chat error:",$),this.createJsonResponse({error:$ instanceof Error?$.message:"Internal error"},500)}}async handleRequest(A){let Q=new URL(A.url);this.logger.debug(`${A.method} ${Q.pathname}`);let B=await this.authenticate(A);if(B)return B;if(Q.pathname==="/health")return this.createJsonResponse({status:"ok",transport:"streamable-http",timestamp:new Date().toISOString()});if(Q.pathname==="/status")return this.createJsonResponse({sessions:Object.keys(this.transports).length,uptime:process.uptime(),memory:process.memoryUsage(),port:this.boundPort??this.config.port??3333});if(Q.pathname==="/mcp")return this.handleMcpRequest(A);if(Q.pathname==="/api/chat"&&A.method==="POST")return this.handleAgentChatRequest(A);return this.createTextResponse("Not Found",404)}connectMCPServer(A,Q){this.mcpServer=A,this.mcpTransport=Q??null,this.logger.debug("MCP server connected to StreamableHTTP transport")}connectAgentService(A){this.agentService=A,this.logger.debug("Agent service connected to StreamableHTTP transport")}async start(){if(this.server)throw Error("Server is already running");let A=Number(this.config.port??3333),Q=this.config.host??"0.0.0.0";try{this.server=Bun.serve({port:A,hostname:Q,fetch:(B)=>this.handleRequest(B)}),this.boundPort=this.server.port??A,this.logger.info(`StreamableHTTP server listening on http://${Q}:${this.boundPort}/mcp`)}catch(B){if(B.code==="EADDRINUSE")this.logger.error(`Port ${A} is already in use`);throw B}}async stop(){for(let A in this.transports)try{let Q=this.transports[A];if(Q)this.logger.debug(`Closing transport for session ${A}`),await Q.close(),delete this.transports[A]}catch(Q){this.logger.error(`Error closing transport for session ${A}:`,Q)}if(this.server)await this.server.stop(),this.logger.info("StreamableHTTP server stopped"),this.server=null,this.boundPort=null}getPort(){if(this.boundPort===null)throw Error("Server is not running");return this.boundPort}getApp(){return{fetch:(A)=>this.handleRequest(A)}}isRunning(){return this.server!==null}getSessionCount(){return Object.keys(this.transports).length}}function n1Q(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}import{randomUUID as s1Q}from"crypto";import{mkdir as a1Q,readFile as t1Q,writeFile as e1Q,chmod as AQQ}from"fs/promises";import{dirname as QQQ,join as BQQ}from"path";function BH0(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function wH0(A){try{return new URL(A)}catch{return}}function yfA(A,Q){if(A===Q)return!0;let B=wH0(A),w=wH0(Q);if(!B||!w)return!1;if(!BH0(B.hostname)||!BH0(w.hostname))return!1;return B.protocol===w.protocol&&B.port===w.port&&o1Q(B.pathname,w.pathname)&&B.search===w.search&&B.hash===w.hash}function o1Q(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function TfA(A,Q){return A.some((B)=>yfA(B,Q))}var wQQ="oauth-auth-codes.json",$QQ=600;function $H0(){return Math.floor(Date.now()/1000)}function IQQ(A){if(!A||typeof A!=="object")return!1;let Q=A;return typeof Q.code==="string"&&typeof Q.client_id==="string"&&typeof Q.redirect_uri==="string"&&typeof Q.code_challenge==="string"&&Q.code_challenge_method==="S256"&&typeof Q.subject==="string"&&typeof Q.created_at==="number"&&typeof Q.expires_at==="number"}function DQQ(A){if(!A||typeof A!=="object")return{codes:[]};let Q=A.codes;if(!Array.isArray(Q))return{codes:[]};return{codes:Q.filter(IQQ)}}async function YQQ(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class rs{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=BQQ(A.storageDir,A.storeFile??wQQ)}async createCode(A){let Q=$H0(),B={code:`ocd_${s1Q()}`,client_id:A.clientId,redirect_uri:A.redirectUri,code_challenge:A.codeChallenge,code_challenge_method:"S256",...A.scope?{scope:A.scope}:{},subject:A.subject,created_at:Q,expires_at:Q+$QQ};return await this.enqueueWrite(async()=>{let w=await this.readStore();w.codes=w.codes.filter(($)=>$.expires_at>Q),w.codes.push(B),await this.writeStore(w)}),B}async consumeCode(A){let Q=$H0(),B;if(await this.enqueueWrite(async()=>{let w=await this.readStore(),$=w.codes.findIndex((Y)=>Y.code===A.code),I=$>=0?w.codes[$]:void 0;if(!I)throw new UW("Authorization code not found");if(I.consumed_at!==void 0)throw new UW("Authorization code already consumed");if(I.expires_at<=Q)throw new UW("Authorization code expired");if(I.client_id!==A.clientId)throw new UW("Authorization code client mismatch");if(!yfA(I.redirect_uri,A.redirectUri))throw new UW("Authorization code redirect URI mismatch");let D=await YQQ(A.codeVerifier);if(I.code_challenge!==D)throw new UW("PKCE verification failed");B={...I,consumed_at:Q},w.codes[$]=B,await this.writeStore(w)}),!B)throw new UW("Authorization code not consumed");return B}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return DQQ(JSON.parse(await t1Q(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{codes:[]};throw A}}async writeStore(A){await a1Q(QQQ(this.storeFile),{recursive:!0,mode:448}),await e1Q(this.storeFile,`${JSON.stringify(A,null,2)}
|
|
1740
|
+
${A.entityContent}`,h1Q);X=`${w.trim()} ${R.imagePrompt}`}catch(R){this.logger.warn("AI prompt distillation failed, using fallback",{error:S0(R)})}}await this.reportProgress(B,{progress:u2.PROCESS,message:"Generating image"});let W=this.context.identity.get(),U=this.context.identity.getProfile(),F=tW0(W,U)+X,Z;try{Z=await this.context.ai.generateImage(F,{...$&&{aspectRatio:$}})}catch(R){return this.logger.error("Image generation failed",{jobId:Q,error:S0(R)}),d$.failure(R)}await this.reportProgress(B,{progress:u2.GENERATE,message:"Creating image entity"});let q=XQ(Y),E=YZ.createImageEntity({dataUrl:Z.dataUrl,title:Y});if(await this.context.entityService.getEntity({entityType:"image",id:q}))this.logger.debug("Deleting existing image for regeneration",{imageId:q}),await this.context.entityService.deleteEntity({entityType:"image",id:q});if(await this.context.entityService.createEntity({entity:{...E,id:q}}),this.logger.debug("Created image entity",{imageId:q}),I&&D){await this.reportProgress(B,{progress:u2.SAVE,message:`Updating ${I} with cover image`});let R=await wr(this.context.entityService,I,D,this.logger);if(!R)return d$.failure(Error(`Target entity not found: ${I}/${D}`));let _=oy(R,q);await this.context.entities.update(_),this.logger.debug("Updated target entity with cover image",{targetEntityType:I,targetEntityId:D,imageId:q})}return await this.reportProgress(B,{progress:u2.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:q,targetEntityType:I,targetEntityId:D}),{success:!0,imageId:q}}catch(X){return this.logger.error("Image generation job failed",{jobId:Q,error:S0(X)}),d$.failure(X)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}var eW0={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.93",description:"Plugin for AI-powered image generation and management",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var c1Q=f.object({defaultAspectRatio:f.enum(["1:1","16:9","9:16","4:3","3:4"]).default("16:9").describe("Default aspect ratio for generated images")});class vfA extends V2{entityType=YZ.entityType;schema=ry;adapter=YZ;constructor(A={}){super("image",eW0,A,c1Q)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,B){if(!A.targetEntityType||!A.targetEntityId)return{kind:"continue",input:A};let w=await XY(B.entityService,A.targetEntityType,A.targetEntityId,this.logger,"Target entity");if(!w.ok)return{kind:"handled",result:{success:!1,error:w.error}};return{kind:"continue",input:{...A,targetEntityId:w.entity.id}}}createGenerationHandler(A){return new is(A,this.logger)}async onRegister(A){let Q=new is(A,this.logger);A.jobs.registerHandler("image-generate",Q)}}function dT(A){return new vfA(A)}eA();import{StdioServerTransport as p1Q}from"@modelcontextprotocol/sdk/server/stdio.js";function AH0(){return{info:(A,...Q)=>console.error(`[STDIO MCP] ${A}`,...Q),debug:(A,...Q)=>console.error(`[STDIO MCP DEBUG] ${A}`,...Q),error:(A,...Q)=>console.error(`[STDIO MCP ERROR] ${A}`,...Q),warn:(A,...Q)=>console.error(`[STDIO MCP WARN] ${A}`,...Q)}}function xfA(){return{info:(A,...Q)=>console.log(`[HTTP MCP] ${A}`,...Q),debug:(A,...Q)=>console.debug(`[HTTP MCP DEBUG] ${A}`,...Q),error:(A,...Q)=>console.error(`[HTTP MCP ERROR] ${A}`,...Q),warn:(A,...Q)=>console.warn(`[HTTP MCP WARN] ${A}`,...Q)}}function ds(A){if(A&&typeof A==="object"&&"info"in A&&"debug"in A&&"error"in A&&"warn"in A){let Q=A;return{info:(B,...w)=>Q.info(B,...w),debug:(B,...w)=>Q.debug(B,...w),error:(B,...w)=>Q.error(B,...w),warn:(B,...w)=>Q.warn(B,...w)}}return xfA()}class HW{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return HW.instance??=new HW(A),HW.instance}static resetInstance(){if(HW.instance)HW.instance.stop(),HW.instance=null}static createFresh(A){return new HW(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?ds(this.config.logger):AH0()}connectMCPServer(A){this.mcpServer=A,this.logger.debug("MCP server connected to stdio transport")}async start(){if(!this.mcpServer)throw Error("MCP server not connected. Call connectMCPServer() first.");if(this.transport)throw Error("Server is already running");this.logger.info("Starting stdio transport"),this.transport=new p1Q,await this.mcpServer.connect(this.transport),this.logger.info("Stdio transport started successfully")}stop(){if(this.logger.info("Stopping stdio transport"),this.transport)this.transport=null;this.logger.info("Stdio transport stopped")}isRunning(){return this.transport!==null}}import{randomUUID as QH0}from"crypto";import{WebStandardStreamableHTTPServerTransport as l1Q}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as i1Q}from"@modelcontextprotocol/sdk/types.js";var d1Q={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Session-Id, MCP-Protocol-Version, Last-Event-ID","Access-Control-Allow-Private-Network":"true","X-Content-Type-Options":"nosniff"};function r1Q(A){let Q=new URL(A.url),w=A.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),$=A.headers.get("x-forwarded-host")??A.headers.get("host");if(!$)return Q.origin;return`${w??Q.protocol.replace(":","")}://${$}`}class aG{static instance=null;transports={};mcpServer=null;mcpTransport=null;agentService=null;server=null;boundPort=null;config;logger;authConfig;constructor(A={}){if(this.config=A,this.logger=this.config.logger?ds(this.config.logger):xfA(),this.authConfig=A.auth??{},!this.authConfig.disabled&&!this.authConfig.token&&!this.authConfig.verifyBearerToken)throw Error("MCP HTTP transport requires an auth token or bearer token verifier. Set MCP_AUTH_TOKEN, configure OAuth verification, or pass auth: { disabled: true } for local dev.")}static getInstance(A){return aG.instance??=new aG(A),aG.instance}static resetInstance(){aG.instance=null}static createFresh(A){return new aG(A)}withCors(A){let Q=new Headers(A.headers);for(let[B,w]of Object.entries(d1Q))Q.set(B,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}createJsonResponse(A,Q=200){return this.withCors(new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json"}}))}createTextResponse(A,Q=200){return this.withCors(new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8"}}))}getAuthErrorResponse(A,Q=401,B){let w=this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},Q);if(!B)return w;let $=new Headers(w.headers);return $.set("WWW-Authenticate",B),new Response(w.body,{status:w.status,statusText:w.statusText,headers:$})}getBearerChallenge(A,Q={}){let w={resource_metadata:`${r1Q(A)}/.well-known/oauth-protected-resource`,...Q};return`Bearer ${Object.entries(w).map(([I,D])=>`${I}="${n1Q(D)}"`).join(", ")}`}async authenticate(A){let Q=new URL(A.url).pathname;if(Q==="/health"||Q==="/status"||Q==="/mcp"&&A.method==="OPTIONS")return null;if(this.authConfig.disabled)return null;let B=A.headers.get("authorization");if(!B?.startsWith("Bearer "))return this.logger.warn("Authentication failed: Missing Bearer token"),this.getAuthErrorResponse("Unauthorized: Bearer token required",401,this.getBearerChallenge(A,{realm:"mcp"}));if(this.authConfig.token){if(B.substring(7)!==this.authConfig.token)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));return this.logger.debug("Authentication successful"),null}try{let w=await this.authConfig.verifyBearerToken?.(A);if(!w)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));let $=this.authConfig.requiredScopes??[],I=$.filter((D)=>!w.scope?.includes(D));if(I.length>0)return this.logger.warn(`Authentication failed: Missing required scope(s): ${I.join(", ")}`),this.getAuthErrorResponse("Forbidden: Missing required scope",403,this.getBearerChallenge(A,{error:"insufficient_scope",scope:$.join(" ")}));return this.logger.debug("Authentication successful"),null}catch(w){return this.logger.warn("Authentication failed: Invalid token",w),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}))}}async handleMcpRequest(A){let Q=A.headers.get("mcp-session-id")??void 0;if(A.method==="GET"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.debug(`GET /mcp - SSE stream for session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="DELETE"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.info(`DELETE /mcp - Terminating session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="OPTIONS")return this.withCors(new Response(null,{status:204}));if(A.method!=="POST")return this.createTextResponse("Method Not Allowed",405);if(!this.mcpServer)return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Service Unavailable: MCP server not connected"},id:null},503);let B=await A.json();this.logger.debug(`POST /mcp - Session: ${Q??"new"}`);try{let w;if(Q&&this.transports[Q])w=this.transports[Q];else if(!Q&&i1Q(B))w=new l1Q({sessionIdGenerator:()=>QH0(),onsessioninitialized:(I)=>{this.logger.info(`Session initialized: ${I}`),this.transports[I]=w},onsessionclosed:(I)=>{this.logger.info(`Session closed: ${I}`),delete this.transports[I]}}),await(this.mcpTransport?this.mcpTransport.createMcpServer():this.mcpServer).connect(w);else return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32000,message:"Bad Request: Server not initialized"},id:null},400);return this.withCors(await w.handleRequest(A,{parsedBody:B}))}catch(w){return this.logger.error("MCP transport error:",w),this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}},500)}}async handleAgentChatRequest(A){if(!this.agentService)return this.createJsonResponse({error:"Agent service not connected"},503);let{message:Q,conversationId:B}=await A.json();if(!Q||typeof Q!=="string")return this.createJsonResponse({error:"Missing or invalid 'message' field"},400);let w=B??QH0();this.logger.debug(`POST /api/chat - conversation: ${w}`);try{let $=await this.agentService.chat(Q,w);return this.createJsonResponse($)}catch($){return this.logger.error("Agent chat error:",$),this.createJsonResponse({error:$ instanceof Error?$.message:"Internal error"},500)}}async handleRequest(A){let Q=new URL(A.url);this.logger.debug(`${A.method} ${Q.pathname}`);let B=await this.authenticate(A);if(B)return B;if(Q.pathname==="/health")return this.createJsonResponse({status:"ok",transport:"streamable-http",timestamp:new Date().toISOString()});if(Q.pathname==="/status")return this.createJsonResponse({sessions:Object.keys(this.transports).length,uptime:process.uptime(),memory:process.memoryUsage(),port:this.boundPort??this.config.port??3333});if(Q.pathname==="/mcp")return this.handleMcpRequest(A);if(Q.pathname==="/api/chat"&&A.method==="POST")return this.handleAgentChatRequest(A);return this.createTextResponse("Not Found",404)}connectMCPServer(A,Q){this.mcpServer=A,this.mcpTransport=Q??null,this.logger.debug("MCP server connected to StreamableHTTP transport")}connectAgentService(A){this.agentService=A,this.logger.debug("Agent service connected to StreamableHTTP transport")}async start(){if(this.server)throw Error("Server is already running");let A=Number(this.config.port??3333),Q=this.config.host??"0.0.0.0";try{this.server=Bun.serve({port:A,hostname:Q,fetch:(B)=>this.handleRequest(B)}),this.boundPort=this.server.port??A,this.logger.info(`StreamableHTTP server listening on http://${Q}:${this.boundPort}/mcp`)}catch(B){if(B.code==="EADDRINUSE")this.logger.error(`Port ${A} is already in use`);throw B}}async stop(){for(let A in this.transports)try{let Q=this.transports[A];if(Q)this.logger.debug(`Closing transport for session ${A}`),await Q.close(),delete this.transports[A]}catch(Q){this.logger.error(`Error closing transport for session ${A}:`,Q)}if(this.server)await this.server.stop(),this.logger.info("StreamableHTTP server stopped"),this.server=null,this.boundPort=null}getPort(){if(this.boundPort===null)throw Error("Server is not running");return this.boundPort}getApp(){return{fetch:(A)=>this.handleRequest(A)}}isRunning(){return this.server!==null}getSessionCount(){return Object.keys(this.transports).length}}function n1Q(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}import{randomUUID as s1Q}from"crypto";import{mkdir as a1Q,readFile as t1Q,writeFile as e1Q,chmod as AQQ}from"fs/promises";import{dirname as QQQ,join as BQQ}from"path";function BH0(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function wH0(A){try{return new URL(A)}catch{return}}function yfA(A,Q){if(A===Q)return!0;let B=wH0(A),w=wH0(Q);if(!B||!w)return!1;if(!BH0(B.hostname)||!BH0(w.hostname))return!1;return B.protocol===w.protocol&&B.port===w.port&&o1Q(B.pathname,w.pathname)&&B.search===w.search&&B.hash===w.hash}function o1Q(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function TfA(A,Q){return A.some((B)=>yfA(B,Q))}var wQQ="oauth-auth-codes.json",$QQ=600;function $H0(){return Math.floor(Date.now()/1000)}function IQQ(A){if(!A||typeof A!=="object")return!1;let Q=A;return typeof Q.code==="string"&&typeof Q.client_id==="string"&&typeof Q.redirect_uri==="string"&&typeof Q.code_challenge==="string"&&Q.code_challenge_method==="S256"&&typeof Q.subject==="string"&&typeof Q.created_at==="number"&&typeof Q.expires_at==="number"}function DQQ(A){if(!A||typeof A!=="object")return{codes:[]};let Q=A.codes;if(!Array.isArray(Q))return{codes:[]};return{codes:Q.filter(IQQ)}}async function YQQ(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class rs{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=BQQ(A.storageDir,A.storeFile??wQQ)}async createCode(A){let Q=$H0(),B={code:`ocd_${s1Q()}`,client_id:A.clientId,redirect_uri:A.redirectUri,code_challenge:A.codeChallenge,code_challenge_method:"S256",...A.scope?{scope:A.scope}:{},subject:A.subject,created_at:Q,expires_at:Q+$QQ};return await this.enqueueWrite(async()=>{let w=await this.readStore();w.codes=w.codes.filter(($)=>$.expires_at>Q),w.codes.push(B),await this.writeStore(w)}),B}async consumeCode(A){let Q=$H0(),B;if(await this.enqueueWrite(async()=>{let w=await this.readStore(),$=w.codes.findIndex((Y)=>Y.code===A.code),I=$>=0?w.codes[$]:void 0;if(!I)throw new UW("Authorization code not found");if(I.consumed_at!==void 0)throw new UW("Authorization code already consumed");if(I.expires_at<=Q)throw new UW("Authorization code expired");if(I.client_id!==A.clientId)throw new UW("Authorization code client mismatch");if(!yfA(I.redirect_uri,A.redirectUri))throw new UW("Authorization code redirect URI mismatch");let D=await YQQ(A.codeVerifier);if(I.code_challenge!==D)throw new UW("PKCE verification failed");B={...I,consumed_at:Q},w.codes[$]=B,await this.writeStore(w)}),!B)throw new UW("Authorization code not consumed");return B}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return DQQ(JSON.parse(await t1Q(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{codes:[]};throw A}}async writeStore(A){await a1Q(QQQ(this.storeFile),{recursive:!0,mode:448}),await e1Q(this.storeFile,`${JSON.stringify(A,null,2)}
|
|
1741
1741
|
`,{mode:384}),await AQQ(this.storeFile,384)}}class UW extends Error{constructor(A){super(A);this.name="InvalidGrantError"}}import{randomUUID as BF0}from"crypto";fA();import{randomUUID as IH0}from"crypto";import{mkdir as XQQ,readFile as WQQ,writeFile as HQQ,chmod as UQQ}from"fs/promises";import{dirname as JQQ,join as GQQ}from"path";var KQQ="oauth-clients.json",fQQ=f.enum(["none","client_secret_basic","client_secret_post"]),FQQ=f.object({redirect_uris:f.array(f.string().url()).min(1),token_endpoint_auth_method:fQQ.default("none"),grant_types:f.array(f.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),response_types:f.array(f.literal("code")).default(["code"]),scope:f.string().optional(),client_name:f.string().optional(),client_uri:f.string().url().optional(),logo_uri:f.string().url().optional(),contacts:f.array(f.string()).optional()});function ZQQ(){return Math.floor(Date.now()/1000)}function zQQ(){return`ocs_${IH0().replaceAll("-","")}`}function NQQ(A){if(!A||typeof A!=="object")return{clients:[]};let Q=A.clients;if(!Array.isArray(Q))return{clients:[]};return{clients:Q.filter(qQQ)}}function qQQ(A){if(!A||typeof A!=="object")return!1;let Q=A;return typeof Q.client_id==="string"&&Array.isArray(Q.redirect_uris)&&Q.redirect_uris.every((B)=>typeof B==="string")&&typeof Q.client_id_issued_at==="number"}class ns{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=GQQ(A.storageDir,A.storeFile??KQQ)}async registerClient(A){let Q=FQQ.safeParse(A);if(!Q.success)throw new rT(Q.error.message);let B=Q.data,w=ZQQ(),$=`oc_${IH0()}`,I=B.token_endpoint_auth_method==="none",D={client_id:$,client_id_issued_at:w,redirect_uris:B.redirect_uris,token_endpoint_auth_method:B.token_endpoint_auth_method,grant_types:B.grant_types,response_types:B.response_types,...B.scope?{scope:B.scope}:{},...B.client_name?{client_name:B.client_name}:{},...B.client_uri?{client_uri:B.client_uri}:{},...B.logo_uri?{logo_uri:B.logo_uri}:{},...B.contacts?{contacts:B.contacts}:{},...!I?{client_secret:zQQ(),client_secret_expires_at:0}:{}};return await this.enqueueWrite(async()=>{let Y=await this.readStore();Y.clients.push(D),await this.writeStore(Y)}),D}async getClient(A){return(await this.readStore()).clients.find((B)=>B.client_id===A)}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return NQQ(JSON.parse(await WQQ(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{clients:[]};throw A}}async writeStore(A){await XQQ(JQQ(this.storeFile),{recursive:!0,mode:448}),await HQQ(this.storeFile,`${JSON.stringify(A,null,2)}
|
|
1742
1742
|
`,{mode:384}),await UQQ(this.storeFile,384)}}class rT extends Error{constructor(A){super(A);this.name="InvalidClientMetadataError"}}function DH0(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function LQQ(A){let Q=new Uint8Array(A);if(Q.length===64)return Q;if(Q[0]!==48)return Q;let B=2;if(Q[1]&&Q[1]>128)B+=Q[1]-128;if(Q[B]!==2)throw Error("Invalid DER ECDSA signature");let w=Q[B+1];if(w===void 0)throw Error("Invalid DER ECDSA signature");let $=B+2,I=Q.slice($,$+w);if(B=$+w,Q[B]!==2)throw Error("Invalid DER ECDSA signature");let D=Q[B+1];if(D===void 0)throw Error("Invalid DER ECDSA signature");let Y=B+2,X=Q.slice(Y,Y+D);return new Uint8Array([...YH0(I),...YH0(X)])}function YH0(A){let Q=A;while(Q.length>32&&Q[0]===0)Q=Q.slice(1);if(Q.length>32)throw Error("Invalid P-256 signature component length");if(Q.length===32)return Q;let B=new Uint8Array(32);return B.set(Q,32-Q.length),B}async function SfA(A,Q){let B={typ:"JWT",alg:"ES256",kid:A.kid},w=`${DH0(B)}.${DH0(Q)}`,$=await crypto.subtle.importKey("jwk",A,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),I=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},$,new TextEncoder().encode(w));return`${w}.${Buffer.from(LQQ(I)).toString("base64url")}`}import{createHash as EQQ}from"crypto";import{mkdir as VQQ,readFile as MQQ,writeFile as CQQ,chmod as OQQ}from"fs/promises";import{dirname as RQQ,join as bQQ}from"path";var PQQ="oauth-signing-key.jwk";function XH0(A){if(!A||typeof A!=="object")return!1;let Q=A;return Q.kty==="EC"&&Q.crv==="P-256"&&typeof Q.x==="string"&&typeof Q.y==="string"&&typeof Q.d==="string"}function WH0(A){let Q=JSON.stringify({crv:A.crv,kty:A.kty,x:A.x,y:A.y});return EQQ("sha256").update(Q).digest("base64url")}function jQQ(A){return{kty:"EC",crv:"P-256",x:A.x,y:A.y,kid:A.kid,use:"sig",alg:"ES256"}}async function kQQ(){let A=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),Q=await crypto.subtle.exportKey("jwk",A.privateKey);if(!XH0(Q))throw Error("Generated OAuth signing key is not a P-256 private JWK");let B=WH0(Q);return{...Q,kid:B,use:"sig",alg:"ES256"}}class os{keyFile;cachedKey;loadPromise;constructor(A){this.keyFile=bQQ(A.storageDir,A.keyFile??PQQ)}async getPrivateJwk(){if(this.cachedKey)return this.cachedKey;this.loadPromise??=this.loadOrCreateKey();try{return this.cachedKey=await this.loadPromise,this.cachedKey}catch(A){throw this.loadPromise=void 0,A}}async loadOrCreateKey(){let A=await this.readExistingKey();if(A)return A;let Q=await kQQ();return await VQQ(RQQ(this.keyFile),{recursive:!0,mode:448}),await CQQ(this.keyFile,`${JSON.stringify(Q,null,2)}
|
|
1743
1743
|
`,{mode:384}),await OQQ(this.keyFile,384),Q}async getPublicJwk(){return jQQ(await this.getPrivateJwk())}async readExistingKey(){try{let A=JSON.parse(await MQQ(this.keyFile,"utf8"));if(!XH0(A))throw Error(`OAuth signing key at ${this.keyFile} is not a private P-256 JWK`);let Q=typeof A.kid==="string"?A.kid:WH0(A);return{...A,kid:Q,use:"sig",alg:"ES256"}}catch(A){if(A.code==="ENOENT")return;throw A}}}var iQ={};_B(iQ,{trimPadding:()=>UH0,toUTF8String:()=>mQQ,toBuffer:()=>TQQ,toBase64:()=>gQQ,isBase64URL:()=>cQQ,isBase64:()=>uQQ,fromUTF8String:()=>hQQ,fromBuffer:()=>SQQ});var HH0=(A)=>{let Q=typeof Uint8Array>"u"?[]:new Uint8Array(256),B=64;for(let w=0;w<64;w++)Q[A.charCodeAt(w)]=w;return Q},_QQ=HH0("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),vQQ=HH0("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),xQQ=/^[-A-Za-z0-9\-_]*$/,yQQ=/^[-A-Za-z0-9+/]*={0,3}$/,FU={};FU.toArrayBuffer=(A,Q)=>{let B=A.length,w=A.length*0.75,$,I=0,D,Y,X,W;if(A[A.length-1]==="="){if(w--,A[A.length-2]==="=")w--}let U=new ArrayBuffer(w),K=new Uint8Array(U),F=Q?vQQ:_QQ;for($=0;$<B;$+=4)D=F[A.charCodeAt($)],Y=F[A.charCodeAt($+1)],X=F[A.charCodeAt($+2)],W=F[A.charCodeAt($+3)],K[I++]=D<<2|Y>>4,K[I++]=(Y&15)<<4|X>>2,K[I++]=(X&3)<<6|W&63;return U};FU.fromArrayBuffer=(A,Q)=>{let B=new Uint8Array(A),w,$="",I=B.length,D=Q?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(w=0;w<I;w+=3)$+=D[B[w]>>2],$+=D[(B[w]&3)<<4|B[w+1]>>4],$+=D[(B[w+1]&15)<<2|B[w+2]>>6],$+=D[B[w+2]&63];let Y=I%3;if(Y===2)$=$.substring(0,$.length-1)+(Q?"":"=");else if(Y===1)$=$.substring(0,$.length-2)+(Q?"":"==");return $};FU.toString=(A,Q)=>{return new TextDecoder().decode(FU.toArrayBuffer(A,Q))};FU.fromString=(A,Q)=>{return FU.fromArrayBuffer(new TextEncoder().encode(A),Q)};FU.validate=(A,Q)=>{if(!(typeof A==="string"||A instanceof String))return!1;try{return Q?xQQ.test(A):yQQ.test(A)}catch(B){return!1}};FU.base64=FU;var tG=FU;function TQQ(A,Q="base64url"){let B=tG.toArrayBuffer(A,Q==="base64url");return new Uint8Array(B)}function SQQ(A,Q="base64url"){let B=new Uint8Array(A);return tG.fromArrayBuffer(B.buffer,Q==="base64url")}function gQQ(A){let Q=tG.toArrayBuffer(A,!0);return tG.fromArrayBuffer(Q)}function hQQ(A){return tG.fromString(A,!0)}function mQQ(A){return tG.toString(A,!0)}function uQQ(A){return tG.validate(A,!1)}function cQQ(A){return A=UH0(A),tG.validate(A,!0)}function UH0(A){return A.replace(/=/g,"")}var g7={};_B(g7,{encode:()=>W2Q,decodeFirst:()=>X2Q});function LR(A,Q,B){if(Q<24)return[Q,1];let w=A.byteLength-B-1,$=new DataView(A.buffer,B+1),I,D=0;switch(Q){case 24:{if(w>0)I=$.getUint8(0),D=2;break}case 25:{if(w>1)I=$.getUint16(0,!1),D=3;break}case 26:{if(w>3)I=$.getUint32(0,!1),D=5;break}case 27:{if(w>7){let Y=$.getBigUint64(0,!1);if(Y>=24n&&Y<=Number.MAX_SAFE_INTEGER)return[Number(Y),9]}break}}if(I&&I>=24)return[I,D];throw Error("Length not supported or not well formed")}var ss=0,nT=1,gfA=2,hfA=3,mfA=4,ufA=5,cfA=6,JH0=7;function ZU(A,Q){let B=A<<5;if(Q<0)throw Error("CBOR Data Item argument must not be negative");let w;if(typeof Q=="number"){if(!Number.isInteger(Q))throw Error("CBOR Data Item argument must be an integer");w=BigInt(Q)}else w=Q;if(A==nT){if(w==0n)throw Error("CBOR Data Item argument cannot be zero when negative");w=w-1n}if(w>18446744073709551615n)throw Error("CBOR number out of range");let $=new Uint8Array(8);if(new DataView($.buffer).setBigUint64(0,w,!1),w<=23)return[B|$[7]];else if(w<=255)return[B|24,$[7]];else if(w<=65535)return[B|25,...$.slice(6)];else if(w<=4294967295)return[B|26,...$.slice(4)];else return[B|27,...$]}class ts{constructor(A,Q){Object.defineProperty(this,"tagId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tagValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tagId=A,this.tagValue=Q}get tag(){return this.tagId}get value(){return this.tagValue}}function GH0(A,Q,B){return LR(A,Q,B)}function pQQ(A,Q,B){let[w,$]=GH0(A,Q,B);return[-w-1,$]}function KH0(A,Q,B){let[w,$]=LR(A,Q,B),I=B+$;return[new Uint8Array(A.buffer.slice(I,I+w)),$+w]}var lQQ=new TextDecoder;function iQQ(A,Q,B){let[w,$]=KH0(A,Q,B);return[lQQ.decode(w),$]}function dQQ(A,Q,B){if(Q===0)return[[],1];let[w,$]=LR(A,Q,B),I=$,D=[];for(let Y=0;Y<w;Y++){if(A.byteLength-B-I<=0)throw Error("array is not supported or well formed");let[W,U]=lq(A,B+I);D.push(W),I+=U}return[D,I]}var as="Map is not supported or well formed";function rQQ(A,Q,B){if(Q===0)return[new Map,1];let[w,$]=LR(A,Q,B),I=$,D=new Map;for(let Y=0;Y<w;Y++){let X=A.byteLength-B-I;if(X<=0)throw Error(as);let[W,U]=lq(A,B+I);if(I+=U,X-=U,X<=0)throw Error(as);if(typeof W!=="string"&&typeof W!=="number")throw Error(as);if(D.has(W))throw Error(as);let[K,F]=lq(A,B+I);I+=F,D.set(W,K)}return[D,I]}function nQQ(A,Q){if(Q+3>A.byteLength)throw Error("CBOR stream ended before end of Float 16");let B=A.getUint16(Q+1,!1);if(B==31744)return[1/0,3];else if(B==32256)return[NaN,3];else if(B==64512)return[-1/0,3];throw Error("Float16 data is unsupported")}function oQQ(A,Q){if(Q+5>A.byteLength)throw Error("CBOR stream ended before end of Float 32");return[A.getFloat32(Q+1,!1),5]}function sQQ(A,Q){if(Q+9>A.byteLength)throw Error("CBOR stream ended before end of Float 64");return[A.getFloat64(Q+1,!1),9]}function aQQ(A,Q,B){let[w,$]=LR(A,Q,B),[I,D]=lq(A,B+$);return[new ts(w,I),$+D]}function lq(A,Q){if(Q>=A.byteLength)throw Error("CBOR stream ended before tag value");let B=A.getUint8(Q),w=B>>5,$=B&31;switch(w){case ss:return GH0(A,$,Q);case nT:return pQQ(A,$,Q);case gfA:return KH0(A,$,Q);case hfA:return iQQ(A,$,Q);case mfA:return dQQ(A,$,Q);case ufA:return rQQ(A,$,Q);case cfA:return aQQ(A,$,Q);case JH0:switch($){case 20:return[!1,1];case 21:return[!0,1];case 22:return[null,1];case 23:return[void 0,1];case 25:return nQQ(A,Q);case 26:return oQQ(A,Q);case 27:return sQQ(A,Q)}}throw Error(`Unsupported or not well formed at ${Q}`)}function tQQ(A){if(A===!0)return 245;else if(A===!1)return 244;else if(A===null)return 246;return 247}function eQQ(A){if(Math.fround(A)==A||!Number.isFinite(A)||Number.isNaN(A)){let Q=new Uint8Array(5);return Q[0]=250,new DataView(Q.buffer).setFloat32(1,A,!1),Q}else{let Q=new Uint8Array(9);return Q[0]=251,new DataView(Q.buffer).setFloat64(1,A,!1),Q}}function A2Q(A){if(typeof A=="number"){if(Number.isSafeInteger(A))if(A<0)return ZU(nT,Math.abs(A));else return ZU(ss,A);return[eQQ(A)]}else if(A<0n)return ZU(nT,A*-1n);else return ZU(ss,A)}var Q2Q=new TextEncoder;function B2Q(A,Q){Q.push(...ZU(hfA,A.length)),Q.push(Q2Q.encode(A))}function w2Q(A,Q){Q.push(...ZU(gfA,A.length)),Q.push(A)}function $2Q(A,Q){Q.push(...ZU(mfA,A.length));for(let B of A)oT(B,Q)}function I2Q(A,Q){Q.push(new Uint8Array(ZU(ufA,A.size)));for(let[B,w]of A.entries())oT(B,Q),oT(w,Q)}function D2Q(A,Q){Q.push(...ZU(cfA,A.tag)),oT(A.value,Q)}function oT(A,Q){if(typeof A=="boolean"||A===null||A==null){Q.push(tQQ(A));return}if(typeof A=="number"||typeof A=="bigint"){Q.push(...A2Q(A));return}if(typeof A=="string"){B2Q(A,Q);return}if(A instanceof Uint8Array){w2Q(A,Q);return}if(Array.isArray(A)){$2Q(A,Q);return}if(A instanceof Map){I2Q(A,Q);return}if(A instanceof ts){D2Q(A,Q);return}throw Error("Not implemented")}function pfA(A,Q){if(A.byteLength===0||A.byteLength<=Q||Q<0)throw Error("No data");if(A instanceof Uint8Array)return lq(new DataView(A.buffer),Q);else if(A instanceof ArrayBuffer)return lq(new DataView(A),Q);return lq(A,Q)}function lfA(A){let Q=[];oT(A,Q);let B=0;for(let I of Q)if(typeof I=="number")B+=1;else B+=I.length;let w=new Uint8Array(B),$=0;for(let I of Q)if(typeof I=="number")w[$]=I,$+=1;else w.set(I,$),$+=I.length;return w}function X2Q(A){let Q=new Uint8Array(A),B=pfA(Q,0),[w]=B;return w}function W2Q(A){return lfA(A)}var NU={};_B(NU,{verify:()=>oK0,getRandomValues:()=>NH0,digest:()=>zH0});function fH0(A){let Q=A.get(cQ.kty);return ifA(Q)&&Q===tI.OKP}function VZ(A){let Q=A.get(cQ.kty);return ifA(Q)&&Q===tI.EC2}function ER(A){let Q=A.get(cQ.kty);return ifA(Q)&&Q===tI.RSA}var cQ;(function(A){A[A.kty=1]="kty",A[A.alg=3]="alg",A[A.crv=-1]="crv",A[A.x=-2]="x",A[A.y=-3]="y",A[A.n=-1]="n",A[A.e=-2]="e"})(cQ||(cQ={}));var tI;(function(A){A[A.OKP=1]="OKP",A[A.EC2=2]="EC2",A[A.RSA=3]="RSA"})(tI||(tI={}));function ifA(A){return Object.values(tI).indexOf(A)>=0}var p9;(function(A){A[A.P256=1]="P256",A[A.P384=2]="P384",A[A.P521=3]="P521",A[A.ED25519=6]="ED25519",A[A.SECP256K1=8]="SECP256K1"})(p9||(p9={}));function FH0(A){return Object.values(p9).indexOf(A)>=0}var G2;(function(A){A[A.ES256=-7]="ES256",A[A.EdDSA=-8]="EdDSA",A[A.ES384=-35]="ES384",A[A.ES512=-36]="ES512",A[A.PS256=-37]="PS256",A[A.PS384=-38]="PS384",A[A.PS512=-39]="PS512",A[A.ES256K=-47]="ES256K",A[A.RS256=-257]="RS256",A[A.RS384=-258]="RS384",A[A.RS512=-259]="RS512",A[A.RS1=-65535]="RS1"})(G2||(G2={}));function zU(A){return Object.values(G2).indexOf(A)>=0}function MZ(A){if([G2.RS1].indexOf(A)>=0)return"SHA-1";else if([G2.ES256,G2.PS256,G2.RS256].indexOf(A)>=0)return"SHA-256";else if([G2.ES384,G2.PS384,G2.RS384].indexOf(A)>=0)return"SHA-384";else if([G2.ES512,G2.PS512,G2.RS512,G2.EdDSA].indexOf(A)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${A} to a WebCrypto alg`)}var sT=void 0;function x4(){return new Promise((Q,B)=>{if(sT)return Q(sT);let w=U2Q.stubThisGlobalThisCrypto();if(w)return sT=w,Q(sT);return B(new ZH0)})}class ZH0 extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}}var U2Q={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(A)=>{sT=A}};async function zH0(A,Q){let B=await x4(),w=MZ(Q),$=await B.subtle.digest(w,A);return new Uint8Array($)}async function NH0(A){return(await x4()).getRandomValues(A),A}async function VR(A){let Q=await x4(),{keyData:B,algorithm:w}=A;return Q.subtle.importKey("jwk",B,w,!1,["verify"])}async function es(A){let{cosePublicKey:Q,signature:B,data:w,shaHashOverride:$}=A,I=await x4(),D=Q.get(cQ.alg),Y=Q.get(cQ.crv),X=Q.get(cQ.x),W=Q.get(cQ.y);if(!D)throw Error("Public key was missing alg (EC2)");if(!Y)throw Error("Public key was missing crv (EC2)");if(!X)throw Error("Public key was missing x (EC2)");if(!W)throw Error("Public key was missing y (EC2)");let U;if(Y===p9.P256)U="P-256";else if(Y===p9.P384)U="P-384";else if(Y===p9.P521)U="P-521";else throw Error(`Unexpected COSE crv value of ${Y} (EC2)`);let K={kty:"EC",crv:U,x:iQ.fromBuffer(X),y:iQ.fromBuffer(W),ext:!1},Z=await VR({keyData:K,algorithm:{name:"ECDSA",namedCurve:U}}),q=MZ(D);if($)q=MZ($);let E={name:"ECDSA",hash:{name:q}};return I.subtle.verify(E,Z,B,w)}function dfA(A){if([G2.EdDSA].indexOf(A)>=0)return"Ed25519";else if([G2.ES256,G2.ES384,G2.ES512,G2.ES256K].indexOf(A)>=0)return"ECDSA";else if([G2.RS256,G2.RS384,G2.RS512,G2.RS1].indexOf(A)>=0)return"RSASSA-PKCS1-v1_5";else if([G2.PS256,G2.PS384,G2.PS512].indexOf(A)>=0)return"RSA-PSS";throw Error(`Could not map COSE alg value of ${A} to a WebCrypto key alg name`)}async function Aa(A){let{cosePublicKey:Q,signature:B,data:w,shaHashOverride:$}=A,I=await x4(),D=Q.get(cQ.alg),Y=Q.get(cQ.n),X=Q.get(cQ.e);if(!D)throw Error("Public key was missing alg (RSA)");if(!zU(D))throw Error(`Public key had invalid alg ${D} (RSA)`);if(!Y)throw Error("Public key was missing n (RSA)");if(!X)throw Error("Public key was missing e (RSA)");let W={kty:"RSA",alg:"",n:iQ.fromBuffer(Y),e:iQ.fromBuffer(X),ext:!1},U={name:dfA(D),hash:{name:MZ(D)}},K={name:dfA(D)};if($)U.hash.name=MZ($);if(U.name==="RSASSA-PKCS1-v1_5"){if(U.hash.name==="SHA-256")W.alg="RS256";else if(U.hash.name==="SHA-384")W.alg="RS384";else if(U.hash.name==="SHA-512")W.alg="RS512";else if(U.hash.name==="SHA-1")W.alg="RS1"}else if(U.name==="RSA-PSS"){let Z=0;if(U.hash.name==="SHA-256")W.alg="PS256",Z=32;else if(U.hash.name==="SHA-384")W.alg="PS384",Z=48;else if(U.hash.name==="SHA-512")W.alg="PS512",Z=64;K.saltLength=Z}else throw Error(`Unexpected RSA key algorithm ${D} (${U.name})`);let F=await VR({keyData:W,algorithm:U});return I.subtle.verify(K,F,B,w)}function Qa(A){let Q=JQ.toHex(A);return[Q.slice(0,8),Q.slice(8,12),Q.slice(12,16),Q.slice(16,20),Q.slice(20,32)].join("-")}function N5(A){let Q;if(typeof A==="string")if(iQ.isBase64URL(A))Q=iQ.toBase64(A);else if(iQ.isBase64(A))Q=A;else throw Error("Certificate is not a valid base64 or base64url string");else Q=iQ.fromBuffer(A,"base64");let B="";for(let w=0;w<Math.ceil(Q.length/64);w+=1){let $=64*w;B+=`${Q.substr($,64)}
|
|
@@ -2316,8 +2316,8 @@ ${R}`)}if(w!==void 0&&I?.algorithms!==void 0){let L=I.algorithms.map((R)=>R.alg)
|
|
|
2316
2316
|
</form>
|
|
2317
2317
|
</main>
|
|
2318
2318
|
</body>
|
|
2319
|
-
</html>`}function BNA(A){return new Response(A,{headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function wNA(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(WF0(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function xt(A){let Q=Pt(A),B=new URL(Q);return{origin:B.origin,rpID:B.hostname}}function xU(A){return A.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}fA();var Tt="email:send",UF0=f.object({to:f.string().email(),subject:f.string().min(1),text:f.string().min(1),html:f.string().min(1).optional(),sensitivity:f.enum(["normal","secret"]).default("normal")}).strict();eA();fA();var JF0={name:"@brains/notifications",private:!0,version:"0.2.0-alpha.
|
|
2320
|
-
`)}}return{to:A.to,subject:FF0(A.subject,Q),body:FF0(A.body,Q)}}function FF0(A,Q){let B=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return A.replaceAll("{{setupUrl}}",Q.setupUrl).replaceAll("{{expiresAt}}",B).replaceAll("{{origin}}",w)}function yg(A){return new DNA(A)}fA();var YNA=f.object({transport:f.enum(["stdio","http"]).default("http"),httpPort:f.number().describe("Port for HTTP transport (only used when transport is 'http')").default(3333),authToken:f.string().describe("Bearer token for HTTP transport authentication").optional()});function ZF0(A,Q){return[]}eA();function XNA(A,Q){A.messaging.subscribe("job-progress",async(B)=>{let w=MC.safeParse(B.payload);if(!w.success)return Q.warn("Received invalid job-progress message",{error:w.error.message}),{success:!1};let $=w.data,I=$.type,D=$.status,Y=$.id;if(Q.debug(`${I} ${Y} - ${D}:`,{id:$.id,message:$.message,progress:$.progress,metadata:$.metadata}),$.batchDetails)Q.debug(`Batch details for ${Y}:`,{totalOperations:$.batchDetails.totalOperations,completedOperations:$.batchDetails.completedOperations,failedOperations:$.batchDetails.failedOperations,currentOperation:$.batchDetails.currentOperation,errors:$.batchDetails.errors});if($.jobDetails)Q.debug(`Job details for ${Y}:`,{jobType:$.jobDetails.jobType,priority:$.jobDetails.priority,retryCount:$.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var zF0={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.92",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/auth-service":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@modelcontextprotocol/sdk":"^1.24.0",cors:"^2.8.5",express:"^4.18.0","express-async-handler":"^1.2.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/cors":"^2.8.17","@types/express":"^4.17.21",typescript:"^5.3.3"}};class eZ extends nH{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",zF0,Q,YNA)}async getTools(){return ZF0(this.id,()=>this.context)}async getResources(){return[]}async onRegister(A){if(this.domain=A.domain,this.config.transport==="http"&&!A.plugins.has("webserver"))throw Error("MCP HTTP transport requires the webserver interface. Standalone HTTP listeners have been removed.");if(this.logger.debug(`MCP interface initialized with ${this.config.transport} transport`),this.config.transport==="http")A.endpoints.register({label:"MCP",url:"/mcp",priority:30,visibility:"trusted"}),A.interactions.register({id:"mcp",label:"MCP",description:"Connect a trusted client through the Model Context Protocol.",href:"/mcp",kind:"protocol",priority:30,visibility:"trusted"});XNA(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=MK();return this.httpServer=aG.createFresh({port:this.config.httpPort,logger:this.logger,auth:this.config.authToken?{token:this.config.authToken}:A?{requiredScopes:["mcp"],verifyBearerToken:async(Q)=>A.verifyBearerToken(Q)}:{disabled:!0}}),this.httpServer}getWebRoutes(){if(this.config.transport!=="http")return[];let A=(Q)=>this.getOrCreateHttpServer().handleRequest(Q);return[{path:"/status",method:"GET",public:!0,handler:A},{path:"/mcp",method:"GET",public:!0,handler:A},{path:"/mcp",method:"POST",public:!0,handler:A},{path:"/mcp",method:"DELETE",public:!0,handler:A},{path:"/mcp",method:"OPTIONS",public:!0,handler:A}]}createDaemon(){return{start:async()=>{await this.startServer()},stop:async()=>{await this.stopServer()},healthCheck:async()=>{let A=this.isServerRunning(),Q="MCP server not running";if(A)if(this.config.transport==="http")Q=`MCP HTTP: ${this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp"}`;else Q="MCP stdio server running";return{status:A?"healthy":"error",message:Q,lastCheck:new Date,details:{transport:this.config.transport,url:this.config.transport==="http"?this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp":void 0,running:A}}}}}isServerRunning(){if(this.config.transport==="stdio")return this.stdioServer!==void 0&&this.mcpTransport!==void 0;else return this.httpServer!==void 0&&this.mcpTransport!==void 0}async startServer(){if(!this.context)throw Error("Context not initialized");let A=this.context;this.mcpTransport=A.mcpTransport;let Q=this.config.transport==="stdio"?"stdio":"http",B=this.context.permissions.getUserLevel("mcp",Q);if(this.config.transport==="http"&&(this.config.authToken||MK()))B="anchor",this.logger.debug("HTTP authentication configured - authenticated users will have anchor permissions");if(this.mcpTransport.setPermissionLevel(B),this.logger.debug(`Starting MCP ${this.config.transport} transport with ${B} permissions`),this.config.transport==="stdio"){this.stdioServer=HW.createFresh();let w=this.mcpTransport.getMcpServer();this.stdioServer.connectMCPServer(w),await this.stdioServer.start(),this.logger.debug("MCP STDIO transport started")}else{this.httpServer=this.getOrCreateHttpServer();let w=this.mcpTransport.getMcpServer();this.httpServer.connectMCPServer(w,this.mcpTransport),this.httpServer.connectAgentService(A.agent),this.logger.debug("MCP HTTP transport mounted on shared webserver host")}}async stopServer(){if(this.logger.debug(`Stopping MCP ${this.config.transport} transport`),this.stdioServer)this.stdioServer.stop(),this.stdioServer=void 0;if(this.httpServer)await this.httpServer.stop(),this.httpServer=void 0;this.mcpTransport=void 0}async handleProgressEvent(A,Q){}async onShutdown(){HW.resetInstance(),aG.resetInstance()}}eA();fA();var SY=X1(Xd0(),1);fA();eA();var pMA=f.object({botToken:f.string().min(1).describe("Discord bot token"),allowedChannels:f.array(f.string()).default([]),requireMention:f.boolean().default(!0),allowDMs:f.boolean().default(!0),showTypingIndicator:f.boolean().default(!0),statusMessage:f.string().default("Mention me to chat"),useThreads:f.boolean().default(!0),threadAutoArchive:f.union([f.literal(60),f.literal(1440),f.literal(4320),f.literal(10080)]).default(1440),...Zx.shape,captureUrlEmoji:f.string().default("\uD83D\uDD16")});var Wd0={name:"@brains/discord",private:!0,version:"0.2.0-alpha.92",description:"Discord interface for Brains",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",test:"bun test"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","discord.js":"^14.14.1"},devDependencies:{"@brains/core":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest"}};var lMA=2000,NxQ=8000,qxQ=100;function u0A(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class xz extends bG{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",Wd0,A,pMA);this.fetchText=Q.fetchText??Qd}async onRegister(A){await super.onRegister(A),this.client=new SY.Client({intents:[SY.GatewayIntentBits.Guilds,SY.GatewayIntentBits.GuildMessages,SY.GatewayIntentBits.MessageContent,SY.GatewayIntentBits.DirectMessages],partials:[SY.Partials.Channel]}),this.client.on(SY.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.once(SY.Events.ClientReady,()=>{this.logger.info("Discord bot connected",{tag:this.client?.user?.tag})})}createDaemon(){return{start:async()=>{if(!this.client)throw Error("Discord client not initialized");await this.client.login(this.config.botToken)},stop:async()=>{for(let A of this.typingIntervals.values())clearInterval(A);if(this.typingIntervals.clear(),this.client)await this.client.destroy(),this.client=null},healthCheck:async()=>({status:this.client?.user?"healthy":"error",message:this.client?.user?`Connected as ${this.client.user.tag}`:"Not connected",lastCheck:new Date})}}sendMessageToChannel({channelId:A,message:Q}){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!u0A(B))return;let w=Ev(Q,lMA);for(let $ of w)B.send($).catch((I)=>this.logger.error("Failed to send message",{error:I}))}async sendMessageWithId({channelId:A,message:Q}){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!u0A(B))return;let w=Ev(Q,lMA),$;for(let I of w)$=(await B.send(I)).id;return $}async editMessage({channelId:A,messageId:Q,newMessage:B}){if(!A||!this.client)return!1;let w=this.client.channels.cache.get(A);if(!u0A(w))return!1;try{return await(await w.messages.fetch(Q)).edit(B.slice(0,lMA)),!0}catch{return!1}}supportsMessageEditing(){return!0}async handleMessage(A){if(A.author.id===this.client?.user?.id)return;if(!this.context)return;let Q=!A.guild,B=A.channel.isThread();if(Q&&!this.config.allowDMs)return;let w=!!this.client?.user&&A.mentions.has(this.client.user,{ignoreEveryone:!0});if(A.author.bot&&!w)return;let $=B&&"ownerId"in A.channel&&A.channel.ownerId===this.client?.user?.id,I=this.getSpaceChannelId(A),D=!Q&&this.isConfiguredSpace(I),Y={channelId:I,isBot:A.author.bot};if(this.config.allowedChannels.length>0&&!Q&&!this.isAllowedChannel(A.channel.id,I))return;let X=Q||$||!this.config.requireMention||w;if(D&&(!X||this.willRouteUseNonSpaceConversation(A)))await this.capturePassiveSpaceMessage(A,I).catch((K)=>this.logger.error("Passive Discord space capture failed",{error:K,channelId:I}));if(!X){if(this.config.captureUrls){let K=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(K.length>0){await A.react(this.config.captureUrlEmoji).catch((F)=>this.logger.debug("React failed",{error:F}));for(let F of K)await this.captureUrlViaAgent(F,A.channel.id,A.author.id,"discord",Y).catch((Z)=>this.logger.error("URL capture failed",{error:Z,url:F}))}}return}let W=this.stripMention(A.content);if(A.attachments.size>0){let K=this.context.permissions.getUserLevel("discord",A.author.id,Y);if(K==="anchor"||K==="trusted")for(let Z of A.attachments.values()){let q=Z.name,E=Z.contentType??void 0,L=Z.size;if(!this.isUploadableTextFile(q,E))continue;if(!this.isFileSizeAllowed(L))continue;try{let R=await this.fetchText(Z.url);W+=`
|
|
2319
|
+
</html>`}function BNA(A){return new Response(A,{headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function wNA(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(WF0(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function xt(A){let Q=Pt(A),B=new URL(Q);return{origin:B.origin,rpID:B.hostname}}function xU(A){return A.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}fA();var Tt="email:send",UF0=f.object({to:f.string().email(),subject:f.string().min(1),text:f.string().min(1),html:f.string().min(1).optional(),sensitivity:f.enum(["normal","secret"]).default("normal")}).strict();eA();fA();var JF0={name:"@brains/notifications",private:!0,version:"0.2.0-alpha.93",description:"Generic notification routing for transactional and administrative messages",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var INA="notifications:send",s8Q=f.object({}),a8Q=f.discriminatedUnion("type",[f.object({type:f.literal("email"),address:f.string().email()}).strict()]),t8Q=f.object({recipient:a8Q,title:f.string().min(1),body:f.string().min(1),html:f.string().min(1).optional(),sensitivity:f.enum(["normal","secret"]).default("normal")}).strict(),GF0=f.discriminatedUnion("status",[f.object({status:f.literal("sent"),deliveryId:f.string().optional()}).strict(),f.object({status:f.literal("failed")}).strict()]);class KF0 extends qB{constructor(A={}){super("notifications",JF0,A,s8Q)}async onRegister(A){A.messaging.subscribe(INA,async(Q)=>{let B=t8Q.parse(Q.payload),w={to:B.recipient.address,subject:B.title,text:B.body,...B.html?{html:B.html}:{},sensitivity:B.sensitivity},$=await A.messaging.send({type:Tt,payload:w});if(!("success"in $)||!$.success||!$.data)return{success:!1,error:"Notification delivery failed"};let I=$.data;if(I.status!=="sent")return{success:!1,error:"Notification delivery failed"};return{success:!0,data:I.id?{status:"sent",deliveryId:I.id}:{status:"sent"}}})}}function St(A={}){return new KF0(A)}eA();fA();var fF0={name:"@brains/auth-service",private:!0,version:"0.2.0-alpha.93",description:"Embedded OAuth/OIDC auth service for brain operator authentication",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@simplewebauthn/server":"^13.3.0",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},files:["src"]};var A6Q=f.union([f.string().email(),f.object({to:f.string().email(),subject:f.string().min(1),body:f.string().min(1)}).strict()]),Q6Q=f.object({issuer:f.string().optional(),trustedIssuers:f.array(f.string()).default([]),allowLocalhostIssuers:f.boolean().optional(),storageDir:f.string().default("./data/auth"),setupEmail:A6Q.optional()}),B6Q=f.object({}),gt;function MK(){return gt}class DNA extends qB{service;constructor(A={}){super("auth-service",fF0,A,Q6Q)}async onRegister(A){await super.onRegister(A);let Q=this.config.issuer??(A.preferLocalUrls?A.localSiteUrl??A.siteUrl:A.siteUrl??A.localSiteUrl);this.service=new yt({storageDir:this.config.storageDir,...Q?{issuer:Q}:{},trustedIssuers:this.config.trustedIssuers,...this.config.allowLocalhostIssuers!==void 0?{allowLocalhostIssuers:this.config.allowLocalhostIssuers}:{},logger:A.logger}),await this.service.initialize(),gt=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(gt===this.service)gt=void 0;this.service=void 0}async getTools(){return[j2(this.id,"get_passkey_setup_url","Get the first-passkey setup URL when operator setup is required. Anchor-only.",B6Q,async()=>{let A=this.getService();if(await A.hasPasskeyCredentials())return J8({status:"complete"});let Q=await A.getOperatorSetupRequired();if(Q)return J8({status:"setup_required",setupUrl:Q.setupUrl,expiresAt:Q.expiresAt});return J8({status:"unavailable",reason:"Passkey setup URL is not available."})},{visibility:"anchor"})]}getWebRoutes(){let A=(Q)=>this.getService().handleRequest(Q);return[{path:"/.well-known/oauth-authorization-server",method:"GET",public:!0,handler:A},{path:"/.well-known/oauth-authorization-server",method:"OPTIONS",public:!0,handler:A},{path:"/.well-known/jwks.json",method:"GET",public:!0,handler:A},{path:"/.well-known/jwks.json",method:"OPTIONS",public:!0,handler:A},{path:"/.well-known/oauth-protected-resource",method:"GET",public:!0,handler:A},{path:"/.well-known/oauth-protected-resource",method:"OPTIONS",public:!0,handler:A},{path:"/setup",method:"GET",public:!0,handler:A},{path:"/login",method:"GET",public:!0,handler:A},{path:"/logout",method:"GET",public:!0,handler:A},{path:"/logout",method:"POST",public:!0,handler:A},{path:"/authorize",method:"GET",public:!0,handler:A},{path:"/authorize",method:"POST",public:!0,handler:A},{path:"/register",method:"POST",public:!0,handler:A},{path:"/register",method:"OPTIONS",public:!0,handler:A},{path:"/token",method:"POST",public:!0,handler:A},{path:"/token",method:"OPTIONS",public:!0,handler:A},{path:"/revoke",method:"POST",public:!0,handler:A},{path:"/revoke",method:"OPTIONS",public:!0,handler:A},{path:"/webauthn/register/options",method:"POST",public:!0,handler:A},{path:"/webauthn/register/verify",method:"POST",public:!0,handler:A},{path:"/webauthn/auth/options",method:"POST",public:!0,handler:A},{path:"/webauthn/auth/verify",method:"POST",public:!0,handler:A}]}getService(){if(!this.service)throw Error("AuthServicePlugin has not been registered");return this.service}async requestSetupEmailIfNeeded(A){if(!this.config.setupEmail)return;let Q=this.getService();if(await Q.hasPasskeyCredentials())return;let B=await Q.getOperatorSetupRequired();if(!B)return;let w=w6Q(this.config.setupEmail,B);if(await Q.hasSetupEmailDelivery(B.setupTokenId,w.to))return;let $=await A.messaging.send({type:INA,payload:{recipient:{type:"email",address:w.to},title:w.subject,body:w.body,sensitivity:"secret"}});if(!("success"in $)||!$.success||!$.data){A.logger.warn("Passkey setup email delivery was not confirmed");return}let I=GF0.safeParse($.data);if(!I.success||I.data.status!=="sent"){A.logger.warn("Passkey setup email delivery was not confirmed");return}await Q.recordSetupEmailDelivery(B.setupTokenId,w.to,I.data.deliveryId?{deliveryId:I.data.deliveryId}:{})}}function w6Q(A,Q){if(typeof A==="string"){let B=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return{to:A,subject:"Set up your brain passkey",body:["Set up your brain passkey using this single-use link:","",Q.setupUrl,"",`This link expires at ${B}.`,`Dashboard: ${w}/`,`MCP endpoint: ${w}/mcp`,"The first successful passkey registration completes setup and closes this link."].join(`
|
|
2320
|
+
`)}}return{to:A.to,subject:FF0(A.subject,Q),body:FF0(A.body,Q)}}function FF0(A,Q){let B=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return A.replaceAll("{{setupUrl}}",Q.setupUrl).replaceAll("{{expiresAt}}",B).replaceAll("{{origin}}",w)}function yg(A){return new DNA(A)}fA();var YNA=f.object({transport:f.enum(["stdio","http"]).default("http"),httpPort:f.number().describe("Port for HTTP transport (only used when transport is 'http')").default(3333),authToken:f.string().describe("Bearer token for HTTP transport authentication").optional()});function ZF0(A,Q){return[]}eA();function XNA(A,Q){A.messaging.subscribe("job-progress",async(B)=>{let w=MC.safeParse(B.payload);if(!w.success)return Q.warn("Received invalid job-progress message",{error:w.error.message}),{success:!1};let $=w.data,I=$.type,D=$.status,Y=$.id;if(Q.debug(`${I} ${Y} - ${D}:`,{id:$.id,message:$.message,progress:$.progress,metadata:$.metadata}),$.batchDetails)Q.debug(`Batch details for ${Y}:`,{totalOperations:$.batchDetails.totalOperations,completedOperations:$.batchDetails.completedOperations,failedOperations:$.batchDetails.failedOperations,currentOperation:$.batchDetails.currentOperation,errors:$.batchDetails.errors});if($.jobDetails)Q.debug(`Job details for ${Y}:`,{jobType:$.jobDetails.jobType,priority:$.jobDetails.priority,retryCount:$.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var zF0={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.93",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/auth-service":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@modelcontextprotocol/sdk":"^1.24.0",cors:"^2.8.5",express:"^4.18.0","express-async-handler":"^1.2.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/cors":"^2.8.17","@types/express":"^4.17.21",typescript:"^5.3.3"}};class eZ extends nH{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",zF0,Q,YNA)}async getTools(){return ZF0(this.id,()=>this.context)}async getResources(){return[]}async onRegister(A){if(this.domain=A.domain,this.config.transport==="http"&&!A.plugins.has("webserver"))throw Error("MCP HTTP transport requires the webserver interface. Standalone HTTP listeners have been removed.");if(this.logger.debug(`MCP interface initialized with ${this.config.transport} transport`),this.config.transport==="http")A.endpoints.register({label:"MCP",url:"/mcp",priority:30,visibility:"trusted"}),A.interactions.register({id:"mcp",label:"MCP",description:"Connect a trusted client through the Model Context Protocol.",href:"/mcp",kind:"protocol",priority:30,visibility:"trusted"});XNA(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=MK();return this.httpServer=aG.createFresh({port:this.config.httpPort,logger:this.logger,auth:this.config.authToken?{token:this.config.authToken}:A?{requiredScopes:["mcp"],verifyBearerToken:async(Q)=>A.verifyBearerToken(Q)}:{disabled:!0}}),this.httpServer}getWebRoutes(){if(this.config.transport!=="http")return[];let A=(Q)=>this.getOrCreateHttpServer().handleRequest(Q);return[{path:"/status",method:"GET",public:!0,handler:A},{path:"/mcp",method:"GET",public:!0,handler:A},{path:"/mcp",method:"POST",public:!0,handler:A},{path:"/mcp",method:"DELETE",public:!0,handler:A},{path:"/mcp",method:"OPTIONS",public:!0,handler:A}]}createDaemon(){return{start:async()=>{await this.startServer()},stop:async()=>{await this.stopServer()},healthCheck:async()=>{let A=this.isServerRunning(),Q="MCP server not running";if(A)if(this.config.transport==="http")Q=`MCP HTTP: ${this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp"}`;else Q="MCP stdio server running";return{status:A?"healthy":"error",message:Q,lastCheck:new Date,details:{transport:this.config.transport,url:this.config.transport==="http"?this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp":void 0,running:A}}}}}isServerRunning(){if(this.config.transport==="stdio")return this.stdioServer!==void 0&&this.mcpTransport!==void 0;else return this.httpServer!==void 0&&this.mcpTransport!==void 0}async startServer(){if(!this.context)throw Error("Context not initialized");let A=this.context;this.mcpTransport=A.mcpTransport;let Q=this.config.transport==="stdio"?"stdio":"http",B=this.context.permissions.getUserLevel("mcp",Q);if(this.config.transport==="http"&&(this.config.authToken||MK()))B="anchor",this.logger.debug("HTTP authentication configured - authenticated users will have anchor permissions");if(this.mcpTransport.setPermissionLevel(B),this.logger.debug(`Starting MCP ${this.config.transport} transport with ${B} permissions`),this.config.transport==="stdio"){this.stdioServer=HW.createFresh();let w=this.mcpTransport.getMcpServer();this.stdioServer.connectMCPServer(w),await this.stdioServer.start(),this.logger.debug("MCP STDIO transport started")}else{this.httpServer=this.getOrCreateHttpServer();let w=this.mcpTransport.getMcpServer();this.httpServer.connectMCPServer(w,this.mcpTransport),this.httpServer.connectAgentService(A.agent),this.logger.debug("MCP HTTP transport mounted on shared webserver host")}}async stopServer(){if(this.logger.debug(`Stopping MCP ${this.config.transport} transport`),this.stdioServer)this.stdioServer.stop(),this.stdioServer=void 0;if(this.httpServer)await this.httpServer.stop(),this.httpServer=void 0;this.mcpTransport=void 0}async handleProgressEvent(A,Q){}async onShutdown(){HW.resetInstance(),aG.resetInstance()}}eA();fA();var SY=X1(Xd0(),1);fA();eA();var pMA=f.object({botToken:f.string().min(1).describe("Discord bot token"),allowedChannels:f.array(f.string()).default([]),requireMention:f.boolean().default(!0),allowDMs:f.boolean().default(!0),showTypingIndicator:f.boolean().default(!0),statusMessage:f.string().default("Mention me to chat"),useThreads:f.boolean().default(!0),threadAutoArchive:f.union([f.literal(60),f.literal(1440),f.literal(4320),f.literal(10080)]).default(1440),...Zx.shape,captureUrlEmoji:f.string().default("\uD83D\uDD16")});var Wd0={name:"@brains/discord",private:!0,version:"0.2.0-alpha.93",description:"Discord interface for Brains",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",test:"bun test"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","discord.js":"^14.14.1"},devDependencies:{"@brains/core":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest"}};var lMA=2000,NxQ=8000,qxQ=100;function u0A(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class xz extends bG{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",Wd0,A,pMA);this.fetchText=Q.fetchText??Qd}async onRegister(A){await super.onRegister(A),this.client=new SY.Client({intents:[SY.GatewayIntentBits.Guilds,SY.GatewayIntentBits.GuildMessages,SY.GatewayIntentBits.MessageContent,SY.GatewayIntentBits.DirectMessages],partials:[SY.Partials.Channel]}),this.client.on(SY.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.once(SY.Events.ClientReady,()=>{this.logger.info("Discord bot connected",{tag:this.client?.user?.tag})})}createDaemon(){return{start:async()=>{if(!this.client)throw Error("Discord client not initialized");await this.client.login(this.config.botToken)},stop:async()=>{for(let A of this.typingIntervals.values())clearInterval(A);if(this.typingIntervals.clear(),this.client)await this.client.destroy(),this.client=null},healthCheck:async()=>({status:this.client?.user?"healthy":"error",message:this.client?.user?`Connected as ${this.client.user.tag}`:"Not connected",lastCheck:new Date})}}sendMessageToChannel({channelId:A,message:Q}){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!u0A(B))return;let w=Ev(Q,lMA);for(let $ of w)B.send($).catch((I)=>this.logger.error("Failed to send message",{error:I}))}async sendMessageWithId({channelId:A,message:Q}){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!u0A(B))return;let w=Ev(Q,lMA),$;for(let I of w)$=(await B.send(I)).id;return $}async editMessage({channelId:A,messageId:Q,newMessage:B}){if(!A||!this.client)return!1;let w=this.client.channels.cache.get(A);if(!u0A(w))return!1;try{return await(await w.messages.fetch(Q)).edit(B.slice(0,lMA)),!0}catch{return!1}}supportsMessageEditing(){return!0}async handleMessage(A){if(A.author.id===this.client?.user?.id)return;if(!this.context)return;let Q=!A.guild,B=A.channel.isThread();if(Q&&!this.config.allowDMs)return;let w=!!this.client?.user&&A.mentions.has(this.client.user,{ignoreEveryone:!0});if(A.author.bot&&!w)return;let $=B&&"ownerId"in A.channel&&A.channel.ownerId===this.client?.user?.id,I=this.getSpaceChannelId(A),D=!Q&&this.isConfiguredSpace(I),Y={channelId:I,isBot:A.author.bot};if(this.config.allowedChannels.length>0&&!Q&&!this.isAllowedChannel(A.channel.id,I))return;let X=Q||$||!this.config.requireMention||w;if(D&&(!X||this.willRouteUseNonSpaceConversation(A)))await this.capturePassiveSpaceMessage(A,I).catch((K)=>this.logger.error("Passive Discord space capture failed",{error:K,channelId:I}));if(!X){if(this.config.captureUrls){let K=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(K.length>0){await A.react(this.config.captureUrlEmoji).catch((F)=>this.logger.debug("React failed",{error:F}));for(let F of K)await this.captureUrlViaAgent(F,A.channel.id,A.author.id,"discord",Y).catch((Z)=>this.logger.error("URL capture failed",{error:Z,url:F}))}}return}let W=this.stripMention(A.content);if(A.attachments.size>0){let K=this.context.permissions.getUserLevel("discord",A.author.id,Y);if(K==="anchor"||K==="trusted")for(let Z of A.attachments.values()){let q=Z.name,E=Z.contentType??void 0,L=Z.size;if(!this.isUploadableTextFile(q,E))continue;if(!this.isFileSizeAllowed(L))continue;try{let R=await this.fetchText(Z.url);W+=`
|
|
2321
2321
|
|
|
2322
2322
|
`+this.formatFileUploadMessage(q,R)}catch(R){this.logger.error("Failed to download attachment",{error:R,filename:q})}}}if(W=W.trim(),!W)return;let U=A.channel.id;await this.routeToAgent(W,U,A,Y)}async capturePassiveSpaceMessage(A,Q){if(!this.context)return;let B=this.stripMention(A.content).trim();if(!B)return;let w=`discord-${Q}`,$=this.getChannelName(A);await this.context.conversations.start({sessionId:w,interfaceType:"discord",channelId:Q,metadata:{channelName:$,interfaceType:"discord",channelId:Q}}),await this.context.conversations.addMessage({conversationId:w,role:"user",content:B,metadata:this.buildUserMessageMetadata(A,Q,$,{threadId:A.channel.isThread()?A.channel.id:void 0})})}async routeToAgent(A,Q,B,w){if(!this.context)return;let $=this.context.agent,I=Q;if(this.config.useThreads&&B.guild&&!B.channel.isThread())try{I=(await B.startThread({name:hH(A,qxQ),autoArchiveDuration:this.config.threadAutoArchive})).id}catch(W){this.logger.error("Failed to create thread",{error:W})}let D=`discord-${I}`,Y=this.context.permissions.getUserLevel("discord",B.author.id,w),X=this.getChannelName(B);this.startProcessingInput(I);try{let W=this.client?.channels.cache.get(I);if(u0A(W))this.startTypingIndicator(W);if(this.pendingConfirmations.has(D)){await this.handleConfirmationResponse(A,D,I);return}let U=await $.chat(A,D,{userPermissionLevel:Y,interfaceType:"discord",channelId:I,channelName:X,...this.buildUserMessageMetadata(B,Q,X,{threadId:I!==Q||B.channel.isThread()?I:void 0})});if(U.pendingConfirmation)this.pendingConfirmations.set(D,!0);let K=await this.sendMessageWithId({channelId:I,message:U.text});if(K&&U.toolResults){for(let F of U.toolResults)if(F.jobId)this.trackAgentResponseForJob(F.jobId,K,I)}}catch(W){this.logger.error("Error handling message",{error:W,channelId:I}),this.sendMessageToChannel({channelId:I,message:`**Error:** ${W instanceof Error?W.message:"Unknown error"}`})}finally{this.endProcessingInput(),this.stopTypingIndicator(I)}}async handleConfirmationResponse(A,Q,B){let w=hC(A);if(!w){this.sendMessageToChannel({channelId:B,message:"_Please reply with **yes** to confirm or **no/cancel** to abort._"});return}this.pendingConfirmations.delete(Q);let $=await this.context?.agent.confirmPendingAction(Q,w.confirmed);if($)await this.sendMessageWithId({channelId:B,message:$.text})}startTypingIndicator(A){if(!this.config.showTypingIndicator)return;A.sendTyping().catch((B)=>this.logger.debug("Typing indicator failed",{error:B}));let Q=setInterval(()=>{A.sendTyping().catch((B)=>this.logger.debug("Typing indicator failed",{error:B}))},NxQ);this.typingIntervals.set(A.id,Q)}stopTypingIndicator(A){let Q=this.typingIntervals.get(A);if(Q)clearInterval(Q),this.typingIntervals.delete(A)}getAuthorDisplayName(A){return A.member?.displayName??A.author.globalName??A.author.username}getChannelName(A){return A.guild?.name??"DM"}getSpaceChannelId(A){if(!A.channel.isThread())return A.channel.id;if("parentId"in A.channel&&typeof A.channel.parentId==="string")return A.channel.parentId;if("parent"in A.channel&&A.channel.parent&&typeof A.channel.parent==="object"&&"id"in A.channel.parent&&typeof A.channel.parent.id==="string")return A.channel.parent.id;return A.channel.id}isConfiguredSpace(A){let Q=`discord:${A}`;return this.context?.spaces.some((B)=>qG(B,Q))??!1}isAllowedChannel(A,Q){return this.config.allowedChannels.includes(A)||this.config.allowedChannels.includes(Q)}willRouteUseNonSpaceConversation(A){if(A.channel.isThread())return this.getSpaceChannelId(A)!==A.channel.id;return this.config.useThreads&&Boolean(A.guild)}buildUserMessageMetadata(A,Q,B,w={}){return{actor:{actorId:`discord:${A.author.id}`,interfaceType:"discord",role:"user",displayName:this.getAuthorDisplayName(A),username:A.author.username,isBot:Boolean(A.author.bot)},source:{messageId:A.id,channelId:Q,channelName:B,...w.threadId?{threadId:w.threadId}:{},metadata:{...A.guild?.id?{guildId:A.guild.id}:{},...A.guild?.name?{guildName:A.guild.name}:{}}}}}stripMention(A){if(!this.client?.user)return A;return A.replace(new RegExp(`<@!?${this.client.user.id}>`,"g"),"").trim()}}eA();import{resolve as iP,join as DyQ}from"path";var iMA=(A,Q,B)=>{return(w,$)=>{let I=-1;return D(0);async function D(Y){if(Y<=I)throw Error("next() called multiple times");I=Y;let X,W=!1,U;if(A[Y])U=A[Y][0][0],w.req.routeIndex=Y;else U=Y===A.length&&$||void 0;if(U)try{X=await U(w,()=>D(Y+1))}catch(K){if(K instanceof Error&&Q)w.error=K,X=await Q(K,w),W=!0;else throw K}else if(w.finalized===!1&&B)X=await B(w);if(X&&(w.finalized===!1||W))w.res=X;return w}}};var Hd0=Symbol();var Ud0=async(A,Q=Object.create(null))=>{let{all:B=!1,dot:w=!1}=Q,I=(A instanceof c0A?A.raw.headers:A.headers).get("Content-Type");if(I?.startsWith("multipart/form-data")||I?.startsWith("application/x-www-form-urlencoded"))return LxQ(A,{all:B,dot:w});return{}};async function LxQ(A,Q){let B=await A.formData();if(B)return ExQ(B,Q);return{}}function ExQ(A,Q){let B=Object.create(null);if(A.forEach((w,$)=>{if(!(Q.all||$.endsWith("[]")))B[$]=w;else VxQ(B,$,w)}),Q.dot)Object.entries(B).forEach(([w,$])=>{if(w.includes("."))MxQ(B,w,$),delete B[w]});return B}var VxQ=(A,Q,B)=>{if(A[Q]!==void 0)if(Array.isArray(A[Q]))A[Q].push(B);else A[Q]=[A[Q],B];else if(!Q.endsWith("[]"))A[Q]=B;else A[Q]=[B]},MxQ=(A,Q,B)=>{let w=A,$=Q.split(".");$.forEach((I,D)=>{if(D===$.length-1)w[I]=B;else{if(!w[I]||typeof w[I]!=="object"||Array.isArray(w[I])||w[I]instanceof File)w[I]=Object.create(null);w=w[I]}})};var rMA=(A)=>{let Q=A.split("/");if(Q[0]==="")Q.shift();return Q},Jd0=(A)=>{let{groups:Q,path:B}=CxQ(A),w=rMA(B);return OxQ(w,Q)},CxQ=(A)=>{let Q=[];return A=A.replace(/\{[^}]+\}/g,(B,w)=>{let $=`@${w}`;return Q.push([$,B]),$}),{groups:Q,path:A}},OxQ=(A,Q)=>{for(let B=Q.length-1;B>=0;B--){let[w]=Q[B];for(let $=A.length-1;$>=0;$--)if(A[$].includes(w)){A[$]=A[$].replace(w,Q[B][1]);break}}return A},p0A={},Gd0=(A,Q)=>{if(A==="*")return"*";let B=A.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(B){let w=`${A}#${Q}`;if(!p0A[w])if(B[2])p0A[w]=Q&&Q[0]!==":"&&Q[0]!=="*"?[w,B[1],new RegExp(`^${B[2]}(?=/${Q})`)]:[A,B[1],new RegExp(`^${B[2]}$`)];else p0A[w]=[A,B[1],!0];return p0A[w]}return null},l0A=(A,Q)=>{try{return Q(A)}catch{return A.replace(/(?:%[0-9A-Fa-f]{2})+/g,(B)=>{try{return Q(B)}catch{return B}})}},nMA=(A)=>l0A(A,decodeURI),oMA=(A)=>{let Q=A.url,B=Q.indexOf("/",Q.indexOf(":")+4),w=B;for(;w<Q.length;w++){let $=Q.charCodeAt(w);if($===37){let I=Q.indexOf("?",w),D=Q.indexOf("#",w),Y=I===-1?D===-1?void 0:D:D===-1?I:Math.min(I,D),X=Q.slice(B,Y);return nMA(X.includes("%25")?X.replace(/%25/g,"%2525"):X)}else if($===63||$===35)break}return Q.slice(B,w)};var Kd0=(A)=>{let Q=oMA(A);return Q.length>1&&Q.at(-1)==="/"?Q.slice(0,-1):Q},zE=(A,Q,...B)=>{if(B.length)Q=zE(Q,...B);return`${A?.[0]==="/"?"":"/"}${A}${Q==="/"?"":`${A?.at(-1)==="/"?"":"/"}${Q?.[0]==="/"?Q.slice(1):Q}`}`},i0A=(A)=>{if(A.charCodeAt(A.length-1)!==63||!A.includes(":"))return null;let Q=A.split("/"),B=[],w="";return Q.forEach(($)=>{if($!==""&&!/\:/.test($))w+="/"+$;else if(/\:/.test($))if(/\?/.test($)){if(B.length===0&&w==="")B.push("/");else B.push(w);let I=$.replace("?","");w+="/"+I,B.push(w)}else w+="/"+$}),B.filter(($,I,D)=>D.indexOf($)===I)},dMA=(A)=>{if(!/[%+]/.test(A))return A;if(A.indexOf("+")!==-1)A=A.replace(/\+/g," ");return A.indexOf("%")!==-1?l0A(A,sMA):A},fd0=(A,Q,B)=>{let w;if(!B&&Q&&!/[%+]/.test(Q)){let D=A.indexOf("?",8);if(D===-1)return;if(!A.startsWith(Q,D+1))D=A.indexOf(`&${Q}`,D+1);while(D!==-1){let Y=A.charCodeAt(D+Q.length+1);if(Y===61){let X=D+Q.length+2,W=A.indexOf("&",X);return dMA(A.slice(X,W===-1?void 0:W))}else if(Y==38||isNaN(Y))return"";D=A.indexOf(`&${Q}`,D+1)}if(w=/[%+]/.test(A),!w)return}let $={};w??=/[%+]/.test(A);let I=A.indexOf("?",8);while(I!==-1){let D=A.indexOf("&",I+1),Y=A.indexOf("=",I);if(Y>D&&D!==-1)Y=-1;let X=A.slice(I+1,Y===-1?D===-1?void 0:D:Y);if(w)X=dMA(X);if(I=D,X==="")continue;let W;if(Y===-1)W="";else if(W=A.slice(Y+1,D===-1?void 0:D),w)W=dMA(W);if(B){if(!($[X]&&Array.isArray($[X])))$[X]=[];$[X].push(W)}else $[X]??=W}return Q?$[Q]:$},Fd0=fd0,Zd0=(A,Q)=>{return fd0(A,Q,!0)},sMA=decodeURIComponent;var zd0=(A)=>l0A(A,sMA),c0A=class{raw;#A;#Q;routeIndex=0;path;bodyCache={};constructor(A,Q="/",B=[[]]){this.raw=A,this.path=Q,this.#Q=B,this.#A={}}param(A){return A?this.#B(A):this.#I()}#B(A){let Q=this.#Q[0][this.routeIndex][1][A],B=this.#$(Q);return B&&/\%/.test(B)?zd0(B):B}#I(){let A={},Q=Object.keys(this.#Q[0][this.routeIndex][1]);for(let B of Q){let w=this.#$(this.#Q[0][this.routeIndex][1][B]);if(w!==void 0)A[B]=/\%/.test(w)?zd0(w):w}return A}#$(A){return this.#Q[1]?this.#Q[1][A]:A}query(A){return Fd0(this.url,A)}queries(A){return Zd0(this.url,A)}header(A){if(A)return this.raw.headers.get(A)??void 0;let Q={};return this.raw.headers.forEach((B,w)=>{Q[w]=B}),Q}async parseBody(A){return this.bodyCache.parsedBody??=await Ud0(this,A)}#w=(A)=>{let{bodyCache:Q,raw:B}=this,w=Q[A];if(w)return w;let $=Object.keys(Q)[0];if($)return Q[$].then((I)=>{if($==="json")I=JSON.stringify(I);return new Response(I)[A]()});return Q[A]=B[A]()};json(){return this.#w("text").then((A)=>JSON.parse(A))}text(){return this.#w("text")}arrayBuffer(){return this.#w("arrayBuffer")}blob(){return this.#w("blob")}formData(){return this.#w("formData")}addValidatedData(A,Q){this.#A[A]=Q}valid(A){return this.#A[A]}get url(){return this.raw.url}get method(){return this.raw.method}get[Hd0](){return this.#Q}get matchedRoutes(){return this.#Q[0].map(([[,A]])=>A)}get routePath(){return this.#Q[0].map(([[,A]])=>A)[this.routeIndex].path}};var Nd0={Stringify:1,BeforeStream:2,Stream:3},qd0=(A,Q)=>{let B=new String(A);return B.isEscaped=!0,B.callbacks=Q,B};var aMA=async(A,Q,B,w,$)=>{if(typeof A==="object"&&!(A instanceof String)){if(!(A instanceof Promise))A=A.toString();if(A instanceof Promise)A=await A}let I=A.callbacks;if(!I?.length)return Promise.resolve(A);if($)$[0]+=A;else $=[A];let D=Promise.all(I.map((Y)=>Y({phase:Q,buffer:$,context:w}))).then((Y)=>Promise.all(Y.filter(Boolean).map((X)=>aMA(X,Q,!1,w,$))).then(()=>$[0]));if(B)return qd0(await D,I);else return D};var RxQ="text/plain; charset=UTF-8",tMA=(A,Q)=>{return{"Content-Type":A,...Q}},Nm=(A,Q)=>new Response(A,Q),Ld0=class{#A;#Q;env={};#B;finalized=!1;error;#I;#$;#w;#H;#X;#W;#Y;#U;#J;constructor(A,Q){if(this.#A=A,Q)this.#$=Q.executionCtx,this.env=Q.env,this.#W=Q.notFoundHandler,this.#J=Q.path,this.#U=Q.matchResult}get req(){return this.#Q??=new c0A(this.#A,this.#J,this.#U),this.#Q}get event(){if(this.#$&&"respondWith"in this.#$)return this.#$;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#$)return this.#$;else throw Error("This context has no ExecutionContext")}get res(){return this.#w||=Nm(null,{headers:this.#Y??=new Headers})}set res(A){if(this.#w&&A){A=Nm(A.body,A);for(let[Q,B]of this.#w.headers.entries()){if(Q==="content-type")continue;if(Q==="set-cookie"){let w=this.#w.headers.getSetCookie();A.headers.delete("set-cookie");for(let $ of w)A.headers.append("set-cookie",$)}else A.headers.set(Q,B)}}this.#w=A,this.finalized=!0}render=(...A)=>{return this.#X??=(Q)=>this.html(Q),this.#X(...A)};setLayout=(A)=>this.#H=A;getLayout=()=>this.#H;setRenderer=(A)=>{this.#X=A};header=(A,Q,B)=>{if(this.finalized)this.#w=Nm(this.#w.body,this.#w);let w=this.#w?this.#w.headers:this.#Y??=new Headers;if(Q===void 0)w.delete(A);else if(B?.append)w.append(A,Q);else w.set(A,Q)};status=(A)=>{this.#I=A};set=(A,Q)=>{this.#B??=new Map,this.#B.set(A,Q)};get=(A)=>{return this.#B?this.#B.get(A):void 0};get var(){if(!this.#B)return{};return Object.fromEntries(this.#B)}#D(A,Q,B){let w=this.#w?new Headers(this.#w.headers):this.#Y??new Headers;if(typeof Q==="object"&&"headers"in Q){let I=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);for(let[D,Y]of I)if(D.toLowerCase()==="set-cookie")w.append(D,Y);else w.set(D,Y)}if(B)for(let[I,D]of Object.entries(B))if(typeof D==="string")w.set(I,D);else{w.delete(I);for(let Y of D)w.append(I,Y)}let $=typeof Q==="number"?Q:Q?.status??this.#I;return Nm(A,{status:$,headers:w})}newResponse=(...A)=>this.#D(...A);body=(A,Q,B)=>this.#D(A,Q,B);text=(A,Q,B)=>{return!this.#Y&&!this.#I&&!Q&&!B&&!this.finalized?new Response(A):this.#D(A,Q,tMA(RxQ,B))};json=(A,Q,B)=>{return this.#D(JSON.stringify(A),Q,tMA("application/json",B))};html=(A,Q,B)=>{let w=($)=>this.#D($,Q,tMA("text/html; charset=UTF-8",B));return typeof A==="object"?aMA(A,Nd0.Stringify,!1,{}).then(w):w(A)};redirect=(A,Q)=>{let B=String(A);return this.header("Location",!/[^\x00-\xFF]/.test(B)?B:encodeURI(B)),this.newResponse(null,Q??302)};notFound=()=>{return this.#W??=()=>Nm(),this.#W(this)}};var kw="ALL",Ed0="all",Vd0=["get","post","put","delete","options","patch"],d0A="Can not add a route since the matcher is already built.",r0A=class extends Error{};var eMA="__COMPOSED_HANDLER";var bxQ=(A)=>{return A.text("404 Not Found",404)},Md0=(A,Q)=>{if("getResponse"in A){let B=A.getResponse();return Q.newResponse(B.body,B)}return console.error(A),Q.text("Internal Server Error",500)},Cd0=class A{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#A="/";routes=[];constructor(Q={}){[...Vd0,Ed0].forEach((I)=>{this[I]=(D,...Y)=>{if(typeof D==="string")this.#A=D;else this.#I(I,this.#A,D);return Y.forEach((X)=>{this.#I(I,this.#A,X)}),this}}),this.on=(I,D,...Y)=>{for(let X of[D].flat()){this.#A=X;for(let W of[I].flat())Y.map((U)=>{this.#I(W.toUpperCase(),this.#A,U)})}return this},this.use=(I,...D)=>{if(typeof I==="string")this.#A=I;else this.#A="*",D.unshift(I);return D.forEach((Y)=>{this.#I(kw,this.#A,Y)}),this};let{strict:w,...$}=Q;Object.assign(this,$),this.getPath=w??!0?Q.getPath??oMA:Kd0}#Q(){let Q=new A({router:this.router,getPath:this.getPath});return Q.errorHandler=this.errorHandler,Q.#B=this.#B,Q.routes=this.routes,Q}#B=bxQ;errorHandler=Md0;route(Q,B){let w=this.basePath(Q);return B.routes.map(($)=>{let I;if(B.errorHandler===Md0)I=$.handler;else I=async(D,Y)=>(await iMA([],B.errorHandler)(D,()=>$.handler(D,Y))).res,I[eMA]=$.handler;w.#I($.method,$.path,I)}),this}basePath(Q){let B=this.#Q();return B._basePath=zE(this._basePath,Q),B}onError=(Q)=>{return this.errorHandler=Q,this};notFound=(Q)=>{return this.#B=Q,this};mount(Q,B,w){let $,I;if(w)if(typeof w==="function")I=w;else if(I=w.optionHandler,w.replaceRequest===!1)$=(X)=>X;else $=w.replaceRequest;let D=I?(X)=>{let W=I(X);return Array.isArray(W)?W:[W]}:(X)=>{let W=void 0;try{W=X.executionCtx}catch{}return[X.env,W]};$||=(()=>{let X=zE(this._basePath,Q),W=X==="/"?0:X.length;return(U)=>{let K=new URL(U.url);return K.pathname=K.pathname.slice(W)||"/",new Request(K,U)}})();let Y=async(X,W)=>{let U=await B($(X.req.raw),...D(X));if(U)return U;await W()};return this.#I(kw,zE(Q,"*"),Y),this}#I(Q,B,w){Q=Q.toUpperCase(),B=zE(this._basePath,B);let $={basePath:this._basePath,path:B,method:Q,handler:w};this.router.add(Q,B,[w,$]),this.routes.push($)}#$(Q,B){if(Q instanceof Error)return this.errorHandler(Q,B);throw Q}#w(Q,B,w,$){if($==="HEAD")return(async()=>new Response(null,await this.#w(Q,B,w,"GET")))();let I=this.getPath(Q,{env:w}),D=this.router.match($,I),Y=new Ld0(Q,{path:I,matchResult:D,env:w,executionCtx:B,notFoundHandler:this.#B});if(D[0].length===1){let W;try{W=D[0][0][0][0](Y,async()=>{Y.res=await this.#B(Y)})}catch(U){return this.#$(U,Y)}return W instanceof Promise?W.then((U)=>U||(Y.finalized?Y.res:this.#B(Y))).catch((U)=>this.#$(U,Y)):W??this.#B(Y)}let X=iMA(D[0],this.errorHandler,this.#B);return(async()=>{try{let W=await X(Y);if(!W.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return W.res}catch(W){return this.#$(W,Y)}})()}fetch=(Q,...B)=>{return this.#w(Q,B[1],B[0],Q.method)};request=(Q,B,w,$)=>{if(Q instanceof Request)return this.fetch(B?new Request(Q,B):Q,w,$);return Q=Q.toString(),this.fetch(new Request(/^https?:\/\//.test(Q)?Q:`http://localhost${zE("/",Q)}`,B),w,$)};fire=()=>{addEventListener("fetch",(Q)=>{Q.respondWith(this.#w(Q.request,Q,void 0,Q.request.method))})}};var qm=[];function n0A(A,Q){let B=this.buildAllMatchers(),w=($,I)=>{let D=B[$]||B[kw],Y=D[2][I];if(Y)return Y;let X=I.match(D[0]);if(!X)return[[],qm];let W=X.indexOf("",1);return[D[1][W],X]};return this.match=w,w(A,Q)}var o0A="[^/]+",Lm=".*",Em="(?:|/.*)",NE=Symbol(),PxQ=new Set(".\\+*[^]$()");function jxQ(A,Q){if(A.length===1)return Q.length===1?A<Q?-1:1:-1;if(Q.length===1)return 1;if(A===Lm||A===Em)return 1;else if(Q===Lm||Q===Em)return-1;if(A===o0A)return 1;else if(Q===o0A)return-1;return A.length===Q.length?A<Q?-1:1:Q.length-A.length}var Od0=class A{#A;#Q;#B=Object.create(null);insert(Q,B,w,$,I){if(Q.length===0){if(this.#A!==void 0)throw NE;if(I)return;this.#A=B;return}let[D,...Y]=Q,X=D==="*"?Y.length===0?["","",Lm]:["","",o0A]:D==="/*"?["","",Em]:D.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),W;if(X){let U=X[1],K=X[2]||o0A;if(U&&X[2]){if(K===".*")throw NE;if(K=K.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(K))throw NE}if(W=this.#B[K],!W){if(Object.keys(this.#B).some((F)=>F!==Lm&&F!==Em))throw NE;if(I)return;if(W=this.#B[K]=new A,U!=="")W.#Q=$.varIndex++}if(!I&&U!=="")w.push([U,W.#Q])}else if(W=this.#B[D],!W){if(Object.keys(this.#B).some((U)=>U.length>1&&U!==Lm&&U!==Em))throw NE;if(I)return;W=this.#B[D]=new A}W.insert(Y,B,w,$,I)}buildRegExpStr(){let B=Object.keys(this.#B).sort(jxQ).map((w)=>{let $=this.#B[w];return(typeof $.#Q==="number"?`(${w})@${$.#Q}`:PxQ.has(w)?`\\${w}`:w)+$.buildRegExpStr()});if(typeof this.#A==="number")B.unshift(`#${this.#A}`);if(B.length===0)return"";if(B.length===1)return B[0];return"(?:"+B.join("|")+")"}};var Rd0=class{#A={varIndex:0};#Q=new Od0;insert(A,Q,B){let w=[],$=[];for(let D=0;;){let Y=!1;if(A=A.replace(/\{[^}]+\}/g,(X)=>{let W=`@\\${D}`;return $[D]=[W,X],D++,Y=!0,W}),!Y)break}let I=A.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let D=$.length-1;D>=0;D--){let[Y]=$[D];for(let X=I.length-1;X>=0;X--)if(I[X].indexOf(Y)!==-1){I[X]=I[X].replace(Y,$[D][1]);break}}return this.#Q.insert(I,Q,w,this.#A,B),w}buildRegExp(){let A=this.#Q.buildRegExpStr();if(A==="")return[/^$/,[],[]];let Q=0,B=[],w=[];return A=A.replace(/#(\d+)|@(\d+)|\.\*\$/g,($,I,D)=>{if(I!==void 0)return B[++Q]=Number(I),"$()";if(D!==void 0)return w[Number(D)]=++Q,"";return""}),[new RegExp(`^${A}`),B,w]}};var kxQ=[/^$/,[],Object.create(null)],bd0=Object.create(null);function Pd0(A){return bd0[A]??=new RegExp(A==="*"?"":`^${A.replace(/\/\*$|([.\\+*[^\]$()])/g,(Q,B)=>B?`\\${B}`:"(?:|/.*)")}$`)}function _xQ(){bd0=Object.create(null)}function vxQ(A){let Q=new Rd0,B=[];if(A.length===0)return kxQ;let w=A.map((W)=>[!/\*|\/:/.test(W[0]),...W]).sort(([W,U],[K,F])=>W?1:K?-1:U.length-F.length),$=Object.create(null);for(let W=0,U=-1,K=w.length;W<K;W++){let[F,Z,q]=w[W];if(F)$[Z]=[q.map(([L])=>[L,Object.create(null)]),qm];else U++;let E;try{E=Q.insert(Z,U,F)}catch(L){throw L===NE?new r0A(Z):L}if(F)continue;B[U]=q.map(([L,R])=>{let _=Object.create(null);R-=1;for(;R>=0;R--){let[O,r]=E[R];_[O]=r}return[L,_]})}let[I,D,Y]=Q.buildRegExp();for(let W=0,U=B.length;W<U;W++)for(let K=0,F=B[W].length;K<F;K++){let Z=B[W][K]?.[1];if(!Z)continue;let q=Object.keys(Z);for(let E=0,L=q.length;E<L;E++)Z[q[E]]=Y[Z[q[E]]]}let X=[];for(let W in D)X[W]=B[D[W]];return[I,X,$]}function cP(A,Q){if(!A)return;for(let B of Object.keys(A).sort((w,$)=>$.length-w.length))if(Pd0(B).test(Q))return[...A[B]];return}var s0A=class{name="RegExpRouter";#A;#Q;constructor(){this.#A={[kw]:Object.create(null)},this.#Q={[kw]:Object.create(null)}}add(A,Q,B){let w=this.#A,$=this.#Q;if(!w||!$)throw Error(d0A);if(!w[A])[w,$].forEach((Y)=>{Y[A]=Object.create(null),Object.keys(Y[kw]).forEach((X)=>{Y[A][X]=[...Y[kw][X]]})});if(Q==="/*")Q="*";let I=(Q.match(/\/:/g)||[]).length;if(/\*$/.test(Q)){let Y=Pd0(Q);if(A===kw)Object.keys(w).forEach((X)=>{w[X][Q]||=cP(w[X],Q)||cP(w[kw],Q)||[]});else w[A][Q]||=cP(w[A],Q)||cP(w[kw],Q)||[];Object.keys(w).forEach((X)=>{if(A===kw||A===X)Object.keys(w[X]).forEach((W)=>{Y.test(W)&&w[X][W].push([B,I])})}),Object.keys($).forEach((X)=>{if(A===kw||A===X)Object.keys($[X]).forEach((W)=>Y.test(W)&&$[X][W].push([B,I]))});return}let D=i0A(Q)||[Q];for(let Y=0,X=D.length;Y<X;Y++){let W=D[Y];Object.keys($).forEach((U)=>{if(A===kw||A===U)$[U][W]||=[...cP(w[U],W)||cP(w[kw],W)||[]],$[U][W].push([B,I-X+Y+1])})}}match=n0A;buildAllMatchers(){let A=Object.create(null);return Object.keys(this.#Q).concat(Object.keys(this.#A)).forEach((Q)=>{A[Q]||=this.#B(Q)}),this.#A=this.#Q=void 0,_xQ(),A}#B(A){let Q=[],B=A===kw;if([this.#A,this.#Q].forEach((w)=>{let $=w[A]?Object.keys(w[A]).map((I)=>[I,w[A][I]]):[];if($.length!==0)B||=!0,Q.push(...$);else if(A!==kw)Q.push(...Object.keys(w[kw]).map((I)=>[I,w[kw][I]]))}),!B)return null;else return vxQ(Q)}};var xxQ=class{name="PreparedRegExpRouter";#A;#Q;constructor(A,Q){this.#A=A,this.#Q=Q}#B(A,Q){let B=this.#A[A];B[1].forEach((w)=>w&&w.push(Q)),Object.values(B[2]).forEach((w)=>w[0].push(Q))}#I(A,Q,B,w,$){let I=this.#A[A];if(!$)I[2][Q][0].push([B,{}]);else w.forEach((D)=>{if(typeof D==="number")I[1][D].push([B,$]);else I[2][D||Q][0].push([B,$])})}add(A,Q,B){if(!this.#A[A]){let $=this.#A[kw],I={};for(let D in $[2])I[D]=[$[2][D][0].slice(),qm];this.#A[A]=[$[0],$[1].map((D)=>Array.isArray(D)?D.slice():0),I]}if(Q==="/*"||Q==="*"){let $=[B,{}];if(A===kw)for(let I in this.#A)this.#B(I,$);else this.#B(A,$);return}let w=this.#Q[Q];if(!w)throw Error(`Path ${Q} is not registered`);for(let[$,I]of w)if(A===kw)for(let D in this.#A)this.#I(D,Q,B,$,I);else this.#I(A,Q,B,$,I)}buildAllMatchers(){return this.#A}match=n0A};var ACA=class{name="SmartRouter";#A=[];#Q=[];constructor(A){this.#A=A.routers}add(A,Q,B){if(!this.#Q)throw Error(d0A);this.#Q.push([A,Q,B])}match(A,Q){if(!this.#Q)throw Error("Fatal error");let B=this.#A,w=this.#Q,$=B.length,I=0,D;for(;I<$;I++){let Y=B[I];try{for(let X=0,W=w.length;X<W;X++)Y.add(...w[X]);D=Y.match(A,Q)}catch(X){if(X instanceof r0A)continue;throw X}this.match=Y.match.bind(Y),this.#A=[Y],this.#Q=void 0;break}if(I===$)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,D}get activeRouter(){if(this.#Q||this.#A.length!==1)throw Error("No active router has been determined yet.");return this.#A[0]}};var Vm=Object.create(null),yxQ=(A)=>{for(let Q in A)return!0;return!1},jd0=class A{#A;#Q;#B;#I=0;#$=Vm;constructor(Q,B,w){if(this.#Q=w||Object.create(null),this.#A=[],Q&&B){let $=Object.create(null);$[Q]={handler:B,possibleKeys:[],score:0},this.#A=[$]}this.#B=[]}insert(Q,B,w){this.#I=++this.#I;let $=this,I=Jd0(B),D=[];for(let Y=0,X=I.length;Y<X;Y++){let W=I[Y],U=I[Y+1],K=Gd0(W,U),F=Array.isArray(K)?K[0]:W;if(F in $.#Q){if($=$.#Q[F],K)D.push(K[1]);continue}if($.#Q[F]=new A,K)$.#B.push(K),D.push(K[1]);$=$.#Q[F]}return $.#A.push({[Q]:{handler:w,possibleKeys:D.filter((Y,X,W)=>W.indexOf(Y)===X),score:this.#I}}),$}#w(Q,B,w,$,I){for(let D=0,Y=B.#A.length;D<Y;D++){let X=B.#A[D],W=X[w]||X[kw],U={};if(W!==void 0){if(W.params=Object.create(null),Q.push(W),$!==Vm||I&&I!==Vm)for(let K=0,F=W.possibleKeys.length;K<F;K++){let Z=W.possibleKeys[K],q=U[W.score];W.params[Z]=I?.[Z]&&!q?I[Z]:$[Z]??I?.[Z],U[W.score]=!0}}}}search(Q,B){let w=[];this.#$=Vm;let I=[this],D=rMA(B),Y=[],X=D.length,W=null;for(let U=0;U<X;U++){let K=D[U],F=U===X-1,Z=[];for(let E=0,L=I.length;E<L;E++){let R=I[E],_=R.#Q[K];if(_)if(_.#$=R.#$,F){if(_.#Q["*"])this.#w(w,_.#Q["*"],Q,R.#$);this.#w(w,_,Q,R.#$)}else Z.push(_);for(let O=0,r=R.#B.length;O<r;O++){let n=R.#B[O],S=R.#$===Vm?{}:{...R.#$};if(n==="*"){let h=R.#Q["*"];if(h)this.#w(w,h,Q,R.#$),h.#$=S,Z.push(h);continue}let[x,T,g]=n;if(!K&&!(g instanceof RegExp))continue;let e=R.#Q[x];if(g instanceof RegExp){if(W===null){W=Array(X);let BA=B[0]==="/"?1:0;for(let k=0;k<X;k++)W[k]=BA,BA+=D[k].length+1}let h=B.substring(W[U]),XA=g.exec(h);if(XA){if(S[T]=XA[0],this.#w(w,e,Q,R.#$,S),yxQ(e.#Q)){e.#$=S;let BA=XA[0].match(/\//)?.length??0;(Y[BA]||=[]).push(e)}continue}}if(g===!0||g.test(K))if(S[T]=K,F){if(this.#w(w,e,Q,S,R.#$),e.#Q["*"])this.#w(w,e.#Q["*"],Q,S,R.#$)}else e.#$=S,Z.push(e)}}let q=Y.shift();I=q?Z.concat(q):Z}if(w.length>1)w.sort((U,K)=>{return U.score-K.score});return[w.map(({handler:U,params:K})=>[U,K])]}};var QCA=class{name="TrieRouter";#A;constructor(){this.#A=new jd0}add(A,Q,B){let w=i0A(Q);if(w){for(let $=0,I=w.length;$<I;$++)this.#A.insert(A,w[$],B);return}this.#A.insert(A,Q,B)}match(A,Q){return this.#A.search(A,Q)}};var pP=class extends Cd0{constructor(A={}){super(A);this.router=A.router??new ACA({routers:[new s0A,new QCA]})}};import{stat as mxQ}from"fs/promises";import{join as uxQ}from"path";var lP=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;var BCA=(A,Q=SxQ)=>{let B=/\.([a-zA-Z0-9]+?)$/,w=A.match(B);if(!w)return;let $=Q[w[1]];if($&&$.startsWith("text"))$+="; charset=utf-8";return $};var TxQ={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},SxQ=TxQ;var kd0=(...A)=>{let Q=A.filter(($)=>$!=="").join("/");Q=Q.replace(/(?<=\/)\/+/g,"");let B=Q.split("/"),w=[];for(let $ of B)if($===".."&&w.length>0&&w.at(-1)!=="..")w.pop();else if($!==".")w.push($);return w.join("/")||"."};var _d0={br:".br",zstd:".zst",gzip:".gz"},gxQ=Object.keys(_d0),hxQ="index.html",vd0=(A)=>{let Q=A.root??"./",B=A.path,w=A.join??kd0;return async($,I)=>{if($.finalized)return I();let D;if(A.path)D=A.path;else try{if(D=nMA($.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(D))throw Error()}catch{return await A.onNotFound?.($.req.path,$),I()}let Y=w(Q,!B&&A.rewriteRequestPath?A.rewriteRequestPath(D):D);if(A.isDir&&await A.isDir(Y))Y=w(Y,hxQ);let X=A.getContent,W=await X(Y,$);if(W instanceof Response)return $.newResponse(W.body,W);if(W){let U=A.mimes&&BCA(Y,A.mimes)||BCA(Y);if($.header("Content-Type",U||"application/octet-stream"),A.precompressed&&(!U||lP.test(U))){let K=new Set($.req.header("Accept-Encoding")?.split(",").map((F)=>F.trim()));for(let F of gxQ){if(!K.has(F))continue;let Z=await X(Y+_d0[F],$);if(Z){W=Z,$.header("Content-Encoding",F),$.header("Vary","Accept-Encoding",{append:!0});break}}}return await A.onFound?.(Y,$),$.body(W)}await A.onNotFound?.(Y,$),await I();return}};var wCA=(A)=>{return async function(B,w){return vd0({...A,getContent:async(D)=>{let Y=Bun.file(D);return await Y.exists()?Y:null},join:uxQ,isDir:async(D)=>{let Y;try{Y=(await mxQ(D)).isDirectory()}catch{}return Y}})(B,w)}};var $CA="x-hono-disable-ssg",KBw=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[$CA]:"true"}})}catch{return null}})();var{write:oBw}=Bun;var lxQ=class{#A;constructor(A){this.#A=A,this.raw=A.raw,this.url=A.url?new URL(A.url):null,this.protocol=A.protocol??null}send(A,Q){this.#A.send(A,Q??{})}raw;binaryType="arraybuffer";get readyState(){return this.#A.readyState}url;protocol;close(A,Q){this.#A.close(A,Q)}};var xd0=(A)=>{return(...Q)=>{if(typeof Q[0]==="function"){let[B,w]=Q;return async function(I,D){let Y=await B(I),X=await A(I,Y,w);if(X)return X;await D()}}else{let[B,w,$]=Q;return(async()=>{let I=await A(B,w,$);if(!I)throw Error("Failed to upgrade WebSocket");return I})()}}};var a0A=(A)=>("server"in A.env)?A.env.server:A.env;var ixQ=xd0((A,Q)=>{let B=a0A(A);if(!B)throw TypeError("env has to include the 2nd argument of fetch.");if(B.upgrade(A.req.raw,{data:{events:Q,url:new URL(A.req.url),protocol:A.req.url}}))return new Response(null);return});var dxQ=["gzip","deflate"],rxQ=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,yd0=(A)=>{let Q=A?.threshold??1024;return async function(w,$){await $();let I=w.res.headers.get("Content-Length");if(w.res.headers.has("Content-Encoding")||w.res.headers.has("Transfer-Encoding")||w.req.method==="HEAD"||I&&Number(I)<Q||!nxQ(w.res)||!oxQ(w.res))return;let D=w.req.header("Accept-Encoding"),Y=A?.encoding??dxQ.find((W)=>D?.includes(W));if(!Y||!w.res.body)return;let X=new CompressionStream(Y);w.res=new Response(w.res.body.pipeThrough(X),w.res),w.res.headers.delete("Content-Length"),w.res.headers.set("Content-Encoding",Y)}},nxQ=(A)=>{let Q=A.headers.get("Content-Type");return Q&&lP.test(Q)},oxQ=(A)=>{let Q=A.headers.get("Cache-Control");return!Q||!rxQ.test(Q)};import{Readable as Td0}from"stream";import{createDeflate as sxQ,createGzip as axQ}from"zlib";var txQ=["gzip","deflate"],exQ=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Sd0=(A)=>{if(typeof CompressionStream<"u")return yd0(A);let Q=A?.threshold??1024;return async function(w,$){await $();let I=w.res.headers.get("Content-Length");if(w.res.headers.has("Content-Encoding")||w.res.headers.has("Transfer-Encoding")||w.req.method==="HEAD"||I&&Number(I)<Q||!AyQ(w.res)||!QyQ(w.res))return;let D=w.req.header("Accept-Encoding"),Y=A?.encoding??txQ.find((X)=>D?.includes(X));if(!Y||!w.res.body)return;try{let X=Y==="gzip"?axQ():sxQ(),W=w.res.body,K=Td0.fromWeb(W).pipe(X),F=Td0.toWeb(K);w.res=new Response(F,w.res),w.res.headers.delete("Content-Length"),w.res.headers.set("Content-Encoding",Y)}catch(X){console.error("Compression error:",X)}}},AyQ=(A)=>{let Q=A.headers.get("Content-Type");return Q&&lP.test(Q)},QyQ=(A)=>{let Q=A.headers.get("Cache-Control");return!Q||!exQ.test(Q)};var ByQ=(A,Q)=>{if(!A)return Q;let B=new Uint8Array(new ArrayBuffer(A.byteLength+Q.byteLength));return B.set(new Uint8Array(A),0),B.set(Q,A.byteLength),B},gd0=async(A,Q)=>{if(!A)return null;let B=void 0,w=A.getReader();for(;;){let{value:$,done:I}=await w.read();if(I)break;B=await Q(ByQ(B,$))}if(!B)return null;return Array.prototype.map.call(new Uint8Array(B),($)=>$.toString(16).padStart(2,"0")).join("")};var wyQ=["cache-control","content-location","date","etag","expires","vary"],hd0=(A)=>A.replace(/^W\//,"");function $yQ(A,Q){return Q!=null&&Q.split(/,\s*/).some((B)=>hd0(B)===hd0(A))}function IyQ(A){if(!A){if(crypto&&crypto.subtle)A=(Q)=>crypto.subtle.digest({name:"SHA-1"},Q)}return A}var md0=(A)=>{let Q=A?.retainedHeaders??wyQ,B=A?.weak??!1,w=IyQ(A?.generateDigest);return async function(I,D){let Y=I.req.header("If-None-Match")??null;await D();let X=I.res,W=X.headers.get("ETag");if(!W){if(!w)return;let U=await gd0(X.clone().body,w);if(U===null)return;W=B?`W/"${U}"`:`"${U}"`}if($yQ(W,Y))I.res=new Response(null,{status:304,statusText:"Not Modified",headers:{ETag:W}}),I.res.headers.forEach((U,K)=>{if(Q.indexOf(K.toLowerCase())===-1)I.res.headers.delete(K)});else I.res.headers.set("ETag",W)}};eA();function t0A(A,Q){return async(B)=>{let w=B.req.raw,$=w.headers.get("content-type")??"",I=w.headers.get("accept")?.includes("application/json"),D={};if($.includes("application/json"))D=await w.json();else if($.includes("form")){let Z=await w.formData();for(let[q,E]of Z.entries())D[q]=E}let Y=`${A.pluginId}_${A.definition.tool}`,X=await Q.send({type:`plugin:${A.pluginId}:tool:execute`,payload:{toolName:Y,args:D,interfaceType:"webserver",userId:"anonymous"},sender:"webserver"}),W=typeof X==="object"&&"data"in X?X.data:X,U=Tv.safeParse(W),K=U.success?U.data:W,F=U.success&&U.data.success===!0;if(I)return B.json(K,F?200:400);if(F&&A.definition.successRedirect)return B.redirect(A.definition.successRedirect);if(!F&&A.definition.errorRedirect)return B.redirect(A.definition.errorRedirect);return B.json(K,F?200:400)}}var ud0="public, max-age=31536000, immutable";class e0A{logger;options;productionServer=null;isPreviewHost(A){if(!A)return!1;let Q=A.replace(/:\d+$/,"").toLowerCase();return/^(?:preview\..+|.+-preview\..+)$/.test(Q)}constructor(A){this.logger=A.logger,this.options={...A,productionDistDir:iP(process.cwd(),A.productionDistDir),sharedImagesDir:iP(process.cwd(),A.sharedImagesDir),...A.previewDistDir&&{previewDistDir:iP(process.cwd(),A.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}let A=this.createApp({distDir:this.options.productionDistDir,compress:!0,defaultCache:"public, max-age=3600",immutableExtensions:/\.(js|css|jpg|jpeg|png|gif|ico|woff|woff2)$/,healthEndpoint:!0}),Q=this.options.previewDistDir?this.createApp({distDir:this.options.previewDistDir,compress:!1,defaultCache:"no-cache",immutableExtensions:/\.(jpg|jpeg|png|gif|ico|webp|svg|woff|woff2)$/,healthEndpoint:!1}):void 0;try{this.productionServer=Bun.serve({port:this.options.productionPort,fetch:async(B)=>{let w=await this.serveImageFastPath(B);if(w)return w;if(Q&&this.isPreviewHost(B.headers.get("host")))return Q.fetch(B);return A.fetch(B)}})}catch(B){let w=String(B);if(w.includes("EADDRINUSE")||w.includes("address already in use"))throw Error(`Port ${this.options.productionPort} is already in use. Another brain may be running \u2014 stop it first or configure a different port.`);throw B}this.logger.info(`Production server listening on http://localhost:${this.productionServer.port}`)}async stop(){if(this.productionServer)await this.productionServer.stop(),this.productionServer=null;this.logger.debug("Webserver stopped")}getStatus(){return{running:this.productionServer!==null,productionUrl:this.productionServer?`http://localhost:${this.productionServer.port}`:void 0,previewUrl:this.productionServer&&this.options.previewDistDir?`http://localhost:${this.productionServer.port}`:void 0}}createApp(A){let Q=new pP;if(A.healthEndpoint)Q.get("/health",async(B)=>{if(this.options.getHealthData){let w=await this.options.getHealthData();return B.json({status:"healthy",...w},200)}return B.json({status:"healthy"},200)});if(Q.use("/*",async(B,w)=>{let $=await this.handleDynamicRoute(B,A);if($)return $;return w()}),A.compress)Q.use("/*",Sd0());return Q.use("/*",md0()),Q.use("/*",async(B,w)=>{if(await w(),A.immutableExtensions.test(B.req.path))B.header("Cache-Control",ud0);else B.header("Cache-Control",A.defaultCache)}),Q.use("/*",this.createCleanUrlMiddleware(A.distDir)),Q.use("/*",wCA({root:A.distDir})),Q.notFound(async(B)=>{let w=Bun.file(DyQ(A.distDir,"404.html"));if(await w.exists())return B.html(await w.text(),404);return B.text("Not Found",404)}),Q}getCurrentWebRoutes(){return this.options.getWebRoutes?.()??this.options.webRoutes??[]}getCurrentApiRoutes(){return this.options.getApiRoutes?.()??this.options.apiRoutes??[]}async handleDynamicRoute(A,Q){if(!Q.healthEndpoint)return null;let B=A.req.method.toUpperCase(),w=A.req.path,$=this.getCurrentWebRoutes().find((D)=>{let Y=D.definition.method??"GET";return D.fullPath===w&&Y===B});if($)return $.definition.handler(A.req.raw);let I=this.getCurrentApiRoutes().find((D)=>{let Y=D.definition.method;return D.fullPath===w&&Y===B});if(I&&this.options.messageBus)return t0A(I,this.options.messageBus)(A);return null}async serveImageFastPath(A){let Q;try{Q=new URL(A.url)}catch{return null}if(!Q.pathname.startsWith("/images/"))return null;let B=Q.pathname.slice(8),w=iP(this.options.sharedImagesDir,B);if(!w.startsWith(this.options.sharedImagesDir))return null;let $=Bun.file(w);if(!await $.exists())return null;return new Response($,{headers:{"Cache-Control":ud0}})}createCleanUrlMiddleware(A){return async(Q,B)=>{let w=Q.req.path;if(w.includes(".")||w==="/"){await B();return}let $=iP(A,`.${w}`,"index.html");if(!$.startsWith(A)){await B();return}let I=Bun.file($);if(await I.exists())return Q.html(await I.text());let D=iP(A,`.${w}.html`);if(D.startsWith(A)){let Y=Bun.file(D);if(await Y.exists())return Q.html(await Y.text())}await B()}}}import{existsSync as pd0}from"fs";import{join as ld0}from"path";fA();var ICA=f.object({enablePreview:f.boolean().default(!0).describe("Enable the preview site server when preview assets are configured"),previewDistDir:f.string().default("./dist/site-preview").describe("Directory for preview site files"),productionDistDir:f.string().describe("Directory for production site files").default("./dist/site-production"),sharedImagesDir:f.string().default("./dist/images").describe("Shared directory for optimized images"),previewPort:f.number().default(4321).describe("Port for preview server"),productionPort:f.number().describe("Port for production server").default(8080),apiPort:f.number().describe("Port for API route server (plugin HTTP endpoints)").default(3335)});var DCA=`<!DOCTYPE html>
|
|
2323
2323
|
<html lang="en">
|
|
@@ -2386,7 +2386,7 @@ ${R}`)}if(w!==void 0&&I?.algorithms!==void 0){let L=I.algorithms.map((R)=>R.alg)
|
|
|
2386
2386
|
<p>Once built, this page will be replaced with your actual website.</p>
|
|
2387
2387
|
</div>
|
|
2388
2388
|
</body>
|
|
2389
|
-
</html>`;var cd0={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.
|
|
2389
|
+
</html>`;var cd0={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.93",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@brains/plugins":"workspace:*","@hono/bun-compress":"^0.1.0",hono:"^4.7.10"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/messaging-service":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class yz extends nH{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",cd0,A,ICA)}async onRegister(A){if(this.siteUrl=A.siteUrl,this.previewUrl=A.previewUrl,this.siteUrl)A.endpoints.register({label:"Site",url:this.siteUrl,priority:10}),A.interactions.register({id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:this.siteUrl,kind:"human",priority:10});if(this.config.enablePreview&&this.previewUrl)A.endpoints.register({label:"Preview",url:this.previewUrl,priority:20,visibility:"anchor"}),A.interactions.register({id:"preview",label:"Preview site",description:"Open the private preview build.",href:this.previewUrl,kind:"admin",priority:20,visibility:"anchor"});this.serverManager=new e0A({logger:A.logger,productionDistDir:this.config.productionDistDir,sharedImagesDir:this.config.sharedImagesDir,productionPort:this.config.productionPort,...this.config.enablePreview&&this.config.previewDistDir&&{previewDistDir:this.config.previewDistDir},...this.config.enablePreview&&this.config.previewPort&&{previewPort:this.config.previewPort},getHealthData:()=>A.appInfo(),getWebRoutes:()=>A.webRoutes.getRoutes(),getApiRoutes:()=>A.apiRoutes.getRoutes(),messageBus:A.apiRoutes.getMessageBus()})}getServerManager(){if(!this.serverManager)throw Error("ServerManager not initialized \u2014 onRegister not called");return this.serverManager}requiresDaemonStartup(){return!0}createDaemon(){return{start:async()=>{await this.ensureDistDirectories(),await this.getServerManager().start()},stop:async()=>{await this.serverManager?.stop()},healthCheck:async()=>{let A=this.serverManager?.getStatus(),Q=A?.running??!1,B=this.siteUrl??A?.productionUrl??`http://localhost:${this.config.productionPort}`,w=this.previewUrl??A?.previewUrl??`http://localhost:${this.config.previewPort}`,$=[];if(Q){if($.push(`Production: ${B}`),A?.previewUrl)$.push(`Preview: ${w}`)}return{status:Q?"healthy":"error",message:Q?$.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!A?.previewUrl,production:Q,previewUrl:A?.previewUrl?w:void 0,productionUrl:Q?B:void 0}}}}}async handleProgressEvent(A,Q){}async ensureDistDirectories(){let{mkdir:A,writeFile:Q}=await import("fs/promises");if(this.config.enablePreview&&this.config.previewDistDir&&!pd0(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(ld0(this.config.previewDistDir,"index.html"),DCA),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!pd0(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(ld0(this.config.productionDistDir,"index.html"),DCA),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}eA();fA();var Nr0="vercel.ai.error",XyQ=Symbol.for(Nr0),id0,dd0,ZB=class A extends(dd0=Error,id0=XyQ,dd0){constructor({name:Q,message:B,cause:w}){super(B);this[id0]=!0,this.name=Q,this.cause=w}static isInstance(Q){return A.hasMarker(Q,Nr0)}static hasMarker(Q,B){let w=Symbol.for(B);return Q!=null&&typeof Q==="object"&&w in Q&&typeof Q[w]==="boolean"&&Q[w]===!0}},qr0="AI_APICallError",Lr0=`vercel.ai.error.${qr0}`,WyQ=Symbol.for(Lr0),rd0,nd0,B8w=class extends(nd0=ZB,rd0=WyQ,nd0){constructor({message:A,url:Q,requestBodyValues:B,statusCode:w,responseHeaders:$,responseBody:I,cause:D,isRetryable:Y=w!=null&&(w===408||w===409||w===429||w>=500),data:X}){super({name:qr0,message:A,cause:D});this[rd0]=!0,this.url=Q,this.requestBodyValues=B,this.statusCode=w,this.responseHeaders=$,this.responseBody=I,this.isRetryable=Y,this.data=X}static isInstance(A){return ZB.hasMarker(A,Lr0)}},Er0="AI_EmptyResponseBodyError",Vr0=`vercel.ai.error.${Er0}`,HyQ=Symbol.for(Vr0),od0,sd0,w8w=class extends(sd0=ZB,od0=HyQ,sd0){constructor({message:A="Empty response body"}={}){super({name:Er0,message:A});this[od0]=!0}static isInstance(A){return ZB.hasMarker(A,Vr0)}};function Mr0(A){if(A==null)return"unknown error";if(typeof A==="string")return A;if(A instanceof Error)return A.message;return JSON.stringify(A)}var Cr0="AI_InvalidArgumentError",Or0=`vercel.ai.error.${Cr0}`,UyQ=Symbol.for(Or0),ad0,td0,Rr0=class extends(td0=ZB,ad0=UyQ,td0){constructor({message:A,cause:Q,argument:B}){super({name:Cr0,message:A,cause:Q});this[ad0]=!0,this.argument=B}static isInstance(A){return ZB.hasMarker(A,Or0)}},br0="AI_InvalidPromptError",Pr0=`vercel.ai.error.${br0}`,JyQ=Symbol.for(Pr0),ed0,Ar0,$8w=class extends(Ar0=ZB,ed0=JyQ,Ar0){constructor({prompt:A,message:Q,cause:B}){super({name:br0,message:`Invalid prompt: ${Q}`,cause:B});this[ed0]=!0,this.prompt=A}static isInstance(A){return ZB.hasMarker(A,Pr0)}},jr0="AI_InvalidResponseDataError",kr0=`vercel.ai.error.${jr0}`,GyQ=Symbol.for(kr0),Qr0,Br0,I8w=class extends(Br0=ZB,Qr0=GyQ,Br0){constructor({data:A,message:Q=`Invalid response data: ${JSON.stringify(A)}.`}){super({name:jr0,message:Q});this[Qr0]=!0,this.data=A}static isInstance(A){return ZB.hasMarker(A,kr0)}},_r0="AI_JSONParseError",vr0=`vercel.ai.error.${_r0}`,KyQ=Symbol.for(vr0),wr0,$r0,YCA=class extends($r0=ZB,wr0=KyQ,$r0){constructor({text:A,cause:Q}){super({name:_r0,message:`JSON parsing failed: Text: ${A}.
|
|
2390
2390
|
Error message: ${Mr0(Q)}`,cause:Q});this[wr0]=!0,this.text=A}static isInstance(A){return ZB.hasMarker(A,vr0)}},xr0="AI_LoadAPIKeyError",yr0=`vercel.ai.error.${xr0}`,fyQ=Symbol.for(yr0),Ir0,Dr0,D8w=class extends(Dr0=ZB,Ir0=fyQ,Dr0){constructor({message:A}){super({name:xr0,message:A});this[Ir0]=!0}static isInstance(A){return ZB.hasMarker(A,yr0)}},Tr0="AI_LoadSettingError",Sr0=`vercel.ai.error.${Tr0}`,FyQ=Symbol.for(Sr0),Yr0,Xr0,Y8w=class extends(Xr0=ZB,Yr0=FyQ,Xr0){constructor({message:A}){super({name:Tr0,message:A});this[Yr0]=!0}static isInstance(A){return ZB.hasMarker(A,Sr0)}},gr0="AI_NoContentGeneratedError",hr0=`vercel.ai.error.${gr0}`,ZyQ=Symbol.for(hr0),Wr0,Hr0,X8w=class extends(Hr0=ZB,Wr0=ZyQ,Hr0){constructor({message:A="No content generated."}={}){super({name:gr0,message:A});this[Wr0]=!0}static isInstance(A){return ZB.hasMarker(A,hr0)}},mr0="AI_NoSuchModelError",ur0=`vercel.ai.error.${mr0}`,zyQ=Symbol.for(ur0),Ur0,Jr0,W8w=class extends(Jr0=ZB,Ur0=zyQ,Jr0){constructor({errorName:A=mr0,modelId:Q,modelType:B,message:w=`No such ${B}: ${Q}`}){super({name:A,message:w});this[Ur0]=!0,this.modelId=Q,this.modelType=B}static isInstance(A){return ZB.hasMarker(A,ur0)}},cr0="AI_TooManyEmbeddingValuesForCallError",pr0=`vercel.ai.error.${cr0}`,NyQ=Symbol.for(pr0),Gr0,Kr0,H8w=class extends(Kr0=ZB,Gr0=NyQ,Kr0){constructor(A){super({name:cr0,message:`Too many values for a single embedding call. The ${A.provider} model "${A.modelId}" can only embed up to ${A.maxEmbeddingsPerCall} values per call, but ${A.values.length} values were provided.`});this[Gr0]=!0,this.provider=A.provider,this.modelId=A.modelId,this.maxEmbeddingsPerCall=A.maxEmbeddingsPerCall,this.values=A.values}static isInstance(A){return ZB.hasMarker(A,pr0)}},lr0="AI_TypeValidationError",ir0=`vercel.ai.error.${lr0}`,qyQ=Symbol.for(ir0),fr0,Fr0,oU=class A extends(Fr0=ZB,fr0=qyQ,Fr0){constructor({value:Q,cause:B,context:w}){let $="Type validation failed";if(w==null?void 0:w.field)$+=` for ${w.field}`;if((w==null?void 0:w.entityName)||(w==null?void 0:w.entityId)){$+=" (";let I=[];if(w.entityName)I.push(w.entityName);if(w.entityId)I.push(`id: "${w.entityId}"`);$+=I.join(", "),$+=")"}super({name:lr0,message:`${$}: Value: ${JSON.stringify(Q)}.
|
|
2391
2391
|
Error message: ${Mr0(B)}`,cause:B});this[fr0]=!0,this.value=Q,this.context=w}static isInstance(Q){return ZB.hasMarker(Q,ir0)}static wrap({value:Q,cause:B,context:w}){var $,I,D;if(A.isInstance(B)&&B.value===Q&&(($=B.context)==null?void 0:$.field)===(w==null?void 0:w.field)&&((I=B.context)==null?void 0:I.entityName)===(w==null?void 0:w.entityName)&&((D=B.context)==null?void 0:D.entityId)===(w==null?void 0:w.entityId))return B;return new A({value:Q,cause:B,context:w})}},dr0="AI_UnsupportedFunctionalityError",rr0=`vercel.ai.error.${dr0}`,LyQ=Symbol.for(rr0),Zr0,zr0,U8w=class extends(zr0=ZB,Zr0=LyQ,zr0){constructor({functionality:A,message:Q=`'${A}' functionality not supported.`}){super({name:dr0,message:Q});this[Zr0]=!0,this.functionality=A}static isInstance(A){return ZB.hasMarker(A,rr0)}};J1();eH();eH();eH();var er0="AI_DownloadError",An0=`vercel.ai.error.${er0}`,EyQ=Symbol.for(An0),nr0,or0,gY=class extends(or0=ZB,nr0=EyQ,or0){constructor({url:A,statusCode:Q,statusText:B,cause:w,message:$=w==null?`Failed to download ${A}: ${Q} ${B}`:`Failed to download ${A}: ${w}`}){super({name:er0,message:$,cause:w});this[nr0]=!0,this.url=A,this.statusCode=Q,this.statusText=B}static isInstance(A){return ZB.hasMarker(A,An0)}},GCA=2147483648;async function Qn0({response:A,url:Q,maxBytes:B=GCA}){let w=A.headers.get("content-length");if(w!=null){let U=parseInt(w,10);if(!isNaN(U)&&U>B)throw new gY({url:Q,message:`Download of ${Q} exceeded maximum size of ${B} bytes (Content-Length: ${U}).`})}let $=A.body;if($==null)return new Uint8Array(0);let I=$.getReader(),D=[],Y=0;try{while(!0){let{done:U,value:K}=await I.read();if(U)break;if(Y+=K.length,Y>B)throw new gY({url:Q,message:`Download of ${Q} exceeded maximum size of ${B} bytes.`});D.push(K)}}finally{try{await I.cancel()}finally{I.releaseLock()}}let X=new Uint8Array(Y),W=0;for(let U of D)X.set(U,W),W+=U.length;return X}function KCA(A){let Q;try{Q=new URL(A)}catch(w){throw new gY({url:A,message:`Invalid URL: ${A}`})}if(Q.protocol==="data:")return;if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw new gY({url:A,message:`URL scheme must be http, https, or data, got ${Q.protocol}`});let B=Q.hostname;if(!B)throw new gY({url:A,message:"URL must have a hostname"});if(B==="localhost"||B.endsWith(".local")||B.endsWith(".localhost"))throw new gY({url:A,message:`URL with hostname ${B} is not allowed`});if(B.startsWith("[")&&B.endsWith("]")){let w=B.slice(1,-1);if(VyQ(w))throw new gY({url:A,message:`URL with IPv6 address ${B} is not allowed`});return}if(Bn0(B)){if(HCA(B))throw new gY({url:A,message:`URL with IP address ${B} is not allowed`});return}}function Bn0(A){let Q=A.split(".");if(Q.length!==4)return!1;return Q.every((B)=>{let w=Number(B);return Number.isInteger(w)&&w>=0&&w<=255&&String(w)===B})}function HCA(A){let Q=A.split(".").map(Number),[B,w]=Q;if(B===0)return!0;if(B===10)return!0;if(B===127)return!0;if(B===169&&w===254)return!0;if(B===172&&w>=16&&w<=31)return!0;if(B===192&&w===168)return!0;return!1}function VyQ(A){let Q=A.toLowerCase();if(Q==="::1")return!0;if(Q==="::")return!0;if(Q.startsWith("::ffff:")){let B=Q.slice(7);if(Bn0(B))return HCA(B);let w=B.split(":");if(w.length===2){let $=parseInt(w[0],16),I=parseInt(w[1],16);if(!isNaN($)&&!isNaN(I)){let D=$>>8&255,Y=$&255,X=I>>8&255,W=I&255;return HCA(`${D}.${Y}.${X}.${W}`)}}}if(Q.startsWith("fc")||Q.startsWith("fd"))return!0;if(Q.startsWith("fe80"))return!0;return!1}var uK=({prefix:A,size:Q=16,alphabet:B="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:w="-"}={})=>{let $=()=>{let I=B.length,D=Array(Q);for(let Y=0;Y<Q;Y++)D[Y]=B[Math.random()*I|0];return D.join("")};if(A==null)return $;if(B.includes(w))throw new Rr0({argument:"separator",message:`The separator "${w}" must not be part of the alphabet "${B}".`});return()=>`${A}${w}${$()}`},wn0=uK();function fCA(A){if(A==null)return"unknown error";if(typeof A==="string")return A;if(A instanceof Error)return A.message;return JSON.stringify(A)}function $n0(A=globalThis){var Q,B,w;if(A.window)return"runtime/browser";if((Q=A.navigator)==null?void 0:Q.userAgent)return`runtime/${A.navigator.userAgent.toLowerCase()}`;if((w=(B=A.process)==null?void 0:B.versions)==null?void 0:w.node)return`runtime/node.js/${A.process.version.substring(0)}`;if(A.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function MyQ(A){if(A==null)return{};let Q={};if(A instanceof Headers)A.forEach((B,w)=>{Q[w.toLowerCase()]=B});else{if(!Array.isArray(A))A=Object.entries(A);for(let[B,w]of A)if(w!=null)Q[B.toLowerCase()]=w}return Q}function A1A(A,...Q){let B=new Headers(MyQ(A)),w=B.get("user-agent")||"";return B.set("user-agent",[w,...Q].filter(Boolean).join(" ")),Object.fromEntries(B.entries())}var CyQ=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,OyQ=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function sr0(A){let Q=JSON.parse(A);if(Q===null||typeof Q!=="object")return Q;if(CyQ.test(A)===!1&&OyQ.test(A)===!1)return Q;return RyQ(Q)}function RyQ(A){let Q=[A];while(Q.length){let B=Q;Q=[];for(let w of B){if(Object.prototype.hasOwnProperty.call(w,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(w,"constructor")&&w.constructor!==null&&typeof w.constructor==="object"&&Object.prototype.hasOwnProperty.call(w.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in w){let I=w[$];if(I&&typeof I==="object")Q.push(I)}}}return A}function byQ(A){let{stackTraceLimit:Q}=Error;try{Error.stackTraceLimit=0}catch(B){return sr0(A)}try{return sr0(A)}finally{Error.stackTraceLimit=Q}}function FCA(A){if(A.type==="object"||Array.isArray(A.type)&&A.type.includes("object")){A.additionalProperties=!1;let{properties:B}=A;if(B!=null)for(let w of Object.keys(B))B[w]=qE(B[w])}if(A.items!=null)A.items=Array.isArray(A.items)?A.items.map(qE):qE(A.items);if(A.anyOf!=null)A.anyOf=A.anyOf.map(qE);if(A.allOf!=null)A.allOf=A.allOf.map(qE);if(A.oneOf!=null)A.oneOf=A.oneOf.map(qE);let{definitions:Q}=A;if(Q!=null)for(let B of Object.keys(Q))Q[B]=qE(Q[B]);return A}function qE(A){if(typeof A==="boolean")return A;return FCA(A)}var PyQ=Symbol("Let zodToJsonSchema decide on which parser to use"),ar0={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},jyQ=(A)=>typeof A==="string"?{...ar0,name:A}:{...ar0,...A};function JD(){return{}}function kyQ(A,Q){var B,w,$;let I={type:"array"};if(((B=A.type)==null?void 0:B._def)&&(($=(w=A.type)==null?void 0:w._def)==null?void 0:$.typeName)!==X0.ZodAny)I.items=Fw(A.type._def,{...Q,currentPath:[...Q.currentPath,"items"]});if(A.minLength)I.minItems=A.minLength.value;if(A.maxLength)I.maxItems=A.maxLength.value;if(A.exactLength)I.minItems=A.exactLength.value,I.maxItems=A.exactLength.value;return I}function _yQ(A){let Q={type:"integer",format:"int64"};if(!A.checks)return Q;for(let B of A.checks)switch(B.kind){case"min":if(B.inclusive)Q.minimum=B.value;else Q.exclusiveMinimum=B.value;break;case"max":if(B.inclusive)Q.maximum=B.value;else Q.exclusiveMaximum=B.value;break;case"multipleOf":Q.multipleOf=B.value;break}return Q}function vyQ(){return{type:"boolean"}}function In0(A,Q){return Fw(A.type._def,Q)}var xyQ=(A,Q)=>{return Fw(A.innerType._def,Q)};function Dn0(A,Q,B){let w=B!=null?B:Q.dateStrategy;if(Array.isArray(w))return{anyOf:w.map(($,I)=>Dn0(A,Q,$))};switch(w){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return yyQ(A)}}var yyQ=(A)=>{let Q={type:"integer",format:"unix-time"};for(let B of A.checks)switch(B.kind){case"min":Q.minimum=B.value;break;case"max":Q.maximum=B.value;break}return Q};function TyQ(A,Q){return{...Fw(A.innerType._def,Q),default:A.defaultValue()}}function SyQ(A,Q){return Q.effectStrategy==="input"?Fw(A.schema._def,Q):JD()}function gyQ(A){return{type:"string",enum:Array.from(A.values)}}var hyQ=(A)=>{if("type"in A&&A.type==="string")return!1;return"allOf"in A};function myQ(A,Q){let B=[Fw(A.left._def,{...Q,currentPath:[...Q.currentPath,"allOf","0"]}),Fw(A.right._def,{...Q,currentPath:[...Q.currentPath,"allOf","1"]})].filter(($)=>!!$),w=[];return B.forEach(($)=>{if(hyQ($))w.push(...$.allOf);else{let I=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:D,...Y}=$;I=Y}w.push(I)}}),w.length?{allOf:w}:void 0}function uyQ(A){let Q=typeof A.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray(A.value)?"array":"object"};return{type:Q==="bigint"?"integer":Q,const:A.value}}var XCA=void 0,yW={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(XCA===void 0)XCA=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return XCA},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Yn0(A,Q){let B={type:"string"};if(A.checks)for(let w of A.checks)switch(w.kind){case"min":B.minLength=typeof B.minLength==="number"?Math.max(B.minLength,w.value):w.value;break;case"max":B.maxLength=typeof B.maxLength==="number"?Math.min(B.maxLength,w.value):w.value;break;case"email":switch(Q.emailStrategy){case"format:email":TW(B,"email",w.message,Q);break;case"format:idn-email":TW(B,"idn-email",w.message,Q);break;case"pattern:zod":A4(B,yW.email,w.message,Q);break}break;case"url":TW(B,"uri",w.message,Q);break;case"uuid":TW(B,"uuid",w.message,Q);break;case"regex":A4(B,w.regex,w.message,Q);break;case"cuid":A4(B,yW.cuid,w.message,Q);break;case"cuid2":A4(B,yW.cuid2,w.message,Q);break;case"startsWith":A4(B,RegExp(`^${WCA(w.value,Q)}`),w.message,Q);break;case"endsWith":A4(B,RegExp(`${WCA(w.value,Q)}$`),w.message,Q);break;case"datetime":TW(B,"date-time",w.message,Q);break;case"date":TW(B,"date",w.message,Q);break;case"time":TW(B,"time",w.message,Q);break;case"duration":TW(B,"duration",w.message,Q);break;case"length":B.minLength=typeof B.minLength==="number"?Math.max(B.minLength,w.value):w.value,B.maxLength=typeof B.maxLength==="number"?Math.min(B.maxLength,w.value):w.value;break;case"includes":{A4(B,RegExp(WCA(w.value,Q)),w.message,Q);break}case"ip":{if(w.version!=="v6")TW(B,"ipv4",w.message,Q);if(w.version!=="v4")TW(B,"ipv6",w.message,Q);break}case"base64url":A4(B,yW.base64url,w.message,Q);break;case"jwt":A4(B,yW.jwt,w.message,Q);break;case"cidr":{if(w.version!=="v6")A4(B,yW.ipv4Cidr,w.message,Q);if(w.version!=="v4")A4(B,yW.ipv6Cidr,w.message,Q);break}case"emoji":A4(B,yW.emoji(),w.message,Q);break;case"ulid":{A4(B,yW.ulid,w.message,Q);break}case"base64":{switch(Q.base64Strategy){case"format:binary":{TW(B,"binary",w.message,Q);break}case"contentEncoding:base64":{B.contentEncoding="base64";break}case"pattern:zod":{A4(B,yW.base64,w.message,Q);break}}break}case"nanoid":A4(B,yW.nanoid,w.message,Q);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return B}function WCA(A,Q){return Q.patternStrategy==="escape"?pyQ(A):A}var cyQ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pyQ(A){let Q="";for(let B=0;B<A.length;B++){if(!cyQ.has(A[B]))Q+="\\";Q+=A[B]}return Q}function TW(A,Q,B,w){var $;if(A.format||(($=A.anyOf)==null?void 0:$.some((I)=>I.format))){if(!A.anyOf)A.anyOf=[];if(A.format)A.anyOf.push({format:A.format}),delete A.format;A.anyOf.push({format:Q,...B&&w.errorMessages&&{errorMessage:{format:B}}})}else A.format=Q}function A4(A,Q,B,w){var $;if(A.pattern||(($=A.allOf)==null?void 0:$.some((I)=>I.pattern))){if(!A.allOf)A.allOf=[];if(A.pattern)A.allOf.push({pattern:A.pattern}),delete A.pattern;A.allOf.push({pattern:tr0(Q,w),...B&&w.errorMessages&&{errorMessage:{pattern:B}}})}else A.pattern=tr0(Q,w)}function tr0(A,Q){var B;if(!Q.applyRegexFlags||!A.flags)return A.source;let w={i:A.flags.includes("i"),m:A.flags.includes("m"),s:A.flags.includes("s")},$=w.i?A.source.toLowerCase():A.source,I="",D=!1,Y=!1,X=!1;for(let W=0;W<$.length;W++){if(D){I+=$[W],D=!1;continue}if(w.i){if(Y){if($[W].match(/[a-z]/)){if(X)I+=$[W],I+=`${$[W-2]}-${$[W]}`.toUpperCase(),X=!1;else if($[W+1]==="-"&&((B=$[W+2])==null?void 0:B.match(/[a-z]/)))I+=$[W],X=!0;else I+=`${$[W]}${$[W].toUpperCase()}`;continue}}else if($[W].match(/[a-z]/)){I+=`[${$[W]}${$[W].toUpperCase()}]`;continue}}if(w.m){if($[W]==="^"){I+=`(^|(?<=[\r
|
|
2392
2392
|
]))`;continue}else if($[W]==="$"){I+=`($|(?=[\r
|
|
@@ -2396,7 +2396,7 @@ Error message: ${Mr0(B)}`,cause:B});this[fr0]=!0,this.value=Q,this.context=w}sta
|
|
|
2396
2396
|
|
|
2397
2397
|
`)},flush(A){A.enqueue(`data: [DONE]
|
|
2398
2398
|
|
|
2399
|
-
`)}})}},DgQ={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function En0({status:A,statusText:Q,headers:B,stream:w,consumeSseStream:$}){let I=w.pipeThrough(new IgQ);if($){let[D,Y]=I.tee();I=D,$({stream:Y})}return new Response(I.pipeThrough(new TextEncoderStream),{status:A,statusText:Q,headers:$gQ(B,DgQ)})}var Cm=J.record(J.string(),LE.optional()),A6w=Q1A(()=>Mm(J.union([J.strictObject({type:J.literal("text-start"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("text-delta"),id:J.string(),delta:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("text-end"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("error"),errorText:J.string()}),J.strictObject({type:J.literal("tool-input-start"),toolCallId:J.string(),toolName:J.string(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),title:J.string().optional()}),J.strictObject({type:J.literal("tool-input-delta"),toolCallId:J.string(),inputTextDelta:J.string()}),J.strictObject({type:J.literal("tool-input-available"),toolCallId:J.string(),toolName:J.string(),input:J.unknown(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),title:J.string().optional()}),J.strictObject({type:J.literal("tool-input-error"),toolCallId:J.string(),toolName:J.string(),input:J.unknown(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),errorText:J.string(),title:J.string().optional()}),J.strictObject({type:J.literal("tool-approval-request"),approvalId:J.string(),toolCallId:J.string()}),J.strictObject({type:J.literal("tool-output-available"),toolCallId:J.string(),output:J.unknown(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),preliminary:J.boolean().optional()}),J.strictObject({type:J.literal("tool-output-error"),toolCallId:J.string(),errorText:J.string(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional()}),J.strictObject({type:J.literal("tool-output-denied"),toolCallId:J.string()}),J.strictObject({type:J.literal("reasoning-start"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("reasoning-delta"),id:J.string(),delta:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("reasoning-end"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("source-url"),sourceId:J.string(),url:J.string(),title:J.string().optional(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("source-document"),sourceId:J.string(),mediaType:J.string(),title:J.string(),filename:J.string().optional(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("file"),url:J.string(),mediaType:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.custom((A)=>typeof A==="string"&&A.startsWith("data-"),{message:'Type must start with "data-"'}),id:J.string().optional(),data:J.unknown(),transient:J.boolean().optional()}),J.strictObject({type:J.literal("start-step")}),J.strictObject({type:J.literal("finish-step")}),J.strictObject({type:J.literal("start"),messageId:J.string().optional(),messageMetadata:J.unknown().optional()}),J.strictObject({type:J.literal("finish"),finishReason:J.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:J.unknown().optional()}),J.strictObject({type:J.literal("abort"),reason:J.string().optional()}),J.strictObject({type:J.literal("message-metadata"),messageMetadata:J.unknown()})])));function YgQ(A){return A.type.startsWith("data-")}function zCA(A){return A.type.startsWith("tool-")}function XgQ(A){return A.type==="dynamic-tool"}function Wn0(A){return zCA(A)||XgQ(A)}function Hn0(A){return A.type.split("-").slice(1).join("-")}function WgQ({lastMessage:A,messageId:Q}){return{message:(A==null?void 0:A.role)==="assistant"?A:{id:Q,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function HgQ({stream:A,messageMetadataSchema:Q,dataPartSchemas:B,runUpdateMessageJob:w,onError:$,onToolCall:I,onData:D}){return A.pipeThrough(new TransformStream({async transform(Y,X){await w(async({state:W,write:U})=>{var K,F,Z,q;function E(O){let n=W.message.parts.filter(Wn0).find((S)=>S.toolCallId===O);if(n==null)throw new rP({chunkType:"tool-invocation",chunkId:O,message:`No tool invocation found for tool call ID "${O}".`});return n}function L(O){var r;let n=W.message.parts.find((T)=>zCA(T)&&T.toolCallId===O.toolCallId),S=O,x=n;if(n!=null){if(n.state=O.state,x.input=S.input,x.output=S.output,x.errorText=S.errorText,x.rawInput=S.rawInput,x.preliminary=S.preliminary,O.title!==void 0)x.title=O.title;if(O.toolMetadata!==void 0)x.toolMetadata=O.toolMetadata;x.providerExecuted=(r=S.providerExecuted)!=null?r:n.providerExecuted;let T=S.providerMetadata;if(T!=null)if(O.state==="output-available"||O.state==="output-error"){let g=n;g.resultProviderMetadata=T}else n.callProviderMetadata=T}else W.message.parts.push({type:`tool-${O.toolName}`,toolCallId:O.toolCallId,state:O.state,title:O.title,...O.toolMetadata!==void 0?{toolMetadata:O.toolMetadata}:{},input:S.input,output:S.output,rawInput:S.rawInput,errorText:S.errorText,providerExecuted:S.providerExecuted,preliminary:S.preliminary,...S.providerMetadata!=null&&(O.state==="output-available"||O.state==="output-error")?{resultProviderMetadata:S.providerMetadata}:{},...S.providerMetadata!=null&&!(O.state==="output-available"||O.state==="output-error")?{callProviderMetadata:S.providerMetadata}:{}})}function R(O){var r,n;let S=W.message.parts.find((g)=>g.type==="dynamic-tool"&&g.toolCallId===O.toolCallId),x=O,T=S;if(S!=null){if(S.state=O.state,T.toolName=O.toolName,T.input=x.input,T.output=x.output,T.errorText=x.errorText,T.rawInput=(r=x.rawInput)!=null?r:T.rawInput,T.preliminary=x.preliminary,O.title!==void 0)T.title=O.title;if(O.toolMetadata!==void 0)T.toolMetadata=O.toolMetadata;T.providerExecuted=(n=x.providerExecuted)!=null?n:S.providerExecuted;let g=x.providerMetadata;if(g!=null)if(O.state==="output-available"||O.state==="output-error"){let e=S;e.resultProviderMetadata=g}else S.callProviderMetadata=g}else W.message.parts.push({type:"dynamic-tool",toolName:O.toolName,toolCallId:O.toolCallId,state:O.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,title:O.title,...O.toolMetadata!==void 0?{toolMetadata:O.toolMetadata}:{},...x.providerMetadata!=null&&(O.state==="output-available"||O.state==="output-error")?{resultProviderMetadata:x.providerMetadata}:{},...x.providerMetadata!=null&&!(O.state==="output-available"||O.state==="output-error")?{callProviderMetadata:x.providerMetadata}:{}})}async function _(O){if(O!=null){let r=W.message.metadata!=null?Ln0(W.message.metadata,O):O;if(Q!=null)await $1A({value:r,schema:Q,context:{field:"message.metadata",entityId:W.message.id}});W.message.metadata=r}}switch(Y.type){case"text-start":{let O={type:"text",text:"",providerMetadata:Y.providerMetadata,state:"streaming"};W.activeTextParts[Y.id]=O,W.message.parts.push(O),U();break}case"text-delta":{let O=W.activeTextParts[Y.id];if(O==null)throw new rP({chunkType:"text-delta",chunkId:Y.id,message:`Received text-delta for missing text part with ID "${Y.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});O.text+=Y.delta,O.providerMetadata=(K=Y.providerMetadata)!=null?K:O.providerMetadata,U();break}case"text-end":{let O=W.activeTextParts[Y.id];if(O==null)throw new rP({chunkType:"text-end",chunkId:Y.id,message:`Received text-end for missing text part with ID "${Y.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});O.state="done",O.providerMetadata=(F=Y.providerMetadata)!=null?F:O.providerMetadata,delete W.activeTextParts[Y.id],U();break}case"reasoning-start":{let O={type:"reasoning",text:"",providerMetadata:Y.providerMetadata,state:"streaming"};W.activeReasoningParts[Y.id]=O,W.message.parts.push(O),U();break}case"reasoning-delta":{let O=W.activeReasoningParts[Y.id];if(O==null)throw new rP({chunkType:"reasoning-delta",chunkId:Y.id,message:`Received reasoning-delta for missing reasoning part with ID "${Y.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});O.text+=Y.delta,O.providerMetadata=(Z=Y.providerMetadata)!=null?Z:O.providerMetadata,U();break}case"reasoning-end":{let O=W.activeReasoningParts[Y.id];if(O==null)throw new rP({chunkType:"reasoning-end",chunkId:Y.id,message:`Received reasoning-end for missing reasoning part with ID "${Y.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});O.providerMetadata=(q=Y.providerMetadata)!=null?q:O.providerMetadata,O.state="done",delete W.activeReasoningParts[Y.id],U();break}case"file":{W.message.parts.push({type:"file",mediaType:Y.mediaType,url:Y.url,...Y.providerMetadata!=null?{providerMetadata:Y.providerMetadata}:{}}),U();break}case"source-url":{W.message.parts.push({type:"source-url",sourceId:Y.sourceId,url:Y.url,title:Y.title,providerMetadata:Y.providerMetadata}),U();break}case"source-document":{W.message.parts.push({type:"source-document",sourceId:Y.sourceId,mediaType:Y.mediaType,title:Y.title,filename:Y.filename,providerMetadata:Y.providerMetadata}),U();break}case"tool-input-start":{let O=W.message.parts.filter(zCA);if(W.partialToolCalls[Y.toolCallId]={text:"",toolName:Y.toolName,index:O.length,dynamic:Y.dynamic,title:Y.title,toolMetadata:Y.toolMetadata},Y.dynamic)R({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-streaming",input:void 0,providerExecuted:Y.providerExecuted,title:Y.title,toolMetadata:Y.toolMetadata,providerMetadata:Y.providerMetadata});else L({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-streaming",input:void 0,providerExecuted:Y.providerExecuted,title:Y.title,toolMetadata:Y.toolMetadata,providerMetadata:Y.providerMetadata});U();break}case"tool-input-delta":{let O=W.partialToolCalls[Y.toolCallId];if(O==null)throw new rP({chunkType:"tool-input-delta",chunkId:Y.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${Y.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});O.text+=Y.inputTextDelta;let{value:r}=await Om(O.text);if(O.dynamic)R({toolCallId:Y.toolCallId,toolName:O.toolName,state:"input-streaming",input:r,title:O.title,toolMetadata:O.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:O.toolName,state:"input-streaming",input:r,title:O.title,toolMetadata:O.toolMetadata});U();break}case"tool-input-available":{if(Y.dynamic)R({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-available",input:Y.input,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:Y.title,toolMetadata:Y.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-available",input:Y.input,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:Y.title,toolMetadata:Y.toolMetadata});if(U(),I&&!Y.providerExecuted)await I({toolCall:Y});break}case"tool-input-error":{let O=W.message.parts.filter(Wn0).find((n)=>n.toolCallId===Y.toolCallId);if(O!=null?O.type==="dynamic-tool":!!Y.dynamic)R({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"output-error",input:Y.input,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,toolMetadata:Y.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"output-error",input:void 0,rawInput:Y.input,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,toolMetadata:Y.toolMetadata});U();break}case"tool-approval-request":{let O=E(Y.toolCallId);O.state="approval-requested",O.approval={id:Y.approvalId},U();break}case"tool-output-denied":{let O=E(Y.toolCallId);O.state="output-denied",U();break}case"tool-output-available":{let O=E(Y.toolCallId);if(O.type==="dynamic-tool")R({toolCallId:Y.toolCallId,toolName:O.toolName,state:"output-available",input:O.input,output:Y.output,preliminary:Y.preliminary,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Hn0(O),state:"output-available",input:O.input,output:Y.output,providerExecuted:Y.providerExecuted,preliminary:Y.preliminary,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});U();break}case"tool-output-error":{let O=E(Y.toolCallId);if(O.type==="dynamic-tool")R({toolCallId:Y.toolCallId,toolName:O.toolName,state:"output-error",input:O.input,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Hn0(O),state:"output-error",input:O.input,rawInput:O.rawInput,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});U();break}case"start-step":{W.message.parts.push({type:"step-start"});break}case"finish-step":{W.activeTextParts={},W.activeReasoningParts={};break}case"start":{if(Y.messageId!=null)W.message.id=Y.messageId;if(await _(Y.messageMetadata),Y.messageId!=null||Y.messageMetadata!=null)U();break}case"finish":{if(Y.finishReason!=null)W.finishReason=Y.finishReason;if(await _(Y.messageMetadata),Y.messageMetadata!=null)U();break}case"message-metadata":{if(await _(Y.messageMetadata),Y.messageMetadata!=null)U();break}case"error":{$==null||$(Error(Y.errorText));break}default:if(YgQ(Y)){if((B==null?void 0:B[Y.type])!=null){let n=W.message.parts.findIndex((x)=>("id"in x)&&("data"in x)&&x.id===Y.id&&x.type===Y.type),S=n>=0?n:W.message.parts.length;await $1A({value:Y.data,schema:B[Y.type],context:{field:`message.parts[${S}].data`,entityName:Y.type,entityId:Y.id}})}let O=Y;if(O.transient){D==null||D(O);break}let r=O.id!=null?W.message.parts.find((n)=>O.type===n.type&&O.id===n.id):void 0;if(r!=null)r.data=O.data;else W.message.parts.push(O);D==null||D(O),U()}}X.enqueue(Y)})}}))}function UgQ({messageId:A,originalMessages:Q=[],onStepFinish:B,onFinish:w,onError:$,stream:I}){let D=Q==null?void 0:Q[Q.length-1];if((D==null?void 0:D.role)!=="assistant")D=void 0;else A=D.id;let Y=!1,X=I.pipeThrough(new TransformStream({transform(q,E){if(q.type==="start"){let L=q;if(L.messageId==null&&A!=null)L.messageId=A}if(q.type==="abort")Y=!0;E.enqueue(q)}}));if(w==null&&B==null)return X;let W=WgQ({lastMessage:D?structuredClone(D):void 0,messageId:A!=null?A:""}),U=async(q)=>{await q({state:W,write:()=>{}})},K=!1,F=async()=>{if(K||!w)return;K=!0;let q=W.message.id===(D==null?void 0:D.id);await w({isAborted:Y,isContinuation:q,responseMessage:W.message,messages:[...q?Q.slice(0,-1):Q,W.message],finishReason:W.finishReason})},Z=async()=>{if(!B)return;let q=W.message.id===(D==null?void 0:D.id);try{await B({isContinuation:q,responseMessage:structuredClone(W.message),messages:[...q?Q.slice(0,-1):Q,structuredClone(W.message)]})}catch(E){$(E)}};return HgQ({stream:X,runUpdateMessageJob:U,onError:$}).pipeThrough(new TransformStream({async transform(q,E){if(q.type==="finish-step")await Z();E.enqueue(q)},async cancel(){await F()},async flush(){await F()}}))}var Q6w=uK({prefix:"aitxt",size:24});function Vn0({execute:A,onError:Q=fCA,originalMessages:B,onStepFinish:w,onFinish:$,generateId:I=wn0}){let D,Y=[],X=new ReadableStream({start(K){D=K}});function W(K){try{D.enqueue(K)}catch(F){}}try{let K=A({writer:{write(F){W(F)},merge(F){Y.push((async()=>{let Z=F.getReader();while(!0){let{done:q,value:E}=await Z.read();if(q)break;W(E)}})().catch((Z)=>{W({type:"error",errorText:Q(Z)})}))},onError:Q}});if(K)Y.push(K.catch((F)=>{W({type:"error",errorText:Q(F)})}))}catch(K){W({type:"error",errorText:Q(K)})}return new Promise(async(K)=>{while(Y.length>0)await Y.shift();K()}).finally(()=>{try{D.close()}catch(K){}}),UgQ({stream:X,messageId:I(),originalMessages:B,onStepFinish:w,onFinish:$,onError:Q})}var s4=J.record(J.string(),LE.optional()),I6w=Q1A(()=>Mm(J.array(J.object({id:J.string(),role:J.enum(["system","user","assistant"]),metadata:J.unknown().optional(),parts:J.array(J.union([J.object({type:J.literal("text"),text:J.string(),state:J.enum(["streaming","done"]).optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("reasoning"),text:J.string(),state:J.enum(["streaming","done"]).optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("source-url"),sourceId:J.string(),url:J.string(),title:J.string().optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("source-document"),sourceId:J.string(),mediaType:J.string(),title:J.string(),filename:J.string().optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("file"),mediaType:J.string(),filename:J.string().optional(),url:J.string(),providerMetadata:FQ.optional()}),J.object({type:J.literal("step-start")}),J.object({type:J.string().startsWith("data-"),id:J.string().optional(),data:J.unknown()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-streaming"),input:J.unknown().optional(),providerExecuted:J.boolean().optional(),callProviderMetadata:FQ.optional(),output:J.never().optional(),errorText:J.never().optional(),approval:J.never().optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-available"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.never().optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-requested"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.never().optional(),reason:J.never().optional()})}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-responded"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.boolean(),reason:J.string().optional()})}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-available"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.unknown(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),preliminary:J.boolean().optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-error"),input:J.unknown().optional(),rawInput:J.unknown().optional(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.string(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-denied"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!1),reason:J.string().optional()})}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-streaming"),providerExecuted:J.boolean().optional(),callProviderMetadata:FQ.optional(),input:J.unknown().optional(),output:J.never().optional(),errorText:J.never().optional(),approval:J.never().optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-available"),providerExecuted:J.boolean().optional(),input:J.unknown(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.never().optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-requested"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.never().optional(),reason:J.never().optional()})}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-responded"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.boolean(),reason:J.string().optional()})}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-available"),providerExecuted:J.boolean().optional(),input:J.unknown(),output:J.unknown(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),preliminary:J.boolean().optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-error"),providerExecuted:J.boolean().optional(),input:J.unknown().optional(),rawInput:J.unknown().optional(),output:J.never().optional(),errorText:J.string(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-denied"),providerExecuted:J.boolean().optional(),input:J.unknown(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!1),reason:J.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var Y6w=uK({prefix:"aiobj",size:24});function Mn0(A){return({url:Q,abortSignal:B})=>mSQ({url:Q,maxBytes:A==null?void 0:A.maxBytes,abortSignal:B})}var W6w=uK({prefix:"aiobj",size:24});var H6w=Mn0();var JgQ="AI_NoSuchProviderError",GgQ=`vercel.ai.error.${JgQ}`,KgQ=Symbol.for(GgQ),fgQ;fgQ=KgQ;var U6w=Mn0();import{join as ZgQ}from"path";var Cn0={name:"@brains/web-chat",private:!0,version:"0.2.0-alpha.92",description:"Web chat interface for Brains",type:"module",exports:{".":"./src/index.ts"},files:["src","dist","package.json"],scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",test:"bun test"},dependencies:{"@ai-sdk/react":"^3.0.116","@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@streamdown/cjk":"^1.0.3","@streamdown/code":"^1.1.1","@streamdown/math":"^1.0.2","@streamdown/mermaid":"^1.0.2",ai:"^6.0.86","class-variance-authority":"^0.7.0",cmdk:"^1.1.1","lucide-react":"^1.16.0",nanoid:"^5.0.4","radix-ui":"^1.4.3",react:"^19.2.6","react-dom":"^19.2.6",shiki:"^4.1.0",streamdown:"^2.5.0","use-stick-to-bottom":"^1.1.4"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/react":"^19.0.3","@types/react-dom":"^19.0.3",typescript:"^5.3.3",vite:"^7.2.4"}};fA();var NCA=f.object({routePath:f.string().default("/chat"),apiPath:f.string().default("/api/chat")});var zgQ=f.object({type:f.literal("text"),text:f.string()}),NgQ=f.object({role:f.string(),parts:f.array(f.unknown()).optional(),content:f.string().optional()}),qgQ=f.object({id:f.string().optional(),messages:f.array(NgQ).min(1)}),LgQ=f.object({id:f.string(),confirmed:f.boolean()}),qCA="web-chat",EgQ=25,VgQ=6,On0=48,Rn0="/chat/assets/app.js",MgQ=ZgQ(import.meta.dir,"..","dist","ui","app.js"),CgQ=`
|
|
2399
|
+
`)}})}},DgQ={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function En0({status:A,statusText:Q,headers:B,stream:w,consumeSseStream:$}){let I=w.pipeThrough(new IgQ);if($){let[D,Y]=I.tee();I=D,$({stream:Y})}return new Response(I.pipeThrough(new TextEncoderStream),{status:A,statusText:Q,headers:$gQ(B,DgQ)})}var Cm=J.record(J.string(),LE.optional()),A6w=Q1A(()=>Mm(J.union([J.strictObject({type:J.literal("text-start"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("text-delta"),id:J.string(),delta:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("text-end"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("error"),errorText:J.string()}),J.strictObject({type:J.literal("tool-input-start"),toolCallId:J.string(),toolName:J.string(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),title:J.string().optional()}),J.strictObject({type:J.literal("tool-input-delta"),toolCallId:J.string(),inputTextDelta:J.string()}),J.strictObject({type:J.literal("tool-input-available"),toolCallId:J.string(),toolName:J.string(),input:J.unknown(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),title:J.string().optional()}),J.strictObject({type:J.literal("tool-input-error"),toolCallId:J.string(),toolName:J.string(),input:J.unknown(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),errorText:J.string(),title:J.string().optional()}),J.strictObject({type:J.literal("tool-approval-request"),approvalId:J.string(),toolCallId:J.string()}),J.strictObject({type:J.literal("tool-output-available"),toolCallId:J.string(),output:J.unknown(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional(),preliminary:J.boolean().optional()}),J.strictObject({type:J.literal("tool-output-error"),toolCallId:J.string(),errorText:J.string(),providerExecuted:J.boolean().optional(),providerMetadata:FQ.optional(),toolMetadata:Cm.optional(),dynamic:J.boolean().optional()}),J.strictObject({type:J.literal("tool-output-denied"),toolCallId:J.string()}),J.strictObject({type:J.literal("reasoning-start"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("reasoning-delta"),id:J.string(),delta:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("reasoning-end"),id:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("source-url"),sourceId:J.string(),url:J.string(),title:J.string().optional(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("source-document"),sourceId:J.string(),mediaType:J.string(),title:J.string(),filename:J.string().optional(),providerMetadata:FQ.optional()}),J.strictObject({type:J.literal("file"),url:J.string(),mediaType:J.string(),providerMetadata:FQ.optional()}),J.strictObject({type:J.custom((A)=>typeof A==="string"&&A.startsWith("data-"),{message:'Type must start with "data-"'}),id:J.string().optional(),data:J.unknown(),transient:J.boolean().optional()}),J.strictObject({type:J.literal("start-step")}),J.strictObject({type:J.literal("finish-step")}),J.strictObject({type:J.literal("start"),messageId:J.string().optional(),messageMetadata:J.unknown().optional()}),J.strictObject({type:J.literal("finish"),finishReason:J.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:J.unknown().optional()}),J.strictObject({type:J.literal("abort"),reason:J.string().optional()}),J.strictObject({type:J.literal("message-metadata"),messageMetadata:J.unknown()})])));function YgQ(A){return A.type.startsWith("data-")}function zCA(A){return A.type.startsWith("tool-")}function XgQ(A){return A.type==="dynamic-tool"}function Wn0(A){return zCA(A)||XgQ(A)}function Hn0(A){return A.type.split("-").slice(1).join("-")}function WgQ({lastMessage:A,messageId:Q}){return{message:(A==null?void 0:A.role)==="assistant"?A:{id:Q,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function HgQ({stream:A,messageMetadataSchema:Q,dataPartSchemas:B,runUpdateMessageJob:w,onError:$,onToolCall:I,onData:D}){return A.pipeThrough(new TransformStream({async transform(Y,X){await w(async({state:W,write:U})=>{var K,F,Z,q;function E(O){let n=W.message.parts.filter(Wn0).find((S)=>S.toolCallId===O);if(n==null)throw new rP({chunkType:"tool-invocation",chunkId:O,message:`No tool invocation found for tool call ID "${O}".`});return n}function L(O){var r;let n=W.message.parts.find((T)=>zCA(T)&&T.toolCallId===O.toolCallId),S=O,x=n;if(n!=null){if(n.state=O.state,x.input=S.input,x.output=S.output,x.errorText=S.errorText,x.rawInput=S.rawInput,x.preliminary=S.preliminary,O.title!==void 0)x.title=O.title;if(O.toolMetadata!==void 0)x.toolMetadata=O.toolMetadata;x.providerExecuted=(r=S.providerExecuted)!=null?r:n.providerExecuted;let T=S.providerMetadata;if(T!=null)if(O.state==="output-available"||O.state==="output-error"){let g=n;g.resultProviderMetadata=T}else n.callProviderMetadata=T}else W.message.parts.push({type:`tool-${O.toolName}`,toolCallId:O.toolCallId,state:O.state,title:O.title,...O.toolMetadata!==void 0?{toolMetadata:O.toolMetadata}:{},input:S.input,output:S.output,rawInput:S.rawInput,errorText:S.errorText,providerExecuted:S.providerExecuted,preliminary:S.preliminary,...S.providerMetadata!=null&&(O.state==="output-available"||O.state==="output-error")?{resultProviderMetadata:S.providerMetadata}:{},...S.providerMetadata!=null&&!(O.state==="output-available"||O.state==="output-error")?{callProviderMetadata:S.providerMetadata}:{}})}function R(O){var r,n;let S=W.message.parts.find((g)=>g.type==="dynamic-tool"&&g.toolCallId===O.toolCallId),x=O,T=S;if(S!=null){if(S.state=O.state,T.toolName=O.toolName,T.input=x.input,T.output=x.output,T.errorText=x.errorText,T.rawInput=(r=x.rawInput)!=null?r:T.rawInput,T.preliminary=x.preliminary,O.title!==void 0)T.title=O.title;if(O.toolMetadata!==void 0)T.toolMetadata=O.toolMetadata;T.providerExecuted=(n=x.providerExecuted)!=null?n:S.providerExecuted;let g=x.providerMetadata;if(g!=null)if(O.state==="output-available"||O.state==="output-error"){let e=S;e.resultProviderMetadata=g}else S.callProviderMetadata=g}else W.message.parts.push({type:"dynamic-tool",toolName:O.toolName,toolCallId:O.toolCallId,state:O.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,title:O.title,...O.toolMetadata!==void 0?{toolMetadata:O.toolMetadata}:{},...x.providerMetadata!=null&&(O.state==="output-available"||O.state==="output-error")?{resultProviderMetadata:x.providerMetadata}:{},...x.providerMetadata!=null&&!(O.state==="output-available"||O.state==="output-error")?{callProviderMetadata:x.providerMetadata}:{}})}async function _(O){if(O!=null){let r=W.message.metadata!=null?Ln0(W.message.metadata,O):O;if(Q!=null)await $1A({value:r,schema:Q,context:{field:"message.metadata",entityId:W.message.id}});W.message.metadata=r}}switch(Y.type){case"text-start":{let O={type:"text",text:"",providerMetadata:Y.providerMetadata,state:"streaming"};W.activeTextParts[Y.id]=O,W.message.parts.push(O),U();break}case"text-delta":{let O=W.activeTextParts[Y.id];if(O==null)throw new rP({chunkType:"text-delta",chunkId:Y.id,message:`Received text-delta for missing text part with ID "${Y.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});O.text+=Y.delta,O.providerMetadata=(K=Y.providerMetadata)!=null?K:O.providerMetadata,U();break}case"text-end":{let O=W.activeTextParts[Y.id];if(O==null)throw new rP({chunkType:"text-end",chunkId:Y.id,message:`Received text-end for missing text part with ID "${Y.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});O.state="done",O.providerMetadata=(F=Y.providerMetadata)!=null?F:O.providerMetadata,delete W.activeTextParts[Y.id],U();break}case"reasoning-start":{let O={type:"reasoning",text:"",providerMetadata:Y.providerMetadata,state:"streaming"};W.activeReasoningParts[Y.id]=O,W.message.parts.push(O),U();break}case"reasoning-delta":{let O=W.activeReasoningParts[Y.id];if(O==null)throw new rP({chunkType:"reasoning-delta",chunkId:Y.id,message:`Received reasoning-delta for missing reasoning part with ID "${Y.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});O.text+=Y.delta,O.providerMetadata=(Z=Y.providerMetadata)!=null?Z:O.providerMetadata,U();break}case"reasoning-end":{let O=W.activeReasoningParts[Y.id];if(O==null)throw new rP({chunkType:"reasoning-end",chunkId:Y.id,message:`Received reasoning-end for missing reasoning part with ID "${Y.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});O.providerMetadata=(q=Y.providerMetadata)!=null?q:O.providerMetadata,O.state="done",delete W.activeReasoningParts[Y.id],U();break}case"file":{W.message.parts.push({type:"file",mediaType:Y.mediaType,url:Y.url,...Y.providerMetadata!=null?{providerMetadata:Y.providerMetadata}:{}}),U();break}case"source-url":{W.message.parts.push({type:"source-url",sourceId:Y.sourceId,url:Y.url,title:Y.title,providerMetadata:Y.providerMetadata}),U();break}case"source-document":{W.message.parts.push({type:"source-document",sourceId:Y.sourceId,mediaType:Y.mediaType,title:Y.title,filename:Y.filename,providerMetadata:Y.providerMetadata}),U();break}case"tool-input-start":{let O=W.message.parts.filter(zCA);if(W.partialToolCalls[Y.toolCallId]={text:"",toolName:Y.toolName,index:O.length,dynamic:Y.dynamic,title:Y.title,toolMetadata:Y.toolMetadata},Y.dynamic)R({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-streaming",input:void 0,providerExecuted:Y.providerExecuted,title:Y.title,toolMetadata:Y.toolMetadata,providerMetadata:Y.providerMetadata});else L({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-streaming",input:void 0,providerExecuted:Y.providerExecuted,title:Y.title,toolMetadata:Y.toolMetadata,providerMetadata:Y.providerMetadata});U();break}case"tool-input-delta":{let O=W.partialToolCalls[Y.toolCallId];if(O==null)throw new rP({chunkType:"tool-input-delta",chunkId:Y.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${Y.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});O.text+=Y.inputTextDelta;let{value:r}=await Om(O.text);if(O.dynamic)R({toolCallId:Y.toolCallId,toolName:O.toolName,state:"input-streaming",input:r,title:O.title,toolMetadata:O.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:O.toolName,state:"input-streaming",input:r,title:O.title,toolMetadata:O.toolMetadata});U();break}case"tool-input-available":{if(Y.dynamic)R({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-available",input:Y.input,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:Y.title,toolMetadata:Y.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"input-available",input:Y.input,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:Y.title,toolMetadata:Y.toolMetadata});if(U(),I&&!Y.providerExecuted)await I({toolCall:Y});break}case"tool-input-error":{let O=W.message.parts.filter(Wn0).find((n)=>n.toolCallId===Y.toolCallId);if(O!=null?O.type==="dynamic-tool":!!Y.dynamic)R({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"output-error",input:Y.input,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,toolMetadata:Y.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Y.toolName,state:"output-error",input:void 0,rawInput:Y.input,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,toolMetadata:Y.toolMetadata});U();break}case"tool-approval-request":{let O=E(Y.toolCallId);O.state="approval-requested",O.approval={id:Y.approvalId},U();break}case"tool-output-denied":{let O=E(Y.toolCallId);O.state="output-denied",U();break}case"tool-output-available":{let O=E(Y.toolCallId);if(O.type==="dynamic-tool")R({toolCallId:Y.toolCallId,toolName:O.toolName,state:"output-available",input:O.input,output:Y.output,preliminary:Y.preliminary,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Hn0(O),state:"output-available",input:O.input,output:Y.output,providerExecuted:Y.providerExecuted,preliminary:Y.preliminary,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});U();break}case"tool-output-error":{let O=E(Y.toolCallId);if(O.type==="dynamic-tool")R({toolCallId:Y.toolCallId,toolName:O.toolName,state:"output-error",input:O.input,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});else L({toolCallId:Y.toolCallId,toolName:Hn0(O),state:"output-error",input:O.input,rawInput:O.rawInput,errorText:Y.errorText,providerExecuted:Y.providerExecuted,providerMetadata:Y.providerMetadata,title:O.title,toolMetadata:O.toolMetadata});U();break}case"start-step":{W.message.parts.push({type:"step-start"});break}case"finish-step":{W.activeTextParts={},W.activeReasoningParts={};break}case"start":{if(Y.messageId!=null)W.message.id=Y.messageId;if(await _(Y.messageMetadata),Y.messageId!=null||Y.messageMetadata!=null)U();break}case"finish":{if(Y.finishReason!=null)W.finishReason=Y.finishReason;if(await _(Y.messageMetadata),Y.messageMetadata!=null)U();break}case"message-metadata":{if(await _(Y.messageMetadata),Y.messageMetadata!=null)U();break}case"error":{$==null||$(Error(Y.errorText));break}default:if(YgQ(Y)){if((B==null?void 0:B[Y.type])!=null){let n=W.message.parts.findIndex((x)=>("id"in x)&&("data"in x)&&x.id===Y.id&&x.type===Y.type),S=n>=0?n:W.message.parts.length;await $1A({value:Y.data,schema:B[Y.type],context:{field:`message.parts[${S}].data`,entityName:Y.type,entityId:Y.id}})}let O=Y;if(O.transient){D==null||D(O);break}let r=O.id!=null?W.message.parts.find((n)=>O.type===n.type&&O.id===n.id):void 0;if(r!=null)r.data=O.data;else W.message.parts.push(O);D==null||D(O),U()}}X.enqueue(Y)})}}))}function UgQ({messageId:A,originalMessages:Q=[],onStepFinish:B,onFinish:w,onError:$,stream:I}){let D=Q==null?void 0:Q[Q.length-1];if((D==null?void 0:D.role)!=="assistant")D=void 0;else A=D.id;let Y=!1,X=I.pipeThrough(new TransformStream({transform(q,E){if(q.type==="start"){let L=q;if(L.messageId==null&&A!=null)L.messageId=A}if(q.type==="abort")Y=!0;E.enqueue(q)}}));if(w==null&&B==null)return X;let W=WgQ({lastMessage:D?structuredClone(D):void 0,messageId:A!=null?A:""}),U=async(q)=>{await q({state:W,write:()=>{}})},K=!1,F=async()=>{if(K||!w)return;K=!0;let q=W.message.id===(D==null?void 0:D.id);await w({isAborted:Y,isContinuation:q,responseMessage:W.message,messages:[...q?Q.slice(0,-1):Q,W.message],finishReason:W.finishReason})},Z=async()=>{if(!B)return;let q=W.message.id===(D==null?void 0:D.id);try{await B({isContinuation:q,responseMessage:structuredClone(W.message),messages:[...q?Q.slice(0,-1):Q,structuredClone(W.message)]})}catch(E){$(E)}};return HgQ({stream:X,runUpdateMessageJob:U,onError:$}).pipeThrough(new TransformStream({async transform(q,E){if(q.type==="finish-step")await Z();E.enqueue(q)},async cancel(){await F()},async flush(){await F()}}))}var Q6w=uK({prefix:"aitxt",size:24});function Vn0({execute:A,onError:Q=fCA,originalMessages:B,onStepFinish:w,onFinish:$,generateId:I=wn0}){let D,Y=[],X=new ReadableStream({start(K){D=K}});function W(K){try{D.enqueue(K)}catch(F){}}try{let K=A({writer:{write(F){W(F)},merge(F){Y.push((async()=>{let Z=F.getReader();while(!0){let{done:q,value:E}=await Z.read();if(q)break;W(E)}})().catch((Z)=>{W({type:"error",errorText:Q(Z)})}))},onError:Q}});if(K)Y.push(K.catch((F)=>{W({type:"error",errorText:Q(F)})}))}catch(K){W({type:"error",errorText:Q(K)})}return new Promise(async(K)=>{while(Y.length>0)await Y.shift();K()}).finally(()=>{try{D.close()}catch(K){}}),UgQ({stream:X,messageId:I(),originalMessages:B,onStepFinish:w,onFinish:$,onError:Q})}var s4=J.record(J.string(),LE.optional()),I6w=Q1A(()=>Mm(J.array(J.object({id:J.string(),role:J.enum(["system","user","assistant"]),metadata:J.unknown().optional(),parts:J.array(J.union([J.object({type:J.literal("text"),text:J.string(),state:J.enum(["streaming","done"]).optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("reasoning"),text:J.string(),state:J.enum(["streaming","done"]).optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("source-url"),sourceId:J.string(),url:J.string(),title:J.string().optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("source-document"),sourceId:J.string(),mediaType:J.string(),title:J.string(),filename:J.string().optional(),providerMetadata:FQ.optional()}),J.object({type:J.literal("file"),mediaType:J.string(),filename:J.string().optional(),url:J.string(),providerMetadata:FQ.optional()}),J.object({type:J.literal("step-start")}),J.object({type:J.string().startsWith("data-"),id:J.string().optional(),data:J.unknown()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-streaming"),input:J.unknown().optional(),providerExecuted:J.boolean().optional(),callProviderMetadata:FQ.optional(),output:J.never().optional(),errorText:J.never().optional(),approval:J.never().optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-available"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.never().optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-requested"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.never().optional(),reason:J.never().optional()})}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-responded"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.boolean(),reason:J.string().optional()})}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-available"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.unknown(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),preliminary:J.boolean().optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-error"),input:J.unknown().optional(),rawInput:J.unknown().optional(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.string(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.literal("dynamic-tool"),toolName:J.string(),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-denied"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!1),reason:J.string().optional()})}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-streaming"),providerExecuted:J.boolean().optional(),callProviderMetadata:FQ.optional(),input:J.unknown().optional(),output:J.never().optional(),errorText:J.never().optional(),approval:J.never().optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("input-available"),providerExecuted:J.boolean().optional(),input:J.unknown(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.never().optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-requested"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.never().optional(),reason:J.never().optional()})}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("approval-responded"),input:J.unknown(),providerExecuted:J.boolean().optional(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.boolean(),reason:J.string().optional()})}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-available"),providerExecuted:J.boolean().optional(),input:J.unknown(),output:J.unknown(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),preliminary:J.boolean().optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-error"),providerExecuted:J.boolean().optional(),input:J.unknown().optional(),rawInput:J.unknown().optional(),output:J.never().optional(),errorText:J.string(),callProviderMetadata:FQ.optional(),resultProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!0),reason:J.string().optional()}).optional()}),J.object({type:J.string().startsWith("tool-"),toolCallId:J.string(),toolMetadata:s4.optional(),state:J.literal("output-denied"),providerExecuted:J.boolean().optional(),input:J.unknown(),output:J.never().optional(),errorText:J.never().optional(),callProviderMetadata:FQ.optional(),approval:J.object({id:J.string(),approved:J.literal(!1),reason:J.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var Y6w=uK({prefix:"aiobj",size:24});function Mn0(A){return({url:Q,abortSignal:B})=>mSQ({url:Q,maxBytes:A==null?void 0:A.maxBytes,abortSignal:B})}var W6w=uK({prefix:"aiobj",size:24});var H6w=Mn0();var JgQ="AI_NoSuchProviderError",GgQ=`vercel.ai.error.${JgQ}`,KgQ=Symbol.for(GgQ),fgQ;fgQ=KgQ;var U6w=Mn0();import{join as ZgQ}from"path";var Cn0={name:"@brains/web-chat",private:!0,version:"0.2.0-alpha.93",description:"Web chat interface for Brains",type:"module",exports:{".":"./src/index.ts"},files:["src","dist","package.json"],scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",test:"bun test"},dependencies:{"@ai-sdk/react":"^3.0.116","@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@streamdown/cjk":"^1.0.3","@streamdown/code":"^1.1.1","@streamdown/math":"^1.0.2","@streamdown/mermaid":"^1.0.2",ai:"^6.0.86","class-variance-authority":"^0.7.0",cmdk:"^1.1.1","lucide-react":"^1.16.0",nanoid:"^5.0.4","radix-ui":"^1.4.3",react:"^19.2.6","react-dom":"^19.2.6",shiki:"^4.1.0",streamdown:"^2.5.0","use-stick-to-bottom":"^1.1.4"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/react":"^19.0.3","@types/react-dom":"^19.0.3",typescript:"^5.3.3",vite:"^7.2.4"}};fA();var NCA=f.object({routePath:f.string().default("/chat"),apiPath:f.string().default("/api/chat")});var zgQ=f.object({type:f.literal("text"),text:f.string()}),NgQ=f.object({role:f.string(),parts:f.array(f.unknown()).optional(),content:f.string().optional()}),qgQ=f.object({id:f.string().optional(),messages:f.array(NgQ).min(1)}),LgQ=f.object({id:f.string(),confirmed:f.boolean()}),qCA="web-chat",EgQ=25,VgQ=6,On0=48,Rn0="/chat/assets/app.js",MgQ=ZgQ(import.meta.dir,"..","dist","ui","app.js"),CgQ=`
|
|
2400
2400
|
/* \u2500\u2500\u2500 Chat tokens \u2014 alias chain pattern matching plugins/dashboard.
|
|
2401
2401
|
Each --chat-* falls back through:
|
|
2402
2402
|
dashboard token (if embedded in a dashboard) \u2192
|
|
@@ -2565,7 +2565,7 @@ button, textarea, input { font: inherit; color: inherit; }
|
|
|
2565
2565
|
.web-chat-header {
|
|
2566
2566
|
display: grid;
|
|
2567
2567
|
grid-template-columns: 1fr auto;
|
|
2568
|
-
align-items:
|
|
2568
|
+
align-items: start;
|
|
2569
2569
|
gap: 1rem;
|
|
2570
2570
|
}
|
|
2571
2571
|
.web-chat-header-eyebrow {
|
|
@@ -2637,11 +2637,14 @@ button, textarea, input { font: inherit; color: inherit; }
|
|
|
2637
2637
|
}
|
|
2638
2638
|
.web-chat-secondary-action svg { width: 12px; height: 12px; }
|
|
2639
2639
|
|
|
2640
|
-
/* Header actions cluster \u2014 theme toggle + New button.
|
|
2640
|
+
/* Header actions cluster \u2014 theme toggle + New button. Sits at the
|
|
2641
|
+
top-right of the header; padding-top aligns it with the h1 baseline
|
|
2642
|
+
rather than the very top of the eyebrow. */
|
|
2641
2643
|
.web-chat-header-actions {
|
|
2642
2644
|
display: inline-flex;
|
|
2643
2645
|
align-items: center;
|
|
2644
2646
|
gap: 0.5rem;
|
|
2647
|
+
padding-top: 1.4rem;
|
|
2645
2648
|
}
|
|
2646
2649
|
.web-chat-icon-action {
|
|
2647
2650
|
display: inline-flex;
|
|
@@ -3630,8 +3633,17 @@ details.web-chat-data-part[open] > summary > .web-chat-data-part-chevron {
|
|
|
3630
3633
|
anchors to the page edge, matching the mockup. */
|
|
3631
3634
|
.web-chat-header {
|
|
3632
3635
|
grid-template-columns: auto 1fr auto;
|
|
3636
|
+
align-items: center;
|
|
3633
3637
|
gap: 0.5rem;
|
|
3634
3638
|
}
|
|
3639
|
+
.web-chat-header-actions { padding-top: 0; }
|
|
3640
|
+
/* Match the theme toggle size to its neighbors (hamburger + New are
|
|
3641
|
+
both 40\xD740 on mobile) so the action row reads as one band. */
|
|
3642
|
+
.web-chat-icon-action {
|
|
3643
|
+
width: 40px;
|
|
3644
|
+
height: 40px;
|
|
3645
|
+
}
|
|
3646
|
+
.web-chat-icon-action svg { width: 16px; height: 16px; }
|
|
3635
3647
|
.web-chat-header-eyebrow { display: none; }
|
|
3636
3648
|
.web-chat-header p { display: none; }
|
|
3637
3649
|
.web-chat-header h1 {
|
|
@@ -3747,7 +3759,7 @@ details.web-chat-data-part[open] > summary > .web-chat-data-part-chevron {
|
|
|
3747
3759
|
|
|
3748
3760
|
`);$=D.pop()??"";for(let Y of D){let X=Y.split(`
|
|
3749
3761
|
`).find((L)=>L.startsWith("data: "));if(!X)continue;let W;try{W=JSON.parse(X.slice(6))}catch{return B.cancel().catch(()=>{}),{success:!1,error:"Malformed SSE event from remote agent"}}let U=W.result;if(!U)continue;if(U.final!==!0)continue;B.cancel().catch(()=>{});let F=U.status,Z=F?.state??"unknown",E=(F?.message?.parts??[]).filter((L)=>L.kind==="text"&&typeof L.text==="string").map((L)=>L.text).join(`
|
|
3750
|
-
`)||"No response text";return{success:!0,data:{state:Z,response:E}}}I=await Sn0(B,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class Rm extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A;this.name="A2ARequestTimeoutError"}}class bm extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A;this.name="A2AStreamIdleTimeoutError"}}async function ugQ(A,Q,B,w){let $=new AbortController,I;try{return await Promise.race([A(Q,{...B,signal:$.signal}),new Promise((D,Y)=>{I=setTimeout(()=>{$.abort(),Y(new Rm(w))},w)})])}catch(D){if(D instanceof Rm)throw D;if($.signal.aborted)throw new Rm(w);throw D}finally{if(I)clearTimeout(I)}}async function Sn0(A,Q){let B;try{return await Promise.race([A.read(),new Promise((w,$)=>{B=setTimeout(()=>$(new bm(Q)),Q)})])}catch(w){if(w instanceof bm)A.cancel().catch(()=>{});throw w}finally{if(B)clearTimeout(B)}}function cgQ(A){if(A instanceof Rm||A instanceof bm)return!0;return A instanceof Error}function pgQ(A,Q){let B=Q>1?` after ${Q} attempts`:"";if(A instanceof bm)return`${A.message}${B}`;let w=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${B}: ${w}`}function hn0(A={}){let Q=A.fetch??globalThis.fetch,B={requestTimeoutMs:A.requestTimeoutMs??xgQ,streamIdleTimeoutMs:A.streamIdleTimeoutMs??ygQ,maxNetworkAttempts:A.maxNetworkAttempts??TgQ};return{name:"a2a_call",description:"Call a saved remote A2A agent by its local directory id. Use this when the user asks what a saved agent has to say or asks a saved agent for its skills/capabilities. Use only a saved agent id such as yeehaa.io. Never pass a display name like Brain, never pass a full URL, and do not use this tool to probe whether an agent exists. If the user gives a URL, an unsaved agent, or an ambiguous name, ask them to add/save or clarify the agent first.",inputSchema:Tn0,visibility:"anchor",handler:async(w)=>{let $=f.object(Tn0).safeParse(w);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};let{agent:I,message:D}=$.data,Y=SgQ(I);if(!Y)return{success:!1,error:"Invalid agent id. Use a saved agent id from your directory, not a URL."};if(!A.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let X=await A.entityService.getEntity({entityType:"agent",id:Y,visibilityScope:F$("a2a_call tool is anchor-only and resolves saved remote agents at any visibility")});if(!X)return{success:!1,error:`Agent ${Y} is not in your directory. Add it first.`};if(X.metadata.status!=="approved")return{success:!1,error:`Agent ${Y} is discovered but not approved yet. Approve it first.`};let W=`https://${Y}`,U=await ggQ(W,Q);if(!U)return{success:!1,error:`Could not fetch Agent Card from ${W}`};let K=U.url,F;if(A.outboundTokens)try{let Z=new URL(K).hostname;F=A.outboundTokens[Z]}catch{}return hgQ(K,D,Q,F,B)}}}var MCA={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.92",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@a2a-js/sdk":"^0.3.12","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",hono:"^4.7.10"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",typescript:"^5.3.3"}};var igQ={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff"};class nP extends nH{agentCard;taskManager=new ECA;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",MCA,A,bn0)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agent,this.permissionContext=A.permissions,this.hasWebserver)A.endpoints.register({label:"A2A",url:"/a2a",priority:25}),A.interactions.register({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),this.logger.info("A2A interface registered",{domain:A.domain});else this.logger.info("A2A interface registered in tool-only mode",{domain:A.domain})}async onReady(A){await this.rebuildAgentCard(A)}async rebuildAgentCard(A){let Q=A.identity.get(),B=A.identity.getProfile(),w=A.tools.listForPermissionLevel("public"),$=this.config.trustedTokens&&Object.keys(this.config.trustedTokens).length>0,I;if(A.entityService.hasEntityType("skill"))try{let D=await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}});if(D.length>0)I=D.map((Y)=>uI.safeParse(Y.metadata)).filter((Y)=>Y.success).map((Y)=>Y.data)}catch{}this.agentCard=Pn0({character:Q,profile:B,version:MCA.version,domain:A.domain,organization:this.config.organization,tools:w,skills:I,authEnabled:$}),this.logger.debug("Agent Card rebuilt",{skills:this.agentCard.skills.length})}getAgentCard(){return this.agentCard}resolveCallerPermission(A){if(!A?.startsWith("Bearer ")||!this.config.trustedTokens)return"public";let Q=A.slice(7),B=this.config.trustedTokens[Q];if(!B||!this.permissionContext)return"public";return this.permissionContext.getUserLevel("a2a",B)}withCors(A){let Q=new Headers(A.headers);for(let[B,w]of Object.entries(igQ))Q.set(B,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}getOrCreateApp(){if(this.app)return this.app;let A=new pP;return A.get("/.well-known/agent-card.json",(Q)=>{if(!this.agentCard)return this.withCors(Q.json({error:"Agent Card not ready"},503));return this.withCors(Q.json(this.agentCard))}),A.get("/a2a",(Q)=>{return this.withCors(Q.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))}),A.options("/a2a",()=>this.withCors(new Response(null,{status:204}))),A.post("/a2a",async(Q)=>{if(!this.agentService)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32603,message:"Agent service not ready"},id:null},503));let B;try{B=await Q.req.json()}catch{return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let w=_n0.safeParse(B);if(!w.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));let $=this.resolveCallerPermission(Q.req.header("Authorization"));if(w.data.method==="message/stream"){let D=xn0.safeParse(w.data.params??{});if(!D.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${D.error.message}`},id:w.data.id}));let{stream:Y}=yn0(w.data.id,D.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(new Response(Y,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let I=await vn0(w.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(Q.json(I))}),this.app=A,A}getWebRoutes(){if(!this.hasWebserver)return[];let A=(Q)=>Promise.resolve(this.getOrCreateApp().fetch(Q));return[{path:"/.well-known/agent-card.json",method:"GET",public:!0,handler:A},{path:"/a2a",method:"GET",public:!0,handler:A},{path:"/a2a",method:"POST",public:!0,handler:A},{path:"/a2a",method:"OPTIONS",public:!0,handler:A}]}async getTools(){return[hn0({outboundTokens:this.config.outboundTokens,requestTimeoutMs:this.config.requestTimeoutMs,streamIdleTimeoutMs:this.config.streamIdleTimeoutMs,maxNetworkAttempts:this.config.maxNetworkAttempts,entityService:this.getContext().entityService})]}async getInstructions(){return"## Agent-to-agent calls\n- Use `a2a_call` only for agents already saved in the local `agent` directory.\n- Pass only the saved local agent id to `a2a_call` (for example `yeehaa.io`). Never pass a full URL or a display name like `Brain`.\n- If the user asks you to ask, message, contact, hear what a saved agent has to say, or ask a saved agent for its own skills/capabilities, treat that as an agent-directory request first and call `a2a_call` in the same turn. Do not stop after listing the agent, drafting the question, searching general content locally, or reading the saved agent entity metadata.\n- If the user gives a full URL for an agent, do not pass that URL to `a2a_call`. Use a saved local agent id only. If that URL is not already saved in the local directory, tell the user to add it first.\n- If the user refers to an agent by name, first make sure that name resolves to exactly one saved agent id. If multiple saved agents could match, ask a concise clarification question naming the matching saved agent ids and do not call any agent yet. Never choose the first match.\n- After asking that clarification question, end the turn. Do not call `a2a_call` later in the same turn.\n- If the target agent is not in the directory, do not create a wish, reminder, todo, note, fallback task, or any new entity. Tell the user to add it first.\n- In these invalid agent-target cases, do not call any tool unless the user explicitly asks you to add/save the agent.\n- Only use creation tools for an agent if the user explicitly asks you to add or save that agent.\n- If the target agent is discovered but not approved yet, do not call it and do not create a wish. Tell the user it must be approved first."}createDaemon(){return{start:async()=>{if(this.hasWebserver)this.logger.info("A2A mounted on shared webserver host");else this.logger.info("A2A running without webserver routes")},stop:async()=>{this.logger.info("A2A server stopped")}}}}eA();class CCA{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,B,w,$=!0){if(this.logger=A,this.fileOperations=w,this.deleteOnFileRemoval=$,B)this.handleImport=async(I)=>{let D=await B({type:"directory-import",data:{paths:[I]}});this.logger.debug("Queued import job for file change",{jobId:D,path:I})},this.handleDelete=async(I)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:I});return}try{let{entityType:D,id:Y}=this.fileOperations.parseEntityFromPath(I),X=await B({type:"directory-delete",data:{entityId:Y,entityType:D,filePath:I}});this.logger.info("Queued delete job for removed file",{jobId:X,path:I,entityId:Y,entityType:D})}catch(D){this.logger.warn("Could not extract entity info from deleted file",{path:I,error:D})}};else this.handleImport=async(I)=>{await Q([I])},this.handleDelete=async(I)=>{this.logger.warn("File deleted but no job queue available",{path:I})}}async handleFileChange(A,Q){this.logger.debug("Processing file change",{event:A,path:Q});try{switch(A){case"add":case"change":await this.handleImport(Q);break;case"delete":case"unlink":await this.handleDelete(Q);break;default:this.logger.debug("Unhandled file event",{event:A,path:Q})}}catch(B){this.logger.error("Failed to handle file change",{event:A,path:Q,error:B})}}}var wa0=X1(Aa0(),1);import{extname as ppQ}from"path";var C1A=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function CE(A){let Q=ppQ(A).toLowerCase();return C1A.includes(Q)}function Qa0(A){switch(A.toLowerCase().replace(".","")){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";default:return"image/png"}}function MOA(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as lpQ,relative as ipQ,sep as Ba0,join as dpQ}from"path";function hY(A,Q){return lpQ(Q)?Q:dpQ(A,Q)}function Qj(A,Q){let B=hY(A,Q),w=ipQ(A,B);return Ba0==="/"?w:w.split(Ba0).join("/")}function rpQ(A,Q){if(!Qj(Q,A).startsWith("image/"))return!1;return CE(A)}function npQ(A,Q){if(Qj(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return rpQ(A,Q)}class COA{watcher;watchCallback;pendingChanges=new Map;batchTimeout;syncPath;watchInterval;logger;onFileChange;constructor(A){this.syncPath=A.syncPath,this.watchInterval=A.watchInterval,this.logger=A.logger,this.onFileChange=A.onFileChange}async start(){if(this.watcher){this.logger.debug("Already watching directory");return}if(this.logger.debug("Starting directory watch",{path:this.syncPath,interval:this.watchInterval}),this.watcher=wa0.default.watch(this.syncPath,{ignored:/(^|[/\\])\../,persistent:!0,interval:this.watchInterval,awaitWriteFinish:{stabilityThreshold:2000,pollInterval:100}}),this.watcher.on("add",(A)=>void this.handleFileChange("add",A)).on("change",(A)=>void this.handleFileChange("change",A)).on("unlink",(A)=>void this.handleFileChange("delete",A)).on("error",(A)=>this.logger.error("Watcher error",A)),this.watchCallback)this.watcher.on("all",this.watchCallback)}stop(){if(this.watcher)this.watcher.close(),this.watcher=void 0,this.logger.info("Stopped directory watch");if(this.batchTimeout)clearTimeout(this.batchTimeout),this.batchTimeout=void 0}setCallback(A){if(this.watchCallback=A,this.watcher)this.watcher.on("all",A)}async handleFileChange(A,Q){if(!npQ(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let B=Qj(this.syncPath,Q);if(this.pendingChanges.set(B,A),this.batchTimeout)clearTimeout(this.batchTimeout);this.batchTimeout=setTimeout(()=>{this.processPendingChanges()},500)}async processPendingChanges(){if(this.pendingChanges.size===0)return;let A=new Map(this.pendingChanges);this.pendingChanges.clear(),this.batchTimeout=void 0,this.logger.debug("Processing batched file changes",{changeCount:A.size});for(let[Q,B]of A){let w=hY(this.syncPath,Q);try{if(this.onFileChange)await this.onFileChange(B,w)}catch($){this.logger.error("Error processing file change",{path:Q,event:B,error:$})}}}isWatching(){return!!this.watcher}getPendingChangesCount(){return this.pendingChanges.size}}async function $a0(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return opQ(Q)}function Ia0(A){if(A)A.stop();return}function Da0(A,Q){if(A)A.setCallback(Q)}async function opQ(A){let{logger:Q,syncPath:B,watchInterval:w,importEntities:$,jobQueueCallback:I,fileOperations:D,deleteOnFileRemoval:Y}=A,X=new CCA(Q,$,I,D,Y),W=new COA({syncPath:B,watchInterval:w,logger:Q,onFileChange:async(U,K)=>{await X.handleFileChange(U,K)}});return await W.start(),W}async function Ya0(A){let Q=Date.now();A.logger.debug("Starting sync (import only)");let B=await A.importEntities(),w=await A.removeOrphanedEntities(),$=Date.now()-Q;return A.markSynced(new Date),A.logger.debug("Sync completed",{duration:$,imported:B.imported,orphansDeleted:w.deleted}),{export:{exported:0,failed:0,errors:[]},import:B,duration:$}}eA();class OOA{logger;syncPath;deleteOnFileRemoval;constructor(A){this.logger=A.logger,this.syncPath=A.syncPath,this.deleteOnFileRemoval=A.deleteOnFileRemoval}prepareBatchOperations(A){let Q=[],B=this.createImportOperations(A);Q.push(...B);let w=B.length;if(this.deleteOnFileRemoval)Q.push({type:"directory-cleanup",data:{}});let $=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:w,totalFiles:$}),{operations:Q,exportOperationsCount:0,importOperationsCount:w,totalFiles:$}}async queueSyncBatch(A,Q,B,w){let $=this.prepareBatchOperations(B);if($.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch($.operations,{source:Q,rootJobId:w?.rootJobId??g5(),metadata:{progressToken:w?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:w?.pluginId??"directory-sync",interfaceType:w?.interfaceType,channelId:w?.channelId}}),operationCount:$.operations.length,exportOperationsCount:$.exportOperationsCount,importOperationsCount:$.importOperationsCount,totalFiles:$.totalFiles}}createImportOperations(A){if(A.length===0)return[];let Q=50,B=[];for(let w=0;w<A.length;w+=Q){let $=A.slice(w,w+Q);B.push({type:"directory-import",data:{batchIndex:Math.floor(w/Q),paths:$,batchSize:$.length}})}return B}}class ROA{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new OOA({logger:A.logger,syncPath:A.syncPath,deleteOnFileRemoval:A.deleteOnFileRemoval})}async queueSyncBatch(A,Q,B){if(this.syncInProgress)return this.logger.debug("Sync already in progress, skipping",{source:Q}),null;this.syncInProgress=!0;try{let w=await this.fileOperations.getAllSyncFiles();return await this.batchOperationsManager.queueSyncBatch(A,Q,w,B)}finally{this.syncInProgress=!1}}}class bOA{options;constructor(A){this.options=A}createExportDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImportDeps(A){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,quarantine:this.options.quarantine,imageJobQueue:this.createImageJobQueueDeps(),entityTypes:A}}createCleanupDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImageJobQueueDeps(){return{logger:this.options.logger,syncPath:this.options.syncPath,jobQueueCallback:this.options.getJobQueueCallback(),coverImageConverter:this.options.coverImageConverter,inlineImageConverter:this.options.inlineImageConverter}}}import{basename as QlQ,dirname as BlQ,extname as wlQ}from"path";import{extname as spQ}from"path";var O1A=[".pdf"],Xa0=".meta.json";function OE(A){let Q=spQ(A).toLowerCase();return O1A.includes(Q)}function Wa0(A){return A.toLowerCase().endsWith(Xa0)}function POA(A){return`${A}${Xa0}`}function Ha0(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as apQ,join as R1A}from"path";function b1A(A,Q){let w=Qj(A,Q).split("/"),$,I;if(w.length===1)$="base",I=w;else if(w.length>1&&w[0])$=w[0],I=w.slice(1);else $="base",I=w;let D;if(I.length>1){let Y=I[I.length-1];if(Y)I[I.length-1]=Ua0(Y);D=I.join(":")}else D=Ua0(I[0]??"");return{entityType:$,id:D}}function Ja0(A,Q,B,w=".md"){let $=Q.split(":").filter((W)=>W.length>0),I=B==="base";if($.length===1)return I?R1A(A,`${$[0]}${w}`):R1A(A,B,`${$[0]}${w}`);let D=$;if($[0]===B)D=$.slice(1);let Y=D[D.length-1],X=D.slice(0,-1);if(I)return R1A(A,...X,`${Y}${w}`);return R1A(A,B,...X,`${Y}${w}`)}function Ga0(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return MOA(Q);let B=A.content.match(/^data:image\/([a-z+]+);base64,/i);return B?.[1]?MOA(B[1]):".md"}function Ua0(A){let Q=apQ(A).toLowerCase();return Q===".md"||C1A.includes(Q)||O1A.includes(Q)?A.slice(0,-Q.length):A}YY();import{mkdir as $lQ,readFile as Bj,writeFile as kOA,stat as IlQ,utimes as DlQ}from"fs/promises";import{join as P1A}from"path";import{mkdir as Ka0,readdir as epQ,stat as AlQ}from"fs/promises";import{access as tpQ}from"fs/promises";async function c6(A){try{return await tpQ(A),!0}catch{return!1}}async function jOA(A,Q){return za0(A,Q,{includeDocuments:!1,includeImages:!1})}async function fa0(A,Q){return za0(A,Q,{includeDocuments:!0,includeImages:!0})}async function Fa0(A,Q){if(!await c6(A))await Ka0(A,{recursive:!0});for(let B of Q)if(B!=="base")await Ka0(P1A(A,B),{recursive:!0})}async function Za0(A,Q){let B=[],w={totalFiles:0,byEntityType:{}};if(!await c6(A))return{files:B,stats:w};let $=await jOA(A,Q);for(let I of $)try{let D=P1A(A,I),Y=await AlQ(D),{entityType:X}=b1A(A,I);B.push({path:I,entityType:X,modified:Y.mtime}),w.totalFiles++,w.byEntityType[X]=(w.byEntityType[X]??0)+1}catch{continue}return{files:B,stats:w}}async function za0(A,Q,B){let w=[];if(!await c6(A))return w;let $=async(I,D="",Y=!1,X=!1)=>{let W=await epQ(I,{withFileTypes:!0});for(let U of W){let K=D?P1A(D,U.name):U.name;if(U.isFile()&&!U.name.endsWith(".invalid")&&!Wa0(U.name)){if(U.name.endsWith(".md"))w.push(K);else if(B.includeImages&&Y&&CE(U.name))w.push(K);else if(B.includeDocuments&&X&&OE(U.name))w.push(K)}else if(U.isDirectory()&&!U.name.startsWith(".")){if(D===""&&!Q.hasEntityType(U.name))continue;let F=P1A(I,U.name),Z=U.name==="image"&&D==="",q=U.name==="document"&&D==="";await $(F,K,Y||Z,X||q)}}};return await $(A),w}function YlQ(A){return typeof A==="object"&&A!==null}class _OA{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return b1A(this.syncPath,A)}async readEntity(A){let Q=hY(this.syncPath,A),B=await IlQ(Q),{entityType:w,id:$}=this.parseEntityFromPath(A),I=B.birthtime.getTime()>0?B.birthtime:B.mtime,D=B.mtime,Y,X;if(CE(A)||OE(A)){let K=(await Bj(Q)).toString("base64"),F=wlQ(A);if(Y=`data:${OE(A)?Ha0(F):Qa0(F)};base64,${K}`,OE(A))X=await this.readDocumentSidecar(Q,A)}else Y=await Bj(Q,"utf-8");let W={entityType:w,id:$,content:Y,created:I,updated:D};if(X)W.metadata=X;return W}async readDocumentSidecar(A,Q){let B={mimeType:"application/pdf",filename:QlQ(Q)},w=POA(A);if(!await c6(w))return B;try{let $=await Bj(w,"utf-8"),I=JSON.parse($),D=YlQ(I)?I:{};return{...B,...D}}catch{return B}}async writeEntity(A){let Q=this.getEntityFilePath(A),B=A.entityType==="image",w=A.entityType==="document";if(B||w){let I=B?/^data:image\/[a-z+]+;base64,(.+)$/i:/^data:application\/pdf;base64,(.+)$/i,D=A.content.match(I),Y=D?.[1]?Buffer.from(D[1],"base64"):Buffer.from(A.content,"base64"),X=!1;if(await c6(Q)){let W=await Bj(Q),U=RB(W.toString("base64")),K=RB(Y.toString("base64"));if(U===K)X=!0}if(!X)await this.ensureEntityDirectory(A,Q),await kOA(Q,Y);if(w)await this.writeDocumentSidecar(A,Q);if(X)return}else{let I=this.entityService.serializeEntity(A);if(await c6(Q)){let D=await Bj(Q,"utf-8"),Y=RB(D),X=RB(I);if(Y===X)return}await this.ensureEntityDirectory(A,Q),await kOA(Q,I,"utf-8")}let $=new Date(A.updated);await DlQ(Q,$,$)}async ensureEntityDirectory(A,Q){if(A.entityType!=="base")await $lQ(BlQ(Q),{recursive:!0})}async writeDocumentSidecar(A,Q){let B=A.metadata,w={};for(let[D,Y]of Object.entries(B)){if(D==="mimeType")continue;if(Y===void 0)continue;w[D]=Y}let $=POA(Q),I=`${JSON.stringify(w,null,2)}
|
|
3762
|
+
`)||"No response text";return{success:!0,data:{state:Z,response:E}}}I=await Sn0(B,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class Rm extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A;this.name="A2ARequestTimeoutError"}}class bm extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A;this.name="A2AStreamIdleTimeoutError"}}async function ugQ(A,Q,B,w){let $=new AbortController,I;try{return await Promise.race([A(Q,{...B,signal:$.signal}),new Promise((D,Y)=>{I=setTimeout(()=>{$.abort(),Y(new Rm(w))},w)})])}catch(D){if(D instanceof Rm)throw D;if($.signal.aborted)throw new Rm(w);throw D}finally{if(I)clearTimeout(I)}}async function Sn0(A,Q){let B;try{return await Promise.race([A.read(),new Promise((w,$)=>{B=setTimeout(()=>$(new bm(Q)),Q)})])}catch(w){if(w instanceof bm)A.cancel().catch(()=>{});throw w}finally{if(B)clearTimeout(B)}}function cgQ(A){if(A instanceof Rm||A instanceof bm)return!0;return A instanceof Error}function pgQ(A,Q){let B=Q>1?` after ${Q} attempts`:"";if(A instanceof bm)return`${A.message}${B}`;let w=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${B}: ${w}`}function hn0(A={}){let Q=A.fetch??globalThis.fetch,B={requestTimeoutMs:A.requestTimeoutMs??xgQ,streamIdleTimeoutMs:A.streamIdleTimeoutMs??ygQ,maxNetworkAttempts:A.maxNetworkAttempts??TgQ};return{name:"a2a_call",description:"Call a saved remote A2A agent by its local directory id. Use this when the user asks what a saved agent has to say or asks a saved agent for its skills/capabilities. Use only a saved agent id such as yeehaa.io. Never pass a display name like Brain, never pass a full URL, and do not use this tool to probe whether an agent exists. If the user gives a URL, an unsaved agent, or an ambiguous name, ask them to add/save or clarify the agent first.",inputSchema:Tn0,visibility:"anchor",handler:async(w)=>{let $=f.object(Tn0).safeParse(w);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};let{agent:I,message:D}=$.data,Y=SgQ(I);if(!Y)return{success:!1,error:"Invalid agent id. Use a saved agent id from your directory, not a URL."};if(!A.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let X=await A.entityService.getEntity({entityType:"agent",id:Y,visibilityScope:F$("a2a_call tool is anchor-only and resolves saved remote agents at any visibility")});if(!X)return{success:!1,error:`Agent ${Y} is not in your directory. Add it first.`};if(X.metadata.status!=="approved")return{success:!1,error:`Agent ${Y} is discovered but not approved yet. Approve it first.`};let W=`https://${Y}`,U=await ggQ(W,Q);if(!U)return{success:!1,error:`Could not fetch Agent Card from ${W}`};let K=U.url,F;if(A.outboundTokens)try{let Z=new URL(K).hostname;F=A.outboundTokens[Z]}catch{}return hgQ(K,D,Q,F,B)}}}var MCA={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.93",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@a2a-js/sdk":"^0.3.12","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",hono:"^4.7.10"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",typescript:"^5.3.3"}};var igQ={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff"};class nP extends nH{agentCard;taskManager=new ECA;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",MCA,A,bn0)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agent,this.permissionContext=A.permissions,this.hasWebserver)A.endpoints.register({label:"A2A",url:"/a2a",priority:25}),A.interactions.register({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),this.logger.info("A2A interface registered",{domain:A.domain});else this.logger.info("A2A interface registered in tool-only mode",{domain:A.domain})}async onReady(A){await this.rebuildAgentCard(A)}async rebuildAgentCard(A){let Q=A.identity.get(),B=A.identity.getProfile(),w=A.tools.listForPermissionLevel("public"),$=this.config.trustedTokens&&Object.keys(this.config.trustedTokens).length>0,I;if(A.entityService.hasEntityType("skill"))try{let D=await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}});if(D.length>0)I=D.map((Y)=>uI.safeParse(Y.metadata)).filter((Y)=>Y.success).map((Y)=>Y.data)}catch{}this.agentCard=Pn0({character:Q,profile:B,version:MCA.version,domain:A.domain,organization:this.config.organization,tools:w,skills:I,authEnabled:$}),this.logger.debug("Agent Card rebuilt",{skills:this.agentCard.skills.length})}getAgentCard(){return this.agentCard}resolveCallerPermission(A){if(!A?.startsWith("Bearer ")||!this.config.trustedTokens)return"public";let Q=A.slice(7),B=this.config.trustedTokens[Q];if(!B||!this.permissionContext)return"public";return this.permissionContext.getUserLevel("a2a",B)}withCors(A){let Q=new Headers(A.headers);for(let[B,w]of Object.entries(igQ))Q.set(B,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}getOrCreateApp(){if(this.app)return this.app;let A=new pP;return A.get("/.well-known/agent-card.json",(Q)=>{if(!this.agentCard)return this.withCors(Q.json({error:"Agent Card not ready"},503));return this.withCors(Q.json(this.agentCard))}),A.get("/a2a",(Q)=>{return this.withCors(Q.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))}),A.options("/a2a",()=>this.withCors(new Response(null,{status:204}))),A.post("/a2a",async(Q)=>{if(!this.agentService)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32603,message:"Agent service not ready"},id:null},503));let B;try{B=await Q.req.json()}catch{return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let w=_n0.safeParse(B);if(!w.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));let $=this.resolveCallerPermission(Q.req.header("Authorization"));if(w.data.method==="message/stream"){let D=xn0.safeParse(w.data.params??{});if(!D.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${D.error.message}`},id:w.data.id}));let{stream:Y}=yn0(w.data.id,D.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(new Response(Y,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let I=await vn0(w.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(Q.json(I))}),this.app=A,A}getWebRoutes(){if(!this.hasWebserver)return[];let A=(Q)=>Promise.resolve(this.getOrCreateApp().fetch(Q));return[{path:"/.well-known/agent-card.json",method:"GET",public:!0,handler:A},{path:"/a2a",method:"GET",public:!0,handler:A},{path:"/a2a",method:"POST",public:!0,handler:A},{path:"/a2a",method:"OPTIONS",public:!0,handler:A}]}async getTools(){return[hn0({outboundTokens:this.config.outboundTokens,requestTimeoutMs:this.config.requestTimeoutMs,streamIdleTimeoutMs:this.config.streamIdleTimeoutMs,maxNetworkAttempts:this.config.maxNetworkAttempts,entityService:this.getContext().entityService})]}async getInstructions(){return"## Agent-to-agent calls\n- Use `a2a_call` only for agents already saved in the local `agent` directory.\n- Pass only the saved local agent id to `a2a_call` (for example `yeehaa.io`). Never pass a full URL or a display name like `Brain`.\n- If the user asks you to ask, message, contact, hear what a saved agent has to say, or ask a saved agent for its own skills/capabilities, treat that as an agent-directory request first and call `a2a_call` in the same turn. Do not stop after listing the agent, drafting the question, searching general content locally, or reading the saved agent entity metadata.\n- If the user gives a full URL for an agent, do not pass that URL to `a2a_call`. Use a saved local agent id only. If that URL is not already saved in the local directory, tell the user to add it first.\n- If the user refers to an agent by name, first make sure that name resolves to exactly one saved agent id. If multiple saved agents could match, ask a concise clarification question naming the matching saved agent ids and do not call any agent yet. Never choose the first match.\n- After asking that clarification question, end the turn. Do not call `a2a_call` later in the same turn.\n- If the target agent is not in the directory, do not create a wish, reminder, todo, note, fallback task, or any new entity. Tell the user to add it first.\n- In these invalid agent-target cases, do not call any tool unless the user explicitly asks you to add/save the agent.\n- Only use creation tools for an agent if the user explicitly asks you to add or save that agent.\n- If the target agent is discovered but not approved yet, do not call it and do not create a wish. Tell the user it must be approved first."}createDaemon(){return{start:async()=>{if(this.hasWebserver)this.logger.info("A2A mounted on shared webserver host");else this.logger.info("A2A running without webserver routes")},stop:async()=>{this.logger.info("A2A server stopped")}}}}eA();class CCA{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,B,w,$=!0){if(this.logger=A,this.fileOperations=w,this.deleteOnFileRemoval=$,B)this.handleImport=async(I)=>{let D=await B({type:"directory-import",data:{paths:[I]}});this.logger.debug("Queued import job for file change",{jobId:D,path:I})},this.handleDelete=async(I)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:I});return}try{let{entityType:D,id:Y}=this.fileOperations.parseEntityFromPath(I),X=await B({type:"directory-delete",data:{entityId:Y,entityType:D,filePath:I}});this.logger.info("Queued delete job for removed file",{jobId:X,path:I,entityId:Y,entityType:D})}catch(D){this.logger.warn("Could not extract entity info from deleted file",{path:I,error:D})}};else this.handleImport=async(I)=>{await Q([I])},this.handleDelete=async(I)=>{this.logger.warn("File deleted but no job queue available",{path:I})}}async handleFileChange(A,Q){this.logger.debug("Processing file change",{event:A,path:Q});try{switch(A){case"add":case"change":await this.handleImport(Q);break;case"delete":case"unlink":await this.handleDelete(Q);break;default:this.logger.debug("Unhandled file event",{event:A,path:Q})}}catch(B){this.logger.error("Failed to handle file change",{event:A,path:Q,error:B})}}}var wa0=X1(Aa0(),1);import{extname as ppQ}from"path";var C1A=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function CE(A){let Q=ppQ(A).toLowerCase();return C1A.includes(Q)}function Qa0(A){switch(A.toLowerCase().replace(".","")){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";default:return"image/png"}}function MOA(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as lpQ,relative as ipQ,sep as Ba0,join as dpQ}from"path";function hY(A,Q){return lpQ(Q)?Q:dpQ(A,Q)}function Qj(A,Q){let B=hY(A,Q),w=ipQ(A,B);return Ba0==="/"?w:w.split(Ba0).join("/")}function rpQ(A,Q){if(!Qj(Q,A).startsWith("image/"))return!1;return CE(A)}function npQ(A,Q){if(Qj(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return rpQ(A,Q)}class COA{watcher;watchCallback;pendingChanges=new Map;batchTimeout;syncPath;watchInterval;logger;onFileChange;constructor(A){this.syncPath=A.syncPath,this.watchInterval=A.watchInterval,this.logger=A.logger,this.onFileChange=A.onFileChange}async start(){if(this.watcher){this.logger.debug("Already watching directory");return}if(this.logger.debug("Starting directory watch",{path:this.syncPath,interval:this.watchInterval}),this.watcher=wa0.default.watch(this.syncPath,{ignored:/(^|[/\\])\../,persistent:!0,interval:this.watchInterval,awaitWriteFinish:{stabilityThreshold:2000,pollInterval:100}}),this.watcher.on("add",(A)=>void this.handleFileChange("add",A)).on("change",(A)=>void this.handleFileChange("change",A)).on("unlink",(A)=>void this.handleFileChange("delete",A)).on("error",(A)=>this.logger.error("Watcher error",A)),this.watchCallback)this.watcher.on("all",this.watchCallback)}stop(){if(this.watcher)this.watcher.close(),this.watcher=void 0,this.logger.info("Stopped directory watch");if(this.batchTimeout)clearTimeout(this.batchTimeout),this.batchTimeout=void 0}setCallback(A){if(this.watchCallback=A,this.watcher)this.watcher.on("all",A)}async handleFileChange(A,Q){if(!npQ(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let B=Qj(this.syncPath,Q);if(this.pendingChanges.set(B,A),this.batchTimeout)clearTimeout(this.batchTimeout);this.batchTimeout=setTimeout(()=>{this.processPendingChanges()},500)}async processPendingChanges(){if(this.pendingChanges.size===0)return;let A=new Map(this.pendingChanges);this.pendingChanges.clear(),this.batchTimeout=void 0,this.logger.debug("Processing batched file changes",{changeCount:A.size});for(let[Q,B]of A){let w=hY(this.syncPath,Q);try{if(this.onFileChange)await this.onFileChange(B,w)}catch($){this.logger.error("Error processing file change",{path:Q,event:B,error:$})}}}isWatching(){return!!this.watcher}getPendingChangesCount(){return this.pendingChanges.size}}async function $a0(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return opQ(Q)}function Ia0(A){if(A)A.stop();return}function Da0(A,Q){if(A)A.setCallback(Q)}async function opQ(A){let{logger:Q,syncPath:B,watchInterval:w,importEntities:$,jobQueueCallback:I,fileOperations:D,deleteOnFileRemoval:Y}=A,X=new CCA(Q,$,I,D,Y),W=new COA({syncPath:B,watchInterval:w,logger:Q,onFileChange:async(U,K)=>{await X.handleFileChange(U,K)}});return await W.start(),W}async function Ya0(A){let Q=Date.now();A.logger.debug("Starting sync (import only)");let B=await A.importEntities(),w=await A.removeOrphanedEntities(),$=Date.now()-Q;return A.markSynced(new Date),A.logger.debug("Sync completed",{duration:$,imported:B.imported,orphansDeleted:w.deleted}),{export:{exported:0,failed:0,errors:[]},import:B,duration:$}}eA();class OOA{logger;syncPath;deleteOnFileRemoval;constructor(A){this.logger=A.logger,this.syncPath=A.syncPath,this.deleteOnFileRemoval=A.deleteOnFileRemoval}prepareBatchOperations(A){let Q=[],B=this.createImportOperations(A);Q.push(...B);let w=B.length;if(this.deleteOnFileRemoval)Q.push({type:"directory-cleanup",data:{}});let $=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:w,totalFiles:$}),{operations:Q,exportOperationsCount:0,importOperationsCount:w,totalFiles:$}}async queueSyncBatch(A,Q,B,w){let $=this.prepareBatchOperations(B);if($.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch($.operations,{source:Q,rootJobId:w?.rootJobId??g5(),metadata:{progressToken:w?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:w?.pluginId??"directory-sync",interfaceType:w?.interfaceType,channelId:w?.channelId}}),operationCount:$.operations.length,exportOperationsCount:$.exportOperationsCount,importOperationsCount:$.importOperationsCount,totalFiles:$.totalFiles}}createImportOperations(A){if(A.length===0)return[];let Q=50,B=[];for(let w=0;w<A.length;w+=Q){let $=A.slice(w,w+Q);B.push({type:"directory-import",data:{batchIndex:Math.floor(w/Q),paths:$,batchSize:$.length}})}return B}}class ROA{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new OOA({logger:A.logger,syncPath:A.syncPath,deleteOnFileRemoval:A.deleteOnFileRemoval})}async queueSyncBatch(A,Q,B){if(this.syncInProgress)return this.logger.debug("Sync already in progress, skipping",{source:Q}),null;this.syncInProgress=!0;try{let w=await this.fileOperations.getAllSyncFiles();return await this.batchOperationsManager.queueSyncBatch(A,Q,w,B)}finally{this.syncInProgress=!1}}}class bOA{options;constructor(A){this.options=A}createExportDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImportDeps(A){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,quarantine:this.options.quarantine,imageJobQueue:this.createImageJobQueueDeps(),entityTypes:A}}createCleanupDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImageJobQueueDeps(){return{logger:this.options.logger,syncPath:this.options.syncPath,jobQueueCallback:this.options.getJobQueueCallback(),coverImageConverter:this.options.coverImageConverter,inlineImageConverter:this.options.inlineImageConverter}}}import{basename as QlQ,dirname as BlQ,extname as wlQ}from"path";import{extname as spQ}from"path";var O1A=[".pdf"],Xa0=".meta.json";function OE(A){let Q=spQ(A).toLowerCase();return O1A.includes(Q)}function Wa0(A){return A.toLowerCase().endsWith(Xa0)}function POA(A){return`${A}${Xa0}`}function Ha0(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as apQ,join as R1A}from"path";function b1A(A,Q){let w=Qj(A,Q).split("/"),$,I;if(w.length===1)$="base",I=w;else if(w.length>1&&w[0])$=w[0],I=w.slice(1);else $="base",I=w;let D;if(I.length>1){let Y=I[I.length-1];if(Y)I[I.length-1]=Ua0(Y);D=I.join(":")}else D=Ua0(I[0]??"");return{entityType:$,id:D}}function Ja0(A,Q,B,w=".md"){let $=Q.split(":").filter((W)=>W.length>0),I=B==="base";if($.length===1)return I?R1A(A,`${$[0]}${w}`):R1A(A,B,`${$[0]}${w}`);let D=$;if($[0]===B)D=$.slice(1);let Y=D[D.length-1],X=D.slice(0,-1);if(I)return R1A(A,...X,`${Y}${w}`);return R1A(A,B,...X,`${Y}${w}`)}function Ga0(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return MOA(Q);let B=A.content.match(/^data:image\/([a-z+]+);base64,/i);return B?.[1]?MOA(B[1]):".md"}function Ua0(A){let Q=apQ(A).toLowerCase();return Q===".md"||C1A.includes(Q)||O1A.includes(Q)?A.slice(0,-Q.length):A}YY();import{mkdir as $lQ,readFile as Bj,writeFile as kOA,stat as IlQ,utimes as DlQ}from"fs/promises";import{join as P1A}from"path";import{mkdir as Ka0,readdir as epQ,stat as AlQ}from"fs/promises";import{access as tpQ}from"fs/promises";async function c6(A){try{return await tpQ(A),!0}catch{return!1}}async function jOA(A,Q){return za0(A,Q,{includeDocuments:!1,includeImages:!1})}async function fa0(A,Q){return za0(A,Q,{includeDocuments:!0,includeImages:!0})}async function Fa0(A,Q){if(!await c6(A))await Ka0(A,{recursive:!0});for(let B of Q)if(B!=="base")await Ka0(P1A(A,B),{recursive:!0})}async function Za0(A,Q){let B=[],w={totalFiles:0,byEntityType:{}};if(!await c6(A))return{files:B,stats:w};let $=await jOA(A,Q);for(let I of $)try{let D=P1A(A,I),Y=await AlQ(D),{entityType:X}=b1A(A,I);B.push({path:I,entityType:X,modified:Y.mtime}),w.totalFiles++,w.byEntityType[X]=(w.byEntityType[X]??0)+1}catch{continue}return{files:B,stats:w}}async function za0(A,Q,B){let w=[];if(!await c6(A))return w;let $=async(I,D="",Y=!1,X=!1)=>{let W=await epQ(I,{withFileTypes:!0});for(let U of W){let K=D?P1A(D,U.name):U.name;if(U.isFile()&&!U.name.endsWith(".invalid")&&!Wa0(U.name)){if(U.name.endsWith(".md"))w.push(K);else if(B.includeImages&&Y&&CE(U.name))w.push(K);else if(B.includeDocuments&&X&&OE(U.name))w.push(K)}else if(U.isDirectory()&&!U.name.startsWith(".")){if(D===""&&!Q.hasEntityType(U.name))continue;let F=P1A(I,U.name),Z=U.name==="image"&&D==="",q=U.name==="document"&&D==="";await $(F,K,Y||Z,X||q)}}};return await $(A),w}function YlQ(A){return typeof A==="object"&&A!==null}class _OA{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return b1A(this.syncPath,A)}async readEntity(A){let Q=hY(this.syncPath,A),B=await IlQ(Q),{entityType:w,id:$}=this.parseEntityFromPath(A),I=B.birthtime.getTime()>0?B.birthtime:B.mtime,D=B.mtime,Y,X;if(CE(A)||OE(A)){let K=(await Bj(Q)).toString("base64"),F=wlQ(A);if(Y=`data:${OE(A)?Ha0(F):Qa0(F)};base64,${K}`,OE(A))X=await this.readDocumentSidecar(Q,A)}else Y=await Bj(Q,"utf-8");let W={entityType:w,id:$,content:Y,created:I,updated:D};if(X)W.metadata=X;return W}async readDocumentSidecar(A,Q){let B={mimeType:"application/pdf",filename:QlQ(Q)},w=POA(A);if(!await c6(w))return B;try{let $=await Bj(w,"utf-8"),I=JSON.parse($),D=YlQ(I)?I:{};return{...B,...D}}catch{return B}}async writeEntity(A){let Q=this.getEntityFilePath(A),B=A.entityType==="image",w=A.entityType==="document";if(B||w){let I=B?/^data:image\/[a-z+]+;base64,(.+)$/i:/^data:application\/pdf;base64,(.+)$/i,D=A.content.match(I),Y=D?.[1]?Buffer.from(D[1],"base64"):Buffer.from(A.content,"base64"),X=!1;if(await c6(Q)){let W=await Bj(Q),U=RB(W.toString("base64")),K=RB(Y.toString("base64"));if(U===K)X=!0}if(!X)await this.ensureEntityDirectory(A,Q),await kOA(Q,Y);if(w)await this.writeDocumentSidecar(A,Q);if(X)return}else{let I=this.entityService.serializeEntity(A);if(await c6(Q)){let D=await Bj(Q,"utf-8"),Y=RB(D),X=RB(I);if(Y===X)return}await this.ensureEntityDirectory(A,Q),await kOA(Q,I,"utf-8")}let $=new Date(A.updated);await DlQ(Q,$,$)}async ensureEntityDirectory(A,Q){if(A.entityType!=="base")await $lQ(BlQ(Q),{recursive:!0})}async writeDocumentSidecar(A,Q){let B=A.metadata,w={};for(let[D,Y]of Object.entries(B)){if(D==="mimeType")continue;if(Y===void 0)continue;w[D]=Y}let $=POA(Q),I=`${JSON.stringify(w,null,2)}
|
|
3751
3763
|
`;if(await c6($)){if(await Bj($,"utf-8")===I)return}await this.ensureEntityDirectory(A,$),await kOA($,I,"utf-8")}getFilePath(A,Q,B=".md"){return Ja0(this.syncPath,A,Q,B)}getEntityFilePath(A){return this.getFilePath(A.id,A.entityType,Ga0(A))}async getAllMarkdownFiles(){return jOA(this.syncPath,this.entityService)}async getAllSyncFiles(){return fa0(this.syncPath,this.entityService)}async ensureDirectoryStructure(A){await Fa0(this.syncPath,A)}shouldUpdateEntity(A,Q){let B=RB(Q.content);return A.contentHash!==B}async gatherFileStatus(){return Za0(this.syncPath,this.entityService)}async syncDirectoryExists(){return c6(this.syncPath)}async fileExists(A){return c6(A)}}v4();fA();v4();async function j1A(A,Q,B,w){let{sourceUrl:$}=A,I=await Q.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:$}},limit:1}});if(I[0])return w.debug("Reusing existing image entity",{sourceUrl:$,imageId:I[0].id}),I[0].id;let D=await B($),{base64:Y}=IZ(D),X=Cq(Y),W=DZ(Y);if(!X||!W)throw Error("Could not detect image format or dimensions");let U=await Q.createEntity({entity:{id:A.id,entityType:"image",content:D,metadata:{title:A.title,alt:A.alt,format:X,width:W.width,height:W.height,sourceUrl:$}}});return w.debug("Created image entity from URL",{sourceUrl:$,imageId:U.entityId}),U.entityId}var Na0=f.object({title:f.string(),slug:f.string().optional(),coverImageUrl:f.string().url(),coverImageId:f.string().optional(),coverImageAlt:f.string().optional()});class vOA{entityService;fetcher;logger;constructor(A,Q,B=wW){this.entityService=A;this.fetcher=B;this.logger=Q.child("FrontmatterImageConverter")}detectCoverImageUrl(A){let Q;try{Q=eD(A)}catch{return null}let{frontmatter:B}=Q,w=Na0.safeParse(B);if(!w.success)return null;if(w.data.coverImageId)return null;let{title:$,slug:I,coverImageUrl:D,coverImageAlt:Y}=w.data;if(!FG(D))return null;return{sourceUrl:D,postTitle:$,postSlug:I??XQ($),customAlt:Y}}async convert(A){let Q;try{Q=eD(A)}catch(W){return this.logger.debug("Parse failed",{error:W}),{content:A,converted:!1}}let{frontmatter:B}=Q,w=Na0.safeParse(B);if(!w.success)return{content:A,converted:!1};if(w.data.coverImageId)return{content:A,converted:!1};let{title:$,slug:I,coverImageUrl:D,coverImageAlt:Y}=w.data;if(!FG(D))return{content:A,converted:!1};let X={postTitle:$,postSlug:I??XQ($),sourceUrl:D,customAlt:Y};try{let W=await this.createImageEntity(X),U={...B};return delete U.coverImageUrl,delete U.coverImageAlt,U.coverImageId=W,{content:b3(U,Q.content),converted:!0,imageId:W}}catch(W){return this.logger.warn("Failed to convert coverImageUrl",{url:D,error:S0(W)}),{content:A,converted:!1}}}async createImageEntity(A){let{postTitle:Q,postSlug:B,sourceUrl:w,customAlt:$}=A,I=`Cover image for ${Q}`;return j1A({id:`${B}-cover`,title:I,alt:$??I,sourceUrl:w},this.entityService,this.fetcher,this.logger)}}v4();fA();class cm{entityService;fetcher;logger;constructor(A,Q,B=wW){this.entityService=A;this.fetcher=B;this.logger=Q.child("MarkdownImageConverter")}detectInlineImages(A,Q){let B=[],w=GGA(A);for(let $ of w){if(!FG($.url))continue;if($.url.startsWith("entity://"))continue;let I=this.reconstructMarkdown($);B.push({sourceUrl:$.url,alt:$.alt,originalMarkdown:I,postSlug:Q})}return B}reconstructMarkdown(A){if(A.title)return``;return``}async convert(A,Q){let B=this.detectInlineImages(A,Q);if(B.length===0)return{content:A,converted:!1,convertedCount:0};let w=A,$=0,I=0;for(let D of B)try{let Y=await this.createImageEntity(D,I++),X=``;w=w.replace(D.originalMarkdown,X),$++,this.logger.debug("Converted inline image",{sourceUrl:D.sourceUrl,imageId:Y})}catch(Y){this.logger.warn("Failed to convert inline image",{sourceUrl:D.sourceUrl,error:S0(Y)})}return{content:w,converted:$>0,convertedCount:$}}async createImageEntity(A,Q){let{sourceUrl:B,alt:w,postSlug:$}=A;return j1A({id:`${$}-inline-${Q}`,title:w||`Inline image ${Q+1} for ${$}`,alt:w||"",sourceUrl:B},this.entityService,this.fetcher,this.logger)}}class xOA{logger;entityService;fileOperations;constructor(A,Q,B){this.logger=A,this.entityService=Q,this.fileOperations=B}async importEntitiesWithProgress(A,Q,B,w){this.logger.debug("Importing entities with progress reporting");let $={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},I=A??await this.fileOperations.getAllSyncFiles(),D=I.length;await Q.report({progress:0,message:`Starting import of ${D} files`});for(let Y=0;Y<D;Y+=B){let X=I.slice(Y,Y+B),W=await w(X);$.imported+=W.imported,$.skipped+=W.skipped,$.failed+=W.failed,$.quarantined+=W.quarantined,$.errors.push(...W.errors),$.quarantinedFiles.push(...W.quarantinedFiles),$.jobIds.push(...W.jobIds);let U=Math.min(Y+B,D),K=Math.round(U/D*40);await Q.report({progress:K,message:`Imported ${U}/${D} files`})}return $}async exportEntitiesWithProgress(A,Q,B,w){this.logger.debug("Exporting entities with progress reporting");let $=A??this.entityService.getEntityTypes();await Q.report({progress:50,message:`Starting export of ${$.length} entity types`});let I=await w(A);return await Q.report({progress:100,message:`Exported ${I.exported} entities`}),this.logger.debug("Export completed",I),I}}fA();import{rename as XlQ,appendFile as WlQ,readFile as HlQ,writeFile as UlQ,access as JlQ}from"fs/promises";import{join as qa0}from"path";class yOA{logger;syncPath;constructor(A,Q){this.logger=A;this.syncPath=Q}isValidationError(A){if(A instanceof f.ZodError)return!0;let Q=S0(A);return Q.includes("invalid_type")||Q.includes("invalid_enum_value")||Q.includes("Required")||Q.includes("Invalid frontmatter")||Q.includes("Unknown entity type")}async quarantineInvalidFile(A,Q,B,w){let $=w(A),I=`${$}.invalid`;try{await XlQ($,I),B.quarantined++,B.quarantinedFiles.push(A);let D=qa0(this.syncPath,".import-errors.log"),Y=new Date().toISOString(),X=S0(Q),W=`${Y} - ${A}: ${X}
|
|
3752
3764
|
\u2192 ${A}.invalid
|
|
3753
3765
|
|
|
@@ -3775,7 +3787,7 @@ details.web-chat-data-part[open] > summary > .web-chat-data-part-chevron {
|
|
|
3775
3787
|
*...and ${A.files.length-10} more files*`)}if(A.exists&&A.stats.totalFiles===0)Q.push(`
|
|
3776
3788
|
## Getting Started
|
|
3777
3789
|
`),Q.push("Your sync directory is empty. Entities will be organized as follows:"),Q.push("- Base entities: `/<entity-id>.md`"),Q.push("- Other types: `/<entity-type>/<entity-id>.md`");return Q.join(`
|
|
3778
|
-
`)}}eA();class wQA extends Sw{directorySync;constructor(A,Q,B){super(A,{schema:xRA,jobTypeName:"directory-export"});this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let w=Date.now();try{let $=await this.directorySync.exportEntitiesWithProgress(A.entityTypes,B,A.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:Q,exported:$.exported,failed:$.failed,duration:Date.now()-w}),$}catch($){throw this.logger.error("Directory export job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}eA();class $QA extends Sw{directorySync;constructor(A,Q,B){super(A,{schema:vRA,jobTypeName:"directory-import"});this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let w=Date.now();try{let $=await this.directorySync.importEntitiesWithProgress(A.paths,B,A.batchSize??100);return this.logger.debug("Directory import job completed",{jobId:Q,imported:$.imported,skipped:$.skipped,failed:$.failed,quarantined:$.quarantined,duration:Date.now()-w}),$}catch($){throw this.logger.error("Directory import job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}eA();class IQA extends Sw{directorySync;context;constructor(A,Q,B){super(A,{schema:_RA,jobTypeName:"directory-sync"});this.context=Q,this.directorySync=B}async process(A,Q,B){let w=Date.now(),$=A.syncDirection??"both";this.logger.info("Starting directory sync job",{jobId:Q,operation:A.operation,syncDirection:$});let I={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},D={exported:0,failed:0,errors:[]};if($!=="export")if(await B.report({progress:10,message:"Scanning directory for changes"}),I=await this.importWithProgress(A.paths,B),$==="import")await this.waitForImportJobs(I.jobIds,B),await B.report({progress:100,message:`Import complete: ${I.imported} imported`});else await B.report({progress:50,message:`Imported ${I.imported} entities`}),await this.waitForImportJobs(I.jobIds,B),await B.report({progress:56,message:"Processing complete, starting export"});if($!=="import"){let X=$==="export"?10:60;await B.report({progress:X,message:"Exporting entities to directory"}),D=await this.exportWithProgress(A.entityTypes,B),await B.report({progress:100,message:$==="export"?`Export complete: ${D.exported} exported`:`Sync complete: ${I.imported} imported, ${D.exported} exported`})}let Y=Date.now()-w;return this.logger.info("Directory sync job completed",{jobId:Q,duration:Y,imported:I.imported,exported:D.exported}),{import:I,export:D,duration:Y}}async importWithProgress(A,Q){try{return await this.directorySync.importEntitiesWithProgress(A,Q,10)}catch(B){throw this.logger.error("Import phase failed",{error:B}),B}}async exportWithProgress(A,Q){try{return await this.directorySync.exportEntitiesWithProgress(A,Q,10)}catch(B){throw this.logger.error("Export phase failed",{error:B}),B}}async waitForImportJobs(A,Q){if(A.length===0)return;this.logger.debug(`Waiting for ${A.length} import jobs to complete`);let{entityService:B}=this.context,w=300000,$=500,I=Date.now(),D=async()=>{let X=(await Promise.all(A.map((U)=>B.getAsyncJobStatus(U)))).filter((U)=>U&&(U.status==="completed"||U.status==="failed")).length;if(X===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-I>w){this.logger.warn(`Timeout waiting for import jobs (${X}/${A.length} completed)`);return}let W=Math.round(X/A.length*100);return await Q.report({progress:50+Math.round(W*0.05),message:`Processing ${X}/${A.length} entities`}),await new Promise((U)=>setTimeout(U,$)),D()};return D()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}eA();class DQA extends Sw{context;constructor(A,Q,B){super(A,{schema:QQA,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,B){let w=QQA.parse(A);this.logger.info("Processing entity deletion for removed file",{entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}),await B.report({progress:0,total:1,message:`Deleting ${w.entityType}:${w.entityId}`});try{let $=await this.context.entityService.deleteEntity({entityType:w.entityType,id:w.entityId});if($)this.logger.info("Successfully deleted entity for removed file",{entityId:w.entityId,entityType:w.entityType});else this.logger.warn("Entity not found in database",{entityId:w.entityId,entityType:w.entityType});return await B.report({progress:1,total:1,message:`Deleted ${w.entityType}:${w.entityId}`}),{deleted:$,entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}}catch($){throw this.logger.error("Failed to delete entity",{entityId:w.entityId,entityType:w.entityType,error:$}),$}}summarizeDataForLog(A){return{entityId:A.entityId,entityType:A.entityType,filePath:A.filePath}}}eA();fA();var YnQ=f.object({});class YQA extends Sw{directorySync;constructor(A,Q){super(A,{schema:YnQ,jobTypeName:"directory-cleanup"});this.directorySync=Q}async process(A,Q,B){await B.report({progress:0,message:"Removing orphaned entities"});let w=await this.directorySync.removeOrphanedEntities();return await B.report({progress:100,message:`Cleanup complete: ${w.deleted} orphans removed`}),w}}eA();v4();fA();r$();v4();import{readFile as XnQ,writeFile as WnQ}from"fs/promises";var HnQ=yRA;class XQA extends Sw{context;fetcher;constructor(A,Q,B=wW){super(Q,{schema:HnQ,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=B}async process(A,Q,B){let{filePath:w,sourceUrl:$,postTitle:I,postSlug:D,customAlt:Y}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:w,sourceUrl:$,postSlug:D});try{await this.reportProgress(B,{progress:u2.INIT,message:`Reading file: ${w}`});let X;try{X=await XnQ(w,"utf-8")}catch(E){return this.logger.error("Failed to read file",{filePath:w,error:S0(E)}),d$.failure(E)}let W;try{W=eD(X)}catch(E){return this.logger.warn("Failed to parse markdown",{filePath:w,error:S0(E)}),d$.failure(E)}let U=W.frontmatter;if(U.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:w}),await this.reportProgress(B,{progress:u2.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress(B,{progress:u2.FETCH,message:"Checking for existing image"});let K=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:$}},limit:1}}),F;if(K[0])F=K[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:$,imageId:F}),await this.reportProgress(B,{progress:u2.EXTRACT,message:`Reusing existing image: ${F}`});else{await this.reportProgress(B,{progress:u2.PROCESS,message:`Fetching image from ${$}`});let E;try{E=await this.fetcher($)}catch(n){return this.logger.error("Failed to fetch image",{sourceUrl:$,error:S0(n)}),d$.failure(n)}await this.reportProgress(B,{progress:u2.GENERATE,message:"Creating image entity"});let{base64:L}=IZ(E),R=Cq(L),_=DZ(L);if(!R||!_)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:$}),d$.failure(Error("Could not detect image format or dimensions"));F=`${D}-cover`;let O=`Cover image for ${I}`,r=Y??O;await this.context.entityService.createEntity({entity:{id:F,entityType:"image",content:E,metadata:{title:O,alt:r,format:R,width:_.width,height:_.height,sourceUrl:$}}}),this.logger.debug("Created image entity",{imageId:F,sourceUrl:$}),await this.reportProgress(B,{progress:u2.EXTRACT,message:`Created image: ${F}`})}await this.reportProgress(B,{progress:u2.SAVE,message:"Updating file"});let Z={...U};delete Z.coverImageUrl,delete Z.coverImageAlt,Z.coverImageId=F;let q=b3(Z,W.content);try{await WnQ(w,q,"utf-8")}catch(E){return this.logger.error("Failed to write file",{filePath:w,error:S0(E)}),d$.failure(E)}return await this.reportProgress(B,{progress:u2.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:w,imageId:F,sourceUrl:$}),{success:!0,imageId:F}}catch(X){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:w,error:S0(X)}),d$.failure(X)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}eA();v4();fA();r$();import{readFile as UnQ,writeFile as JnQ}from"fs/promises";class WQA extends Sw{converter;constructor(A,Q,B=wW){super(Q,{schema:TRA,jobTypeName:"inline-image-convert"});this.converter=new cm(A.entityService,Q,B)}async process(A,Q,B){let{filePath:w,postSlug:$}=A;this.logger.debug("Starting inline image conversion job",{jobId:Q,filePath:w,postSlug:$});try{await this.reportProgress(B,{progress:u2.INIT,message:`Reading file: ${w}`});let I;try{I=await UnQ(w,"utf-8")}catch(X){let W=S0(X);return this.logger.error("Failed to read file",{filePath:w,error:W}),{success:!1,error:W}}await this.reportProgress(B,{progress:u2.FETCH,message:"Detecting inline images"});let D=this.converter.detectInlineImages(I,$);if(D.length===0)return this.logger.debug("No inline images to convert",{filePath:w}),await this.reportProgress(B,{progress:u2.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:w,count:D.length}),await this.reportProgress(B,{progress:u2.PROCESS,message:`Converting ${D.length} images`});let Y=await this.converter.convert(I,$);if(!Y.converted)return this.logger.debug("No images were converted",{filePath:w}),await this.reportProgress(B,{progress:u2.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress(B,{progress:u2.SAVE,message:"Writing updated file"});try{await JnQ(w,Y.content,"utf-8")}catch(X){let W=S0(X);return this.logger.error("Failed to write file",{filePath:w,error:W}),{success:!1,error:W}}return await this.reportProgress(B,{progress:u2.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:w,convertedCount:Y.convertedCount}),{success:!0,convertedCount:Y.convertedCount}}catch(I){let D=S0(I);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:w,error:D}),{success:!1,error:D}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function aA1(A,Q,B){let w=($)=>B.child($);A.jobs.registerHandler("directory-sync",new IQA(w("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new wQA(w("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new $QA(w("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new DQA(w("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new YQA(w("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new XQA(A,w("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new WQA(A,w("InlineImageConversionJobHandler"))),B.debug("Registered async job handlers")}eA();import{unlink as GnQ,access as KnQ}from"fs/promises";function tA1(A,Q,B,w){let{subscribe:$}=A.messaging,{entityService:I}=A;$("entity:created",async(D)=>{let{entity:Y}=D.payload;try{await Q.fileOps.writeEntity(Y),B.debug("Auto-exported created entity",{id:Y.id,entityType:Y.entityType})}catch(X){B.error("Auto-export FAILED for created entity",{id:Y.id,entityType:Y.entityType,error:X instanceof Error?X.message:String(X),stack:X instanceof Error?X.stack:void 0})}return{success:!0}}),$("entity:updated",async(D)=>{let{entityType:Y,entityId:X}=D.payload;try{let W=await I.getEntity({entityType:Y,id:X});if(!W)return B.debug("Entity not found in DB, skipping export",{entityType:Y,entityId:X}),{success:!1};await Q.fileOps.writeEntity(W),B.debug("Auto-exported updated entity",{id:W.id,entityType:W.entityType})}catch(W){B.error("Auto-export FAILED for updated entity",{entityType:Y,entityId:X,error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0})}return{success:!0}}),$("entity:deleted",async(D)=>{let{entityId:Y,entityType:X}=D.payload,W=Q.fileOps.getFilePath(Y,X);if(await KnQ(W).then(()=>!0,()=>!1))await GnQ(W),B.debug("Auto-deleted entity file",{id:Y,entityType:X,path:W});return{success:!0}}),B.debug("Setup auto-sync for entity events",{entityTypes:w})}function eA1(A,Q,B){Q.setJobQueueCallback(async(w)=>{let $=[{type:w.type,data:w.data}];return A.jobs.enqueueBatch($,{priority:5,source:"directory-sync-watcher",rootJobId:g5(),metadata:{operationType:"file_operations",operationTarget:B,pluginId:"directory-sync"}})})}fA();eA();import{readdir as B01,mkdir as FnQ,copyFile as ZnQ}from"fs/promises";import{join as Q01,resolve as SRA}from"path";import{join as fnQ}from"path";async function A01(A){if(!await c6(fnQ(A,".git")))return!1;try{return await iK(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function znQ(A,Q){if(!await c6(A))return!0;if((await B01(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await A01(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function w01(A,Q){let B=await B01(A,{withFileTypes:!0});for(let w of B){let $=Q01(A,w.name),I=Q01(Q,w.name);if(w.isDirectory()){if(!await c6(I))await FnQ(I,{recursive:!0});await w01($,I)}else await ZnQ($,I)}}async function $01(A,Q,B){let w=SRA(process.cwd(),A);B=B?SRA(B):SRA(process.cwd(),"seed-content");let $=await znQ(w,Q);if($&&await c6(B))Q.debug("Copying seed content to brain-data directory"),await w01(B,w),Q.debug("Seed content copied successfully");else if($)Q.debug("No seed content directory found, starting with empty brain-data");else Q.debug("brain-data directory not empty, skipping seed content")}function I01(A,Q,B,w,$){let I=!1,D=async()=>{if(I)return;I=!0;let Y=Q();if(B.seedContent){let X=B.syncPath??A.dataDir;await $01(X,w,B.seedContentPath)}try{if($){w.debug("Git enabled \u2014 pulling before import");let W=await $.pull();if(W.files.length>0)w.info("Pulled changes from remote",{filesChanged:W.files.length})}w.debug("Starting initial sync");let X=await Y.sync();w.debug("Initial sync completed",{imported:X.import.imported,failed:X.import.failed,duration:X.duration}),await A.messaging.send({type:n3.initialSyncCompleted,payload:{success:!0},...{broadcast:!0}})}catch(X){w.error("Initial sync failed",X),await A.messaging.send({type:n3.initialSyncCompleted,payload:{success:!1,error:S0(X)},...{broadcast:!0}})}};A.messaging.subscribe(n3.pluginsRegistered,async()=>{return w.debug("Plugins registered, starting initial sync"),await D(),{success:!0}})}fA();function D01(A,Q,B,w){let $=new T3(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(Y){w.error("Git auto-commit failed",{error:Y})}})},B),I=["entity:created","entity:updated","entity:deleted"],D=[];for(let Y of I){let X=A.subscribe(Y,async()=>{return $.trigger(),{success:!0}});D.push(X)}return()=>{$.dispose();for(let Y of D)Y()}}function Y01(A,Q,B,w,$){if(w<=0)return()=>{};let I=w*60*1000,D=!1,Y=async()=>{if(D)return;D=!0;try{let{files:W,result:U}=await A.withLock(async()=>{let K=await A.pull();if(K.files.length===0)return{files:[],result:null};let F=await Q.queueSyncBatch(B,"periodic-sync");return{files:K.files,result:F}});if(W.length>0)$.info("Periodic sync: pulled changes",{filesChanged:W.length});if(U)$.debug("Periodic sync: queued imports",{importOperations:U.importOperationsCount,totalFiles:U.totalFiles})}catch(W){$.error("Periodic git sync failed",{error:W})}finally{D=!1}},X=setInterval(()=>{Y()},I);return $.info("Started periodic git sync",{intervalMinutes:w}),()=>{clearInterval(X)}}import{spawnSync as W01}from"child_process";import{cpSync as NnQ,existsSync as X01,mkdirSync as qnQ,mkdtempSync as LnQ,rmSync as EnQ}from"fs";import{tmpdir as VnQ}from"os";import{fileURLToPath as MnQ}from"url";import{join as CnQ,resolve as OnQ}from"path";function mz(A,Q){let B=W01("git",Q,{cwd:A,stdio:"pipe"});if(B.status!==0){let w=B.stderr.toString().trim(),$=B.stdout.toString().trim();throw Error(w||$||`git ${Q.join(" ")} failed`)}}function RnQ(A){return A.startsWith("file://")}function bnQ(A){return MnQ(A)}function PnQ(A,Q){return W01("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function H01(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!RnQ(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",B=bnQ(A.gitUrl),w=OnQ(A.seedContentPath);if(!X01(w))throw Error(`Seed content path not found: ${w}`);if(!X01(B))A.logger.debug("Creating local bare content remote",{remotePath:B,branch:Q}),qnQ(B,{recursive:!0}),mz(process.cwd(),["init","--bare",`--initial-branch=${Q}`,B]);if(PnQ(B,Q)){A.logger.debug("Content remote already initialized",{remotePath:B,branch:Q});return}A.logger.debug("Seeding local content remote",{remotePath:B,seedPath:w,branch:Q});let $=LnQ(CnQ(VnQ(),"directory-sync-seed-"));try{mz($,["init",`--initial-branch=${Q}`]),mz($,["config","user.name",A.authorName??"Brain"]),mz($,["config","user.email",A.authorEmail??"brain@localhost"]),NnQ(w,$,{recursive:!0}),mz($,["add","."]),mz($,["commit","-m","seed content remote"]),mz($,["remote","add","origin",A.gitUrl]),mz($,["push","-u","origin",Q])}finally{EnQ($,{recursive:!0,force:!0})}}function U01(A,Q,B,w,$){let{subscribe:I}=A.messaging;I("entity:export:request",async(D)=>{try{return{success:!0,data:await Q().exportEntities(D.payload.entityTypes)}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Export failed"}}}),I("entity:import:request",async(D)=>{try{let Y=Q(),X=D.payload.paths,W=await Y.importEntities(X);if(X&&X.length>0)await Y.removeOrphanedEntities();return{success:!0,data:W}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Import failed"}}}),I("sync:status:request",async()=>{try{let Y=await Q().getStatus();return{success:!0,data:{syncPath:Y.syncPath,isInitialized:Y.exists,watchEnabled:Y.watching}}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Status check failed"}}}),I("sync:configure:request",async(D)=>{try{return await B({syncPath:D.payload.syncPath}),{success:!0,data:{syncPath:D.payload.syncPath,configured:!0}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Configuration failed"}}}),I("git-sync:get-repo-info",async()=>{if(!$?.repo)return{success:!1,error:"Git not configured"};return{success:!0,data:{repo:$.repo,branch:$.branch??"main"}}}),w.debug("Registered message handlers")}eA();fA();eA();fA();function J01(A,Q){return j2(A,"history","Get version history for an entity from git. Without sha: returns commit list. With sha: returns entity content at that version.",f.object({entityType:f.string().describe("Entity type (e.g. post, note, link)"),id:f.string().describe("Entity ID"),sha:f.string().optional().describe("Commit SHA to retrieve content at. Omit to list commit history."),limit:f.number().int().positive().optional().default(10).describe("Max commits to return (list mode only)")}),async(B)=>{let w=`${B.entityType}/${B.id}.md`;try{if(B.sha){let I=await Q.show(B.sha,w);return J8({sha:B.sha,entityType:B.entityType,id:B.id,content:I},`Content at ${B.sha.slice(0,7)}`)}let $=await Q.log(w,B.limit);if($.length===0)return J8({commits:[]},`No history found for ${B.entityType}/${B.id}`);return J8({commits:$,entityType:B.entityType,id:B.id},`${$.length} version${$.length===1?"":"s"} found`)}catch($){return h5($ instanceof Error?$.message:"History lookup failed")}})}function G01(A,Q,B,w){let $=[j2(B,"sync","Sync brain entities with the filesystem. Use this for refresh, pull, sync, or backup-to-git requests. Pulls from git if configured, then imports files. Git commit and push happen automatically after imports complete.",f.object({}),async(I,D)=>{try{let Y=D.channelId?`${D.interfaceType}:${D.channelId}`:`plugin:${B}`,X={interfaceType:D.interfaceType,channelId:D.channelId},W=w!==void 0,U=()=>A.queueSyncBatch(Q,Y,X),K=w?await w.withLock(async()=>{return await w.pull(),U()}):await U();if(!K)return J8({gitPulled:W},"No files to sync");return J8({batchId:K.batchId,importOperations:K.importOperationsCount,totalFiles:K.totalFiles,gitPulled:W},`Sync started: ${K.importOperationsCount} import jobs queued for ${K.totalFiles} files${W?" (pulled from git)":""}`)}catch(Y){return h5(Y instanceof Error?Y.message:"Sync failed")}},{cli:{name:"sync"}}),j2(B,"status","Get sync and git repository status \u2014 last sync time, watching state, pending git changes. Use this for status questions, not for actually syncing or backing up.",f.object({}),async()=>{try{let I=await A.getStatus(),D={syncPath:I.syncPath,lastSync:I.lastSync?.toISOString(),watching:I.watching};if(w){let Y=await w.getStatus();D.git={isRepo:Y.isRepo,branch:Y.branch,hasChanges:Y.hasChanges,ahead:Y.ahead,behind:Y.behind,remote:Y.remote}}return J8(D)}catch(I){return h5(I instanceof Error?I.message:"Status check failed")}},{visibility:"public"})];if(w)$.push(J01(B,w));return $}var K01={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.92",description:"Directory-based entity synchronization plugin for Brains",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":{types:"./src/index.ts",import:"./src/index.ts"}},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",clean:"rm -rf .turbo"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chokidar:"^3.5.3","simple-git":"^3.21.0"},devDependencies:{"@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},peerDependencies:{}};class gRA extends qB{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",K01,A,Au)}requireDirectorySync(){if(!this.directorySync)throw Error("DirectorySync service not initialized");return this.directorySync}hasGitSync(){return this.gitSync!==void 0}async onRegister(A){let{logger:Q,entityService:B}=A;A.templates.register({status:{name:"status",description:"Directory synchronization status",schema:Qu,basePrompt:"",formatter:new BQA,requiredPermission:"anchor"}});let w=this.config.syncPath??A.dataDir;this.directorySync=new pm({syncPath:w,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,entityService:B,logger:Q});try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:w})}catch(D){throw this.logger.error("Failed to initialize directory",D),D}await this.registerJobHandlers(A);let $=this.requireDirectorySync();if(tA1(A,$,this.logger,this.config.entityTypes),this.config.autoSync)eA1(A,$,this.config.syncPath??A.dataDir);let I=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!I)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(I&&this.config.git){await H01({gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,seedContentPath:this.config.seedContentPath,bootstrapFromSeed:this.config.git.bootstrapFromSeed,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail,logger:this.logger.child("ContentRemoteBootstrap")});let D=this.config.syncPath??A.dataDir;if(this.gitSync=new kRA({logger:this.logger.child("GitSync"),dataDir:D,repo:this.config.git.repo,gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,authToken:this.config.git.authToken,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail}),await this.gitSync.initialize(),this.logger.info("Git integration enabled",{repo:this.config.git.repo}),this.gitCleanups.push(D01(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(Y01(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)I01(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);U01(A,()=>this.requireDirectorySync(),(D)=>this.configure(D),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return G01(A,this.getContext(),this.id,this.gitSync)}async onShutdown(){for(let A of this.gitCleanups)A();this.gitCleanups=[],this.directorySync?.stopWatching(),this.gitSync?.cleanup()}getDirectorySync(){return this.directorySync}async configure(A){this.requireDirectorySync();let Q=this.getContext();this.directorySync=new pm({...this.config,syncPath:A.syncPath,entityService:Q.entityService,logger:Q.logger}),await this.directorySync.initialize(),this.logger.info("Directory sync reconfigured",{path:A.syncPath})}async registerJobHandlers(A){aA1(A,this.requireDirectorySync(),this.logger)}}function jE(A={}){return new gRA(A)}eA();fA();var f01={name:"@brains/email-resend",private:!0,version:"0.2.0-alpha.92",description:"Generic email delivery adapter for Resend",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var _nQ=f.object({apiKey:f.string().min(1).optional(),from:f.string().min(1).optional()});class F01 extends qB{fetchImpl;constructor(A={},Q={}){super("email-resend",f01,A,_nQ);this.fetchImpl=Q.fetchImpl??fetch}async onRegister(A){if(!this.config.apiKey||!this.config.from){this.logger.warn("Email Resend adapter is disabled because apiKey or from is missing");return}let Q=this.logger;A.messaging.subscribe(Tt,async(B)=>{let w=UF0.parse(B.payload);try{return{success:!0,data:await this.sendWithResend(w)}}catch($){if(w.sensitivity==="secret")Q.warn("Email delivery failed for a secret message");else Q.warn("Email delivery failed",{to:w.to,subject:w.subject,error:$ instanceof Error?$.message:String($)});return{success:!1,error:"Email delivery failed"}}})}async sendWithResend(A){let Q=this.config.apiKey,B=this.config.from;if(!Q||!B)return{status:"failed"};let w=await this.fetchImpl("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({from:B,to:A.to,subject:A.subject,text:A.text,...A.html?{html:A.html}:{}})});if(!w.ok)throw Error("Resend email request failed");let $=await w.json();return $.id?{status:"sent",id:$.id}:{status:"sent"}}}function HQA(A={}){return new F01(A)}eA();import{render as bD1}from"preact-render-to-string";import{h as GV}from"preact";function Z01(A){var Q,B,w="";if(typeof A=="string"||typeof A=="number")w+=A;else if(typeof A=="object")if(Array.isArray(A)){var $=A.length;for(Q=0;Q<$;Q++)A[Q]&&(B=Z01(A[Q]))&&(w&&(w+=" "),w+=B)}else for(B in A)A[B]&&(w&&(w+=" "),w+=B);return w}function Xj(){for(var A,Q,B=0,w="",$=arguments.length;B<$;B++)(A=arguments[B])&&(Q=Z01(A))&&(w&&(w+=" "),w+=Q);return w}var vnQ=(A)=>{let Q=ynQ(A),{conflictingClassGroups:B,conflictingClassGroupModifiers:w}=A;return{getClassGroupId:(D)=>{let Y=D.split("-");if(Y[0]===""&&Y.length!==1)Y.shift();return E01(Y,Q)||xnQ(D)},getConflictingClassGroupIds:(D,Y)=>{let X=B[D]||[];if(Y&&w[D])return[...X,...w[D]];return X}}},E01=(A,Q)=>{if(A.length===0)return Q.classGroupId;let B=A[0],w=Q.nextPart.get(B),$=w?E01(A.slice(1),w):void 0;if($)return $;if(Q.validators.length===0)return;let I=A.join("-");return Q.validators.find(({validator:D})=>D(I))?.classGroupId},z01=/^\[(.+)\]$/,xnQ=(A)=>{if(z01.test(A)){let Q=z01.exec(A)[1],B=Q?.substring(0,Q.indexOf(":"));if(B)return"arbitrary.."+B}},ynQ=(A)=>{let{theme:Q,prefix:B}=A,w={nextPart:new Map,validators:[]};return SnQ(Object.entries(A.classGroups),B).forEach(([I,D])=>{mRA(D,w,I,Q)}),w},mRA=(A,Q,B,w)=>{A.forEach(($)=>{if(typeof $==="string"){let I=$===""?Q:N01(Q,$);I.classGroupId=B;return}if(typeof $==="function"){if(TnQ($)){mRA($(w),Q,B,w);return}Q.validators.push({validator:$,classGroupId:B});return}Object.entries($).forEach(([I,D])=>{mRA(D,N01(Q,I),B,w)})})},N01=(A,Q)=>{let B=A;return Q.split("-").forEach((w)=>{if(!B.nextPart.has(w))B.nextPart.set(w,{nextPart:new Map,validators:[]});B=B.nextPart.get(w)}),B},TnQ=(A)=>A.isThemeGetter,SnQ=(A,Q)=>{if(!Q)return A;return A.map(([B,w])=>{let $=w.map((I)=>{if(typeof I==="string")return Q+I;if(typeof I==="object")return Object.fromEntries(Object.entries(I).map(([D,Y])=>[Q+D,Y]));return I});return[B,$]})},gnQ=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,B=new Map,w=new Map,$=(I,D)=>{if(B.set(I,D),Q++,Q>A)Q=0,w=B,B=new Map};return{get(I){let D=B.get(I);if(D!==void 0)return D;if((D=w.get(I))!==void 0)return $(I,D),D},set(I,D){if(B.has(I))B.set(I,D);else $(I,D)}}};var hnQ=(A)=>{let{separator:Q,experimentalParseClassName:B}=A,w=Q.length===1,$=Q[0],I=Q.length,D=(Y)=>{let X=[],W=0,U=0,K;for(let L=0;L<Y.length;L++){let R=Y[L];if(W===0){if(R===$&&(w||Y.slice(L,L+I)===Q)){X.push(Y.slice(U,L)),U=L+I;continue}if(R==="/"){K=L;continue}}if(R==="[")W++;else if(R==="]")W--}let F=X.length===0?Y:Y.substring(U),Z=F.startsWith("!"),q=Z?F.substring(1):F,E=K&&K>U?K-U:void 0;return{modifiers:X,hasImportantModifier:Z,baseClassName:q,maybePostfixModifierPosition:E}};if(B)return(Y)=>B({className:Y,parseClassName:D});return D},mnQ=(A)=>{if(A.length<=1)return A;let Q=[],B=[];return A.forEach((w)=>{if(w[0]==="[")Q.push(...B.sort(),w),B=[];else B.push(w)}),Q.push(...B.sort()),Q},unQ=(A)=>({cache:gnQ(A.cacheSize),parseClassName:hnQ(A),...vnQ(A)}),cnQ=/\s+/,pnQ=(A,Q)=>{let{parseClassName:B,getClassGroupId:w,getConflictingClassGroupIds:$}=Q,I=[],D=A.trim().split(cnQ),Y="";for(let X=D.length-1;X>=0;X-=1){let W=D[X],{modifiers:U,hasImportantModifier:K,baseClassName:F,maybePostfixModifierPosition:Z}=B(W),q=Boolean(Z),E=w(q?F.substring(0,Z):F);if(!E){if(!q){Y=W+(Y.length>0?" "+Y:Y);continue}if(E=w(F),!E){Y=W+(Y.length>0?" "+Y:Y);continue}q=!1}let L=mnQ(U).join(":"),R=K?L+"!":L,_=R+E;if(I.includes(_))continue;I.push(_);let O=$(E,q);for(let r=0;r<O.length;++r){let n=O[r];I.push(R+n)}Y=W+(Y.length>0?" "+Y:Y)}return Y};function lnQ(){let A=0,Q,B,w="";while(A<arguments.length)if(Q=arguments[A++]){if(B=V01(Q))w&&(w+=" "),w+=B}return w}var V01=(A)=>{if(typeof A==="string")return A;let Q,B="";for(let w=0;w<A.length;w++)if(A[w]){if(Q=V01(A[w]))B&&(B+=" "),B+=Q}return B};function q01(A,...Q){let B,w,$,I=D;function D(X){let W=Q.reduce((U,K)=>K(U),A());return B=unQ(W),w=B.cache.get,$=B.cache.set,I=Y,Y(X)}function Y(X){let W=w(X);if(W)return W;let U=pnQ(X,B);return $(X,U),U}return function(){return I(lnQ.apply(null,arguments))}}var N8=(A)=>{let Q=(B)=>B[A]||[];return Q.isThemeGetter=!0,Q},M01=/^\[(?:([a-z-]+):)?(.+)\]$/i,inQ=/^\d+\/\d+$/,dnQ=new Set(["px","full","screen"]),rnQ=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,nnQ=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,onQ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,snQ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,anQ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,dK=(A)=>Wj(A)||dnQ.has(A)||inQ.test(A),uz=(A)=>Hj(A,"length",IoQ),Wj=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),hRA=(A)=>Hj(A,"number",Wj),Bu=(A)=>Boolean(A)&&Number.isInteger(Number(A)),tnQ=(A)=>A.endsWith("%")&&Wj(A.slice(0,-1)),g2=(A)=>M01.test(A),cz=(A)=>rnQ.test(A),enQ=new Set(["length","size","percentage"]),AoQ=(A)=>Hj(A,enQ,C01),QoQ=(A)=>Hj(A,"position",C01),BoQ=new Set(["image","url"]),woQ=(A)=>Hj(A,BoQ,YoQ),$oQ=(A)=>Hj(A,"",DoQ),wu=()=>!0,Hj=(A,Q,B)=>{let w=M01.exec(A);if(w){if(w[1])return typeof Q==="string"?w[1]===Q:Q.has(w[1]);return B(w[2])}return!1},IoQ=(A)=>nnQ.test(A)&&!onQ.test(A),C01=()=>!1,DoQ=(A)=>snQ.test(A),YoQ=(A)=>anQ.test(A);var L01=()=>{let A=N8("colors"),Q=N8("spacing"),B=N8("blur"),w=N8("brightness"),$=N8("borderColor"),I=N8("borderRadius"),D=N8("borderSpacing"),Y=N8("borderWidth"),X=N8("contrast"),W=N8("grayscale"),U=N8("hueRotate"),K=N8("invert"),F=N8("gap"),Z=N8("gradientColorStops"),q=N8("gradientColorStopPositions"),E=N8("inset"),L=N8("margin"),R=N8("opacity"),_=N8("padding"),O=N8("saturate"),r=N8("scale"),n=N8("sepia"),S=N8("skew"),x=N8("space"),T=N8("translate"),g=()=>["auto","contain","none"],e=()=>["auto","hidden","clip","visible","scroll"],h=()=>["auto",g2,Q],XA=()=>[g2,Q],BA=()=>["",dK,uz],k=()=>["auto",Wj,g2],C=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],j=()=>["solid","dashed","dotted","double","none"],i=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],u=()=>["start","end","center","between","around","evenly","stretch"],AA=()=>["","0",g2],o=()=>["auto","avoid","all","avoid-page","page","left","right","column"],UA=()=>[Wj,g2];return{cacheSize:500,separator:":",theme:{colors:[wu],spacing:[dK,uz],blur:["none","",cz,g2],brightness:UA(),borderColor:[A],borderRadius:["none","","full",cz,g2],borderSpacing:XA(),borderWidth:BA(),contrast:UA(),grayscale:AA(),hueRotate:UA(),invert:AA(),gap:XA(),gradientColorStops:[A],gradientColorStopPositions:[tnQ,uz],inset:h(),margin:h(),opacity:UA(),padding:XA(),saturate:UA(),scale:UA(),sepia:AA(),skew:UA(),space:XA(),translate:XA()},classGroups:{aspect:[{aspect:["auto","square","video",g2]}],container:["container"],columns:[{columns:[cz]}],"break-after":[{"break-after":o()}],"break-before":[{"break-before":o()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...C(),g2]}],overflow:[{overflow:e()}],"overflow-x":[{"overflow-x":e()}],"overflow-y":[{"overflow-y":e()}],overscroll:[{overscroll:g()}],"overscroll-x":[{"overscroll-x":g()}],"overscroll-y":[{"overscroll-y":g()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[E]}],"inset-x":[{"inset-x":[E]}],"inset-y":[{"inset-y":[E]}],start:[{start:[E]}],end:[{end:[E]}],top:[{top:[E]}],right:[{right:[E]}],bottom:[{bottom:[E]}],left:[{left:[E]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Bu,g2]}],basis:[{basis:h()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",g2]}],grow:[{grow:AA()}],shrink:[{shrink:AA()}],order:[{order:["first","last","none",Bu,g2]}],"grid-cols":[{"grid-cols":[wu]}],"col-start-end":[{col:["auto",{span:["full",Bu,g2]},g2]}],"col-start":[{"col-start":k()}],"col-end":[{"col-end":k()}],"grid-rows":[{"grid-rows":[wu]}],"row-start-end":[{row:["auto",{span:[Bu,g2]},g2]}],"row-start":[{"row-start":k()}],"row-end":[{"row-end":k()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",g2]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",g2]}],gap:[{gap:[F]}],"gap-x":[{"gap-x":[F]}],"gap-y":[{"gap-y":[F]}],"justify-content":[{justify:["normal",...u()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...u(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...u(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[_]}],px:[{px:[_]}],py:[{py:[_]}],ps:[{ps:[_]}],pe:[{pe:[_]}],pt:[{pt:[_]}],pr:[{pr:[_]}],pb:[{pb:[_]}],pl:[{pl:[_]}],m:[{m:[L]}],mx:[{mx:[L]}],my:[{my:[L]}],ms:[{ms:[L]}],me:[{me:[L]}],mt:[{mt:[L]}],mr:[{mr:[L]}],mb:[{mb:[L]}],ml:[{ml:[L]}],"space-x":[{"space-x":[x]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[x]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",g2,Q]}],"min-w":[{"min-w":[g2,Q,"min","max","fit"]}],"max-w":[{"max-w":[g2,Q,"none","full","min","max","fit","prose",{screen:[cz]},cz]}],h:[{h:[g2,Q,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[g2,Q,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[g2,Q,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[g2,Q,"auto","min","max","fit"]}],"font-size":[{text:["base",cz,uz]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",hRA]}],"font-family":[{font:[wu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",g2]}],"line-clamp":[{"line-clamp":["none",Wj,hRA]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",dK,g2]}],"list-image":[{"list-image":["none",g2]}],"list-style-type":[{list:["none","disc","decimal",g2]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[A]}],"placeholder-opacity":[{"placeholder-opacity":[R]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[A]}],"text-opacity":[{"text-opacity":[R]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...j(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",dK,uz]}],"underline-offset":[{"underline-offset":["auto",dK,g2]}],"text-decoration-color":[{decoration:[A]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:XA()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",g2]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",g2]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[R]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...C(),QoQ]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",AoQ]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},woQ]}],"bg-color":[{bg:[A]}],"gradient-from-pos":[{from:[q]}],"gradient-via-pos":[{via:[q]}],"gradient-to-pos":[{to:[q]}],"gradient-from":[{from:[Z]}],"gradient-via":[{via:[Z]}],"gradient-to":[{to:[Z]}],rounded:[{rounded:[I]}],"rounded-s":[{"rounded-s":[I]}],"rounded-e":[{"rounded-e":[I]}],"rounded-t":[{"rounded-t":[I]}],"rounded-r":[{"rounded-r":[I]}],"rounded-b":[{"rounded-b":[I]}],"rounded-l":[{"rounded-l":[I]}],"rounded-ss":[{"rounded-ss":[I]}],"rounded-se":[{"rounded-se":[I]}],"rounded-ee":[{"rounded-ee":[I]}],"rounded-es":[{"rounded-es":[I]}],"rounded-tl":[{"rounded-tl":[I]}],"rounded-tr":[{"rounded-tr":[I]}],"rounded-br":[{"rounded-br":[I]}],"rounded-bl":[{"rounded-bl":[I]}],"border-w":[{border:[Y]}],"border-w-x":[{"border-x":[Y]}],"border-w-y":[{"border-y":[Y]}],"border-w-s":[{"border-s":[Y]}],"border-w-e":[{"border-e":[Y]}],"border-w-t":[{"border-t":[Y]}],"border-w-r":[{"border-r":[Y]}],"border-w-b":[{"border-b":[Y]}],"border-w-l":[{"border-l":[Y]}],"border-opacity":[{"border-opacity":[R]}],"border-style":[{border:[...j(),"hidden"]}],"divide-x":[{"divide-x":[Y]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[Y]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[R]}],"divide-style":[{divide:j()}],"border-color":[{border:[$]}],"border-color-x":[{"border-x":[$]}],"border-color-y":[{"border-y":[$]}],"border-color-s":[{"border-s":[$]}],"border-color-e":[{"border-e":[$]}],"border-color-t":[{"border-t":[$]}],"border-color-r":[{"border-r":[$]}],"border-color-b":[{"border-b":[$]}],"border-color-l":[{"border-l":[$]}],"divide-color":[{divide:[$]}],"outline-style":[{outline:["",...j()]}],"outline-offset":[{"outline-offset":[dK,g2]}],"outline-w":[{outline:[dK,uz]}],"outline-color":[{outline:[A]}],"ring-w":[{ring:BA()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[A]}],"ring-opacity":[{"ring-opacity":[R]}],"ring-offset-w":[{"ring-offset":[dK,uz]}],"ring-offset-color":[{"ring-offset":[A]}],shadow:[{shadow:["","inner","none",cz,$oQ]}],"shadow-color":[{shadow:[wu]}],opacity:[{opacity:[R]}],"mix-blend":[{"mix-blend":[...i(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":i()}],filter:[{filter:["","none"]}],blur:[{blur:[B]}],brightness:[{brightness:[w]}],contrast:[{contrast:[X]}],"drop-shadow":[{"drop-shadow":["","none",cz,g2]}],grayscale:[{grayscale:[W]}],"hue-rotate":[{"hue-rotate":[U]}],invert:[{invert:[K]}],saturate:[{saturate:[O]}],sepia:[{sepia:[n]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[B]}],"backdrop-brightness":[{"backdrop-brightness":[w]}],"backdrop-contrast":[{"backdrop-contrast":[X]}],"backdrop-grayscale":[{"backdrop-grayscale":[W]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[U]}],"backdrop-invert":[{"backdrop-invert":[K]}],"backdrop-opacity":[{"backdrop-opacity":[R]}],"backdrop-saturate":[{"backdrop-saturate":[O]}],"backdrop-sepia":[{"backdrop-sepia":[n]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[D]}],"border-spacing-x":[{"border-spacing-x":[D]}],"border-spacing-y":[{"border-spacing-y":[D]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",g2]}],duration:[{duration:UA()}],ease:[{ease:["linear","in","out","in-out",g2]}],delay:[{delay:UA()}],animate:[{animate:["none","spin","ping","pulse","bounce",g2]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[r]}],"scale-x":[{"scale-x":[r]}],"scale-y":[{"scale-y":[r]}],rotate:[{rotate:[Bu,g2]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",g2]}],accent:[{accent:["auto",A]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",g2]}],"caret-color":[{caret:[A]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":XA()}],"scroll-mx":[{"scroll-mx":XA()}],"scroll-my":[{"scroll-my":XA()}],"scroll-ms":[{"scroll-ms":XA()}],"scroll-me":[{"scroll-me":XA()}],"scroll-mt":[{"scroll-mt":XA()}],"scroll-mr":[{"scroll-mr":XA()}],"scroll-mb":[{"scroll-mb":XA()}],"scroll-ml":[{"scroll-ml":XA()}],"scroll-p":[{"scroll-p":XA()}],"scroll-px":[{"scroll-px":XA()}],"scroll-py":[{"scroll-py":XA()}],"scroll-ps":[{"scroll-ps":XA()}],"scroll-pe":[{"scroll-pe":XA()}],"scroll-pt":[{"scroll-pt":XA()}],"scroll-pr":[{"scroll-pr":XA()}],"scroll-pb":[{"scroll-pb":XA()}],"scroll-pl":[{"scroll-pl":XA()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",g2]}],fill:[{fill:[A,"none"]}],"stroke-w":[{stroke:[dK,uz,hRA]}],stroke:[{stroke:[A,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},XoQ=(A,{cacheSize:Q,prefix:B,separator:w,experimentalParseClassName:$,extend:I={},override:D={}})=>{$u(A,"cacheSize",Q),$u(A,"prefix",B),$u(A,"separator",w),$u(A,"experimentalParseClassName",$);for(let Y in D)WoQ(A[Y],D[Y]);for(let Y in I)HoQ(A[Y],I[Y]);return A},$u=(A,Q,B)=>{if(B!==void 0)A[Q]=B},WoQ=(A,Q)=>{if(Q)for(let B in Q)$u(A,B,Q[B])},HoQ=(A,Q)=>{if(Q)for(let B in Q){let w=Q[B];if(w!==void 0)A[B]=(A[B]||[]).concat(w)}},UQA=(A,...Q)=>typeof A==="function"?q01(L01,A,...Q):q01(()=>XoQ(L01(),A),...Q);var UoQ=UQA({extend:{classGroups:{"font-size":[{text:["display-2xl","display-xl","display-lg","display-md","display-sm","heading-lg","heading-md","heading-sm","body-xl","body-lg","body-md","body-sm","body-xs","label-md","label-sm","label-xs"]}]}}});function e1(...A){return UoQ(Xj(A))}var O01=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,R01=Xj,_w=(A,Q)=>(B)=>{var w;if((Q===null||Q===void 0?void 0:Q.variants)==null)return R01(A,B===null||B===void 0?void 0:B.class,B===null||B===void 0?void 0:B.className);let{variants:$,defaultVariants:I}=Q,D=Object.keys($).map((W)=>{let U=B===null||B===void 0?void 0:B[W],K=I===null||I===void 0?void 0:I[W];if(U===null)return null;let F=O01(U)||O01(K);return $[W][F]}),Y=B&&Object.entries(B).reduce((W,U)=>{let[K,F]=U;if(F===void 0)return W;return W[K]=F,W},{}),X=Q===null||Q===void 0?void 0:(w=Q.compoundVariants)===null||w===void 0?void 0:w.reduce((W,U)=>{let{class:K,className:F,...Z}=U;return Object.entries(Z).every((q)=>{let[E,L]=q;return Array.isArray(L)?L.includes({...I,...Y}[E]):{...I,...Y}[E]===L})?[...W,K,F]:W},[]);return R01(A,D,X,B===null||B===void 0?void 0:B.class,B===null||B===void 0?void 0:B.className)};import{jsxDEV as uRA}from"preact/jsx-dev-runtime";var b01=_w("p-4 rounded-lg border",{variants:{variant:{warning:"bg-warning border-warning text-warning",error:"bg-error border-error text-error",success:"bg-success border-success text-success",info:"bg-info border-info text-info"}},defaultVariants:{variant:"info"}});function cRA({variant:A,title:Q,children:B,className:w}){return uRA("div",{className:e1(b01({variant:A}),w),role:"alert",children:[Q&&uRA("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),uRA("div",{className:e1(Q&&"mt-1","text-sm text-current opacity-75"),children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as JoQ}from"preact/jsx-dev-runtime";var P01=_w("inline-flex items-center justify-center font-bold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",{variants:{variant:{default:"bg-brand hover:bg-brand-dark text-theme-inverse",secondary:"bg-theme-muted hover:bg-theme-subtle text-theme border border-theme",ghost:"hover:bg-theme-subtle text-theme"},size:{sm:"h-8 px-3 text-sm rounded-md",md:"h-10 px-4 py-2 text-sm rounded-lg",lg:"h-12 px-6 text-base rounded-lg"}},defaultVariants:{variant:"default",size:"md"}});function kE({variant:A,size:Q,className:B,children:w,ssrOnClick:$,type:I="button",...D}){return JoQ("button",{type:I,className:e1(P01({variant:A,size:Q}),B),...D,...$&&{onclick:$},children:w},void 0,!1,void 0,this)}import{jsxDEV as GoQ}from"preact/jsx-dev-runtime";var j01=_w("inline-flex items-center justify-center font-semibold transition-all text-center",{variants:{variant:{primary:"bg-brand text-theme-inverse hover:bg-brand-dark focus:ring-brand/20 focus:outline-none focus:ring-4",accent:"bg-accent text-theme-inverse hover:bg-accent-dark focus:ring-accent/20 focus:outline-none focus:ring-4",secondary:"bg-theme-muted text-theme hover:bg-theme-muted-dark focus:outline-none focus:ring-4",outline:"border-2 border-brand text-brand hover:bg-brand hover:text-theme-inverse focus:ring-brand/20 focus:outline-none focus:ring-4","outline-light":"border-2 border-theme-light text-theme-inverse hover:bg-theme-inverse hover:text-brand hover:border-theme-inverse focus:outline-none focus:ring-4",unstyled:""},size:{icon:"w-10 h-10 rounded-full",sm:"px-3 py-1.5 text-sm rounded-lg",md:"px-4 py-2 text-sm rounded-lg",lg:"px-6 py-3 text-base rounded-xl",xl:"px-8 py-4 text-lg rounded-xl","2xl":"px-10 py-5 text-lg rounded-2xl"}},defaultVariants:{size:"md"}});function o5({href:A,children:Q,variant:B,size:w,external:$=!1,className:I,"aria-label":D}){let Y=$?{target:"_blank",rel:"noopener noreferrer"}:{};return GoQ("a",{href:A,className:e1(j01({variant:B,size:w}),I),"aria-label":D,...Y,children:Q},void 0,!1,void 0,this)}import{jsxDEV as JQA}from"preact/jsx-dev-runtime";var k01=_w("transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2",{variants:{variant:{default:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent hover:border-brand/40",light:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent",dark:"rounded-[10px] bg-theme-dark hover:bg-theme-muted text-theme-inverse",footer:"rounded-full bg-theme-toggle hover:bg-theme-toggle-hover text-theme-toggle-icon"},size:{sm:"p-1.5",md:"p-2",lg:"p-3"}},defaultVariants:{variant:"default",size:"md"}}),KoQ={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function Uj({variant:A,size:Q,className:B}){let w=KoQ[Q??"md"];return JQA("button",{onclick:"toggleTheme()",type:"button",className:e1(k01({variant:A,size:Q}),B),"aria-label":"Toggle dark mode",children:JQA("svg",{className:e1(w,"transition-colors"),fill:"none",stroke:"currentColor",strokeWidth:1.6,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[JQA("path",{className:"sun-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},void 0,!1,void 0,this),JQA("path",{className:"moon-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M20.354 15.354A9 9 0 018.646 3.646 9 9 0 1020.354 15.354z"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as pRA}from"preact/jsx-dev-runtime";var _01=_w("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function GQA({items:A,className:Q,linkClassName:B="hover:text-accent transition-colors",orientation:w,children:$}){if(A.length===0&&!$)return null;let I=[...A].sort((D,Y)=>D.priority-Y.priority);return pRA("ul",{className:e1(_01({orientation:w}),Q),children:[I.map((D)=>pRA("li",{children:pRA("a",{href:D.href,className:B,children:D.label},void 0,!1,void 0,this)},D.href,!1,void 0,this)),$]},void 0,!0,void 0,this)}import{jsxDEV as tDw}from"preact/jsx-dev-runtime";import{jsxDEV as QYw}from"preact/jsx-dev-runtime";import{createContext as p02,h as l02}from"preact";import{useContext as i02}from"preact/hooks";GfA();var cB1=X1(uB1(),1),u02=new mT({gfm:!0,breaks:!0}),c02={allowedTags:["h1","h2","h3","h4","h5","h6","p","br","hr","ul","ol","li","blockquote","cite","code","pre","em","strong","del","ins","sub","sup","a","img","span","table","thead","tbody","tr","th","td","div"],allowedAttributes:{a:["href","title","name"],img:["src","srcset","sizes","alt","title","width","height","class","loading","decoding"],code:["class"],pre:["class"],span:["class"],cite:["class"],div:["class"],th:["align","colspan","rowspan","scope"],td:["align","colspan","rowspan"]},allowedSchemes:["http","https","mailto","tel"],allowedSchemesByTag:{img:["http","https","entity"]},allowProtocolRelative:!1,disallowedTagsMode:"discard"};function JPA(A,Q){let{imageRenderer:B}=Q??{},$=(B?new mT({gfm:!0,breaks:!0}).use({renderer:{image(I,D,Y){return B(I,D,Y)??!1}}}):u02).parse(A);return $=$.replace(/<\/blockquote>\s*<p>(\u2014|--|\u2013)([\s\S]*?)<\/p>/g,`</blockquote>
|
|
3790
|
+
`)}}eA();class wQA extends Sw{directorySync;constructor(A,Q,B){super(A,{schema:xRA,jobTypeName:"directory-export"});this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let w=Date.now();try{let $=await this.directorySync.exportEntitiesWithProgress(A.entityTypes,B,A.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:Q,exported:$.exported,failed:$.failed,duration:Date.now()-w}),$}catch($){throw this.logger.error("Directory export job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}eA();class $QA extends Sw{directorySync;constructor(A,Q,B){super(A,{schema:vRA,jobTypeName:"directory-import"});this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let w=Date.now();try{let $=await this.directorySync.importEntitiesWithProgress(A.paths,B,A.batchSize??100);return this.logger.debug("Directory import job completed",{jobId:Q,imported:$.imported,skipped:$.skipped,failed:$.failed,quarantined:$.quarantined,duration:Date.now()-w}),$}catch($){throw this.logger.error("Directory import job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}eA();class IQA extends Sw{directorySync;context;constructor(A,Q,B){super(A,{schema:_RA,jobTypeName:"directory-sync"});this.context=Q,this.directorySync=B}async process(A,Q,B){let w=Date.now(),$=A.syncDirection??"both";this.logger.info("Starting directory sync job",{jobId:Q,operation:A.operation,syncDirection:$});let I={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},D={exported:0,failed:0,errors:[]};if($!=="export")if(await B.report({progress:10,message:"Scanning directory for changes"}),I=await this.importWithProgress(A.paths,B),$==="import")await this.waitForImportJobs(I.jobIds,B),await B.report({progress:100,message:`Import complete: ${I.imported} imported`});else await B.report({progress:50,message:`Imported ${I.imported} entities`}),await this.waitForImportJobs(I.jobIds,B),await B.report({progress:56,message:"Processing complete, starting export"});if($!=="import"){let X=$==="export"?10:60;await B.report({progress:X,message:"Exporting entities to directory"}),D=await this.exportWithProgress(A.entityTypes,B),await B.report({progress:100,message:$==="export"?`Export complete: ${D.exported} exported`:`Sync complete: ${I.imported} imported, ${D.exported} exported`})}let Y=Date.now()-w;return this.logger.info("Directory sync job completed",{jobId:Q,duration:Y,imported:I.imported,exported:D.exported}),{import:I,export:D,duration:Y}}async importWithProgress(A,Q){try{return await this.directorySync.importEntitiesWithProgress(A,Q,10)}catch(B){throw this.logger.error("Import phase failed",{error:B}),B}}async exportWithProgress(A,Q){try{return await this.directorySync.exportEntitiesWithProgress(A,Q,10)}catch(B){throw this.logger.error("Export phase failed",{error:B}),B}}async waitForImportJobs(A,Q){if(A.length===0)return;this.logger.debug(`Waiting for ${A.length} import jobs to complete`);let{entityService:B}=this.context,w=300000,$=500,I=Date.now(),D=async()=>{let X=(await Promise.all(A.map((U)=>B.getAsyncJobStatus(U)))).filter((U)=>U&&(U.status==="completed"||U.status==="failed")).length;if(X===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-I>w){this.logger.warn(`Timeout waiting for import jobs (${X}/${A.length} completed)`);return}let W=Math.round(X/A.length*100);return await Q.report({progress:50+Math.round(W*0.05),message:`Processing ${X}/${A.length} entities`}),await new Promise((U)=>setTimeout(U,$)),D()};return D()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}eA();class DQA extends Sw{context;constructor(A,Q,B){super(A,{schema:QQA,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,B){let w=QQA.parse(A);this.logger.info("Processing entity deletion for removed file",{entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}),await B.report({progress:0,total:1,message:`Deleting ${w.entityType}:${w.entityId}`});try{let $=await this.context.entityService.deleteEntity({entityType:w.entityType,id:w.entityId});if($)this.logger.info("Successfully deleted entity for removed file",{entityId:w.entityId,entityType:w.entityType});else this.logger.warn("Entity not found in database",{entityId:w.entityId,entityType:w.entityType});return await B.report({progress:1,total:1,message:`Deleted ${w.entityType}:${w.entityId}`}),{deleted:$,entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}}catch($){throw this.logger.error("Failed to delete entity",{entityId:w.entityId,entityType:w.entityType,error:$}),$}}summarizeDataForLog(A){return{entityId:A.entityId,entityType:A.entityType,filePath:A.filePath}}}eA();fA();var YnQ=f.object({});class YQA extends Sw{directorySync;constructor(A,Q){super(A,{schema:YnQ,jobTypeName:"directory-cleanup"});this.directorySync=Q}async process(A,Q,B){await B.report({progress:0,message:"Removing orphaned entities"});let w=await this.directorySync.removeOrphanedEntities();return await B.report({progress:100,message:`Cleanup complete: ${w.deleted} orphans removed`}),w}}eA();v4();fA();r$();v4();import{readFile as XnQ,writeFile as WnQ}from"fs/promises";var HnQ=yRA;class XQA extends Sw{context;fetcher;constructor(A,Q,B=wW){super(Q,{schema:HnQ,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=B}async process(A,Q,B){let{filePath:w,sourceUrl:$,postTitle:I,postSlug:D,customAlt:Y}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:w,sourceUrl:$,postSlug:D});try{await this.reportProgress(B,{progress:u2.INIT,message:`Reading file: ${w}`});let X;try{X=await XnQ(w,"utf-8")}catch(E){return this.logger.error("Failed to read file",{filePath:w,error:S0(E)}),d$.failure(E)}let W;try{W=eD(X)}catch(E){return this.logger.warn("Failed to parse markdown",{filePath:w,error:S0(E)}),d$.failure(E)}let U=W.frontmatter;if(U.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:w}),await this.reportProgress(B,{progress:u2.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress(B,{progress:u2.FETCH,message:"Checking for existing image"});let K=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:$}},limit:1}}),F;if(K[0])F=K[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:$,imageId:F}),await this.reportProgress(B,{progress:u2.EXTRACT,message:`Reusing existing image: ${F}`});else{await this.reportProgress(B,{progress:u2.PROCESS,message:`Fetching image from ${$}`});let E;try{E=await this.fetcher($)}catch(n){return this.logger.error("Failed to fetch image",{sourceUrl:$,error:S0(n)}),d$.failure(n)}await this.reportProgress(B,{progress:u2.GENERATE,message:"Creating image entity"});let{base64:L}=IZ(E),R=Cq(L),_=DZ(L);if(!R||!_)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:$}),d$.failure(Error("Could not detect image format or dimensions"));F=`${D}-cover`;let O=`Cover image for ${I}`,r=Y??O;await this.context.entityService.createEntity({entity:{id:F,entityType:"image",content:E,metadata:{title:O,alt:r,format:R,width:_.width,height:_.height,sourceUrl:$}}}),this.logger.debug("Created image entity",{imageId:F,sourceUrl:$}),await this.reportProgress(B,{progress:u2.EXTRACT,message:`Created image: ${F}`})}await this.reportProgress(B,{progress:u2.SAVE,message:"Updating file"});let Z={...U};delete Z.coverImageUrl,delete Z.coverImageAlt,Z.coverImageId=F;let q=b3(Z,W.content);try{await WnQ(w,q,"utf-8")}catch(E){return this.logger.error("Failed to write file",{filePath:w,error:S0(E)}),d$.failure(E)}return await this.reportProgress(B,{progress:u2.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:w,imageId:F,sourceUrl:$}),{success:!0,imageId:F}}catch(X){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:w,error:S0(X)}),d$.failure(X)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}eA();v4();fA();r$();import{readFile as UnQ,writeFile as JnQ}from"fs/promises";class WQA extends Sw{converter;constructor(A,Q,B=wW){super(Q,{schema:TRA,jobTypeName:"inline-image-convert"});this.converter=new cm(A.entityService,Q,B)}async process(A,Q,B){let{filePath:w,postSlug:$}=A;this.logger.debug("Starting inline image conversion job",{jobId:Q,filePath:w,postSlug:$});try{await this.reportProgress(B,{progress:u2.INIT,message:`Reading file: ${w}`});let I;try{I=await UnQ(w,"utf-8")}catch(X){let W=S0(X);return this.logger.error("Failed to read file",{filePath:w,error:W}),{success:!1,error:W}}await this.reportProgress(B,{progress:u2.FETCH,message:"Detecting inline images"});let D=this.converter.detectInlineImages(I,$);if(D.length===0)return this.logger.debug("No inline images to convert",{filePath:w}),await this.reportProgress(B,{progress:u2.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:w,count:D.length}),await this.reportProgress(B,{progress:u2.PROCESS,message:`Converting ${D.length} images`});let Y=await this.converter.convert(I,$);if(!Y.converted)return this.logger.debug("No images were converted",{filePath:w}),await this.reportProgress(B,{progress:u2.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress(B,{progress:u2.SAVE,message:"Writing updated file"});try{await JnQ(w,Y.content,"utf-8")}catch(X){let W=S0(X);return this.logger.error("Failed to write file",{filePath:w,error:W}),{success:!1,error:W}}return await this.reportProgress(B,{progress:u2.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:w,convertedCount:Y.convertedCount}),{success:!0,convertedCount:Y.convertedCount}}catch(I){let D=S0(I);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:w,error:D}),{success:!1,error:D}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function aA1(A,Q,B){let w=($)=>B.child($);A.jobs.registerHandler("directory-sync",new IQA(w("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new wQA(w("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new $QA(w("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new DQA(w("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new YQA(w("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new XQA(A,w("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new WQA(A,w("InlineImageConversionJobHandler"))),B.debug("Registered async job handlers")}eA();import{unlink as GnQ,access as KnQ}from"fs/promises";function tA1(A,Q,B,w){let{subscribe:$}=A.messaging,{entityService:I}=A;$("entity:created",async(D)=>{let{entity:Y}=D.payload;try{await Q.fileOps.writeEntity(Y),B.debug("Auto-exported created entity",{id:Y.id,entityType:Y.entityType})}catch(X){B.error("Auto-export FAILED for created entity",{id:Y.id,entityType:Y.entityType,error:X instanceof Error?X.message:String(X),stack:X instanceof Error?X.stack:void 0})}return{success:!0}}),$("entity:updated",async(D)=>{let{entityType:Y,entityId:X}=D.payload;try{let W=await I.getEntity({entityType:Y,id:X});if(!W)return B.debug("Entity not found in DB, skipping export",{entityType:Y,entityId:X}),{success:!1};await Q.fileOps.writeEntity(W),B.debug("Auto-exported updated entity",{id:W.id,entityType:W.entityType})}catch(W){B.error("Auto-export FAILED for updated entity",{entityType:Y,entityId:X,error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0})}return{success:!0}}),$("entity:deleted",async(D)=>{let{entityId:Y,entityType:X}=D.payload,W=Q.fileOps.getFilePath(Y,X);if(await KnQ(W).then(()=>!0,()=>!1))await GnQ(W),B.debug("Auto-deleted entity file",{id:Y,entityType:X,path:W});return{success:!0}}),B.debug("Setup auto-sync for entity events",{entityTypes:w})}function eA1(A,Q,B){Q.setJobQueueCallback(async(w)=>{let $=[{type:w.type,data:w.data}];return A.jobs.enqueueBatch($,{priority:5,source:"directory-sync-watcher",rootJobId:g5(),metadata:{operationType:"file_operations",operationTarget:B,pluginId:"directory-sync"}})})}fA();eA();import{readdir as B01,mkdir as FnQ,copyFile as ZnQ}from"fs/promises";import{join as Q01,resolve as SRA}from"path";import{join as fnQ}from"path";async function A01(A){if(!await c6(fnQ(A,".git")))return!1;try{return await iK(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function znQ(A,Q){if(!await c6(A))return!0;if((await B01(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await A01(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function w01(A,Q){let B=await B01(A,{withFileTypes:!0});for(let w of B){let $=Q01(A,w.name),I=Q01(Q,w.name);if(w.isDirectory()){if(!await c6(I))await FnQ(I,{recursive:!0});await w01($,I)}else await ZnQ($,I)}}async function $01(A,Q,B){let w=SRA(process.cwd(),A);B=B?SRA(B):SRA(process.cwd(),"seed-content");let $=await znQ(w,Q);if($&&await c6(B))Q.debug("Copying seed content to brain-data directory"),await w01(B,w),Q.debug("Seed content copied successfully");else if($)Q.debug("No seed content directory found, starting with empty brain-data");else Q.debug("brain-data directory not empty, skipping seed content")}function I01(A,Q,B,w,$){let I=!1,D=async()=>{if(I)return;I=!0;let Y=Q();if(B.seedContent){let X=B.syncPath??A.dataDir;await $01(X,w,B.seedContentPath)}try{if($){w.debug("Git enabled \u2014 pulling before import");let W=await $.pull();if(W.files.length>0)w.info("Pulled changes from remote",{filesChanged:W.files.length})}w.debug("Starting initial sync");let X=await Y.sync();w.debug("Initial sync completed",{imported:X.import.imported,failed:X.import.failed,duration:X.duration}),await A.messaging.send({type:n3.initialSyncCompleted,payload:{success:!0},...{broadcast:!0}})}catch(X){w.error("Initial sync failed",X),await A.messaging.send({type:n3.initialSyncCompleted,payload:{success:!1,error:S0(X)},...{broadcast:!0}})}};A.messaging.subscribe(n3.pluginsRegistered,async()=>{return w.debug("Plugins registered, starting initial sync"),await D(),{success:!0}})}fA();function D01(A,Q,B,w){let $=new T3(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(Y){w.error("Git auto-commit failed",{error:Y})}})},B),I=["entity:created","entity:updated","entity:deleted"],D=[];for(let Y of I){let X=A.subscribe(Y,async()=>{return $.trigger(),{success:!0}});D.push(X)}return()=>{$.dispose();for(let Y of D)Y()}}function Y01(A,Q,B,w,$){if(w<=0)return()=>{};let I=w*60*1000,D=!1,Y=async()=>{if(D)return;D=!0;try{let{files:W,result:U}=await A.withLock(async()=>{let K=await A.pull();if(K.files.length===0)return{files:[],result:null};let F=await Q.queueSyncBatch(B,"periodic-sync");return{files:K.files,result:F}});if(W.length>0)$.info("Periodic sync: pulled changes",{filesChanged:W.length});if(U)$.debug("Periodic sync: queued imports",{importOperations:U.importOperationsCount,totalFiles:U.totalFiles})}catch(W){$.error("Periodic git sync failed",{error:W})}finally{D=!1}},X=setInterval(()=>{Y()},I);return $.info("Started periodic git sync",{intervalMinutes:w}),()=>{clearInterval(X)}}import{spawnSync as W01}from"child_process";import{cpSync as NnQ,existsSync as X01,mkdirSync as qnQ,mkdtempSync as LnQ,rmSync as EnQ}from"fs";import{tmpdir as VnQ}from"os";import{fileURLToPath as MnQ}from"url";import{join as CnQ,resolve as OnQ}from"path";function mz(A,Q){let B=W01("git",Q,{cwd:A,stdio:"pipe"});if(B.status!==0){let w=B.stderr.toString().trim(),$=B.stdout.toString().trim();throw Error(w||$||`git ${Q.join(" ")} failed`)}}function RnQ(A){return A.startsWith("file://")}function bnQ(A){return MnQ(A)}function PnQ(A,Q){return W01("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function H01(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!RnQ(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",B=bnQ(A.gitUrl),w=OnQ(A.seedContentPath);if(!X01(w))throw Error(`Seed content path not found: ${w}`);if(!X01(B))A.logger.debug("Creating local bare content remote",{remotePath:B,branch:Q}),qnQ(B,{recursive:!0}),mz(process.cwd(),["init","--bare",`--initial-branch=${Q}`,B]);if(PnQ(B,Q)){A.logger.debug("Content remote already initialized",{remotePath:B,branch:Q});return}A.logger.debug("Seeding local content remote",{remotePath:B,seedPath:w,branch:Q});let $=LnQ(CnQ(VnQ(),"directory-sync-seed-"));try{mz($,["init",`--initial-branch=${Q}`]),mz($,["config","user.name",A.authorName??"Brain"]),mz($,["config","user.email",A.authorEmail??"brain@localhost"]),NnQ(w,$,{recursive:!0}),mz($,["add","."]),mz($,["commit","-m","seed content remote"]),mz($,["remote","add","origin",A.gitUrl]),mz($,["push","-u","origin",Q])}finally{EnQ($,{recursive:!0,force:!0})}}function U01(A,Q,B,w,$){let{subscribe:I}=A.messaging;I("entity:export:request",async(D)=>{try{return{success:!0,data:await Q().exportEntities(D.payload.entityTypes)}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Export failed"}}}),I("entity:import:request",async(D)=>{try{let Y=Q(),X=D.payload.paths,W=await Y.importEntities(X);if(X&&X.length>0)await Y.removeOrphanedEntities();return{success:!0,data:W}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Import failed"}}}),I("sync:status:request",async()=>{try{let Y=await Q().getStatus();return{success:!0,data:{syncPath:Y.syncPath,isInitialized:Y.exists,watchEnabled:Y.watching}}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Status check failed"}}}),I("sync:configure:request",async(D)=>{try{return await B({syncPath:D.payload.syncPath}),{success:!0,data:{syncPath:D.payload.syncPath,configured:!0}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Configuration failed"}}}),I("git-sync:get-repo-info",async()=>{if(!$?.repo)return{success:!1,error:"Git not configured"};return{success:!0,data:{repo:$.repo,branch:$.branch??"main"}}}),w.debug("Registered message handlers")}eA();fA();eA();fA();function J01(A,Q){return j2(A,"history","Get version history for an entity from git. Without sha: returns commit list. With sha: returns entity content at that version.",f.object({entityType:f.string().describe("Entity type (e.g. post, note, link)"),id:f.string().describe("Entity ID"),sha:f.string().optional().describe("Commit SHA to retrieve content at. Omit to list commit history."),limit:f.number().int().positive().optional().default(10).describe("Max commits to return (list mode only)")}),async(B)=>{let w=`${B.entityType}/${B.id}.md`;try{if(B.sha){let I=await Q.show(B.sha,w);return J8({sha:B.sha,entityType:B.entityType,id:B.id,content:I},`Content at ${B.sha.slice(0,7)}`)}let $=await Q.log(w,B.limit);if($.length===0)return J8({commits:[]},`No history found for ${B.entityType}/${B.id}`);return J8({commits:$,entityType:B.entityType,id:B.id},`${$.length} version${$.length===1?"":"s"} found`)}catch($){return h5($ instanceof Error?$.message:"History lookup failed")}})}function G01(A,Q,B,w){let $=[j2(B,"sync","Sync brain entities with the filesystem. Use this for refresh, pull, sync, or backup-to-git requests. Pulls from git if configured, then imports files. Git commit and push happen automatically after imports complete.",f.object({}),async(I,D)=>{try{let Y=D.channelId?`${D.interfaceType}:${D.channelId}`:`plugin:${B}`,X={interfaceType:D.interfaceType,channelId:D.channelId},W=w!==void 0,U=()=>A.queueSyncBatch(Q,Y,X),K=w?await w.withLock(async()=>{return await w.pull(),U()}):await U();if(!K)return J8({gitPulled:W},"No files to sync");return J8({batchId:K.batchId,importOperations:K.importOperationsCount,totalFiles:K.totalFiles,gitPulled:W},`Sync started: ${K.importOperationsCount} import jobs queued for ${K.totalFiles} files${W?" (pulled from git)":""}`)}catch(Y){return h5(Y instanceof Error?Y.message:"Sync failed")}},{cli:{name:"sync"}}),j2(B,"status","Get sync and git repository status \u2014 last sync time, watching state, pending git changes. Use this for status questions, not for actually syncing or backing up.",f.object({}),async()=>{try{let I=await A.getStatus(),D={syncPath:I.syncPath,lastSync:I.lastSync?.toISOString(),watching:I.watching};if(w){let Y=await w.getStatus();D.git={isRepo:Y.isRepo,branch:Y.branch,hasChanges:Y.hasChanges,ahead:Y.ahead,behind:Y.behind,remote:Y.remote}}return J8(D)}catch(I){return h5(I instanceof Error?I.message:"Status check failed")}},{visibility:"public"})];if(w)$.push(J01(B,w));return $}var K01={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.93",description:"Directory-based entity synchronization plugin for Brains",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":{types:"./src/index.ts",import:"./src/index.ts"}},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",clean:"rm -rf .turbo"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chokidar:"^3.5.3","simple-git":"^3.21.0"},devDependencies:{"@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},peerDependencies:{}};class gRA extends qB{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",K01,A,Au)}requireDirectorySync(){if(!this.directorySync)throw Error("DirectorySync service not initialized");return this.directorySync}hasGitSync(){return this.gitSync!==void 0}async onRegister(A){let{logger:Q,entityService:B}=A;A.templates.register({status:{name:"status",description:"Directory synchronization status",schema:Qu,basePrompt:"",formatter:new BQA,requiredPermission:"anchor"}});let w=this.config.syncPath??A.dataDir;this.directorySync=new pm({syncPath:w,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,entityService:B,logger:Q});try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:w})}catch(D){throw this.logger.error("Failed to initialize directory",D),D}await this.registerJobHandlers(A);let $=this.requireDirectorySync();if(tA1(A,$,this.logger,this.config.entityTypes),this.config.autoSync)eA1(A,$,this.config.syncPath??A.dataDir);let I=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!I)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(I&&this.config.git){await H01({gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,seedContentPath:this.config.seedContentPath,bootstrapFromSeed:this.config.git.bootstrapFromSeed,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail,logger:this.logger.child("ContentRemoteBootstrap")});let D=this.config.syncPath??A.dataDir;if(this.gitSync=new kRA({logger:this.logger.child("GitSync"),dataDir:D,repo:this.config.git.repo,gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,authToken:this.config.git.authToken,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail}),await this.gitSync.initialize(),this.logger.info("Git integration enabled",{repo:this.config.git.repo}),this.gitCleanups.push(D01(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(Y01(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)I01(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);U01(A,()=>this.requireDirectorySync(),(D)=>this.configure(D),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return G01(A,this.getContext(),this.id,this.gitSync)}async onShutdown(){for(let A of this.gitCleanups)A();this.gitCleanups=[],this.directorySync?.stopWatching(),this.gitSync?.cleanup()}getDirectorySync(){return this.directorySync}async configure(A){this.requireDirectorySync();let Q=this.getContext();this.directorySync=new pm({...this.config,syncPath:A.syncPath,entityService:Q.entityService,logger:Q.logger}),await this.directorySync.initialize(),this.logger.info("Directory sync reconfigured",{path:A.syncPath})}async registerJobHandlers(A){aA1(A,this.requireDirectorySync(),this.logger)}}function jE(A={}){return new gRA(A)}eA();fA();var f01={name:"@brains/email-resend",private:!0,version:"0.2.0-alpha.93",description:"Generic email delivery adapter for Resend",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var _nQ=f.object({apiKey:f.string().min(1).optional(),from:f.string().min(1).optional()});class F01 extends qB{fetchImpl;constructor(A={},Q={}){super("email-resend",f01,A,_nQ);this.fetchImpl=Q.fetchImpl??fetch}async onRegister(A){if(!this.config.apiKey||!this.config.from){this.logger.warn("Email Resend adapter is disabled because apiKey or from is missing");return}let Q=this.logger;A.messaging.subscribe(Tt,async(B)=>{let w=UF0.parse(B.payload);try{return{success:!0,data:await this.sendWithResend(w)}}catch($){if(w.sensitivity==="secret")Q.warn("Email delivery failed for a secret message");else Q.warn("Email delivery failed",{to:w.to,subject:w.subject,error:$ instanceof Error?$.message:String($)});return{success:!1,error:"Email delivery failed"}}})}async sendWithResend(A){let Q=this.config.apiKey,B=this.config.from;if(!Q||!B)return{status:"failed"};let w=await this.fetchImpl("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({from:B,to:A.to,subject:A.subject,text:A.text,...A.html?{html:A.html}:{}})});if(!w.ok)throw Error("Resend email request failed");let $=await w.json();return $.id?{status:"sent",id:$.id}:{status:"sent"}}}function HQA(A={}){return new F01(A)}eA();import{render as bD1}from"preact-render-to-string";import{h as GV}from"preact";function Z01(A){var Q,B,w="";if(typeof A=="string"||typeof A=="number")w+=A;else if(typeof A=="object")if(Array.isArray(A)){var $=A.length;for(Q=0;Q<$;Q++)A[Q]&&(B=Z01(A[Q]))&&(w&&(w+=" "),w+=B)}else for(B in A)A[B]&&(w&&(w+=" "),w+=B);return w}function Xj(){for(var A,Q,B=0,w="",$=arguments.length;B<$;B++)(A=arguments[B])&&(Q=Z01(A))&&(w&&(w+=" "),w+=Q);return w}var vnQ=(A)=>{let Q=ynQ(A),{conflictingClassGroups:B,conflictingClassGroupModifiers:w}=A;return{getClassGroupId:(D)=>{let Y=D.split("-");if(Y[0]===""&&Y.length!==1)Y.shift();return E01(Y,Q)||xnQ(D)},getConflictingClassGroupIds:(D,Y)=>{let X=B[D]||[];if(Y&&w[D])return[...X,...w[D]];return X}}},E01=(A,Q)=>{if(A.length===0)return Q.classGroupId;let B=A[0],w=Q.nextPart.get(B),$=w?E01(A.slice(1),w):void 0;if($)return $;if(Q.validators.length===0)return;let I=A.join("-");return Q.validators.find(({validator:D})=>D(I))?.classGroupId},z01=/^\[(.+)\]$/,xnQ=(A)=>{if(z01.test(A)){let Q=z01.exec(A)[1],B=Q?.substring(0,Q.indexOf(":"));if(B)return"arbitrary.."+B}},ynQ=(A)=>{let{theme:Q,prefix:B}=A,w={nextPart:new Map,validators:[]};return SnQ(Object.entries(A.classGroups),B).forEach(([I,D])=>{mRA(D,w,I,Q)}),w},mRA=(A,Q,B,w)=>{A.forEach(($)=>{if(typeof $==="string"){let I=$===""?Q:N01(Q,$);I.classGroupId=B;return}if(typeof $==="function"){if(TnQ($)){mRA($(w),Q,B,w);return}Q.validators.push({validator:$,classGroupId:B});return}Object.entries($).forEach(([I,D])=>{mRA(D,N01(Q,I),B,w)})})},N01=(A,Q)=>{let B=A;return Q.split("-").forEach((w)=>{if(!B.nextPart.has(w))B.nextPart.set(w,{nextPart:new Map,validators:[]});B=B.nextPart.get(w)}),B},TnQ=(A)=>A.isThemeGetter,SnQ=(A,Q)=>{if(!Q)return A;return A.map(([B,w])=>{let $=w.map((I)=>{if(typeof I==="string")return Q+I;if(typeof I==="object")return Object.fromEntries(Object.entries(I).map(([D,Y])=>[Q+D,Y]));return I});return[B,$]})},gnQ=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,B=new Map,w=new Map,$=(I,D)=>{if(B.set(I,D),Q++,Q>A)Q=0,w=B,B=new Map};return{get(I){let D=B.get(I);if(D!==void 0)return D;if((D=w.get(I))!==void 0)return $(I,D),D},set(I,D){if(B.has(I))B.set(I,D);else $(I,D)}}};var hnQ=(A)=>{let{separator:Q,experimentalParseClassName:B}=A,w=Q.length===1,$=Q[0],I=Q.length,D=(Y)=>{let X=[],W=0,U=0,K;for(let L=0;L<Y.length;L++){let R=Y[L];if(W===0){if(R===$&&(w||Y.slice(L,L+I)===Q)){X.push(Y.slice(U,L)),U=L+I;continue}if(R==="/"){K=L;continue}}if(R==="[")W++;else if(R==="]")W--}let F=X.length===0?Y:Y.substring(U),Z=F.startsWith("!"),q=Z?F.substring(1):F,E=K&&K>U?K-U:void 0;return{modifiers:X,hasImportantModifier:Z,baseClassName:q,maybePostfixModifierPosition:E}};if(B)return(Y)=>B({className:Y,parseClassName:D});return D},mnQ=(A)=>{if(A.length<=1)return A;let Q=[],B=[];return A.forEach((w)=>{if(w[0]==="[")Q.push(...B.sort(),w),B=[];else B.push(w)}),Q.push(...B.sort()),Q},unQ=(A)=>({cache:gnQ(A.cacheSize),parseClassName:hnQ(A),...vnQ(A)}),cnQ=/\s+/,pnQ=(A,Q)=>{let{parseClassName:B,getClassGroupId:w,getConflictingClassGroupIds:$}=Q,I=[],D=A.trim().split(cnQ),Y="";for(let X=D.length-1;X>=0;X-=1){let W=D[X],{modifiers:U,hasImportantModifier:K,baseClassName:F,maybePostfixModifierPosition:Z}=B(W),q=Boolean(Z),E=w(q?F.substring(0,Z):F);if(!E){if(!q){Y=W+(Y.length>0?" "+Y:Y);continue}if(E=w(F),!E){Y=W+(Y.length>0?" "+Y:Y);continue}q=!1}let L=mnQ(U).join(":"),R=K?L+"!":L,_=R+E;if(I.includes(_))continue;I.push(_);let O=$(E,q);for(let r=0;r<O.length;++r){let n=O[r];I.push(R+n)}Y=W+(Y.length>0?" "+Y:Y)}return Y};function lnQ(){let A=0,Q,B,w="";while(A<arguments.length)if(Q=arguments[A++]){if(B=V01(Q))w&&(w+=" "),w+=B}return w}var V01=(A)=>{if(typeof A==="string")return A;let Q,B="";for(let w=0;w<A.length;w++)if(A[w]){if(Q=V01(A[w]))B&&(B+=" "),B+=Q}return B};function q01(A,...Q){let B,w,$,I=D;function D(X){let W=Q.reduce((U,K)=>K(U),A());return B=unQ(W),w=B.cache.get,$=B.cache.set,I=Y,Y(X)}function Y(X){let W=w(X);if(W)return W;let U=pnQ(X,B);return $(X,U),U}return function(){return I(lnQ.apply(null,arguments))}}var N8=(A)=>{let Q=(B)=>B[A]||[];return Q.isThemeGetter=!0,Q},M01=/^\[(?:([a-z-]+):)?(.+)\]$/i,inQ=/^\d+\/\d+$/,dnQ=new Set(["px","full","screen"]),rnQ=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,nnQ=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,onQ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,snQ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,anQ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,dK=(A)=>Wj(A)||dnQ.has(A)||inQ.test(A),uz=(A)=>Hj(A,"length",IoQ),Wj=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),hRA=(A)=>Hj(A,"number",Wj),Bu=(A)=>Boolean(A)&&Number.isInteger(Number(A)),tnQ=(A)=>A.endsWith("%")&&Wj(A.slice(0,-1)),g2=(A)=>M01.test(A),cz=(A)=>rnQ.test(A),enQ=new Set(["length","size","percentage"]),AoQ=(A)=>Hj(A,enQ,C01),QoQ=(A)=>Hj(A,"position",C01),BoQ=new Set(["image","url"]),woQ=(A)=>Hj(A,BoQ,YoQ),$oQ=(A)=>Hj(A,"",DoQ),wu=()=>!0,Hj=(A,Q,B)=>{let w=M01.exec(A);if(w){if(w[1])return typeof Q==="string"?w[1]===Q:Q.has(w[1]);return B(w[2])}return!1},IoQ=(A)=>nnQ.test(A)&&!onQ.test(A),C01=()=>!1,DoQ=(A)=>snQ.test(A),YoQ=(A)=>anQ.test(A);var L01=()=>{let A=N8("colors"),Q=N8("spacing"),B=N8("blur"),w=N8("brightness"),$=N8("borderColor"),I=N8("borderRadius"),D=N8("borderSpacing"),Y=N8("borderWidth"),X=N8("contrast"),W=N8("grayscale"),U=N8("hueRotate"),K=N8("invert"),F=N8("gap"),Z=N8("gradientColorStops"),q=N8("gradientColorStopPositions"),E=N8("inset"),L=N8("margin"),R=N8("opacity"),_=N8("padding"),O=N8("saturate"),r=N8("scale"),n=N8("sepia"),S=N8("skew"),x=N8("space"),T=N8("translate"),g=()=>["auto","contain","none"],e=()=>["auto","hidden","clip","visible","scroll"],h=()=>["auto",g2,Q],XA=()=>[g2,Q],BA=()=>["",dK,uz],k=()=>["auto",Wj,g2],C=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],j=()=>["solid","dashed","dotted","double","none"],i=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],u=()=>["start","end","center","between","around","evenly","stretch"],AA=()=>["","0",g2],o=()=>["auto","avoid","all","avoid-page","page","left","right","column"],UA=()=>[Wj,g2];return{cacheSize:500,separator:":",theme:{colors:[wu],spacing:[dK,uz],blur:["none","",cz,g2],brightness:UA(),borderColor:[A],borderRadius:["none","","full",cz,g2],borderSpacing:XA(),borderWidth:BA(),contrast:UA(),grayscale:AA(),hueRotate:UA(),invert:AA(),gap:XA(),gradientColorStops:[A],gradientColorStopPositions:[tnQ,uz],inset:h(),margin:h(),opacity:UA(),padding:XA(),saturate:UA(),scale:UA(),sepia:AA(),skew:UA(),space:XA(),translate:XA()},classGroups:{aspect:[{aspect:["auto","square","video",g2]}],container:["container"],columns:[{columns:[cz]}],"break-after":[{"break-after":o()}],"break-before":[{"break-before":o()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...C(),g2]}],overflow:[{overflow:e()}],"overflow-x":[{"overflow-x":e()}],"overflow-y":[{"overflow-y":e()}],overscroll:[{overscroll:g()}],"overscroll-x":[{"overscroll-x":g()}],"overscroll-y":[{"overscroll-y":g()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[E]}],"inset-x":[{"inset-x":[E]}],"inset-y":[{"inset-y":[E]}],start:[{start:[E]}],end:[{end:[E]}],top:[{top:[E]}],right:[{right:[E]}],bottom:[{bottom:[E]}],left:[{left:[E]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Bu,g2]}],basis:[{basis:h()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",g2]}],grow:[{grow:AA()}],shrink:[{shrink:AA()}],order:[{order:["first","last","none",Bu,g2]}],"grid-cols":[{"grid-cols":[wu]}],"col-start-end":[{col:["auto",{span:["full",Bu,g2]},g2]}],"col-start":[{"col-start":k()}],"col-end":[{"col-end":k()}],"grid-rows":[{"grid-rows":[wu]}],"row-start-end":[{row:["auto",{span:[Bu,g2]},g2]}],"row-start":[{"row-start":k()}],"row-end":[{"row-end":k()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",g2]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",g2]}],gap:[{gap:[F]}],"gap-x":[{"gap-x":[F]}],"gap-y":[{"gap-y":[F]}],"justify-content":[{justify:["normal",...u()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...u(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...u(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[_]}],px:[{px:[_]}],py:[{py:[_]}],ps:[{ps:[_]}],pe:[{pe:[_]}],pt:[{pt:[_]}],pr:[{pr:[_]}],pb:[{pb:[_]}],pl:[{pl:[_]}],m:[{m:[L]}],mx:[{mx:[L]}],my:[{my:[L]}],ms:[{ms:[L]}],me:[{me:[L]}],mt:[{mt:[L]}],mr:[{mr:[L]}],mb:[{mb:[L]}],ml:[{ml:[L]}],"space-x":[{"space-x":[x]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[x]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",g2,Q]}],"min-w":[{"min-w":[g2,Q,"min","max","fit"]}],"max-w":[{"max-w":[g2,Q,"none","full","min","max","fit","prose",{screen:[cz]},cz]}],h:[{h:[g2,Q,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[g2,Q,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[g2,Q,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[g2,Q,"auto","min","max","fit"]}],"font-size":[{text:["base",cz,uz]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",hRA]}],"font-family":[{font:[wu]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",g2]}],"line-clamp":[{"line-clamp":["none",Wj,hRA]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",dK,g2]}],"list-image":[{"list-image":["none",g2]}],"list-style-type":[{list:["none","disc","decimal",g2]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[A]}],"placeholder-opacity":[{"placeholder-opacity":[R]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[A]}],"text-opacity":[{"text-opacity":[R]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...j(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",dK,uz]}],"underline-offset":[{"underline-offset":["auto",dK,g2]}],"text-decoration-color":[{decoration:[A]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:XA()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",g2]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",g2]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[R]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...C(),QoQ]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",AoQ]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},woQ]}],"bg-color":[{bg:[A]}],"gradient-from-pos":[{from:[q]}],"gradient-via-pos":[{via:[q]}],"gradient-to-pos":[{to:[q]}],"gradient-from":[{from:[Z]}],"gradient-via":[{via:[Z]}],"gradient-to":[{to:[Z]}],rounded:[{rounded:[I]}],"rounded-s":[{"rounded-s":[I]}],"rounded-e":[{"rounded-e":[I]}],"rounded-t":[{"rounded-t":[I]}],"rounded-r":[{"rounded-r":[I]}],"rounded-b":[{"rounded-b":[I]}],"rounded-l":[{"rounded-l":[I]}],"rounded-ss":[{"rounded-ss":[I]}],"rounded-se":[{"rounded-se":[I]}],"rounded-ee":[{"rounded-ee":[I]}],"rounded-es":[{"rounded-es":[I]}],"rounded-tl":[{"rounded-tl":[I]}],"rounded-tr":[{"rounded-tr":[I]}],"rounded-br":[{"rounded-br":[I]}],"rounded-bl":[{"rounded-bl":[I]}],"border-w":[{border:[Y]}],"border-w-x":[{"border-x":[Y]}],"border-w-y":[{"border-y":[Y]}],"border-w-s":[{"border-s":[Y]}],"border-w-e":[{"border-e":[Y]}],"border-w-t":[{"border-t":[Y]}],"border-w-r":[{"border-r":[Y]}],"border-w-b":[{"border-b":[Y]}],"border-w-l":[{"border-l":[Y]}],"border-opacity":[{"border-opacity":[R]}],"border-style":[{border:[...j(),"hidden"]}],"divide-x":[{"divide-x":[Y]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[Y]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[R]}],"divide-style":[{divide:j()}],"border-color":[{border:[$]}],"border-color-x":[{"border-x":[$]}],"border-color-y":[{"border-y":[$]}],"border-color-s":[{"border-s":[$]}],"border-color-e":[{"border-e":[$]}],"border-color-t":[{"border-t":[$]}],"border-color-r":[{"border-r":[$]}],"border-color-b":[{"border-b":[$]}],"border-color-l":[{"border-l":[$]}],"divide-color":[{divide:[$]}],"outline-style":[{outline:["",...j()]}],"outline-offset":[{"outline-offset":[dK,g2]}],"outline-w":[{outline:[dK,uz]}],"outline-color":[{outline:[A]}],"ring-w":[{ring:BA()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[A]}],"ring-opacity":[{"ring-opacity":[R]}],"ring-offset-w":[{"ring-offset":[dK,uz]}],"ring-offset-color":[{"ring-offset":[A]}],shadow:[{shadow:["","inner","none",cz,$oQ]}],"shadow-color":[{shadow:[wu]}],opacity:[{opacity:[R]}],"mix-blend":[{"mix-blend":[...i(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":i()}],filter:[{filter:["","none"]}],blur:[{blur:[B]}],brightness:[{brightness:[w]}],contrast:[{contrast:[X]}],"drop-shadow":[{"drop-shadow":["","none",cz,g2]}],grayscale:[{grayscale:[W]}],"hue-rotate":[{"hue-rotate":[U]}],invert:[{invert:[K]}],saturate:[{saturate:[O]}],sepia:[{sepia:[n]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[B]}],"backdrop-brightness":[{"backdrop-brightness":[w]}],"backdrop-contrast":[{"backdrop-contrast":[X]}],"backdrop-grayscale":[{"backdrop-grayscale":[W]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[U]}],"backdrop-invert":[{"backdrop-invert":[K]}],"backdrop-opacity":[{"backdrop-opacity":[R]}],"backdrop-saturate":[{"backdrop-saturate":[O]}],"backdrop-sepia":[{"backdrop-sepia":[n]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[D]}],"border-spacing-x":[{"border-spacing-x":[D]}],"border-spacing-y":[{"border-spacing-y":[D]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",g2]}],duration:[{duration:UA()}],ease:[{ease:["linear","in","out","in-out",g2]}],delay:[{delay:UA()}],animate:[{animate:["none","spin","ping","pulse","bounce",g2]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[r]}],"scale-x":[{"scale-x":[r]}],"scale-y":[{"scale-y":[r]}],rotate:[{rotate:[Bu,g2]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[S]}],"skew-y":[{"skew-y":[S]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",g2]}],accent:[{accent:["auto",A]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",g2]}],"caret-color":[{caret:[A]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":XA()}],"scroll-mx":[{"scroll-mx":XA()}],"scroll-my":[{"scroll-my":XA()}],"scroll-ms":[{"scroll-ms":XA()}],"scroll-me":[{"scroll-me":XA()}],"scroll-mt":[{"scroll-mt":XA()}],"scroll-mr":[{"scroll-mr":XA()}],"scroll-mb":[{"scroll-mb":XA()}],"scroll-ml":[{"scroll-ml":XA()}],"scroll-p":[{"scroll-p":XA()}],"scroll-px":[{"scroll-px":XA()}],"scroll-py":[{"scroll-py":XA()}],"scroll-ps":[{"scroll-ps":XA()}],"scroll-pe":[{"scroll-pe":XA()}],"scroll-pt":[{"scroll-pt":XA()}],"scroll-pr":[{"scroll-pr":XA()}],"scroll-pb":[{"scroll-pb":XA()}],"scroll-pl":[{"scroll-pl":XA()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",g2]}],fill:[{fill:[A,"none"]}],"stroke-w":[{stroke:[dK,uz,hRA]}],stroke:[{stroke:[A,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},XoQ=(A,{cacheSize:Q,prefix:B,separator:w,experimentalParseClassName:$,extend:I={},override:D={}})=>{$u(A,"cacheSize",Q),$u(A,"prefix",B),$u(A,"separator",w),$u(A,"experimentalParseClassName",$);for(let Y in D)WoQ(A[Y],D[Y]);for(let Y in I)HoQ(A[Y],I[Y]);return A},$u=(A,Q,B)=>{if(B!==void 0)A[Q]=B},WoQ=(A,Q)=>{if(Q)for(let B in Q)$u(A,B,Q[B])},HoQ=(A,Q)=>{if(Q)for(let B in Q){let w=Q[B];if(w!==void 0)A[B]=(A[B]||[]).concat(w)}},UQA=(A,...Q)=>typeof A==="function"?q01(L01,A,...Q):q01(()=>XoQ(L01(),A),...Q);var UoQ=UQA({extend:{classGroups:{"font-size":[{text:["display-2xl","display-xl","display-lg","display-md","display-sm","heading-lg","heading-md","heading-sm","body-xl","body-lg","body-md","body-sm","body-xs","label-md","label-sm","label-xs"]}]}}});function e1(...A){return UoQ(Xj(A))}var O01=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,R01=Xj,_w=(A,Q)=>(B)=>{var w;if((Q===null||Q===void 0?void 0:Q.variants)==null)return R01(A,B===null||B===void 0?void 0:B.class,B===null||B===void 0?void 0:B.className);let{variants:$,defaultVariants:I}=Q,D=Object.keys($).map((W)=>{let U=B===null||B===void 0?void 0:B[W],K=I===null||I===void 0?void 0:I[W];if(U===null)return null;let F=O01(U)||O01(K);return $[W][F]}),Y=B&&Object.entries(B).reduce((W,U)=>{let[K,F]=U;if(F===void 0)return W;return W[K]=F,W},{}),X=Q===null||Q===void 0?void 0:(w=Q.compoundVariants)===null||w===void 0?void 0:w.reduce((W,U)=>{let{class:K,className:F,...Z}=U;return Object.entries(Z).every((q)=>{let[E,L]=q;return Array.isArray(L)?L.includes({...I,...Y}[E]):{...I,...Y}[E]===L})?[...W,K,F]:W},[]);return R01(A,D,X,B===null||B===void 0?void 0:B.class,B===null||B===void 0?void 0:B.className)};import{jsxDEV as uRA}from"preact/jsx-dev-runtime";var b01=_w("p-4 rounded-lg border",{variants:{variant:{warning:"bg-warning border-warning text-warning",error:"bg-error border-error text-error",success:"bg-success border-success text-success",info:"bg-info border-info text-info"}},defaultVariants:{variant:"info"}});function cRA({variant:A,title:Q,children:B,className:w}){return uRA("div",{className:e1(b01({variant:A}),w),role:"alert",children:[Q&&uRA("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),uRA("div",{className:e1(Q&&"mt-1","text-sm text-current opacity-75"),children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as JoQ}from"preact/jsx-dev-runtime";var P01=_w("inline-flex items-center justify-center font-bold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",{variants:{variant:{default:"bg-brand hover:bg-brand-dark text-theme-inverse",secondary:"bg-theme-muted hover:bg-theme-subtle text-theme border border-theme",ghost:"hover:bg-theme-subtle text-theme"},size:{sm:"h-8 px-3 text-sm rounded-md",md:"h-10 px-4 py-2 text-sm rounded-lg",lg:"h-12 px-6 text-base rounded-lg"}},defaultVariants:{variant:"default",size:"md"}});function kE({variant:A,size:Q,className:B,children:w,ssrOnClick:$,type:I="button",...D}){return JoQ("button",{type:I,className:e1(P01({variant:A,size:Q}),B),...D,...$&&{onclick:$},children:w},void 0,!1,void 0,this)}import{jsxDEV as GoQ}from"preact/jsx-dev-runtime";var j01=_w("inline-flex items-center justify-center font-semibold transition-all text-center",{variants:{variant:{primary:"bg-brand text-theme-inverse hover:bg-brand-dark focus:ring-brand/20 focus:outline-none focus:ring-4",accent:"bg-accent text-theme-inverse hover:bg-accent-dark focus:ring-accent/20 focus:outline-none focus:ring-4",secondary:"bg-theme-muted text-theme hover:bg-theme-muted-dark focus:outline-none focus:ring-4",outline:"border-2 border-brand text-brand hover:bg-brand hover:text-theme-inverse focus:ring-brand/20 focus:outline-none focus:ring-4","outline-light":"border-2 border-theme-light text-theme-inverse hover:bg-theme-inverse hover:text-brand hover:border-theme-inverse focus:outline-none focus:ring-4",unstyled:""},size:{icon:"w-10 h-10 rounded-full",sm:"px-3 py-1.5 text-sm rounded-lg",md:"px-4 py-2 text-sm rounded-lg",lg:"px-6 py-3 text-base rounded-xl",xl:"px-8 py-4 text-lg rounded-xl","2xl":"px-10 py-5 text-lg rounded-2xl"}},defaultVariants:{size:"md"}});function o5({href:A,children:Q,variant:B,size:w,external:$=!1,className:I,"aria-label":D}){let Y=$?{target:"_blank",rel:"noopener noreferrer"}:{};return GoQ("a",{href:A,className:e1(j01({variant:B,size:w}),I),"aria-label":D,...Y,children:Q},void 0,!1,void 0,this)}import{jsxDEV as JQA}from"preact/jsx-dev-runtime";var k01=_w("transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2",{variants:{variant:{default:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent hover:border-brand/40",light:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent",dark:"rounded-[10px] bg-theme-dark hover:bg-theme-muted text-theme-inverse",footer:"rounded-full bg-theme-toggle hover:bg-theme-toggle-hover text-theme-toggle-icon"},size:{sm:"p-1.5",md:"p-2",lg:"p-3"}},defaultVariants:{variant:"default",size:"md"}}),KoQ={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function Uj({variant:A,size:Q,className:B}){let w=KoQ[Q??"md"];return JQA("button",{onclick:"toggleTheme()",type:"button",className:e1(k01({variant:A,size:Q}),B),"aria-label":"Toggle dark mode",children:JQA("svg",{className:e1(w,"transition-colors"),fill:"none",stroke:"currentColor",strokeWidth:1.6,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[JQA("path",{className:"sun-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},void 0,!1,void 0,this),JQA("path",{className:"moon-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M20.354 15.354A9 9 0 018.646 3.646 9 9 0 1020.354 15.354z"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as pRA}from"preact/jsx-dev-runtime";var _01=_w("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function GQA({items:A,className:Q,linkClassName:B="hover:text-accent transition-colors",orientation:w,children:$}){if(A.length===0&&!$)return null;let I=[...A].sort((D,Y)=>D.priority-Y.priority);return pRA("ul",{className:e1(_01({orientation:w}),Q),children:[I.map((D)=>pRA("li",{children:pRA("a",{href:D.href,className:B,children:D.label},void 0,!1,void 0,this)},D.href,!1,void 0,this)),$]},void 0,!0,void 0,this)}import{jsxDEV as tDw}from"preact/jsx-dev-runtime";import{jsxDEV as QYw}from"preact/jsx-dev-runtime";import{createContext as p02,h as l02}from"preact";import{useContext as i02}from"preact/hooks";GfA();var cB1=X1(uB1(),1),u02=new mT({gfm:!0,breaks:!0}),c02={allowedTags:["h1","h2","h3","h4","h5","h6","p","br","hr","ul","ol","li","blockquote","cite","code","pre","em","strong","del","ins","sub","sup","a","img","span","table","thead","tbody","tr","th","td","div"],allowedAttributes:{a:["href","title","name"],img:["src","srcset","sizes","alt","title","width","height","class","loading","decoding"],code:["class"],pre:["class"],span:["class"],cite:["class"],div:["class"],th:["align","colspan","rowspan","scope"],td:["align","colspan","rowspan"]},allowedSchemes:["http","https","mailto","tel"],allowedSchemesByTag:{img:["http","https","entity"]},allowProtocolRelative:!1,disallowedTagsMode:"discard"};function JPA(A,Q){let{imageRenderer:B}=Q??{},$=(B?new mT({gfm:!0,breaks:!0}).use({renderer:{image(I,D,Y){return B(I,D,Y)??!1}}}):u02).parse(A);return $=$.replace(/<\/blockquote>\s*<p>(\u2014|--|\u2013)([\s\S]*?)<\/p>/g,`</blockquote>
|
|
3779
3791
|
<cite class="block-attribution"><span class="emdash">$1</span>$2</cite>`),cB1.default($,c02)}var pB1=p02(null);function bj({imageRenderer:A,children:Q}){return l02(pB1.Provider,{value:A??null},Q)}function lB1(){return i02(pB1)}function Qf(){let A=lB1();return(Q)=>JPA(Q,A?{imageRenderer:A}:void 0)}var d02=/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,r02={"&":"&","<":"<",">":">",""":'"',"'":"'"},n02=/&(?:amp|lt|gt|quot|#39);/g;function o02(A){return A.replace(n02,(Q)=>r02[Q]??Q)}function GPA(A){return A.replace(d02,(Q,B)=>{return`<div class="mermaid">${o02(B)}</div>`})}var iB1=/<!--\s*\.slide:\s*(.*?)\s*-->/g;function dB1(A){let Q={};for(let w of A.matchAll(iB1)){let $=w[1]??"";for(let D of $.matchAll(/([\w-]+)=["']([^"']*?)["']/g)){let Y=D[1],X=D[2];if(Y&&X!==void 0)Q[Y]=X}let I=$.replace(/([\w-]+)=["']([^"']*?)["']/g,"").trim();if(I)for(let D of I.matchAll(/(?:^|\s)([\w-]+)(?=\s|$)/g)){let Y=D[1];if(Y)Q[Y]="true"}}let B=A.replace(iB1,"").replace(/^\n+/,"").replace(/\n{3,}/g,`
|
|
3780
3792
|
|
|
3781
3793
|
`).trim();return{attributes:Q,markdown:B}}var s02=/<!--\s*\.break\s*-->/;function rB1(A){let Q=A.split(s02);return Q.length>1?Q:null}import{jsxDEV as Bf}from"preact/jsx-dev-runtime";var KPA=({markdown:A})=>{let Q=Qf(),w=A.split(/^---$/gm).map((D)=>D.trim()).map((D)=>{let{attributes:Y,markdown:X}=dB1(D),W=rB1(X),U;if(W)U=`<div class="slide-columns">${W.map((F)=>`<div class="slide-column">${GPA(Q(F.trim()))}</div>`).join("")}</div>`;else U=GPA(Q(X));return{attributes:Y,htmlContent:U}}),$=w.some((D)=>D.htmlContent.includes('class="mermaid"')),I=w.map(({attributes:D,htmlContent:Y},X)=>Bf("section",{...D,dangerouslySetInnerHTML:{__html:Y}},X,!1,void 0,this));return Bf("section",{className:"presentation-section",children:[Bf("link",{rel:"stylesheet",href:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.css"},void 0,!1,void 0,this),Bf("div",{className:"reveal",children:Bf("div",{className:"slides",children:I},void 0,!1,void 0,this)},void 0,!1,void 0,this),Bf("script",{src:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.js",defer:!0},void 0,!1,void 0,this),$&&Bf("script",{src:"https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js",defer:!0},void 0,!1,void 0,this),Bf("script",{dangerouslySetInnerHTML:{__html:`
|
|
@@ -4619,13 +4631,13 @@ ${A.map((I)=>({url:`${Q}${I.path}`,lastmod:B,changefreq:I.path==="/"?"daily":"we
|
|
|
4619
4631
|
`+$:B,D=KJ(this.outputDir,"styles","main.css");await this.cssProcessor.process(I,D,this.workingDir,this.outputDir,this.logger);let Y=await K9.readFile(D,"utf-8"),X=w.length>0?w:Q;if(X.length>0){let W=X.join(`
|
|
4620
4632
|
`)+`
|
|
4621
4633
|
|
|
4622
|
-
`+Y;await K9.writeFile(D,W,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=KJ(process.cwd(),"public");try{await K9.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await K9.readdir(A,{withFileTypes:!0});for(let B of Q){let w=KJ(A,B.name),$=KJ(this.outputDir,B.name);if(B.isDirectory())await this.copyDirectory(w,$);else await K9.copyFile(w,$),this.logger.debug(`Copied static asset: ${B.name}`)}this.logger.debug("Static assets copied successfully")}async writeInlineStaticAssets(A){if(!A)return;let Q=Object.entries(A);if(Q.length===0)return;this.logger.debug(`Writing ${Q.length} inline static asset(s) from SitePackage`),await Promise.all(Q.map(async([B,w])=>{let $=B.startsWith("/")?B.slice(1):B,I=KJ(this.outputDir,$);await K9.mkdir(BX2(I),{recursive:!0}),await K9.writeFile(I,w,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await K9.mkdir(Q,{recursive:!0});let B=await K9.readdir(A,{withFileTypes:!0});for(let w of B){let $=KJ(A,w.name),I=KJ(Q,w.name);if(w.isDirectory())await this.copyDirectory($,I);else await K9.copyFile($,I)}}}function nkA(A){return new PD1(A)}y6();fA();fA();y6();var jD1=f.object({environment:f.enum(["preview","production"]),outputDir:f.string(),workingDir:f.string().optional(),sharedImagesDir:f.string().default("./dist/images"),enableContentGeneration:f.boolean().default(!1),cleanBeforeBuild:f.boolean().default(!0),siteConfig:yI,layouts:f.record(f.any()),themeCSS:f.string().optional()}),azw=f.object({success:f.boolean(),outputDir:f.string(),filesGenerated:f.number(),routesBuilt:f.number(),errors:f.array(f.string()).optional(),warnings:f.array(f.string()).optional()});function kD1(A){let Q=A.list(),B=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:B}}function _D1(A,Q,B){let w=Q.getProfile(),$=B.getNavigationItems("primary"),I=B.getNavigationItems("secondary");return{...A,...w.socialLinks!==void 0&&{socialLinks:w.socialLinks},navigation:{primary:$,secondary:I},copyright:A.copyright??"Powered by Rizom"}}y6();v4();y6();fA();var wX2=f.object({id:f.string(),entityType:f.string(),content:f.string(),metadata:f.object({slug:f.string()}).passthrough()}).passthrough(),$X2=f.object({content:f.string(),metadata:f.object({width:f.number().optional(),height:f.number().optional()}).passthrough()});async function cBA(A,Q){let B=Q.urlGenerator??v9.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((O)=>cBA(O,{...Q,urlGenerator:B})));if(typeof A!=="object")return A;let w={},$=Object.entries(A),I=await Promise.all($.map(([,O])=>cBA(O,{...Q,urlGenerator:B})));for(let O=0;O<$.length;O++){let r=$[O];if(r)w[r[0]]=I[O]}let D=wX2.safeParse(A);if(!D.success)return w;let Y=D.data,X=Y.entityType,W=Y.metadata.slug,U=Q.pipelineContext.entityDisplay?.[X],K=U?U.label:X.charAt(0).toUpperCase()+X.slice(1),F=U?U.pluralName??U.label.toLowerCase()+"s":vI(X),Z=`/${F}`,q=F.charAt(0).toUpperCase()+F.slice(1),E=ny(Y),L=E?Q.imageBuildService?.get(E):void 0,R={};if(L)R={coverImageUrl:L.src,coverImageWidth:L.width,coverImageHeight:L.height,...L.srcset&&{coverImageSrcset:L.srcset,coverImageSizes:L.sizes}};else{let O=await IX2(E,Q.pipelineContext.services.entityService);if(O)R={coverImageUrl:O.url,...O.width&&{coverImageWidth:O.width},...O.height&&{coverImageHeight:O.height}}}return{...w,...Y,url:B.generateUrl(X,W),typeLabel:K,listUrl:Z,listLabel:q,...R}}async function IX2(A,Q){if(!A)return;let B=await Q.getEntity({entityType:"image",id:A}),w=$X2.safeParse(B);if(!w.success)return;return{url:w.data.content,...w.data.metadata.width&&{width:w.data.metadata.width},...w.data.metadata.height&&{height:w.data.metadata.height}}}async function vD1(A,Q){let B=new Set;try{let w=A.getEntityTypes();for(let $ of w){if($==="image")continue;let I=await A.listEntities({entityType:$});for(let D of I){let Y=ny(D);if(Y)B.add(Y)}}}catch(w){Q.warn("Failed to collect image IDs for pre-resolution",{error:S0(w)})}return[...B]}async function xD1(A,Q,B,w,$){if(!A.template)return A.content??null;let I=A.template,D=A.dataQuery?{dataParams:A.dataQuery,fallback:A.content,publishedOnly:B,visibilityScope:w}:{savedContent:{entityType:"site-content",entityId:`${Q.id}:${A.id}`},fallback:A.content,visibilityScope:w},Y=await $.pipelineContext.services.resolveTemplateContent(I,D);if(!Y)return null;return cBA(Y,{pipelineContext:$.pipelineContext,imageBuildService:$.imageBuildService,urlGenerator:v9.getInstance()})}function yD1(A){return{routes:A.routes,siteConfig:{title:A.siteMetadata.title,description:A.siteMetadata.description,...A.siteMetadata.url&&{url:A.siteMetadata.url},...A.siteMetadata.copyright&&{copyright:A.siteMetadata.copyright},...A.siteMetadata.themeMode&&{themeMode:A.siteMetadata.themeMode},...A.siteMetadata.analyticsScript&&{analyticsScript:A.siteMetadata.analyticsScript}},headScripts:A.buildOptions.headScripts,...A.buildOptions.staticAssets&&{staticAssets:A.buildOptions.staticAssets},getContent:async(Q,B)=>{let w=A.parsedOptions.environment==="production";return xD1(B,Q,w,"public",{pipelineContext:A.pipelineContext,imageBuildService:A.imageBuildService})},getViewTemplate:(Q)=>{return A.pipelineContext.services.getViewTemplate(Q)},layouts:A.parsedOptions.layouts,getSiteLayoutInfo:async()=>{return _D1(A.siteMetadata,A.pipelineContext.profileService,A.pipelineContext.routeRegistry)},...A.parsedOptions.themeCSS!==void 0&&{themeCSS:A.parsedOptions.themeCSS},...A.buildOptions.slots&&{slots:A.buildOptions.slots},imageBuildService:A.imageBuildService}}import{join as DX2}from"path";async function TD1(A){let Q=A.parsedOptions.workingDir??DX2(A.parsedOptions.outputDir,".preact-work"),B=A.staticSiteBuilderFactory({logger:A.logger.child("StaticSiteBuilder"),workingDir:Q,outputDir:A.parsedOptions.outputDir});if(A.parsedOptions.cleanBeforeBuild)await B.clean();return B}async function SD1(A){await new mBA({logger:A.pipelineContext.logger.child("DynamicRouteGenerator"),entityService:A.pipelineContext.services.entityService,listViewTemplateNames:()=>A.pipelineContext.services.listViewTemplateNames()},A.pipelineContext.routeRegistry,A.pipelineContext.entityDisplay,{visibilityScope:"public",...A.publishedOnly!==void 0&&{publishedOnly:A.publishedOnly}}).generateEntityRoutes()}async function gD1(A){let Q=new hBA(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),B=await vD1(A.pipelineContext.services.entityService,A.pipelineContext.logger);if(B.length>0)await Q.resolveAll(B);return Q}async function hD1(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,(B)=>{Q?.report(B).catch(()=>{})})}function mD1(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function uD1(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function cD1(A){let Q=jD1.parse(A.buildOptions),B=p$.from(A.progress),w=[];try{await B?.report({message:"Starting site build",progress:0,total:100}),await B?.report({message:"Generating dynamic routes",progress:10,total:100}),await SD1({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let $=await TD1({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),I=kD1(A.pipelineContext.routeRegistry);w.push(...I.warnings);let{routes:D}=I;await B?.report({message:`Building ${D.length} routes`,progress:20,total:100}),await B?.report({message:"Resolving images",progress:25,total:100});let Y=await gD1({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),X=yD1({routes:D,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:Y,siteMetadata:Q.siteConfig});return await hD1({staticSiteBuilder:$,buildContext:X,reporter:B}),await B?.report({message:"Site build complete",progress:100,total:100}),mD1({outputDir:Q.outputDir,routesBuilt:D.length,warnings:w})}catch($){let I=Error("Site build process failed");return A.pipelineContext.logger.error("Site build failed",{error:I,originalError:$}),uD1({outputDir:Q.outputDir,errorMessage:I.message})}}class RD{static instance=null;static defaultStaticSiteBuilderFactory=nkA;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){RD.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,B,w,$=void 0){return RD.instance??=new RD(A,RD.defaultStaticSiteBuilderFactory,Q,B,w,$),RD.instance}static resetInstance(){RD.instance=null}static createFresh(A,Q,B,w,$,I=void 0){return new RD(A,$??RD.defaultStaticSiteBuilderFactory,Q,B,w,I)}constructor(A,Q,B,w,$,I){this.pipelineContext={logger:A,services:B,routeRegistry:w,profileService:$,entityDisplay:I},this.staticSiteBuilderFactory=Q,v9.getInstance().configure(I)}async build(A,Q){return cD1({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}fA();class okA{config;context;pluginId;logger;debounces=new Map;unsubscribeFunctions=[];constructor(A,Q,B,w){this.config=A;this.context=Q;this.pluginId=B;this.logger=w}requestBuild(A){let Q=A??(this.config.previewOutputDir?"preview":"production"),B=this.debounces.get(Q);if(!B)B=new T3(()=>{this.enqueueBuild(Q)},this.config.rebuildDebounce),this.debounces.set(Q,B);B.trigger()}setupAutoRebuild(){let A=new Set(["base"]),Q=async(w)=>{let{entityType:$}=w.payload;if(!A.has($))this.logger.debug(`Entity type ${$} will trigger rebuild`),this.requestBuild();return{success:!0}},B=["entity:created","entity:updated","entity:deleted"];for(let w of B)this.unsubscribeFunctions.push(this.context.messaging.subscribe(w,Q));this.logger.debug(`Auto-rebuild enabled (${this.config.rebuildDebounce}ms debounce), excluding types: ${[...A].join(", ")}`)}dispose(){for(let A of this.debounces.values())A.dispose();this.debounces.clear();for(let A of this.unsubscribeFunctions)A();this.unsubscribeFunctions=[]}async enqueueBuild(A){let Q=A==="production"?this.config.productionOutputDir:this.config.previewOutputDir;this.logger.debug(`Triggering ${A} site rebuild`);try{await this.context.jobs.enqueue({type:"site-build",data:{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:0,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip"}}),this.logger.debug("Site rebuild enqueued")}catch(B){this.logger.error("Failed to enqueue site rebuild",{error:B})}}}y6();function YX2(A,Q){return A.map((B)=>({...B,template:B.template.includes(":")?B.template:`${Q}:${B.template}`}))}function pBA(A,Q,B){for(let w of A)B.register({...w,pluginId:Q,sections:w.sections?YX2(w.sections,Q):[]})}function pD1(A,Q,B){A.messaging.subscribe("plugin:site-builder:route:register",async(w)=>{try{let $=Gd.parse(w.payload),{routes:I,pluginId:D}=$;return pBA(I,D,Q),{success:!0}}catch($){return B.error("Failed to register routes",{error:$}),{success:!1,error:"Failed to register routes"}}}),A.messaging.subscribe("plugin:site-builder:route:unregister",async(w)=>{try{let $=Kd.parse(w.payload),{paths:I,pluginId:D}=$;if(I)for(let Y of I)Q.unregister(Y);else if(D)Q.unregisterByPlugin(D);return{success:!0}}catch($){return B.error("Failed to unregister routes",{error:$}),{success:!1,error:"Failed to unregister routes"}}}),A.messaging.subscribe("plugin:site-builder:route:list",async(w)=>{try{let $=fd.parse(w.payload);return{success:!0,data:{routes:Q.list($.pluginId?$:void 0)}}}catch($){return B.error("Failed to list routes",{error:$}),{success:!1,error:"Failed to list routes"}}}),A.messaging.subscribe("plugin:site-builder:route:get",async(w)=>{try{let $=Fd.parse(w.payload);return{success:!0,data:{route:Q.get($.path)}}}catch($){return B.error("Failed to get route",{error:$}),{success:!1,error:"Failed to get route"}}}),A.messaging.subscribe("site-builder:routes:list",async()=>{return{success:!0,data:Q.list()}})}import{promises as lD1}from"fs";import{join as iD1}from"path";async function XX2(A,Q,B){let w=A.siteConfig.url??"https://example.com",$=Q.list(),I=dkA(w,A.environment);await lD1.writeFile(iD1(A.outputDir,"robots.txt"),I,"utf-8"),B.info(`Generated robots.txt for ${A.environment} environment`);let D=rkA($,w);await lD1.writeFile(iD1(A.outputDir,"sitemap.xml"),D,"utf-8"),B.info(`Generated sitemap.xml with ${$.length} URLs`)}function dD1(A){let{context:Q,routeRegistry:B,logger:w}=A;Q.messaging.subscribe("site:build:completed",async($)=>{try{let I=$.payload;return w.info(`Received site:build:completed event for ${I.environment} environment - generating SEO files`),await XX2(I,B,w),{success:!0}}catch(I){return w.error("Failed to generate SEO files",I),{success:!1}}})}eA();fA();y6();var rD1=f.object({environment:f.enum(["preview","production"]).optional(),outputDir:f.string(),workingDir:f.string().optional(),enableContentGeneration:f.boolean().optional(),siteConfig:yI.optional()});y6();y6();async function Rc(A,Q){try{let B=await A({type:gv,payload:void 0});if("success"in B&&B.success&&B.data){let w=yI.safeParse(B.data);if(w.success)return yI.parse({...Q,...w.data})}}catch{}return Q}class skA extends Sw{sendMessage;cfg;constructor(A,Q,B){super(A,{schema:rD1,jobTypeName:"site-build"});this.sendMessage=Q;this.cfg=B}async process(A,Q,B){let w=A.environment??"preview",$=A.enableContentGeneration??!1;try{this.logger.debug("Starting site build job",{jobId:Q,environment:w,outputDir:A.outputDir}),await B.report({progress:0,total:100,message:`Starting site build for ${w} environment`});let I=B.createSub({scale:{start:10,end:90}}),D=await Rc(this.sendMessage,A.siteConfig??this.cfg.defaultSiteConfig),Y=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:$,environment:w,cleanBeforeBuild:!0,siteConfig:D,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},I.toCallback());if(await B.report({progress:100,total:100,message:`Site build completed: ${Y.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:Q,environment:w,routesBuilt:Y.routesBuilt,success:Y.success}),Y.success){this.logger.info(`Emitting site:build:completed event for ${w} environment`);let X=w==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage({type:"site:build:completed",payload:{outputDir:A.outputDir,environment:w,routesBuilt:Y.routesBuilt,siteConfig:{...D,url:X},generateEntityUrl:(W,U)=>v9.getInstance().generateUrl(W,U)},broadcast:!0})}return{success:Y.success,routesBuilt:Y.routesBuilt,outputDir:A.outputDir,environment:w,...Y.errors&&{errors:Y.errors},...Y.warnings&&{warnings:Y.warnings}}}catch(I){throw this.logger.error("Site build job failed",I),I}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}fA();y6();var WX2=f.object({slot:f.enum(h3).optional().default("primary"),limit:f.number().optional()});class akA{routeRegistry;logger;id="site:navigation";name="Site Navigation DataSource";description="Provides navigation items for site menus";constructor(A,Q){this.routeRegistry=A;this.logger=Q;this.logger.debug("NavigationDataSource initialized")}async fetch(A,Q,B){let w=WX2.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:w});let $=this.routeRegistry.getNavigationItems(w.slot),I=w.limit?$.slice(0,w.limit):$,D=I.map((X)=>({label:X.label,href:X.href}));this.logger.debug("NavigationDataSource returning",{slot:w.slot,itemCount:I.length,items:D});let Y={navigation:D};return Q.parse(Y)}}y6();eA();fA();var HX2=f.object({environment:f.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function nD1(A,Q){return[j2(A,"build-site","Build a static site from registered routes. Call this for every user build/rebuild request, including repeated requests like 'build it again' or 'one more build'.",HX2,async(B)=>{return Q(B.environment),{success:!0,message:`Site build requested${B.environment?` for ${B.environment}`:""} (debounced)`,data:{}}},{cli:{name:"build"}})]}fA();y6();var oD1=f.object({previewOutputDir:f.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:f.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:f.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:f.string().optional().describe("Working directory for builds").default("./.preact-work"),siteInfo:yI.default({title:"Brain",description:"A knowledge management system"}),themeCSS:f.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:f.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),templates:f.any().optional().describe("Template definitions to register"),routes:f.array(m3).optional().describe("Routes to register"),layouts:f.record(f.any()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:f.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:f.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),entityDisplay:f.record(f.object({label:f.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:f.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')"),layout:f.string().optional().describe("Layout name for this entity type's generated routes (defaults to 'default')"),paginate:f.boolean().optional().describe("Enable pagination for list pages"),pageSize:f.number().optional().describe("Items per page (default: 10)"),navigation:f.object({show:f.boolean().optional().describe("Show in navigation"),slot:f.enum(h3).optional().describe("Navigation slot (primary or secondary)"),priority:f.number().min(0).max(100).optional().describe("Navigation priority (0-100)")}).optional().describe("Navigation settings for this entity type")})).optional().describe("Display metadata per entity type \u2014 label, plural name, layout, pagination, navigation slot. Consulted when auto-generating routes for active entity plugins."),staticAssets:f.record(f.string()).optional().describe("Static files to write to the output directory at build time. Keys are output paths (e.g. '/canvases/tree.js'), values are file contents as strings. Typically supplied by a SitePackage via text imports.")});var sD1={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.92",description:"Static site generation plugin for Brain system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint .",clean:"rm -rf dist"},dependencies:{"@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*","@tailwindcss/typography":"^0.5.19",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",eslint:"^8.56.0",typescript:"^5.3.3"}};class tkA extends qB{siteBuilder;pluginContext;_routeRegistry;_slotRegistry;profileService;layouts;rebuildManager;headScripts=new Map;get routeRegistry(){if(!this._routeRegistry)throw Error("RouteRegistry not initialized - plugin not registered");return this._routeRegistry}constructor(A={}){let Q=A.layouts??{};super("site-builder",sD1,{...A,layouts:Q},oD1);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new uBA(A.logger),this._slotRegistry=new qBA,A.messaging.subscribe("plugin:site-builder:slot:register",async(B)=>{let{slotName:w,pluginId:$,render:I,priority:D}=B.payload;return this._slotRegistry?.register(w,{pluginId:$,render:I,...D!==void 0&&{priority:D}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async(B)=>{let{pluginId:w,script:$}=B.payload;return this.headScripts.set(w,$),{success:!0}}),A.entities.registerDataSource(new akA(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=k7.getInstance(A.entityService,A.logger),pD1(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)pBA(this.config.routes,this.id,this.routeRegistry);let Q={entityService:A.entityService,sendMessage:A.messaging.send,resolveTemplateContent:(B,w)=>A.templates.resolve(B,w),getViewTemplate:(B)=>A.views.get(B),listViewTemplateNames:()=>A.views.list().map((B)=>B.name)};if(this.siteBuilder=RD.getInstance(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new skA(this.logger.child("SiteBuildJobHandler"),A.messaging.send,{siteBuilder:this.siteBuilder,layouts:this.layouts,defaultSiteConfig:this.config.siteInfo,sharedImagesDir:this.config.sharedImagesDir,siteUrl:A.siteUrl,previewUrl:A.previewUrl,themeCSS:this.config.themeCSS,slots:this._slotRegistry,getHeadScripts:()=>this.getRegisteredHeadScripts(),...this.config.staticAssets&&{staticAssets:this.config.staticAssets}})),this.rebuildManager=new okA(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe(hv,async()=>{let B=await this.getInstructions();if(B)A.registerInstructions(B);return{success:!0}}),dD1({context:A,routeRegistry:this._routeRegistry,logger:this.logger})}getRegisteredHeadScripts(){return Array.from(this.headScripts.values())}async getTools(){if(!this.pluginContext||!this.rebuildManager)throw Error("Plugin context not initialized");let A=this.rebuildManager;return nD1(this.id,(Q)=>A.requestBuild(Q))}async getResources(){let A=this.getContext();return[{uri:"brain://site",name:"Site Metadata",description:"Site metadata \u2014 title, description, domain, URLs",mimeType:"application/json",handler:async()=>{let Q=await Rc(A.messaging.send,this.config.siteInfo);return{contents:[{uri:"brain://site",mimeType:"application/json",text:JSON.stringify({...Q,domain:A.domain,siteUrl:A.siteUrl,previewUrl:A.previewUrl},null,2)}]}}},{uri:"site://routes",name:"Site Routes",description:"All registered routes with sections and templates",mimeType:"application/json",handler:async()=>{let Q=this.routeRegistry.list();return{contents:[{uri:"site://routes",mimeType:"application/json",text:JSON.stringify(Q.map((B)=>({id:B.id,path:B.path,title:B.title,description:B.description,sections:B.sections.map((w)=>({id:w.id,template:w.template}))})),null,2)}]}}},{uri:"site://templates",name:"View Templates",description:"All registered view templates",mimeType:"application/json",handler:async()=>{let Q=A.views.list();return{contents:[{uri:"site://templates",mimeType:"application/json",text:JSON.stringify(Q.map((B)=>({name:B.name,description:B.description,hasWebRenderer:!!B.renderers.web})),null,2)}]}}}]}getSiteBuilder(){return this.siteBuilder}getSlotRegistry(){return this._slotRegistry}async getInstructions(){let A=this.getContext(),Q="## Site Builder Actions\n- When the user asks to build, rebuild, publish, or build the website/site again, call `site-builder_build-site` immediately.\n- Every repeated build request requires a fresh `site-builder_build-site` call. Do not say a build was started, queued, or requested unless this turn invoked the tool.",B=await Rc(A.messaging.send,this.config.siteInfo);return`## Your Site
|
|
4634
|
+
`+Y;await K9.writeFile(D,W,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=KJ(process.cwd(),"public");try{await K9.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await K9.readdir(A,{withFileTypes:!0});for(let B of Q){let w=KJ(A,B.name),$=KJ(this.outputDir,B.name);if(B.isDirectory())await this.copyDirectory(w,$);else await K9.copyFile(w,$),this.logger.debug(`Copied static asset: ${B.name}`)}this.logger.debug("Static assets copied successfully")}async writeInlineStaticAssets(A){if(!A)return;let Q=Object.entries(A);if(Q.length===0)return;this.logger.debug(`Writing ${Q.length} inline static asset(s) from SitePackage`),await Promise.all(Q.map(async([B,w])=>{let $=B.startsWith("/")?B.slice(1):B,I=KJ(this.outputDir,$);await K9.mkdir(BX2(I),{recursive:!0}),await K9.writeFile(I,w,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await K9.mkdir(Q,{recursive:!0});let B=await K9.readdir(A,{withFileTypes:!0});for(let w of B){let $=KJ(A,w.name),I=KJ(Q,w.name);if(w.isDirectory())await this.copyDirectory($,I);else await K9.copyFile($,I)}}}function nkA(A){return new PD1(A)}y6();fA();fA();y6();var jD1=f.object({environment:f.enum(["preview","production"]),outputDir:f.string(),workingDir:f.string().optional(),sharedImagesDir:f.string().default("./dist/images"),enableContentGeneration:f.boolean().default(!1),cleanBeforeBuild:f.boolean().default(!0),siteConfig:yI,layouts:f.record(f.any()),themeCSS:f.string().optional()}),azw=f.object({success:f.boolean(),outputDir:f.string(),filesGenerated:f.number(),routesBuilt:f.number(),errors:f.array(f.string()).optional(),warnings:f.array(f.string()).optional()});function kD1(A){let Q=A.list(),B=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:B}}function _D1(A,Q,B){let w=Q.getProfile(),$=B.getNavigationItems("primary"),I=B.getNavigationItems("secondary");return{...A,...w.socialLinks!==void 0&&{socialLinks:w.socialLinks},navigation:{primary:$,secondary:I},copyright:A.copyright??"Powered by Rizom"}}y6();v4();y6();fA();var wX2=f.object({id:f.string(),entityType:f.string(),content:f.string(),metadata:f.object({slug:f.string()}).passthrough()}).passthrough(),$X2=f.object({content:f.string(),metadata:f.object({width:f.number().optional(),height:f.number().optional()}).passthrough()});async function cBA(A,Q){let B=Q.urlGenerator??v9.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((O)=>cBA(O,{...Q,urlGenerator:B})));if(typeof A!=="object")return A;let w={},$=Object.entries(A),I=await Promise.all($.map(([,O])=>cBA(O,{...Q,urlGenerator:B})));for(let O=0;O<$.length;O++){let r=$[O];if(r)w[r[0]]=I[O]}let D=wX2.safeParse(A);if(!D.success)return w;let Y=D.data,X=Y.entityType,W=Y.metadata.slug,U=Q.pipelineContext.entityDisplay?.[X],K=U?U.label:X.charAt(0).toUpperCase()+X.slice(1),F=U?U.pluralName??U.label.toLowerCase()+"s":vI(X),Z=`/${F}`,q=F.charAt(0).toUpperCase()+F.slice(1),E=ny(Y),L=E?Q.imageBuildService?.get(E):void 0,R={};if(L)R={coverImageUrl:L.src,coverImageWidth:L.width,coverImageHeight:L.height,...L.srcset&&{coverImageSrcset:L.srcset,coverImageSizes:L.sizes}};else{let O=await IX2(E,Q.pipelineContext.services.entityService);if(O)R={coverImageUrl:O.url,...O.width&&{coverImageWidth:O.width},...O.height&&{coverImageHeight:O.height}}}return{...w,...Y,url:B.generateUrl(X,W),typeLabel:K,listUrl:Z,listLabel:q,...R}}async function IX2(A,Q){if(!A)return;let B=await Q.getEntity({entityType:"image",id:A}),w=$X2.safeParse(B);if(!w.success)return;return{url:w.data.content,...w.data.metadata.width&&{width:w.data.metadata.width},...w.data.metadata.height&&{height:w.data.metadata.height}}}async function vD1(A,Q){let B=new Set;try{let w=A.getEntityTypes();for(let $ of w){if($==="image")continue;let I=await A.listEntities({entityType:$});for(let D of I){let Y=ny(D);if(Y)B.add(Y)}}}catch(w){Q.warn("Failed to collect image IDs for pre-resolution",{error:S0(w)})}return[...B]}async function xD1(A,Q,B,w,$){if(!A.template)return A.content??null;let I=A.template,D=A.dataQuery?{dataParams:A.dataQuery,fallback:A.content,publishedOnly:B,visibilityScope:w}:{savedContent:{entityType:"site-content",entityId:`${Q.id}:${A.id}`},fallback:A.content,visibilityScope:w},Y=await $.pipelineContext.services.resolveTemplateContent(I,D);if(!Y)return null;return cBA(Y,{pipelineContext:$.pipelineContext,imageBuildService:$.imageBuildService,urlGenerator:v9.getInstance()})}function yD1(A){return{routes:A.routes,siteConfig:{title:A.siteMetadata.title,description:A.siteMetadata.description,...A.siteMetadata.url&&{url:A.siteMetadata.url},...A.siteMetadata.copyright&&{copyright:A.siteMetadata.copyright},...A.siteMetadata.themeMode&&{themeMode:A.siteMetadata.themeMode},...A.siteMetadata.analyticsScript&&{analyticsScript:A.siteMetadata.analyticsScript}},headScripts:A.buildOptions.headScripts,...A.buildOptions.staticAssets&&{staticAssets:A.buildOptions.staticAssets},getContent:async(Q,B)=>{let w=A.parsedOptions.environment==="production";return xD1(B,Q,w,"public",{pipelineContext:A.pipelineContext,imageBuildService:A.imageBuildService})},getViewTemplate:(Q)=>{return A.pipelineContext.services.getViewTemplate(Q)},layouts:A.parsedOptions.layouts,getSiteLayoutInfo:async()=>{return _D1(A.siteMetadata,A.pipelineContext.profileService,A.pipelineContext.routeRegistry)},...A.parsedOptions.themeCSS!==void 0&&{themeCSS:A.parsedOptions.themeCSS},...A.buildOptions.slots&&{slots:A.buildOptions.slots},imageBuildService:A.imageBuildService}}import{join as DX2}from"path";async function TD1(A){let Q=A.parsedOptions.workingDir??DX2(A.parsedOptions.outputDir,".preact-work"),B=A.staticSiteBuilderFactory({logger:A.logger.child("StaticSiteBuilder"),workingDir:Q,outputDir:A.parsedOptions.outputDir});if(A.parsedOptions.cleanBeforeBuild)await B.clean();return B}async function SD1(A){await new mBA({logger:A.pipelineContext.logger.child("DynamicRouteGenerator"),entityService:A.pipelineContext.services.entityService,listViewTemplateNames:()=>A.pipelineContext.services.listViewTemplateNames()},A.pipelineContext.routeRegistry,A.pipelineContext.entityDisplay,{visibilityScope:"public",...A.publishedOnly!==void 0&&{publishedOnly:A.publishedOnly}}).generateEntityRoutes()}async function gD1(A){let Q=new hBA(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),B=await vD1(A.pipelineContext.services.entityService,A.pipelineContext.logger);if(B.length>0)await Q.resolveAll(B);return Q}async function hD1(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,(B)=>{Q?.report(B).catch(()=>{})})}function mD1(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function uD1(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function cD1(A){let Q=jD1.parse(A.buildOptions),B=p$.from(A.progress),w=[];try{await B?.report({message:"Starting site build",progress:0,total:100}),await B?.report({message:"Generating dynamic routes",progress:10,total:100}),await SD1({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let $=await TD1({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),I=kD1(A.pipelineContext.routeRegistry);w.push(...I.warnings);let{routes:D}=I;await B?.report({message:`Building ${D.length} routes`,progress:20,total:100}),await B?.report({message:"Resolving images",progress:25,total:100});let Y=await gD1({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),X=yD1({routes:D,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:Y,siteMetadata:Q.siteConfig});return await hD1({staticSiteBuilder:$,buildContext:X,reporter:B}),await B?.report({message:"Site build complete",progress:100,total:100}),mD1({outputDir:Q.outputDir,routesBuilt:D.length,warnings:w})}catch($){let I=Error("Site build process failed");return A.pipelineContext.logger.error("Site build failed",{error:I,originalError:$}),uD1({outputDir:Q.outputDir,errorMessage:I.message})}}class RD{static instance=null;static defaultStaticSiteBuilderFactory=nkA;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){RD.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,B,w,$=void 0){return RD.instance??=new RD(A,RD.defaultStaticSiteBuilderFactory,Q,B,w,$),RD.instance}static resetInstance(){RD.instance=null}static createFresh(A,Q,B,w,$,I=void 0){return new RD(A,$??RD.defaultStaticSiteBuilderFactory,Q,B,w,I)}constructor(A,Q,B,w,$,I){this.pipelineContext={logger:A,services:B,routeRegistry:w,profileService:$,entityDisplay:I},this.staticSiteBuilderFactory=Q,v9.getInstance().configure(I)}async build(A,Q){return cD1({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}fA();class okA{config;context;pluginId;logger;debounces=new Map;unsubscribeFunctions=[];constructor(A,Q,B,w){this.config=A;this.context=Q;this.pluginId=B;this.logger=w}requestBuild(A){let Q=A??(this.config.previewOutputDir?"preview":"production"),B=this.debounces.get(Q);if(!B)B=new T3(()=>{this.enqueueBuild(Q)},this.config.rebuildDebounce),this.debounces.set(Q,B);B.trigger()}setupAutoRebuild(){let A=new Set(["base"]),Q=async(w)=>{let{entityType:$}=w.payload;if(!A.has($))this.logger.debug(`Entity type ${$} will trigger rebuild`),this.requestBuild();return{success:!0}},B=["entity:created","entity:updated","entity:deleted"];for(let w of B)this.unsubscribeFunctions.push(this.context.messaging.subscribe(w,Q));this.logger.debug(`Auto-rebuild enabled (${this.config.rebuildDebounce}ms debounce), excluding types: ${[...A].join(", ")}`)}dispose(){for(let A of this.debounces.values())A.dispose();this.debounces.clear();for(let A of this.unsubscribeFunctions)A();this.unsubscribeFunctions=[]}async enqueueBuild(A){let Q=A==="production"?this.config.productionOutputDir:this.config.previewOutputDir;this.logger.debug(`Triggering ${A} site rebuild`);try{await this.context.jobs.enqueue({type:"site-build",data:{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:0,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip"}}),this.logger.debug("Site rebuild enqueued")}catch(B){this.logger.error("Failed to enqueue site rebuild",{error:B})}}}y6();function YX2(A,Q){return A.map((B)=>({...B,template:B.template.includes(":")?B.template:`${Q}:${B.template}`}))}function pBA(A,Q,B){for(let w of A)B.register({...w,pluginId:Q,sections:w.sections?YX2(w.sections,Q):[]})}function pD1(A,Q,B){A.messaging.subscribe("plugin:site-builder:route:register",async(w)=>{try{let $=Gd.parse(w.payload),{routes:I,pluginId:D}=$;return pBA(I,D,Q),{success:!0}}catch($){return B.error("Failed to register routes",{error:$}),{success:!1,error:"Failed to register routes"}}}),A.messaging.subscribe("plugin:site-builder:route:unregister",async(w)=>{try{let $=Kd.parse(w.payload),{paths:I,pluginId:D}=$;if(I)for(let Y of I)Q.unregister(Y);else if(D)Q.unregisterByPlugin(D);return{success:!0}}catch($){return B.error("Failed to unregister routes",{error:$}),{success:!1,error:"Failed to unregister routes"}}}),A.messaging.subscribe("plugin:site-builder:route:list",async(w)=>{try{let $=fd.parse(w.payload);return{success:!0,data:{routes:Q.list($.pluginId?$:void 0)}}}catch($){return B.error("Failed to list routes",{error:$}),{success:!1,error:"Failed to list routes"}}}),A.messaging.subscribe("plugin:site-builder:route:get",async(w)=>{try{let $=Fd.parse(w.payload);return{success:!0,data:{route:Q.get($.path)}}}catch($){return B.error("Failed to get route",{error:$}),{success:!1,error:"Failed to get route"}}}),A.messaging.subscribe("site-builder:routes:list",async()=>{return{success:!0,data:Q.list()}})}import{promises as lD1}from"fs";import{join as iD1}from"path";async function XX2(A,Q,B){let w=A.siteConfig.url??"https://example.com",$=Q.list(),I=dkA(w,A.environment);await lD1.writeFile(iD1(A.outputDir,"robots.txt"),I,"utf-8"),B.info(`Generated robots.txt for ${A.environment} environment`);let D=rkA($,w);await lD1.writeFile(iD1(A.outputDir,"sitemap.xml"),D,"utf-8"),B.info(`Generated sitemap.xml with ${$.length} URLs`)}function dD1(A){let{context:Q,routeRegistry:B,logger:w}=A;Q.messaging.subscribe("site:build:completed",async($)=>{try{let I=$.payload;return w.info(`Received site:build:completed event for ${I.environment} environment - generating SEO files`),await XX2(I,B,w),{success:!0}}catch(I){return w.error("Failed to generate SEO files",I),{success:!1}}})}eA();fA();y6();var rD1=f.object({environment:f.enum(["preview","production"]).optional(),outputDir:f.string(),workingDir:f.string().optional(),enableContentGeneration:f.boolean().optional(),siteConfig:yI.optional()});y6();y6();async function Rc(A,Q){try{let B=await A({type:gv,payload:void 0});if("success"in B&&B.success&&B.data){let w=yI.safeParse(B.data);if(w.success)return yI.parse({...Q,...w.data})}}catch{}return Q}class skA extends Sw{sendMessage;cfg;constructor(A,Q,B){super(A,{schema:rD1,jobTypeName:"site-build"});this.sendMessage=Q;this.cfg=B}async process(A,Q,B){let w=A.environment??"preview",$=A.enableContentGeneration??!1;try{this.logger.debug("Starting site build job",{jobId:Q,environment:w,outputDir:A.outputDir}),await B.report({progress:0,total:100,message:`Starting site build for ${w} environment`});let I=B.createSub({scale:{start:10,end:90}}),D=await Rc(this.sendMessage,A.siteConfig??this.cfg.defaultSiteConfig),Y=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:$,environment:w,cleanBeforeBuild:!0,siteConfig:D,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},I.toCallback());if(await B.report({progress:100,total:100,message:`Site build completed: ${Y.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:Q,environment:w,routesBuilt:Y.routesBuilt,success:Y.success}),Y.success){this.logger.info(`Emitting site:build:completed event for ${w} environment`);let X=w==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage({type:"site:build:completed",payload:{outputDir:A.outputDir,environment:w,routesBuilt:Y.routesBuilt,siteConfig:{...D,url:X},generateEntityUrl:(W,U)=>v9.getInstance().generateUrl(W,U)},broadcast:!0})}return{success:Y.success,routesBuilt:Y.routesBuilt,outputDir:A.outputDir,environment:w,...Y.errors&&{errors:Y.errors},...Y.warnings&&{warnings:Y.warnings}}}catch(I){throw this.logger.error("Site build job failed",I),I}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}fA();y6();var WX2=f.object({slot:f.enum(h3).optional().default("primary"),limit:f.number().optional()});class akA{routeRegistry;logger;id="site:navigation";name="Site Navigation DataSource";description="Provides navigation items for site menus";constructor(A,Q){this.routeRegistry=A;this.logger=Q;this.logger.debug("NavigationDataSource initialized")}async fetch(A,Q,B){let w=WX2.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:w});let $=this.routeRegistry.getNavigationItems(w.slot),I=w.limit?$.slice(0,w.limit):$,D=I.map((X)=>({label:X.label,href:X.href}));this.logger.debug("NavigationDataSource returning",{slot:w.slot,itemCount:I.length,items:D});let Y={navigation:D};return Q.parse(Y)}}y6();eA();fA();var HX2=f.object({environment:f.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function nD1(A,Q){return[j2(A,"build-site","Build a static site from registered routes. Call this for every user build/rebuild request, including repeated requests like 'build it again' or 'one more build'.",HX2,async(B)=>{return Q(B.environment),{success:!0,message:`Site build requested${B.environment?` for ${B.environment}`:""} (debounced)`,data:{}}},{cli:{name:"build"}})]}fA();y6();var oD1=f.object({previewOutputDir:f.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:f.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:f.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:f.string().optional().describe("Working directory for builds").default("./.preact-work"),siteInfo:yI.default({title:"Brain",description:"A knowledge management system"}),themeCSS:f.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:f.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),templates:f.any().optional().describe("Template definitions to register"),routes:f.array(m3).optional().describe("Routes to register"),layouts:f.record(f.any()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:f.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:f.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),entityDisplay:f.record(f.object({label:f.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:f.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')"),layout:f.string().optional().describe("Layout name for this entity type's generated routes (defaults to 'default')"),paginate:f.boolean().optional().describe("Enable pagination for list pages"),pageSize:f.number().optional().describe("Items per page (default: 10)"),navigation:f.object({show:f.boolean().optional().describe("Show in navigation"),slot:f.enum(h3).optional().describe("Navigation slot (primary or secondary)"),priority:f.number().min(0).max(100).optional().describe("Navigation priority (0-100)")}).optional().describe("Navigation settings for this entity type")})).optional().describe("Display metadata per entity type \u2014 label, plural name, layout, pagination, navigation slot. Consulted when auto-generating routes for active entity plugins."),staticAssets:f.record(f.string()).optional().describe("Static files to write to the output directory at build time. Keys are output paths (e.g. '/canvases/tree.js'), values are file contents as strings. Typically supplied by a SitePackage via text imports.")});var sD1={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.93",description:"Static site generation plugin for Brain system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint .",clean:"rm -rf dist"},dependencies:{"@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*","@tailwindcss/typography":"^0.5.19",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",eslint:"^8.56.0",typescript:"^5.3.3"}};class tkA extends qB{siteBuilder;pluginContext;_routeRegistry;_slotRegistry;profileService;layouts;rebuildManager;headScripts=new Map;get routeRegistry(){if(!this._routeRegistry)throw Error("RouteRegistry not initialized - plugin not registered");return this._routeRegistry}constructor(A={}){let Q=A.layouts??{};super("site-builder",sD1,{...A,layouts:Q},oD1);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new uBA(A.logger),this._slotRegistry=new qBA,A.messaging.subscribe("plugin:site-builder:slot:register",async(B)=>{let{slotName:w,pluginId:$,render:I,priority:D}=B.payload;return this._slotRegistry?.register(w,{pluginId:$,render:I,...D!==void 0&&{priority:D}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async(B)=>{let{pluginId:w,script:$}=B.payload;return this.headScripts.set(w,$),{success:!0}}),A.entities.registerDataSource(new akA(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=k7.getInstance(A.entityService,A.logger),pD1(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)pBA(this.config.routes,this.id,this.routeRegistry);let Q={entityService:A.entityService,sendMessage:A.messaging.send,resolveTemplateContent:(B,w)=>A.templates.resolve(B,w),getViewTemplate:(B)=>A.views.get(B),listViewTemplateNames:()=>A.views.list().map((B)=>B.name)};if(this.siteBuilder=RD.getInstance(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new skA(this.logger.child("SiteBuildJobHandler"),A.messaging.send,{siteBuilder:this.siteBuilder,layouts:this.layouts,defaultSiteConfig:this.config.siteInfo,sharedImagesDir:this.config.sharedImagesDir,siteUrl:A.siteUrl,previewUrl:A.previewUrl,themeCSS:this.config.themeCSS,slots:this._slotRegistry,getHeadScripts:()=>this.getRegisteredHeadScripts(),...this.config.staticAssets&&{staticAssets:this.config.staticAssets}})),this.rebuildManager=new okA(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe(hv,async()=>{let B=await this.getInstructions();if(B)A.registerInstructions(B);return{success:!0}}),dD1({context:A,routeRegistry:this._routeRegistry,logger:this.logger})}getRegisteredHeadScripts(){return Array.from(this.headScripts.values())}async getTools(){if(!this.pluginContext||!this.rebuildManager)throw Error("Plugin context not initialized");let A=this.rebuildManager;return nD1(this.id,(Q)=>A.requestBuild(Q))}async getResources(){let A=this.getContext();return[{uri:"brain://site",name:"Site Metadata",description:"Site metadata \u2014 title, description, domain, URLs",mimeType:"application/json",handler:async()=>{let Q=await Rc(A.messaging.send,this.config.siteInfo);return{contents:[{uri:"brain://site",mimeType:"application/json",text:JSON.stringify({...Q,domain:A.domain,siteUrl:A.siteUrl,previewUrl:A.previewUrl},null,2)}]}}},{uri:"site://routes",name:"Site Routes",description:"All registered routes with sections and templates",mimeType:"application/json",handler:async()=>{let Q=this.routeRegistry.list();return{contents:[{uri:"site://routes",mimeType:"application/json",text:JSON.stringify(Q.map((B)=>({id:B.id,path:B.path,title:B.title,description:B.description,sections:B.sections.map((w)=>({id:w.id,template:w.template}))})),null,2)}]}}},{uri:"site://templates",name:"View Templates",description:"All registered view templates",mimeType:"application/json",handler:async()=>{let Q=A.views.list();return{contents:[{uri:"site://templates",mimeType:"application/json",text:JSON.stringify(Q.map((B)=>({name:B.name,description:B.description,hasWebRenderer:!!B.renderers.web})),null,2)}]}}}]}getSiteBuilder(){return this.siteBuilder}getSlotRegistry(){return this._slotRegistry}async getInstructions(){let A=this.getContext(),Q="## Site Builder Actions\n- When the user asks to build, rebuild, publish, or build the website/site again, call `site-builder_build-site` immediately.\n- Every repeated build request requires a fresh `site-builder_build-site` call. Do not say a build was started, queued, or requested unless this turn invoked the tool.",B=await Rc(A.messaging.send,this.config.siteInfo);return`## Your Site
|
|
4623
4635
|
${[`**Title:** ${B.title}`,`**Description:** ${B.description}`,A.domain&&`**Domain:** ${A.domain}`,A.siteUrl&&`**URL:** ${A.siteUrl}`].filter(Boolean).join(`
|
|
4624
4636
|
`)}
|
|
4625
4637
|
|
|
4626
4638
|
## Site Builder Actions
|
|
4627
4639
|
- When the user asks to build, rebuild, publish, or build the website/site again, call \`site-builder_build-site\` immediately.
|
|
4628
|
-
- Every repeated build request requires a fresh \`site-builder_build-site\` call. Do not say a build was started, queued, or requested unless this turn invoked the tool.`}async onShutdown(){this.logger.debug("Shutting down site-builder plugin"),this.rebuildManager?.dispose(),RD.resetInstance(),this.logger.debug("Cleaned up all event subscriptions")}}function KV(A={}){return new tkA(A)}eA();y6();fA();eA();y6();var aD1=f.object({}),bc=a1.extend({id:f.literal("site-info"),entityType:f.literal("site-info"),metadata:aD1}),ekA=zd,Ik=yI.omit({url:!0,analyticsScript:!0});eA();class fJ extends zQ{constructor(){super({entityType:"site-info",schema:bc,frontmatterSchema:Ik,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=Ik.parse(A);return this.buildMarkdown("",Q)}parseSiteInfoBody(A){return this.parseFrontmatter(A)}fromMarkdown(A){return{content:A,entityType:"site-info"}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseFrontmatter(A.content);return this.buildMarkdown("",Q)}}class FJ{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,B){return FJ.instance??=new FJ(A,Q,B),FJ.instance}static resetInstance(){FJ.instance=null}static createFresh(A,Q,B){return new FJ(A,Q,B)}constructor(A,Q,B){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new fJ;let w=FJ.getDefaultSiteInfo();this.defaultSiteInfo={...w,...B}}async initialize(){try{if(!await this.entityService.getEntity({entityType:"site-info",id:"site-info"})){if(await this.entityService.getEntity({entityType:"site-info",id:"site-info"}))return;this.logger.info("No site info found, creating default site info");let B=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({entity:{id:"site-info",entityType:"site-info",content:B,metadata:{}}}),this.logger.info("Default site info created successfully")}}catch(A){this.logger.error("Failed to initialize site info",{error:A})}}async getSiteInfo(){try{let A=await this.entityService.getEntity({entityType:"site-info",id:"site-info"});if(A)return this.adapter.parseSiteInfoBody(A.content)}catch(A){this.logger.debug("Site info not found, using defaults",{error:A})}return this.defaultSiteInfo}}var JX2=new fJ;class lBA{logger;id="site-info:entities";name="Site Info DataSource";description="Provides site metadata (title, description, CTA) and profile social links";constructor(A){this.logger=A}async fetch(A,Q,B){let{entityService:w}=B,$;try{let Y=await w.getEntity({entityType:"site-info",id:"site-info"});$=Y?JX2.parseSiteInfoBody(Y.content):{title:"Brain",description:"A knowledge management system"}}catch{$={title:"Brain",description:"A knowledge management system"}}let I;try{let Y=await w.getEntity({entityType:"anchor-profile",id:"anchor-profile"});if(Y)I=Y.metadata.socialLinks}catch{}let D={...$,socialLinks:I,copyright:$.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:D.title,hasSocialLinks:!!D.socialLinks}),Q.parse(D)}}var tD1={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.
|
|
4640
|
+
- Every repeated build request requires a fresh \`site-builder_build-site\` call. Do not say a build was started, queued, or requested unless this turn invoked the tool.`}async onShutdown(){this.logger.debug("Shutting down site-builder plugin"),this.rebuildManager?.dispose(),RD.resetInstance(),this.logger.debug("Cleaned up all event subscriptions")}}function KV(A={}){return new tkA(A)}eA();y6();fA();eA();y6();var aD1=f.object({}),bc=a1.extend({id:f.literal("site-info"),entityType:f.literal("site-info"),metadata:aD1}),ekA=zd,Ik=yI.omit({url:!0,analyticsScript:!0});eA();class fJ extends zQ{constructor(){super({entityType:"site-info",schema:bc,frontmatterSchema:Ik,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=Ik.parse(A);return this.buildMarkdown("",Q)}parseSiteInfoBody(A){return this.parseFrontmatter(A)}fromMarkdown(A){return{content:A,entityType:"site-info"}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseFrontmatter(A.content);return this.buildMarkdown("",Q)}}class FJ{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,B){return FJ.instance??=new FJ(A,Q,B),FJ.instance}static resetInstance(){FJ.instance=null}static createFresh(A,Q,B){return new FJ(A,Q,B)}constructor(A,Q,B){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new fJ;let w=FJ.getDefaultSiteInfo();this.defaultSiteInfo={...w,...B}}async initialize(){try{if(!await this.entityService.getEntity({entityType:"site-info",id:"site-info"})){if(await this.entityService.getEntity({entityType:"site-info",id:"site-info"}))return;this.logger.info("No site info found, creating default site info");let B=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({entity:{id:"site-info",entityType:"site-info",content:B,metadata:{}}}),this.logger.info("Default site info created successfully")}}catch(A){this.logger.error("Failed to initialize site info",{error:A})}}async getSiteInfo(){try{let A=await this.entityService.getEntity({entityType:"site-info",id:"site-info"});if(A)return this.adapter.parseSiteInfoBody(A.content)}catch(A){this.logger.debug("Site info not found, using defaults",{error:A})}return this.defaultSiteInfo}}var JX2=new fJ;class lBA{logger;id="site-info:entities";name="Site Info DataSource";description="Provides site metadata (title, description, CTA) and profile social links";constructor(A){this.logger=A}async fetch(A,Q,B){let{entityService:w}=B,$;try{let Y=await w.getEntity({entityType:"site-info",id:"site-info"});$=Y?JX2.parseSiteInfoBody(Y.content):{title:"Brain",description:"A knowledge management system"}}catch{$={title:"Brain",description:"A knowledge management system"}}let I;try{let Y=await w.getEntity({entityType:"anchor-profile",id:"anchor-profile"});if(Y)I=Y.metadata.socialLinks}catch{}let D={...$,socialLinks:I,copyright:$.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:D.title,hasSocialLinks:!!D.socialLinks}),Q.parse(D)}}var tD1={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.93",description:"Site info entity \u2014 site metadata, title, description, CTA",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/entity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var KX2=new fJ;class A_A extends V2{entityType="site-info";schema=bc;adapter=KX2;defaultSiteInfo;constructor(A){super("site-info",tD1);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new lBA(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=FJ.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe(gv,async()=>{return{success:!0,data:await Q.getSiteInfo()}}),A.messaging.subscribe("entity:updated",async(B)=>{if(B.payload.entityType==="site-info"){let $=await Q.getSiteInfo();await A.messaging.send({type:hv,payload:$,broadcast:!0})}return{success:!0}}),A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function fV(A){return new A_A(A)}var fX2=new fJ;async function Pc(A){let B=(await A.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!B)throw Error("Site info not found \u2014 create a site-info entity");return fX2.parseSiteInfoBody(B.content)}fA();var FX2=Ik.extend({navigation:f.object({primary:f.array(f.object({label:f.string(),href:f.string(),priority:f.number()})),secondary:f.array(f.object({label:f.string(),href:f.string(),priority:f.number()}))}),copyright:f.string(),socialLinks:f.array(f.object({platform:f.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:f.string().describe("Profile or contact URL"),label:f.string().optional().describe("Optional display label")})).optional().describe("Social media links from profile entity")});eA();ZJ();_c();fA();var Q_A=f.object({defaultPrompt:f.string().default("Write a blog post about my recent work and insights"),paginate:f.boolean().default(!0),pageSize:f.number().default(10)});eA();fA();r$();var NX2=f.object({prompt:f.string().optional(),title:f.string().optional(),content:f.string().optional(),excerpt:f.string().optional(),coverImageId:f.string().optional(),seriesName:f.string().optional(),seriesIndex:f.number().optional(),skipAi:f.boolean().optional()}),Nqw=xI.extend({title:f.string().optional(),slug:f.string().optional()});class B_A extends S9{constructor(A,Q){super(A,Q,{schema:NX2,jobTypeName:"blog-generation",entityType:"post"})}async generate(A,Q){let{prompt:B,coverImageId:w,seriesName:$,seriesIndex:I,skipAi:D}=A,{title:Y,content:X,excerpt:W}=A;if(D){if(!Y)this.failEarly("Title is required when skipAi is true");X=X??`## Introduction
|
|
4629
4641
|
|
|
4630
4642
|
Add your introduction here.
|
|
4631
4643
|
|
|
@@ -4670,7 +4682,7 @@ The excerpt should be clear, concise, and compelling.`});fA();nw();ZJ();import{j
|
|
|
4670
4682
|
Note: This is part of a series called "${B.seriesName}".`:""}`;return A.ai.generate({prompt:w,templateName:"blog:generation"})}),A.eval.registerHandler("generateExcerpt",async(Q)=>{let B=uX2.parse(Q);return A.ai.generate({prompt:`Title: ${B.title}
|
|
4671
4683
|
|
|
4672
4684
|
Content:
|
|
4673
|
-
${B.content}`,templateName:"blog:excerpt"})})}var WY1={name:"@brains/blog",private:!0,version:"0.2.0-alpha.
|
|
4685
|
+
${B.content}`,templateName:"blog:excerpt"})})}var WY1={name:"@brains/blog",private:!0,version:"0.2.0-alpha.93",description:"AI-powered blog post generation from existing brain content",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Y_A extends V2{entityType=FV.entityType;schema=Dk;adapter=FV;constructor(A={}){super("blog",WY1,A,Q_A)}getEntityTypeConfig(){return{weight:2}}createGenerationHandler(A){return new B_A(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return wY1()}getDataSources(){return[new $_A(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (JY1(),UY1));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),await $Y1(A,this.logger),IY1(A,this.logger),YY1(A,this.logger),XY1(A),this.logger.info("Blog plugin registered (routes auto-generated at /posts/)")}}function X_A(A={}){return new Y_A(A)}ZJ();_c();eA();fA();fA();Z$();Aw();var iY=f.object({title:f.string(),slug:f.string(),coverImageId:f.string().optional()}),GY1=iY.pick({title:!0,slug:!0}),Xk=a1.extend({metadata:GY1}),rBA=Xk.extend({frontmatter:iY}),nBA=rBA.extend({description:f.string().optional(),postCount:f.number(),coverImageUrl:f.string().optional(),coverImageWidth:f.number().optional(),coverImageHeight:f.number().optional()}),KY1=f.object({description:f.string().optional()});function ZV(A){return new vB(KY1,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}Aw();class W_A extends zQ{constructor(){super({entityType:"series",schema:Xk,frontmatterSchema:iY,supportsCoverImage:!0,bodyFormatter:ZV("")})}toMarkdown(A){let Q,B={};try{Q=this.parseFrontMatter(A.content,iY).coverImageId,B=ZV(A.metadata.title).parse(this.extractBody(A.content))}catch{}let w={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},I=ZV(A.metadata.title).format(B);return this.buildMarkdown(I,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,iY);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,iY);return ZV(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var Wk=new W_A;eA();fA();YY();class H_A{entityService;logger;constructor(A,Q){this.entityService=A;this.logger=Q}async syncAllSeries(){this.logger.debug("Syncing series from all entity types");let A=await this.collectSeriesNames();this.logger.debug(`Found ${A.size} unique series`);let Q=await this.entityService.listEntities({entityType:"series",options:{limit:1000}}),B=new Map(Q.map(($)=>[$.id,$])),w=new Set;for(let $ of A){let I=XQ($);w.add(I);let D=B.get(I),Y=D?.content??this.createSeriesContent($),X=RB(Y);if(D?.contentHash===X)continue;let W={id:I,entityType:"series",content:Y,contentHash:X,created:D?.created??new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:$,slug:XQ($)}};await this.entityService.upsertEntity({entity:W}),this.logger.debug(`Upserted series: ${$}`)}for(let $ of Q)if(!w.has($.id))await this.entityService.deleteEntity({entityType:"series",id:$.id}),this.logger.debug(`Deleted orphaned series: ${$.id}`)}async handleEntityChange(A,Q){let B=this.getSeriesName(A);if(B)await this.ensureSeriesExists(B);if(Q&&Q!==B)await this.cleanupOrphanedSeries(Q)}async handleEntityDeleted(){await this.syncAllSeries()}getSeriesName(A){let B=A.metadata.seriesName;return typeof B==="string"?B:void 0}async ensureSeriesExists(A){let Q=XQ(A);if(await this.entityService.getEntity({entityType:"series",id:Q}))return;let w=this.createSeriesContent(A),$={id:Q,entityType:"series",content:w,contentHash:RB(w),created:new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:A,slug:XQ(A)}};await this.entityService.upsertEntity({entity:$}),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=XQ(A);if(!await this.entityService.getEntity({entityType:"series",id:Q}))return;if(!await this.hasSeriesReferences(A))await this.entityService.deleteEntity({entityType:"series",id:Q}),this.logger.debug(`Deleted orphaned series: ${A}`)}async hasSeriesReferences(A){let Q=this.entityService.getEntityTypes();for(let B of Q){if(B==="series")continue;if((await this.entityService.listEntities({entityType:B,options:{filter:{metadata:{seriesName:A}},limit:1}})).length>0)return!0}return!1}async collectSeriesNames(){let A=new Set,Q=this.entityService.getEntityTypes();for(let B of Q){if(B==="series")continue;let w=await this.entityService.listEntities({entityType:B,options:{limit:1000}});for(let $ of w){let I=this.getSeriesName($);if(I)A.add(I)}}return A}createSeriesContent(A){let Q={title:A,slug:XQ(A)};return o$("",Q)}}eA();fA();var lX2=f.object({entityType:f.literal("series"),query:f.object({id:f.string().optional(),limit:f.number().optional(),page:f.number().optional(),pageSize:f.number().optional()}).passthrough()}),iX2=f.object({type:f.enum(["list","detail"]),seriesName:f.string().optional()});function dX2(A){let Q=iX2.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let B=lX2.safeParse(A);if(B.success){let{query:w}=B.data;if(w.id)return{type:"detail",seriesSlug:w.id};return{type:"list"}}throw Error('Invalid series query format. Expected { type: "list"|"detail" } or { entityType: "series", query: { id?: string } }')}function fY1(A){let Q=$2(A.content,iY);return rBA.parse({...A,frontmatter:Q.metadata})}class U_A{logger;id="series:entities";name="Series DataSource";description="Fetches series list and detail data";constructor(A){this.logger=A}async fetch(A,Q,B){let w=dX2(A),$=B.entityService;if(w.type==="list")return this.fetchSeriesList(Q,$);if(w.seriesName)return this.fetchSeriesDetail(w.seriesName,Q,$);if(w.seriesSlug)return this.fetchSeriesDetailBySlug(w.seriesSlug,Q,$);throw Error("Invalid series query: must specify seriesName or slug for detail")}async fetchSeriesList(A,Q){let B=await Q.listEntities({entityType:"series",options:{limit:1000}}),w=await this.countEntitiesPerSeries(Q),$=B.map((I)=>{let D=fY1(I),Y=Wk.parseBody(I.content);return{...D,description:Y.description,postCount:w.get(I.metadata.title)??0}});return this.logger.debug(`Found ${$.length} series entities`),A.parse({series:$})}async fetchSeriesDetail(A,Q,B,w){if(!w)w=(await B.listEntities({entityType:"series",options:{filter:{metadata:{title:A}}}}))[0];if(!w)throw Error(`Series not found: ${A}`);let $=fY1(w),I=Wk.parseBody(w.content),D=await this.getSeriesMembers(A,B);return this.logger.debug(`Found ${D.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:D,series:{...$,description:I.description,postCount:D.length},description:I.description})}async fetchSeriesDetailBySlug(A,Q,B){let $=(await B.listEntities({entityType:"series",options:{filter:{metadata:{slug:A}}}}))[0];if(!$)return this.logger.warn(`Series not found with slug: ${A}`),Q.parse({seriesName:A,posts:[]});return this.fetchSeriesDetail($.metadata.title,Q,B,$)}async countEntitiesPerSeries(A){let Q=new Map,B=A.getEntityTypes();for(let w of B){if(w==="series")continue;let $=await A.listEntities({entityType:w,options:{limit:1000}});for(let I of $){let D=this.getSeriesName(I);if(D)Q.set(D,(Q.get(D)??0)+1)}}return Q}async getSeriesMembers(A,Q){let B=[],w=Q.getEntityTypes();for(let $ of w){if($==="series")continue;let I=await Q.listEntities({entityType:$,options:{filter:{metadata:{seriesName:A}}}});B.push(...I)}return B.sort(($,I)=>{let D=$.metadata.seriesIndex,Y=I.metadata.seriesIndex;return(typeof D==="number"?D:999)-(typeof Y==="number"?Y:999)}),B}getSeriesName(A){let B=A.metadata.seriesName;return typeof B==="string"?B:void 0}}eA();fA();YY();var rX2=f.object({prompt:f.string().optional(),title:f.string().optional(),seriesId:f.string().optional()});class oBA{logger;context;constructor(A,Q){this.logger=A;this.context=Q}async process(A){let Q=A.seriesId??A.title;if(!Q)return{success:!1,error:"seriesId or title required"};let B=await this.context.entityService.getEntity({entityType:"series",id:Q});if(!B)return{success:!1,error:`Series not found: ${Q}`};let w=await this.gatherMemberSummaries(B.metadata.title);if(w.length===0)return{success:!1,error:`No members found in series: ${B.metadata.title}`};let $=A.prompt??`Series name: ${B.metadata.title}
|
|
4674
4686
|
|
|
4675
4687
|
Content in this series:
|
|
4676
4688
|
${w.join(`
|
|
@@ -4682,7 +4694,7 @@ Your task is to write a series description (2-3 sentences) that:
|
|
|
4682
4694
|
3. Is engaging and makes readers want to explore the content
|
|
4683
4695
|
4. Works well as a series overview on a website
|
|
4684
4696
|
|
|
4685
|
-
Be concise and focus on what makes this series unique and valuable.`});var EY1={name:"@brains/series",private:!0,version:"0.2.0-alpha.
|
|
4697
|
+
Be concise and focus on what makes this series unique and valuable.`});var EY1={name:"@brains/series",private:!0,version:"0.2.0-alpha.93",description:"Cross-content series \u2014 auto-derived from entities with seriesName metadata",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts,.tsx","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/entity-service":"workspace:*","@brains/job-queue":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var VY1=f.discriminatedUnion("mode",[f.object({mode:f.literal("derive"),reason:f.string().optional()}),f.object({mode:f.literal("source"),entityId:f.string(),entityType:f.string(),seriesName:f.string()})]);class J_A extends V2{entityType="series";schema=Xk;adapter=Wk;manager;constructor(){super("series",EY1)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new oBA(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...qY1(),description:LY1}}getDataSources(){return[new U_A(this.logger.child("SeriesDataSource"))]}getDerivedEntityProjections(A){return[{id:"series-projection",targetType:"series",job:{type:"series:project",handler:this.createSeriesProjectionHandler(A)},initialSync:{jobData:{mode:"derive",reason:"initial-sync"},jobOptions:this.getSyncProjectionJobOptions("initial-sync")},sourceChange:{sourceTypes:["*"],events:["entity:created","entity:updated","entity:deleted"],requireInitialSync:!0,jobData:(Q)=>{if(Q.entityType==="series")return null;if(!Q.entity||!this.hasSeriesName(Q.entity))return null;let B=Q.entity.metadata.seriesName;return{mode:"source",entityId:Q.entity.id,entityType:Q.entity.entityType,seriesName:B}},jobOptions:(Q)=>{if(!Q.entity||!this.hasSeriesName(Q.entity))return;return this.getSourceProjectionJobOptions(Q.entity)}}}]}async onRegister(A){this.manager=new H_A(A.entityService,this.logger.child("SeriesManager"))}createSeriesProjectionHandler(A){return{process:async(Q)=>{let B=VY1.parse(Q);if(B.mode==="derive")return await this.projectAll(A),{success:!0};let w=await A.entityService.getEntity({entityType:B.entityType,id:B.entityId});if(w)await this.projectSource(w);else await this.requireManager().cleanupOrphanedSeries(B.seriesName);return{success:!0}},validateAndParse:(Q)=>{let B=VY1.safeParse(Q??{});return B.success?B.data:null}}}requireManager(){if(!this.manager)throw Error("SeriesPlugin not registered");return this.manager}hasSeriesName(A){return typeof A.metadata.seriesName==="string"}getSyncProjectionJobOptions(A){return{source:this.id,deduplication:"coalesce",deduplicationKey:`series-sync:${A}`,metadata:{operationType:"data_processing",operationTarget:"series"}}}getSourceProjectionJobOptions(A){return{source:this.id,deduplication:"coalesce",deduplicationKey:`series-source:${A.entityType}:${A.id}`,metadata:{operationType:"data_processing",operationTarget:`series:${A.entityType}:${A.id}`}}}async projectSource(A){await this.requireManager().handleEntityChange(A)}async projectAll(A){await this.requireManager().syncAllSeries();let Q=new oBA(this.logger.child("SeriesGenerationHandler"),A),B=await A.entityService.listEntities({entityType:"series",options:{limit:1000}});for(let w of B)try{if(!this.adapter.parseBody(w.content).description)this.logger.info(`Generating description for series: ${w.metadata.title}`),await Q.process({seriesId:w.id})}catch($){this.logger.error(`Failed to generate description for series: ${w.id}`,{error:$})}}}function G_A(){return new J_A}eA();fA();eA();fA();fA();eA();var tX2=f.enum(["draft","queued","published"]),MY1="publishedAt is required when deck status is published",CY1=(A)=>A.status==="published"&&!A.publishedAt,K_A=(A)=>{if(CY1(A))throw Error(MY1)},JN=f.object({title:f.string(),slug:f.string().optional(),description:f.string().optional(),author:f.string().optional(),status:tX2,publishedAt:f.string().datetime().optional(),event:f.string().optional(),coverImageId:f.string().optional()}),eX2=JN.pick({title:!0,description:!0,status:!0,publishedAt:!0,coverImageId:!0}).extend({slug:f.string()}).superRefine((A,Q)=>{if(!CY1(A))return;Q.addIssue({code:f.ZodIssueCode.custom,path:["publishedAt"],message:MY1})}),sBA=a1.extend({entityType:f.literal("deck"),metadata:eX2}),aBA=sBA.extend({frontmatter:JN,body:f.string()}),Tc=aBA.extend({url:f.string().optional(),typeLabel:f.string().optional(),listUrl:f.string().optional(),listLabel:f.string().optional(),coverImageUrl:f.string().optional(),coverImageWidth:f.number().optional(),coverImageHeight:f.number().optional()});class f_A extends zQ{constructor(){super({entityType:"deck",schema:sBA,frontmatterSchema:JN,supportsCoverImage:!0})}validateSlideStructure(A){if(!/^---$/gm.test(A))throw Error("Invalid deck: markdown must contain slide separators (---) to be a valid presentation")}toMarkdown(A){let Q=this.extractBody(A.content);this.validateSlideStructure(Q);let B=this.parseFrontMatter(A.content,JN);K_A(B);let w={...B,slug:B.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontmatter(A),B=this.extractBody(A);K_A(Q),this.validateSlideStructure(B);let w=Q.slug??XQ(Q.title),$=Q.status;return{entityType:"deck",content:A,metadata:{slug:w,title:Q.title,description:Q.description,status:$,publishedAt:Q.publishedAt,coverImageId:Q.coverImageId}}}generateTitle(A){return A.metadata.title}generateSummary(A){if(A.metadata.description)return A.metadata.description;return`Presentation: ${A.metadata.title}`}generateFrontMatter(A){return this.toMarkdown(A)}}var Sc=new f_A;fA();nw();var AW2=f.object({markdown:f.string().describe("Markdown content with slide separators (---)")}),F_A=R1({name:"deck-detail",description:"Render a presentation deck as Reveal.js slides",schema:AW2,dataSourceId:"decks:entities",requiredPermission:"public",layout:{component:KPA,fullscreen:!0}});nw();fA();var Z_A=f.object({decks:f.array(aBA)}),z_A=f.object({decks:f.array(Tc),pageTitle:f.string().optional(),pageLabel:f.string().optional()});import{jsxDEV as N_A}from"preact/jsx-dev-runtime";var QW2="Presentations",q_A=({decks:A,pageLabel:Q})=>{let B=A.map(($)=>({id:$.id,url:$.url,title:$.frontmatter.title,date:$.frontmatter.publishedAt??$.created,description:$.frontmatter.description}));return N_A("div",{className:"deck-list bg-theme",children:N_A("div",{className:"container mx-auto max-w-[1100px] px-6 py-16 md:px-12 md:py-24",children:N_A(_u,{label:Q&&Q!=="Decks"?Q:QW2,items:B},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)};Z$();class tBA extends vB{constructor(){super(Z_A,{title:"Deck List",mappings:[{key:"decks",label:"Decks",type:"array",itemType:"object"}]})}}var L_A=R1({name:"deck-list",description:"List view of all presentation decks",schema:z_A,dataSourceId:"decks:entities",requiredPermission:"public",formatter:new tBA,layout:{component:q_A}});fA();eA();var BW2=f.object({title:f.string().max(80).describe("A short, punchy title (2-5 words) that's memorable and evocative"),content:f.string().describe("Full slide deck content in markdown format with slide separators (---). Each slide should have a header and focused content."),description:f.string().describe("A concise 1-2 sentence summary that captures the essence of the talk")}),OY1=R1({name:"decks:generation",description:"Template for AI to generate complete slide decks from prompts",schema:BW2,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are creating slide decks in a distinctive voice that blends philosophy, technology, and culture.
|
|
4686
4698
|
|
|
4687
4699
|
Your task is to generate a complete slide deck based on the user's prompt.
|
|
4688
4700
|
|
|
@@ -4990,12 +5002,12 @@ ${Y}`,templateName:"decks:description"})).description,await this.reportProgress(
|
|
|
4990
5002
|
font-weight: 600;
|
|
4991
5003
|
}
|
|
4992
5004
|
`}},void 0,!1,void 0,this),$.map((W,U)=>$7("section",{className:`deck-carousel-slide${U===0?" is-cover":""}`,children:[$7("header",{className:"deck-carousel-header",children:$7("span",{className:"deck-carousel-wordmark","aria-label":B??Q,children:[$7("span",{className:"wm-primary",children:I.primary},void 0,!1,void 0,this),I.secondary!==void 0&&$7(WW2,{children:[$7("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),$7("span",{className:"wm-secondary",children:I.secondary},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),$7("div",{className:"deck-carousel-body",children:$7("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:X(W.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),$7("footer",{className:"deck-carousel-footer",children:[$7("span",{className:"deck-carousel-footer-meta",children:w??Q},void 0,!1,void 0,this),$7("span",{className:"deck-carousel-counter","aria-label":`Slide ${U+1} of ${D}`,children:[$7("span",{className:"deck-carousel-counter-current",children:String(U+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",$7("span",{children:Y},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},U,!0,void 0,this))]},void 0,!0,void 0,this)}import{mkdtemp as _W2,rm as vW2}from"fs/promises";import{tmpdir as xW2}from"os";import{join as yW2}from"path";class Hk extends Error{code;constructor(A,Q){super(A);this.code=Q;this.name="MediaRenderError"}}function kY1(A={}){return{async launch(){try{return await(await import("playwright-core")).chromium.launch({headless:!0,...A})}catch(Q){throw new Hk(`Failed to launch Chromium for media rendering: ${GW2(Q)}`,"browser-launch-failed")}}}}async function hc(A,Q={}){return HW2(Q.browserFactory??kY1(),Q.timeoutMs??30000,async(B)=>{let w=await B.newPage();try{await w.goto(A,{waitUntil:Q.waitUntil??"networkidle",timeout:Q.timeoutMs??30000});let $={...Q.width!==void 0&&{width:Q.width},...Q.height!==void 0&&{height:Q.height},...Q.format!==void 0&&{format:Q.format},printBackground:Q.printBackground??!0,preferCSSPageSize:Q.preferCSSPageSize??!0,...Q.margin!==void 0&&{margin:Q.margin}},I=await w.pdf($),D=Buffer.from(I);if(JW2(D),Q.maxBytes!==void 0&&D.length>Q.maxBytes)throw new Hk(`Rendered PDF is ${D.length} bytes, exceeding maxBytes=${Q.maxBytes}`,"output-too-large");return D}finally{await UW2(w)}})}async function HW2(A,Q,B){let w,$=!1,I={browser:null},D=(W)=>{W.close().catch(()=>{try{W.process?.()?.kill("SIGKILL")}catch{}})},Y=new Promise((W,U)=>{w=setTimeout(()=>{if($=!0,I.browser)D(I.browser);U(new Hk(`Media render timed out after ${Q}ms`,"render-timeout"))},Q)}),X=A.launch().then((W)=>{if(I.browser=W,$)D(W);return W});try{let W=await Promise.race([X,Y]);try{return await Promise.race([B(W),Y])}finally{if(!$)try{await W.close()}catch{try{W.process?.()?.kill("SIGKILL")}catch{}}}}finally{if(w)clearTimeout(w)}}async function UW2(A){await A.close?.().catch(()=>{return})}function JW2(A){if(A.subarray(0,4).toString("ascii")!=="%PDF")throw new Hk("Rendered output was not a PDF","invalid-output")}function GW2(A){return A instanceof Error?A.message:String(A)}import{h as M_A}from"preact";import{render as KW2}from"preact-render-to-string";fA();function C_A(A){let Q=fW2(A.template,A.format),B=f.record(f.unknown()).parse(A.content),w=f.record(f.unknown()).parse(A.template.schema.parse(B)),$=new rj(A.siteConfig.title),I=FW2(A.imageBuildService),D=M_A(xj,{headCollector:$,children:M_A(bj,{imageRenderer:I,children:M_A(Q,w)})}),Y=KW2(D);if(!$.getHeadProps())$.setHeadProps({title:A.siteConfig.title});let X=ZW2($.generateHeadHTML(),A.noindex??!0);return qc(Y,X,A.siteConfig.title,A.siteConfig.themeMode)}function fW2(A,Q){let B=A.renderers[Q];if(!B||typeof B!=="function")throw Error(`No ${Q} renderer for template: ${A.name}`);return B}function FW2(A){return A?.createImageRenderer()??null}function ZW2(A,Q){if(!Q)return A;return`${A}
|
|
4993
|
-
<meta name="robots" content="noindex,nofollow">`}import{createServer as zW2}from"http";import{lstat as _Y1,mkdir as xY1,readFile as NW2,writeFile as yY1}from"fs/promises";import{dirname as qW2,extname as LW2,join as O_A,posix as EW2,resolve as eBA,sep as vY1}from"path";async function b_A(A){let Q=MW2(A.mediaPath),B=CW2(A.outputDir,Q),w=C_A({template:A.template,format:A.format,content:A.content,siteConfig:A.siteConfig,imageBuildService:A.imageBuildService});return await xY1(qW2(B),{recursive:!0}),await yY1(B,w,"utf-8"),await VW2(A.outputDir,A.themeCSS),{urlPath:Q,filePath:B}}async function VW2(A,Q){let B=O_A(A,"styles");await xY1(B,{recursive:!0}),await yY1(O_A(B,"main.css"),Q,"utf-8")}async function P_A(A){let Q=eBA(A.rootDir),B=A.host??"127.0.0.1",w=zW2(async(D,Y)=>{try{let X=new URL(D.url??"/",`http://${B}`),W=decodeURIComponent(X.pathname);if(OW2(W)){Y.writeHead(403),Y.end("Forbidden");return}let U=W.startsWith("/")?W.slice(1):W,K=eBA(Q,U);if(!R_A(Q,K)){Y.writeHead(403),Y.end("Forbidden");return}let F=await RW2(K);if(!F||!R_A(Q,F)){Y.writeHead(404),Y.end("Not found");return}let Z=await NW2(F);Y.writeHead(200,{"content-type":bW2(F)}),Y.end(Z)}catch{Y.writeHead(404),Y.end("Not found")}});await PW2(w,B);let $=jW2(w),I=`http://${B}:${$}`;return{baseUrl:I,urlFor:(D)=>`${I}${D.startsWith("/")?D:`/${D}`}`,close:()=>kW2(w)}}function MW2(A){if(!A.startsWith("/_media/"))throw Error("Media render paths must start with /_media/");if(A.split("/").filter(Boolean).some((w)=>w===".."))throw Error("Media render path cannot contain traversal");let B=EW2.normalize(A);if(!B.startsWith("/_media/"))throw Error("Media render path cannot contain traversal");return B.endsWith("/")?B:`${B}/`}function CW2(A,Q){let B=eBA(A),w=Q.slice(1),$=eBA(B,w,"index.html");if(!R_A(B,$))throw Error("Media render path cannot contain traversal");return $}function OW2(A){return A.split("/").some((Q)=>Q==="..")}function R_A(A,Q){let B=A.endsWith(vY1)?A:`${A}${vY1}`;return Q===A||Q.startsWith(B)}async function RW2(A){try{let Q=await _Y1(A);if(Q.isSymbolicLink())return null;if(Q.isDirectory()){let B=O_A(A,"index.html"),w=await _Y1(B).catch(()=>null);if(!w||w.isSymbolicLink())return null;return w.isFile()?B:null}if(Q.isFile())return A;return null}catch{return null}}function bW2(A){switch(LW2(A).toLowerCase()){case".css":return"text/css; charset=utf-8";case".html":return"text/html; charset=utf-8";case".js":return"application/javascript; charset=utf-8";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".svg":return"image/svg+xml";case".webp":return"image/webp";default:return"application/octet-stream"}}async function PW2(A,Q){await new Promise((B,w)=>{let $=(D)=>{A.off("listening",I),w(D)},I=()=>{A.off("error",$),B()};A.once("error",$),A.once("listening",I),A.listen(0,Q)})}function jW2(A){let Q=A.address();if(typeof Q!=="object"||Q===null)throw Error("Static render server did not bind to a TCP port");return Q.port}async function kW2(A){await new Promise((Q,B)=>{A.close((w)=>{if(w){B(w);return}Q()})})}fA();var TW2=26214400,SW2=60000,TY1=20;class j_A{context;renderPdf;getThemeMode;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??hc,this.getThemeMode=Q.getThemeMode??(async()=>"dark")}async resolve(A){if(A.sourceEntityType!=="deck")return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let B=gW2(Q,{brandLabel:this.resolveBrandLabel()});if(B.slides.length>TY1)throw Error(`Refusing to render carousel with ${B.slides.length} slides; maxSlides=${TY1}`);let w=await this.getThemeMode(),$=await _W2(yW2(xW2(),"brain-deck-carousel-"));try{let I=await b_A({outputDir:$,mediaPath:`/_media/carousel/${Q.id}`,template:jY1,format:"pdf",content:B,siteConfig:{title:B.title,themeMode:w},themeCSS:this.context.themeCSS}),D=await P_A({rootDir:$});try{return{type:"document",data:await this.renderPdf(D.urlFor(I.urlPath),{maxBytes:TW2,timeoutMs:SW2,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${hW2(Q)}-carousel.pdf`}}finally{await D.close()}}finally{await vW2($,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name;return Q.length>0?Q:void 0}}function gW2(A,Q={}){let{frontmatter:B,content:w}=eD(A.content),$=typeof B.title==="string"?B.title:A.metadata.title,I=typeof B.event==="string"&&B.event.length>0?B.event:void 0,D=w.split(/^---$/gm).map((Y)=>Y.trim()).filter((Y)=>Y.length>0).map((Y)=>({markdown:Y}));return{title:$,slides:D,...Q.brandLabel?{brandLabel:Q.brandLabel}:{},...I?{eyebrow:I}:{}}}function hW2(A){let Q=A.metadata.slug;return Q.length>0?Q:XQ(A.metadata.title)}var SY1={name:"@brains/decks",private:!0,version:"0.2.0-alpha.
|
|
5005
|
+
<meta name="robots" content="noindex,nofollow">`}import{createServer as zW2}from"http";import{lstat as _Y1,mkdir as xY1,readFile as NW2,writeFile as yY1}from"fs/promises";import{dirname as qW2,extname as LW2,join as O_A,posix as EW2,resolve as eBA,sep as vY1}from"path";async function b_A(A){let Q=MW2(A.mediaPath),B=CW2(A.outputDir,Q),w=C_A({template:A.template,format:A.format,content:A.content,siteConfig:A.siteConfig,imageBuildService:A.imageBuildService});return await xY1(qW2(B),{recursive:!0}),await yY1(B,w,"utf-8"),await VW2(A.outputDir,A.themeCSS),{urlPath:Q,filePath:B}}async function VW2(A,Q){let B=O_A(A,"styles");await xY1(B,{recursive:!0}),await yY1(O_A(B,"main.css"),Q,"utf-8")}async function P_A(A){let Q=eBA(A.rootDir),B=A.host??"127.0.0.1",w=zW2(async(D,Y)=>{try{let X=new URL(D.url??"/",`http://${B}`),W=decodeURIComponent(X.pathname);if(OW2(W)){Y.writeHead(403),Y.end("Forbidden");return}let U=W.startsWith("/")?W.slice(1):W,K=eBA(Q,U);if(!R_A(Q,K)){Y.writeHead(403),Y.end("Forbidden");return}let F=await RW2(K);if(!F||!R_A(Q,F)){Y.writeHead(404),Y.end("Not found");return}let Z=await NW2(F);Y.writeHead(200,{"content-type":bW2(F)}),Y.end(Z)}catch{Y.writeHead(404),Y.end("Not found")}});await PW2(w,B);let $=jW2(w),I=`http://${B}:${$}`;return{baseUrl:I,urlFor:(D)=>`${I}${D.startsWith("/")?D:`/${D}`}`,close:()=>kW2(w)}}function MW2(A){if(!A.startsWith("/_media/"))throw Error("Media render paths must start with /_media/");if(A.split("/").filter(Boolean).some((w)=>w===".."))throw Error("Media render path cannot contain traversal");let B=EW2.normalize(A);if(!B.startsWith("/_media/"))throw Error("Media render path cannot contain traversal");return B.endsWith("/")?B:`${B}/`}function CW2(A,Q){let B=eBA(A),w=Q.slice(1),$=eBA(B,w,"index.html");if(!R_A(B,$))throw Error("Media render path cannot contain traversal");return $}function OW2(A){return A.split("/").some((Q)=>Q==="..")}function R_A(A,Q){let B=A.endsWith(vY1)?A:`${A}${vY1}`;return Q===A||Q.startsWith(B)}async function RW2(A){try{let Q=await _Y1(A);if(Q.isSymbolicLink())return null;if(Q.isDirectory()){let B=O_A(A,"index.html"),w=await _Y1(B).catch(()=>null);if(!w||w.isSymbolicLink())return null;return w.isFile()?B:null}if(Q.isFile())return A;return null}catch{return null}}function bW2(A){switch(LW2(A).toLowerCase()){case".css":return"text/css; charset=utf-8";case".html":return"text/html; charset=utf-8";case".js":return"application/javascript; charset=utf-8";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".svg":return"image/svg+xml";case".webp":return"image/webp";default:return"application/octet-stream"}}async function PW2(A,Q){await new Promise((B,w)=>{let $=(D)=>{A.off("listening",I),w(D)},I=()=>{A.off("error",$),B()};A.once("error",$),A.once("listening",I),A.listen(0,Q)})}function jW2(A){let Q=A.address();if(typeof Q!=="object"||Q===null)throw Error("Static render server did not bind to a TCP port");return Q.port}async function kW2(A){await new Promise((Q,B)=>{A.close((w)=>{if(w){B(w);return}Q()})})}fA();var TW2=26214400,SW2=60000,TY1=20;class j_A{context;renderPdf;getThemeMode;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??hc,this.getThemeMode=Q.getThemeMode??(async()=>"dark")}async resolve(A){if(A.sourceEntityType!=="deck")return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let B=gW2(Q,{brandLabel:this.resolveBrandLabel()});if(B.slides.length>TY1)throw Error(`Refusing to render carousel with ${B.slides.length} slides; maxSlides=${TY1}`);let w=await this.getThemeMode(),$=await _W2(yW2(xW2(),"brain-deck-carousel-"));try{let I=await b_A({outputDir:$,mediaPath:`/_media/carousel/${Q.id}`,template:jY1,format:"pdf",content:B,siteConfig:{title:B.title,themeMode:w},themeCSS:this.context.themeCSS}),D=await P_A({rootDir:$});try{return{type:"document",data:await this.renderPdf(D.urlFor(I.urlPath),{maxBytes:TW2,timeoutMs:SW2,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${hW2(Q)}-carousel.pdf`}}finally{await D.close()}}finally{await vW2($,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name;return Q.length>0?Q:void 0}}function gW2(A,Q={}){let{frontmatter:B,content:w}=eD(A.content),$=typeof B.title==="string"?B.title:A.metadata.title,I=typeof B.event==="string"&&B.event.length>0?B.event:void 0,D=w.split(/^---$/gm).map((Y)=>Y.trim()).filter((Y)=>Y.length>0).map((Y)=>({markdown:Y}));return{title:$,slides:D,...Q.brandLabel?{brandLabel:Q.brandLabel}:{},...I?{eyebrow:I}:{}}}function hW2(A){let Q=A.metadata.slug;return Q.length>0?Q:XQ(A.metadata.title)}var SY1={name:"@brains/decks",private:!0,version:"0.2.0-alpha.93",description:"Presentation decks plugin for creating and viewing slide presentations",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class k_A extends V2{deps;entityType=Sc.entityType;schema=Sc.schema;adapter=Sc;unregisterCarouselAttachmentProvider;constructor(A={}){super("decks",SY1);this.deps=A}createGenerationHandler(A){return new V_A(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":F_A,"deck-list":L_A,generation:OY1,description:RY1}}getDataSources(){return[new E_A(this.logger)]}getEntityTypeConfig(){return{weight:1.5}}async onRegister(A){await this.registerWithPublishPipeline(A),this.subscribeToPublishExecute(A),this.registerCarouselAttachmentProvider(A),this.registerEvalHandlers(A),this.logger.info("Decks plugin registered")}async onShutdown(){this.unregisterCarouselAttachmentProvider?.(),this.unregisterCarouselAttachmentProvider=void 0}async registerWithPublishPipeline(A){await A.messaging.send({type:"publish:register",payload:{entityType:"deck",provider:{name:"internal",publish:async()=>({id:"internal"})}}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:B,entityId:w}=Q.payload;if(B!=="deck")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"deck",id:w});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:B,entityId:w,error:`Deck not found: ${w}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let I=new Date().toISOString(),D={...$,metadata:{...$.metadata,status:"published",publishedAt:I}};await A.entityService.updateEntity({entity:{...D,content:this.adapter.toMarkdown(D)}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:B,entityId:w,result:{id:w}}})}catch($){await A.messaging.send({type:"publish:report:failure",payload:{entityType:B,entityId:w,error:S0($)}})}return{success:!0}})}registerCarouselAttachmentProvider(A){let Q={...this.deps,getThemeMode:this.deps.getThemeMode??(async()=>{try{return(await Pc(A.entityService)).themeMode??"dark"}catch{return"dark"}})};this.unregisterCarouselAttachmentProvider=A.attachments.register("deck",bY1,new j_A(A,Q))}registerEvalHandlers(A){A.eval.registerHandler("generateDeck",async(Q)=>{let B=f.object({prompt:f.string(),event:f.string().optional()}).parse(Q);return A.ai.generate({prompt:`${B.prompt}${B.event?`
|
|
4994
5006
|
|
|
4995
5007
|
Note: This presentation is for "${B.event}".`:""}`,templateName:"decks:generation"})}),A.eval.registerHandler("generateDescription",async(Q)=>{let B=f.object({title:f.string(),content:f.string()}).parse(Q);return A.ai.generate({prompt:`Title: ${B.title}
|
|
4996
5008
|
|
|
4997
5009
|
Content:
|
|
4998
|
-
${B.content}`,templateName:"decks:description"})})}}function mc(){return new k_A}eA();fA();fA();Aw();var __A=f.literal("application/pdf"),v_A=f.object({title:f.string().optional(),mimeType:__A,filename:f.string().min(1),pageCount:f.number().int().min(0).optional(),sourceEntityType:f.string().min(1).optional(),sourceEntityId:f.string().min(1).optional(),attachmentType:f.string().min(1).optional(),dedupKey:f.string().min(1).optional()}),Uk=a1.extend({entityType:f.literal("document"),content:f.string().regex(/^data:application\/pdf;base64,.+$/),metadata:v_A});function uc(A){let Q=A.match(/^data:(application\/pdf);base64,(.+)$/i);if(!Q?.[1]||!Q[2])throw Error("Invalid PDF document data URL");return{mimeType:"application/pdf",base64:Q[2]}}function AwA(A){return`data:application/pdf;base64,${Buffer.from(A).toString("base64")}`}function x_A(A){let Q=Buffer.from(A).toString("latin1"),B=0,w=/\/Type\s*\/Pages\b[^]*?\/Count\s+(\d+)|\/Count\s+(\d+)[^]*?\/Type\s*\/Pages\b/g;for(let I of Q.matchAll(w)){let D=parseInt(I[1]??I[2]??"0",10);if(D>B)B=D}if(B>0)return B;return Q.match(/\/Type\s*\/Page(?!\w)/g)?.length??0}class QwA{entityType="document";schema=Uk;toMarkdown(A){return A.content}fromMarkdown(A){return uc(A),{entityType:"document",content:A}}extractMetadata(A){return A.metadata}parseFrontMatter(A,Q){return Q.parse({})}generateFrontMatter(A){return""}getBodyTemplate(){return""}createDocumentEntity(A){let{dataUrl:Q,...B}=A,{mimeType:w}=uc(Q);return{entityType:"document",content:Q,metadata:{mimeType:w,...B}}}}var zV=new QwA;eA();fA();var cW2=26214400,pW2=20,lW2=60000,BwA=f.object({renderUrl:f.string().url().optional(),sourceEntityType:f.string().min(1),sourceEntityId:f.string().min(1),attachmentType:f.string().min(1),documentId:f.string().min(1).optional(),title:f.string().min(1).optional(),filename:f.string().min(1).optional(),dedupKey:f.string().min(1).optional(),pageCount:f.number().int().min(0).optional(),maxPageCount:f.number().int().positive().optional(),maxBytes:f.number().int().positive().optional(),timeoutMs:f.number().int().positive().optional(),width:f.union([f.string(),f.number()]).optional(),height:f.union([f.string(),f.number()]).optional(),format:f.string().optional(),targetEntityType:f.string().min(1).optional(),targetEntityId:f.string().min(1).optional()}),wwA=BwA.refine((A)=>A.targetEntityType===void 0&&A.targetEntityId===void 0||A.targetEntityType!==void 0&&A.targetEntityId!==void 0,{message:"targetEntityType and targetEntityId must be provided together",path:["targetEntityId"]});class $wA extends Sw{context;renderPdf;constructor(A,Q,B={}){super(A,{schema:wwA,jobTypeName:"document-generate"});this.context=Q;this.renderPdf=B.renderPdf??hc}async process(A,Q,B){this.logger.debug("Starting document generation job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});let w=A.maxPageCount??pW2,$=A.maxBytes??cW2,I=A.timeoutMs??lW2;if(A.pageCount!==void 0&&A.pageCount>w)throw Error(`Refusing to render ${A.pageCount} page PDF; maxPageCount=${w}`);let D=iW2(A),Y=await this.findDocumentByDedupKey(D);if(Y)return await this.reportProgress(B,{progress:100,message:"Reusing existing generated document"}),{success:!0,documentId:Y.id,reused:!0};await this.reportProgress(B,{progress:20,message:"Rendering PDF document"});try{let X=await this.resolveDocumentAttachment(A,{timeoutMs:I,maxBytes:$}),W=X.data;if(W.byteLength>$)throw Error(`Rendered PDF exceeds maxBytes=${$}: ${W.byteLength} bytes`);let U=x_A(W);if(U>w)throw Error(`Rendered PDF has ${U} pages, exceeding maxPageCount=${w}`);let K=U>0?U:A.pageCount;await this.reportProgress(B,{progress:70,message:"Storing PDF document"});let F=gY1(A,Q),Z=A.filename??(A.renderUrl===void 0?X.filename:`${F}.pdf`),q=zV.createDocumentEntity({dataUrl:AwA(W),filename:Z,...A.title&&{title:A.title},...K!==void 0&&{pageCount:K},sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,dedupKey:D});if(await this.context.entityService.getEntity({entityType:"document",id:F}))await this.context.entityService.deleteEntity({entityType:"document",id:F});if(await this.context.entityService.createEntity({entity:{...q,id:F}}),A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,F);return await this.reportProgress(B,{progress:100,message:"PDF document generation complete"}),{success:!0,documentId:F,reused:!1}}catch(X){throw this.logger.error("Document generation failed",{jobId:Q,error:S0(X)}),X}}async resolveDocumentAttachment(A,Q){if(A.renderUrl!==void 0)return{type:"document",data:await this.renderPdf(A.renderUrl,{timeoutMs:Q.timeoutMs,maxBytes:Q.maxBytes,printBackground:!0,preferCSSPageSize:!0,...A.width!==void 0&&{width:A.width},...A.height!==void 0&&{height:A.height},...A.format!==void 0&&{format:A.format}}),mimeType:"application/pdf",filename:A.filename??`${gY1(A,"document")}.pdf`};let B=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!B)throw Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`);return B}async findDocumentByDedupKey(A){let Q=await this.context.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}});if(Q.length>1)this.logger.warn("Multiple documents share dedupKey; using first",{dedupKey:A,count:Q.length,ids:Q.map((B)=>B.id)});return Q[0]}async attachDocumentToTarget(A,Q,B){let w=await this.context.entityService.getEntity({entityType:A,id:Q});if(!w)throw Error(`Target entity not found: ${A}/${Q}`);let{frontmatter:$}=eD(w.content),I=Array.isArray($.documents)?$.documents.filter(dW2):[],D=I.some((Y)=>Y.id===B)?I:[...I,{id:B}];await this.context.entityService.updateEntity({entity:{...w,content:rM(w.content,"documents",D)}})}}function iW2(A){return A.dedupKey??`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl??"resolved-attachment"}`}function gY1(A,Q){let B=A.documentId??A.filename?.replace(/\.pdf$/i,"")??`${A.attachmentType}-${A.sourceEntityType}-${A.sourceEntityId}-${Q}`;return XQ(B)}function dW2(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}eA();function y_A(A,Q){return[j2(A,"generate","Generate a durable PDF document entity from a source attachment or render URL, with optional target documents[] attachment.",BwA,async(B,w)=>{let $=wwA.safeParse(B);if(!$.success)return h5($.error.message);let I=await Q($.data,w);return J8({jobId:I})},{cli:{name:"document-generate"}})]}var hY1={name:"@brains/document-plugin",private:!0,version:"0.2.0-alpha.
|
|
5010
|
+
${B.content}`,templateName:"decks:description"})})}}function mc(){return new k_A}eA();fA();fA();Aw();var __A=f.literal("application/pdf"),v_A=f.object({title:f.string().optional(),mimeType:__A,filename:f.string().min(1),pageCount:f.number().int().min(0).optional(),sourceEntityType:f.string().min(1).optional(),sourceEntityId:f.string().min(1).optional(),attachmentType:f.string().min(1).optional(),dedupKey:f.string().min(1).optional()}),Uk=a1.extend({entityType:f.literal("document"),content:f.string().regex(/^data:application\/pdf;base64,.+$/),metadata:v_A});function uc(A){let Q=A.match(/^data:(application\/pdf);base64,(.+)$/i);if(!Q?.[1]||!Q[2])throw Error("Invalid PDF document data URL");return{mimeType:"application/pdf",base64:Q[2]}}function AwA(A){return`data:application/pdf;base64,${Buffer.from(A).toString("base64")}`}function x_A(A){let Q=Buffer.from(A).toString("latin1"),B=0,w=/\/Type\s*\/Pages\b[^]*?\/Count\s+(\d+)|\/Count\s+(\d+)[^]*?\/Type\s*\/Pages\b/g;for(let I of Q.matchAll(w)){let D=parseInt(I[1]??I[2]??"0",10);if(D>B)B=D}if(B>0)return B;return Q.match(/\/Type\s*\/Page(?!\w)/g)?.length??0}class QwA{entityType="document";schema=Uk;toMarkdown(A){return A.content}fromMarkdown(A){return uc(A),{entityType:"document",content:A}}extractMetadata(A){return A.metadata}parseFrontMatter(A,Q){return Q.parse({})}generateFrontMatter(A){return""}getBodyTemplate(){return""}createDocumentEntity(A){let{dataUrl:Q,...B}=A,{mimeType:w}=uc(Q);return{entityType:"document",content:Q,metadata:{mimeType:w,...B}}}}var zV=new QwA;eA();fA();var cW2=26214400,pW2=20,lW2=60000,BwA=f.object({renderUrl:f.string().url().optional(),sourceEntityType:f.string().min(1),sourceEntityId:f.string().min(1),attachmentType:f.string().min(1),documentId:f.string().min(1).optional(),title:f.string().min(1).optional(),filename:f.string().min(1).optional(),dedupKey:f.string().min(1).optional(),pageCount:f.number().int().min(0).optional(),maxPageCount:f.number().int().positive().optional(),maxBytes:f.number().int().positive().optional(),timeoutMs:f.number().int().positive().optional(),width:f.union([f.string(),f.number()]).optional(),height:f.union([f.string(),f.number()]).optional(),format:f.string().optional(),targetEntityType:f.string().min(1).optional(),targetEntityId:f.string().min(1).optional()}),wwA=BwA.refine((A)=>A.targetEntityType===void 0&&A.targetEntityId===void 0||A.targetEntityType!==void 0&&A.targetEntityId!==void 0,{message:"targetEntityType and targetEntityId must be provided together",path:["targetEntityId"]});class $wA extends Sw{context;renderPdf;constructor(A,Q,B={}){super(A,{schema:wwA,jobTypeName:"document-generate"});this.context=Q;this.renderPdf=B.renderPdf??hc}async process(A,Q,B){this.logger.debug("Starting document generation job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});let w=A.maxPageCount??pW2,$=A.maxBytes??cW2,I=A.timeoutMs??lW2;if(A.pageCount!==void 0&&A.pageCount>w)throw Error(`Refusing to render ${A.pageCount} page PDF; maxPageCount=${w}`);let D=iW2(A),Y=await this.findDocumentByDedupKey(D);if(Y)return await this.reportProgress(B,{progress:100,message:"Reusing existing generated document"}),{success:!0,documentId:Y.id,reused:!0};await this.reportProgress(B,{progress:20,message:"Rendering PDF document"});try{let X=await this.resolveDocumentAttachment(A,{timeoutMs:I,maxBytes:$}),W=X.data;if(W.byteLength>$)throw Error(`Rendered PDF exceeds maxBytes=${$}: ${W.byteLength} bytes`);let U=x_A(W);if(U>w)throw Error(`Rendered PDF has ${U} pages, exceeding maxPageCount=${w}`);let K=U>0?U:A.pageCount;await this.reportProgress(B,{progress:70,message:"Storing PDF document"});let F=gY1(A,Q),Z=A.filename??(A.renderUrl===void 0?X.filename:`${F}.pdf`),q=zV.createDocumentEntity({dataUrl:AwA(W),filename:Z,...A.title&&{title:A.title},...K!==void 0&&{pageCount:K},sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,dedupKey:D});if(await this.context.entityService.getEntity({entityType:"document",id:F}))await this.context.entityService.deleteEntity({entityType:"document",id:F});if(await this.context.entityService.createEntity({entity:{...q,id:F}}),A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,F);return await this.reportProgress(B,{progress:100,message:"PDF document generation complete"}),{success:!0,documentId:F,reused:!1}}catch(X){throw this.logger.error("Document generation failed",{jobId:Q,error:S0(X)}),X}}async resolveDocumentAttachment(A,Q){if(A.renderUrl!==void 0)return{type:"document",data:await this.renderPdf(A.renderUrl,{timeoutMs:Q.timeoutMs,maxBytes:Q.maxBytes,printBackground:!0,preferCSSPageSize:!0,...A.width!==void 0&&{width:A.width},...A.height!==void 0&&{height:A.height},...A.format!==void 0&&{format:A.format}}),mimeType:"application/pdf",filename:A.filename??`${gY1(A,"document")}.pdf`};let B=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!B)throw Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`);return B}async findDocumentByDedupKey(A){let Q=await this.context.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}});if(Q.length>1)this.logger.warn("Multiple documents share dedupKey; using first",{dedupKey:A,count:Q.length,ids:Q.map((B)=>B.id)});return Q[0]}async attachDocumentToTarget(A,Q,B){let w=await this.context.entityService.getEntity({entityType:A,id:Q});if(!w)throw Error(`Target entity not found: ${A}/${Q}`);let{frontmatter:$}=eD(w.content),I=Array.isArray($.documents)?$.documents.filter(dW2):[],D=I.some((Y)=>Y.id===B)?I:[...I,{id:B}];await this.context.entityService.updateEntity({entity:{...w,content:rM(w.content,"documents",D)}})}}function iW2(A){return A.dedupKey??`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl??"resolved-attachment"}`}function gY1(A,Q){let B=A.documentId??A.filename?.replace(/\.pdf$/i,"")??`${A.attachmentType}-${A.sourceEntityType}-${A.sourceEntityId}-${Q}`;return XQ(B)}function dW2(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}eA();function y_A(A,Q){return[j2(A,"generate","Generate a durable PDF document entity from a source attachment or render URL, with optional target documents[] attachment.",BwA,async(B,w)=>{let $=wwA.safeParse(B);if(!$.success)return h5($.error.message);let I=await Q($.data,w);return J8({jobId:I})},{cli:{name:"document-generate"}})]}var hY1={name:"@brains/document-plugin",private:!0,version:"0.2.0-alpha.93",description:"Document entity type for generated PDFs and publishable document attachments",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};var nW2=f.object({});class T_A extends qB{entityType=zV.entityType;schema=Uk;adapter=zV;pluginContext;constructor(){super("document",hY1,{},nW2)}async onRegister(A){this.pluginContext=A,A.entities.register(this.entityType,this.schema,this.adapter,{embeddable:!1}),A.jobs.registerHandler("generate",new $wA(this.logger.child("DocumentGenerationJobHandler"),A))}async getInstructions(){return'When a user asks to generate, save, prepare, or preview a deck carousel PDF, call document_generate with sourceEntityType: "deck", sourceEntityId set to the deck ID, and attachmentType: "carousel". Do not use generic attachment types like "document" for deck carousel PDFs.'}async getTools(){let A=this.pluginContext;if(!A)throw Error("Plugin context not initialized");return y_A(this.id,(Q,B)=>A.jobs.enqueue({type:"generate",data:Q,toolContext:B}))}}function S_A(){return new T_A}eA();fA();fA();eA();var GN=f.object({title:f.string().optional()}),mY1=GN.pick({title:!0}).required(),Jk=a1.extend({entityType:f.literal("base"),metadata:mY1}),oW2=Jk.extend({frontmatter:GN,body:f.string()});eA();fA();class g_A extends zQ{constructor(){super({entityType:"base",schema:Jk,frontmatterSchema:GN})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,GN);if(B.title)return this.buildMarkdown(Q,B)}catch{}return Q}fromMarkdown(A){let Q=this.extractTitle(A)??"Untitled";return{content:A,entityType:"base",metadata:{title:Q}}}parseNoteFrontmatter(A){try{return this.parseFrontMatter(A.content,GN)}catch{return{}}}createNoteContent(A,Q){try{let B=this.parseFrontMatter(Q,f.record(f.unknown()));if(Object.keys(B).length===0)return Q;let w={...B,title:B.title??A},$=this.extractBody(Q);return this.buildMarkdown($,w)}catch{return Q}}extractTitle(A){try{let B=this.parseFrontMatter(A,GN);if(B.title)return B.title}catch{}let Q=A.match(/^#\s+(.+)$/m);if(Q?.[1])return Q[1].trim();return null}}var Gk=new g_A;fA();var h_A=f.object({defaultPrompt:f.string().default("Create a note summarizing key concepts from my knowledge base")});fA();eA();var uY1=f.object({title:f.string().max(80).describe("A clear, descriptive title for the note (3-8 words)"),body:f.string().describe("Note content in markdown format with clear organization and structure")}),m_A=R1({name:"note:generation",description:"Template for AI to generate notes from prompts",schema:uY1,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create personal knowledge notes for research and reference.
|
|
4999
5011
|
|
|
5000
5012
|
Your task is to generate a well-structured note based on the user's prompt.
|
|
5001
5013
|
|
|
@@ -5005,7 +5017,7 @@ Guidelines:
|
|
|
5005
5017
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
5006
5018
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
5007
5019
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
5008
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});eA();fA();r$();var cY1=f.object({prompt:f.string(),title:f.string().optional()}),sW2=xI.extend({title:f.string().optional()});class IwA extends S9{constructor(A,Q){super(A,Q,{schema:cY1,jobTypeName:"note-generation",entityType:"base"})}async generate(A,Q){await this.reportProgress(Q,{progress:10,message:"Generating note content with AI"});let B=await this.context.ai.generate({prompt:A.prompt,templateName:"note:generation"}),w=A.title??B.title;return await this.reportProgress(Q,{progress:50,message:`Generated note: "${w}"`}),{id:w,content:Gk.createNoteContent(w,B.body),metadata:{title:w},title:w,resultExtras:{title:w}}}summarizeDataForLog(A){return{prompt:A.prompt,title:A.title}}}var pY1={name:"@brains/note",private:!0,version:"0.2.0-alpha.
|
|
5020
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});eA();fA();r$();var cY1=f.object({prompt:f.string(),title:f.string().optional()}),sW2=xI.extend({title:f.string().optional()});class IwA extends S9{constructor(A,Q){super(A,Q,{schema:cY1,jobTypeName:"note-generation",entityType:"base"})}async generate(A,Q){await this.reportProgress(Q,{progress:10,message:"Generating note content with AI"});let B=await this.context.ai.generate({prompt:A.prompt,templateName:"note:generation"}),w=A.title??B.title;return await this.reportProgress(Q,{progress:50,message:`Generated note: "${w}"`}),{id:w,content:Gk.createNoteContent(w,B.body),metadata:{title:w},title:w,resultExtras:{title:w}}}summarizeDataForLog(A){return{prompt:A.prompt,title:A.title}}}var pY1={name:"@brains/note",private:!0,version:"0.2.0-alpha.93",description:"Personal knowledge capture with markdown-first workflow",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class u_A extends V2{entityType=Gk.entityType;schema=Jk;adapter=Gk;constructor(A={}){super("note",pY1,A,h_A)}createGenerationHandler(A){return new IwA(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:m_A}}async onRegister(A){A.eval.registerHandler("generateNote",async(Q)=>{let B=f.object({prompt:f.string()}).parse(Q);return A.ai.generate({prompt:B.prompt,templateName:"note:generation"})})}}function NV(A={}){return new u_A(A)}eA();fA();fA();eA();var lY1=f.object({ref:f.string(),label:f.string()}),iY1=f.enum(["pending","draft","published"]),qf=f.object({status:iY1,title:f.string(),url:f.string().url(),description:f.string().optional(),domain:f.string(),capturedAt:f.string().datetime(),source:lY1}),dY1=qf.pick({title:!0,status:!0}),cc=a1.extend({entityType:f.literal("link"),metadata:dY1}),c_A=f.object({enableSummarization:f.boolean().default(!0).describe("Generate AI summaries for captured links"),jinaApiKey:f.string().optional().describe("Jina Reader API key for higher rate limits (500 RPM vs 20 RPM without key)")});eA();class KN extends zQ{constructor(){super({entityType:"link",schema:cc,frontmatterSchema:qf})}createLinkContent(A){let Q={status:A.status,title:A.title,url:A.url,description:A.description,domain:A.domain,capturedAt:A.capturedAt,source:A.source},B=A.summary??"";return this.buildMarkdown(B,Q)}parseLinkContent(A){return{frontmatter:this.parseFrontMatter(A,qf),summary:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseLinkContent(A);return{content:A,entityType:"link",metadata:{title:Q.title,status:Q.status}}}}var p_A=new KN;eA();fA();var tW2=f.object({success:f.boolean().describe("Set to true if you can extract meaningful content. Set to false only if the provided content is empty, just an error message, or otherwise unusable."),error:f.string().describe("If success is false, explain why content could not be extracted. Use an empty string when success is true."),title:f.string().max(80).describe("The page title - extract from the content or create a descriptive one. Leave empty string if success is false."),description:f.string().describe("A one-sentence description of what the page is about. Leave empty string if success is false."),summary:f.string().describe("A 1-2 paragraph summary of the main content. Leave empty string if success is false.")}),rY1=R1({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:tW2,basePrompt:`You are an expert at extracting key information from webpage content.
|
|
5009
5021
|
|
|
5010
5022
|
You will receive webpage content in markdown format. Your job is to extract structured information from it.
|
|
5011
5023
|
|
|
@@ -5027,7 +5039,7 @@ Accuracy rules:
|
|
|
5027
5039
|
|
|
5028
5040
|
`))return{success:!1,error:D.trim(),errorType:"fetch_failed"};return{success:!0,content:D}}catch(B){return this.handleFetchError(B,A)}}handleHttpError(A,Q){if(A===400)return{success:!1,error:`Invalid or non-existent URL: ${Q}`,errorType:"url_not_found"};if(A===404)return{success:!1,error:`Page not found: ${Q}`,errorType:"url_not_found"};if(A>=500)return{success:!1,error:`Server error while fetching ${Q}`,errorType:"url_unreachable"};return{success:!1,error:`HTTP ${A} error while fetching ${Q}`,errorType:"fetch_failed"}}handleFetchError(A,Q){if(A instanceof Error){if(A.name==="AbortError")return{success:!1,error:`Request timeout while fetching ${Q}`,errorType:"url_unreachable"};if(A.message.includes("ENOTFOUND")||A.message.includes("getaddrinfo"))return{success:!1,error:`Domain not found: ${new URL(Q).hostname}`,errorType:"url_not_found"};if(A.message.includes("ECONNREFUSED")||A.message.includes("ETIMEDOUT"))return{success:!1,error:`Could not connect to ${Q}`,errorType:"url_unreachable"};return{success:!1,error:`Failed to fetch ${Q}: ${A.message}`,errorType:"fetch_failed"}}return{success:!1,error:`Unknown error fetching ${Q}`,errorType:"fetch_failed"}}}import{createHash as BH2}from"crypto";class qV{static URL_PATTERN=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi;static extractUrls(A){let Q=A.match(qV.URL_PATTERN)??[];return[...new Set(Q)]}static normalizeUrl(A){try{let Q=new URL(A),B=Q.pathname.replace(/\/$/,"")||"/";return`${Q.protocol}//${Q.host}${B}`}catch{return A}}static generateEntityId(A){let Q=this.normalizeUrl(A),B=BH2("sha256").update(Q).digest("hex");try{return`${new URL(Q).hostname.replace(/\./g,"-")}-${B.substring(0,6)}`}catch{return B.substring(0,12)}}static isValidUrl(A){try{let Q=new URL(A);return["http:","https:"].includes(Q.protocol)}catch{return!1}}}eA();fA();r$();var wH2=f.object({url:f.string().url(),metadata:f.object({interfaceId:f.string().optional(),userId:f.string().optional(),channelId:f.string().optional(),channelName:f.string().optional(),timestamp:f.string().optional()}).optional()}),uOw=f.object({success:f.boolean(),entityId:f.string().optional(),title:f.string().optional(),url:f.string().optional(),status:f.enum(["pending","draft","published"]).optional(),error:f.string().optional()});class YwA extends Sw{context;linkAdapter;urlFetcher;constructor(A,Q,B){super(A,{schema:wH2,jobTypeName:"link-capture"});this.context=Q,this.linkAdapter=new KN,this.urlFetcher=new Kk(B?.jinaApiKey?{jinaApiKey:B.jinaApiKey}:void 0)}async process(A,Q,B){let{url:w,metadata:$}=A;try{await B.report({progress:u2.START,total:100,message:"Starting link capture"});let I=qV.generateEntityId(w);await B.report({progress:u2.INIT,total:100,message:"Checking for existing link"});let D=await this.context.entityService.getEntity({entityType:"link",id:I});if(D){this.logger.info("Link already captured, returning existing",{url:w,entityId:I});let{frontmatter:Z}=this.linkAdapter.parseLinkContent(D.content);return{success:!0,entityId:D.id,title:Z.title,url:w,status:D.metadata.status}}await B.report({progress:u2.FETCH,total:100,message:"Fetching webpage content"});let Y=await this.urlFetcher.fetch(w);if(!Y.success){if(Y.errorType==="url_not_found"||Y.errorType==="url_unreachable")return this.logger.warn("Link URL not accessible",{url:w,errorType:Y.errorType,error:Y.error}),{success:!1,error:`Could not capture link: ${Y.error}`}}await B.report({progress:u2.PROCESS,total:100,message:"Extracting content with AI"});let X=await this.context.ai.generate({templateName:"link:extraction",prompt:Y.success?`Extract structured information from this webpage content:
|
|
5029
5041
|
|
|
5030
|
-
${Y.content}`:`The URL ${w} could not be fetched. Return success: false with error: "${Y.error}"`,data:{url:w,hasContent:Y.success},interfacePermissionGrant:"public"});this.logger.debug("AI extraction result",{result:X}),await B.report({progress:u2.EXTRACT,total:100,message:"Processing extraction results"});let W=this.resolveSource($),U=new Date().toISOString();if(X.success===!1||!X.title||!X.description||!X.summary){let Z=X.title||new URL(w).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:w}),await B.report({progress:u2.SAVE,total:100,message:"Saving link as pending"});let q=this.linkAdapter.createLinkContent({status:"pending",title:Z,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:U,source:W}),E=await this.context.entityService.createEntity({entity:{id:I,entityType:"link",content:q,metadata:{status:"pending",title:Z}}});return await B.report({progress:u2.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:E.entityId,title:Z,url:w,status:"pending"}}await B.report({progress:u2.SAVE,total:100,message:`Saving link: "${X.title}"`});let K=this.linkAdapter.createLinkContent({status:"draft",title:X.title,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:U,source:W}),F=await this.context.entityService.createEntity({entity:{id:I,entityType:"link",content:K,metadata:{status:"draft",title:X.title}}});return await B.report({progress:u2.COMPLETE,total:100,message:`Link captured: "${X.title}"`}),{success:!0,entityId:F.entityId,title:X.title,url:w,status:"draft"}}catch(I){return this.logger.error("Link capture job failed",{error:I,jobId:Q,data:A}),d$.failure(I)}}resolveSource(A){let Q=A?.channelId,B=A?.channelName;if(Q)return{ref:`matrix:${Q}`,label:B??Q};let w=A?.interfaceId??"cli";return{ref:`${w}:local`,label:w.toUpperCase()}}summarizeDataForLog(A){return{url:A.url,interfaceId:A.metadata?.interfaceId}}}var sY1={name:"@brains/link",private:!0,version:"0.2.0-alpha.
|
|
5042
|
+
${Y.content}`:`The URL ${w} could not be fetched. Return success: false with error: "${Y.error}"`,data:{url:w,hasContent:Y.success},interfacePermissionGrant:"public"});this.logger.debug("AI extraction result",{result:X}),await B.report({progress:u2.EXTRACT,total:100,message:"Processing extraction results"});let W=this.resolveSource($),U=new Date().toISOString();if(X.success===!1||!X.title||!X.description||!X.summary){let Z=X.title||new URL(w).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:w}),await B.report({progress:u2.SAVE,total:100,message:"Saving link as pending"});let q=this.linkAdapter.createLinkContent({status:"pending",title:Z,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:U,source:W}),E=await this.context.entityService.createEntity({entity:{id:I,entityType:"link",content:q,metadata:{status:"pending",title:Z}}});return await B.report({progress:u2.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:E.entityId,title:Z,url:w,status:"pending"}}await B.report({progress:u2.SAVE,total:100,message:`Saving link: "${X.title}"`});let K=this.linkAdapter.createLinkContent({status:"draft",title:X.title,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:U,source:W}),F=await this.context.entityService.createEntity({entity:{id:I,entityType:"link",content:K,metadata:{status:"draft",title:X.title}}});return await B.report({progress:u2.COMPLETE,total:100,message:`Link captured: "${X.title}"`}),{success:!0,entityId:F.entityId,title:X.title,url:w,status:"draft"}}catch(I){return this.logger.error("Link capture job failed",{error:I,jobId:Q,data:A}),d$.failure(I)}}resolveSource(A){let Q=A?.channelId,B=A?.channelName;if(Q)return{ref:`matrix:${Q}`,label:B??Q};let w=A?.interfaceId??"cli";return{ref:`${w}:local`,label:w.toUpperCase()}}summarizeDataForLog(A){return{url:A.url,interfaceId:A.metadata?.interfaceId}}}var sY1={name:"@brains/link",private:!0,version:"0.2.0-alpha.93",description:"Web content capture plugin with AI-powered extraction and structured storage",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class o_A extends V2{entityType=p_A.entityType;schema=cc;adapter=p_A;shell;constructor(A={}){super("link",sY1,A,c_A)}async register(A){this.shell=A;let Q=await super.register(A);if(!this.context)throw Error("LinkPlugin context was not initialized during register()");return A.getJobQueueService().registerHandler("link-capture",new YwA(this.logger.child("LinkCaptureJobHandler"),this.context,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0),this.id),Q}async interceptCreate(A,Q,B){if(A.content)try{let I=this.adapter.fromMarkdown(A.content).metadata,D=typeof I?.title==="string"?I.title:void 0,Y=typeof I?.status==="string"?I.status:void 0,X=this.extractFirstUrl(A.content);if(D&&Y&&X){let W=XQ(X)||XQ(D)||`${A.entityType}-${Date.now()}`,U=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await B.entityService.createEntity({entity:{id:W,entityType:A.entityType,content:A.content,metadata:{title:D,status:Y},created:U,updated:U}})).entityId,status:"created"}}}}}catch{}let w=A.url??this.extractFirstUrl(A.content,A.prompt,A.title);if(w){if(!this.shell)throw Error("LinkPlugin shell was not initialized during register()");try{return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await this.shell.getJobQueueService().enqueue({type:"link-capture",data:{url:w,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},options:{source:this.id,metadata:{operationType:"data_processing",pluginId:this.id,interfaceType:Q.interfaceType,...Q.channelId?{channelId:Q.channelId}:{}}}})}}}}catch($){return{kind:"handled",result:{success:!1,error:$ instanceof Error?$.message:"Failed to queue link capture job"}}}}if(A.content)return{kind:"handled",result:{success:!1,error:"Direct link creation requires full link markdown/frontmatter, or provide a URL to capture."}};if(A.prompt)return{kind:"handled",result:{success:!1,error:"Link creation requires a URL in the prompt, content, or title, or full link markdown content for direct creation."}};return{kind:"continue",input:A}}createGenerationHandler(A){return new YwA(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:rY1,"link-list":nY1,"link-detail":oY1}}getDataSources(){return[new n_A(this.logger.child("LinksDataSource"))]}async onRegister(A){A.eval.registerHandler("extractContent",async(Q)=>{let{url:B}=f.object({url:f.string().url()}).parse(Q),$=await new Kk(this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0).fetch(B);if(!$.success)return{success:!1,error:$.error,errorType:$.errorType};return A.ai.generate({templateName:"link:extraction",prompt:`Extract structured information from this webpage content:
|
|
5031
5043
|
|
|
5032
5044
|
${$.content}`,data:{url:B,hasContent:!0},interfacePermissionGrant:"public"})})}extractFirstUrl(...A){for(let Q of A){if(!Q)continue;let[B]=qV.extractUrls(Q);if(B)return B}return}}function aY1(A={}){return new o_A(A)}var LV=aY1;fA();var YRw=f.object({id:f.string().optional(),metadata:f.object({conversationId:f.string().optional(),interfaceId:f.string().optional(),userId:f.string().optional(),messageId:f.string().optional(),timestamp:f.string().optional()}).optional()});eA();fA();nw();fA();eA();var tY1=f.enum(["draft","published"]),dY=f.object({title:f.string(),slug:f.string().optional(),status:tY1,publishedAt:f.string().datetime().optional(),description:f.string(),year:f.number(),coverImageId:f.string().optional(),url:f.string().url().optional()}),eY1=dY.pick({title:!0,status:!0,publishedAt:!0,year:!0}).extend({slug:f.string()}),fk=a1.extend({entityType:f.literal("project"),metadata:eY1}),XwA=f.object({context:f.string(),problem:f.string(),solution:f.string(),outcome:f.string()}),lc=fk.extend({frontmatter:dY,body:f.string(),structuredContent:XwA.optional(),coverImageUrl:f.string().optional()}),Fk=lc.extend({url:f.string().optional(),typeLabel:f.string().optional(),coverImageUrl:f.string().optional(),coverImageWidth:f.number().optional(),coverImageHeight:f.number().optional()}),IH2=lc.extend({url:f.string(),typeLabel:f.string(),coverImageUrl:f.string().optional(),coverImageWidth:f.number().optional(),coverImageHeight:f.number().optional()});eA();fA();Z$();class s_A extends vB{constructor(){super(XwA,{title:"Project",mappings:[{key:"context",label:"Context",type:"string"},{key:"problem",label:"Problem",type:"string"},{key:"solution",label:"Solution",type:"string"},{key:"outcome",label:"Outcome",type:"string"}]})}}var a_A=new s_A;class t_A extends zQ{constructor(){super({entityType:"project",schema:fk,frontmatterSchema:dY,supportsCoverImage:!0,bodyFormatter:a_A})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,dY),w={...B,slug:B.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,dY),B=Q.slug??XQ(Q.title);return{content:A,entityType:"project",metadata:{title:Q.title,slug:B,status:Q.status,publishedAt:Q.publishedAt,year:Q.year}}}parseProjectFrontmatter(A){return this.parseFrontMatter(A.content,dY)}parseStructuredContent(A){return a_A.parse(this.extractBody(A.content))}createProjectContent(A,Q){let B=a_A.format(Q);return this.buildMarkdown(B,A)}}var fN=new t_A;fA();var e_A=f.object({});import{jsxDEV as PD,Fragment as YH2}from"preact/jsx-dev-runtime";var DH2=({project:A})=>{let{frontmatter:Q,url:B,coverImageUrl:w}=A;return PD(zB,{href:B,children:[w&&PD("img",{src:w,alt:Q.title,className:"w-full h-56 object-cover rounded-md mb-4"},void 0,!1,void 0,this),PD(k$,{children:Q.title},void 0,!1,void 0,this),PD("p",{className:"text-theme leading-relaxed",children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},AvA=({projects:A,pageTitle:Q,pagination:B,baseUrl:w="/projects"})=>{let $=Q??"Projects",I=B?.totalItems??A.length,D=`Browse all ${I} ${I===1?"project":"projects"}`;return PD(YH2,{children:[PD(Z2,{title:$,description:D},void 0,!1,void 0,this),PD("div",{className:"project-list bg-theme",children:PD("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[PD("h1",{className:"text-4xl font-bold text-heading mb-12",children:$},void 0,!1,void 0,this),PD("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:A.map((Y)=>PD(DH2,{project:Y},Y.id,!1,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&PD("div",{className:"mt-12",children:PD(If,{currentPage:B.currentPage,totalPages:B.totalPages,baseUrl:w},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as rB,Fragment as AX1}from"preact/jsx-dev-runtime";var XH2=({prevProject:A,nextProject:Q})=>{if(!A&&!Q)return null;return rB("nav",{className:"pt-12 mt-12 border-t border-theme-muted",children:rB("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[A?rB(zB,{href:A.url,variant:"compact",children:[rB("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Previous"},void 0,!1,void 0,this),rB("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:A.metadata.title},void 0,!1,void 0,this)]},void 0,!0,void 0,this):rB("div",{},void 0,!1,void 0,this),Q&&rB(zB,{href:Q.url,variant:"compact",className:"md:text-right",children:[rB("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Next"},void 0,!1,void 0,this),rB("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:Q.metadata.title},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},WwA=({title:A,content:Q})=>{if(!Q)return null;return rB("section",{className:"mb-12",children:[rB("h2",{className:"text-2xl font-bold text-heading mb-4",children:A},void 0,!1,void 0,this),rB(CD,{markdown:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},QvA=({project:A,prevProject:Q,nextProject:B})=>{let{frontmatter:w,structuredContent:$,metadata:I,coverImageUrl:D}=A;return rB(AX1,{children:[rB(Z2,{title:w.title,description:w.description,...D&&{ogImage:D},ogType:"article"},void 0,!1,void 0,this),rB("article",{className:"project-detail",children:rB("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:rB("div",{className:"max-w-3xl mx-auto",children:[D&&A.coverImageWidth&&A.coverImageHeight&&rB(wf,{src:D,alt:w.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8 shadow-lg"},void 0,!1,void 0,this),rB("h1",{className:"text-4xl md:text-5xl font-bold text-heading leading-tight tracking-tight mb-4",children:w.title},void 0,!1,void 0,this),rB("div",{className:"flex flex-wrap items-center gap-4 text-theme-muted mb-8",children:[rB("span",{className:"text-sm",children:I.year},void 0,!1,void 0,this),w.url&&rB(AX1,{children:[rB("span",{className:"text-theme-muted",children:"|"},void 0,!1,void 0,this),rB("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",className:"text-brand hover:text-brand-dark transition-colors",children:"View Project"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),rB("p",{className:"text-lg text-theme mb-12 leading-relaxed",children:w.description},void 0,!1,void 0,this),$&&rB("div",{className:"case-study",children:[rB(WwA,{title:"Context",content:$.context},void 0,!1,void 0,this),rB(WwA,{title:"Problem",content:$.problem},void 0,!1,void 0,this),rB(WwA,{title:"Solution",content:$.solution},void 0,!1,void 0,this),rB(WwA,{title:"Outcome",content:$.outcome},void 0,!1,void 0,this)]},void 0,!0,void 0,this),rB(XH2,{prevProject:Q,nextProject:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};fA();eA();var WH2=f.object({title:f.string().max(80).describe("A clear, compelling project title (3-8 words). Should capture the essence of the project."),description:f.string().describe("A 1-2 sentence summary of the project for portfolio cards. Focus on the core value delivered."),context:f.string().describe("Background information: Who was the client/user? What was the situation? What constraints existed? (2-4 paragraphs)"),problem:f.string().describe("The challenge: What specific problem needed solving? What were the pain points? (2-3 paragraphs)"),solution:f.string().describe("The approach: What was built? What technologies/methods were used? How did it work? (3-5 paragraphs)"),outcome:f.string().describe("The results: What impact did this have? What metrics improved? What was learned? (2-3 paragraphs)")}),BvA=R1({name:"portfolio:generation",description:"Template for AI to generate portfolio project case studies",schema:WH2,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create a professional portfolio case study based on REAL project information.
|
|
5033
5045
|
|
|
@@ -5051,7 +5063,7 @@ ${A.prompt}
|
|
|
5051
5063
|
|
|
5052
5064
|
Project year: ${A.year}
|
|
5053
5065
|
|
|
5054
|
-
Use the project request as the primary source of truth. If retrieved knowledge context describes a different project or conflicts with this request, ignore that unrelated context.`}class HwA extends S9{constructor(A,Q){super(A,Q,{schema:HH2,jobTypeName:"project-generation",entityType:"project"})}async generate(A,Q){let{year:B}=A;await this.reportProgress(Q,{progress:10,message:"Generating project content with AI"});let w=await this.context.ai.generate({prompt:wvA(A),templateName:"portfolio:generation"}),$=A.title??w.title,I=XQ($);await this.reportProgress(Q,{progress:50,message:`Generated project: "${$}"`});let D={title:$,slug:I,status:"draft",description:w.description,year:B},Y={context:w.context,problem:w.problem,solution:w.solution,outcome:w.outcome};return{id:I,content:fN.createProjectContent(D,Y),metadata:{title:$,slug:I,status:"draft",year:B},title:$,resultExtras:{title:$}}}summarizeDataForLog(A){return{prompt:A.prompt.substring(0,100),year:A.year,title:A.title}}}eA();eA();function UH2(A){let Q=$2(A.content,dY),B=fN.parseStructuredContent(A);return lc.parse({...A,frontmatter:Q.metadata,body:Q.content,structuredContent:B})}class UwA extends f5{id="portfolio:entities";name="Portfolio Project DataSource";description="Fetches and transforms project entities for rendering";config={entityType:"project",defaultSort:[{field:"year",direction:"desc"},{field:"title",direction:"asc"}],defaultLimit:10,enableNavigation:!0};constructor(A){super(A);this.logger.debug("ProjectDataSource initialized")}transformEntity(A){return UH2(A)}buildDetailResult(A,Q){return{project:A,prevProject:Q?.prev??null,nextProject:Q?.next??null}}buildListResult(A,Q,B){return{projects:A,pagination:Q,baseUrl:B.baseUrl}}}var QX1={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.
|
|
5066
|
+
Use the project request as the primary source of truth. If retrieved knowledge context describes a different project or conflicts with this request, ignore that unrelated context.`}class HwA extends S9{constructor(A,Q){super(A,Q,{schema:HH2,jobTypeName:"project-generation",entityType:"project"})}async generate(A,Q){let{year:B}=A;await this.reportProgress(Q,{progress:10,message:"Generating project content with AI"});let w=await this.context.ai.generate({prompt:wvA(A),templateName:"portfolio:generation"}),$=A.title??w.title,I=XQ($);await this.reportProgress(Q,{progress:50,message:`Generated project: "${$}"`});let D={title:$,slug:I,status:"draft",description:w.description,year:B},Y={context:w.context,problem:w.problem,solution:w.solution,outcome:w.outcome};return{id:I,content:fN.createProjectContent(D,Y),metadata:{title:$,slug:I,status:"draft",year:B},title:$,resultExtras:{title:$}}}summarizeDataForLog(A){return{prompt:A.prompt.substring(0,100),year:A.year,title:A.title}}}eA();eA();function UH2(A){let Q=$2(A.content,dY),B=fN.parseStructuredContent(A);return lc.parse({...A,frontmatter:Q.metadata,body:Q.content,structuredContent:B})}class UwA extends f5{id="portfolio:entities";name="Portfolio Project DataSource";description="Fetches and transforms project entities for rendering";config={entityType:"project",defaultSort:[{field:"year",direction:"desc"},{field:"title",direction:"asc"}],defaultLimit:10,enableNavigation:!0};constructor(A){super(A);this.logger.debug("ProjectDataSource initialized")}transformEntity(A){return UH2(A)}buildDetailResult(A,Q){return{project:A,prevProject:Q?.prev??null,nextProject:Q?.next??null}}buildListResult(A,Q,B){return{projects:A,pagination:Q,baseUrl:B.baseUrl}}}var QX1={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.93",description:"Portfolio showcase for projects and case studies",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest",typescript:"^5.3.3"}};var GH2=f.object({projects:f.array(Fk),pageTitle:f.string().optional(),pagination:T9.nullable(),baseUrl:f.string().optional()});function KH2(A,Q){for(let B of[A,Q]){let w=B?.match(/\b(19\d{2}|20\d{2})\b/);if(w?.[1])return Number(w[1])}return null}class $vA extends V2{entityType=fN.entityType;schema=fk;adapter=fN;constructor(A={}){super("portfolio",QX1,A,e_A)}async interceptCreate(A,Q,B){if(!A.prompt||A.content)return{kind:"continue",input:A};let w=KH2(A.title,A.prompt);if(!w)return{kind:"continue",input:A};return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await B.jobs.enqueue({type:"project:generation",data:{prompt:A.prompt,...A.title?{title:A.title}:{},year:w},toolContext:Q,options:{source:this.id,metadata:{operationType:"content_operations"}}})}}}}createGenerationHandler(A){return new HwA(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":R1({name:"project-list",description:"Portfolio project list page template",schema:GH2,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:AvA}}),"project-detail":R1({name:"project-detail",description:"Individual project case study template",schema:f.object({project:Fk,prevProject:Fk.nullable(),nextProject:Fk.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:QvA}}),generation:BvA}}getDataSources(){return[new UwA(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),await this.registerWithPublishPipeline(A),this.subscribeToPublishExecute(A)}registerEvalHandlers(A){A.eval.registerHandler("generateProject",async(Q)=>{let B=f.object({prompt:f.string(),year:f.number()}).parse(Q);return A.ai.generate({prompt:wvA(B),templateName:"portfolio:generation"})})}async registerWithPublishPipeline(A){let Q={name:"internal",publish:async()=>({id:"internal"})};await A.messaging.send({type:"publish:register",payload:{entityType:"project",provider:Q}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:B,entityId:w}=Q.payload;if(B!=="project")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"project",id:w});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:B,entityId:w,error:`Project not found: ${w}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let I=$2($.content,dY),D=new Date().toISOString(),Y=o$(I.content,{...I.metadata,status:"published",publishedAt:D});await A.entityService.updateEntity({entity:{...$,content:Y,metadata:{...$.metadata,status:"published",publishedAt:D}}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:B,entityId:w,publishedAt:D}})}catch($){await A.messaging.send({type:"publish:report:failure",payload:{entityType:B,entityId:w,error:S0($)}})}return{success:!0}})}}function IvA(A={}){return new $vA(A)}eA();fA();var fH2=f.enum(["public","shared","restricted"]),BX1=f.object({includeEntityTypes:f.array(f.string()).default([]),minRelevanceScore:f.number().min(0).max(1).default(0.5),mergeSimilarityThreshold:f.number().min(0).max(1).default(0.85),autoMerge:f.boolean().default(!0),extractableStatuses:f.array(f.string()).default(["published"]),enableAutoExtraction:f.boolean().default(!0),extractionVisibility:fH2.default("public"),sourceChangeBatchDelayMs:f.number().int().min(0).default(1000)});eA();fA();eA();var FH2=f.object({}),JwA=a1.extend({entityType:f.literal("topic"),metadata:FH2}),Ebw=f.object({content:f.string()}),wX1=f.object({title:f.string().describe("Topic title")});var EV="topics",nB="topic",DvA="topics-projection",$X1="topic:project",GwA="topics-plugin",IX1="topics:batch-completed",DX1="topics-source-batch";class Lf extends zQ{constructor(){super({entityType:nB,schema:JwA,frontmatterSchema:wX1})}buildFrontmatter(A){return{title:A}}toMarkdown(A){let Q=this.parseTopicBody(A.content);return this.buildMarkdown(Q.content,this.buildFrontmatter(Q.title))}fromMarkdown(A){return{content:A,entityType:nB}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseTopicBody(A.content),w=this.buildMarkdown("",this.buildFrontmatter(Q.title)).match(/^---\n[\s\S]*?\n---/);return w?w[0]:""}parseTopicBody(A){if(A.startsWith("---"))try{let Q=this.parseFrontmatter(A);return{content:this.extractBody(A).replace(/\n*## Sources[\s\S]*$/,"").trim(),formatted:A,title:Q.title}}catch{return{content:A,formatted:A,title:"Unknown Topic"}}return{content:A,formatted:A,title:"Unknown Topic"}}createTopicBody(A){return this.buildMarkdown(A.content,this.buildFrontmatter(A.title))}}eA();fA();fA();var ZH2=f.object({title:f.string().max(100),content:f.string(),relevanceScore:f.number().min(0).max(1)}),YX1=f.array(ZH2);var zH2=f.object({topics:YX1}),XX1=R1({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:zH2,basePrompt:`You are an expert at analyzing content and extracting key topics.
|
|
5055
5067
|
|
|
5056
5068
|
Analyze the provided content and extract meaningful topics discussed.
|
|
5057
5069
|
|
|
@@ -5154,13 +5166,13 @@ ${A.incomingTopic.content}`})}}function PH2(A){if(A.length===0)return"";return A
|
|
|
5154
5166
|
|
|
5155
5167
|
${Q.content}`}).join(`
|
|
5156
5168
|
|
|
5157
|
-
`)}async function VV(A,Q,B,w={}){if(A.length===0)return{created:0,merged:0,skipped:0,batches:0};let $=w.minRelevanceScore??0,I=w.autoMerge??!1,D=w.mergeSimilarityThreshold??0.85,Y=w.targetVisibility??"public",X=NX1(A),W=new QH(Q.entityService,B),U=w.topicMergeSynthesizer??new JvA(Q,B),K=await zwA(Q.entityService,void 0,Y),F=new Map,Z=0,q=0,E=0;for(let R of X){B.info(`Processing batch of ${R.length} entities`);let _=PH2(R),O=NwA({entityTitle:`Batch of ${R.length} entities`,entityType:"batch",content:_,existingTopicTitles:K});try{let n=(await Q.ai.generate({prompt:O,templateName:"topics:extraction"})).topics.filter((S)=>S.relevanceScore>=$);for(let S of n)try{if(I){let g=await W.findMergeCandidate({incoming:S,threshold:D,additionalCandidates:Array.from(F.values()),targetVisibility:Y});if(g){let e=await U.synthesize({existingTopic:g.topic,incomingTopic:S}),h=await W.applySynthesizedMerge({existingId:g.topic.id,synthesized:{...e,title:g.title},visibility:Y});if(!h)throw Error(`Failed to merge topic: ${S.title}`);F.set(h.id,h),q++;continue}}let x=W.getTopicIdForTitle(S.title,Y);if(F.has(x)){E++;continue}let T=await W.createTopicOptimistic({title:S.title,content:S.content,visibility:Y});if(T.topic)F.set(T.topic.id,T.topic);if(T.created)Z++;else E++}catch(x){B.error("Topic batch item failed",{title:S.title,error:S0(x)})}}catch(r){B.error("Batch topic extraction failed",{batchSize:R.length,promptChars:O.length,error:S0(r)})}}let L={created:Z,merged:q,skipped:E,batches:X.length};if(Z>0||q>0)await Q.messaging.send({type:IX1,payload:L,broadcast:!0});return L}eA();fA();var jH2=f.discriminatedUnion("mode",[f.object({mode:f.literal("derive"),reason:f.string().optional()}),f.object({mode:f.literal("rebuild"),reason:f.string().optional()}),f.object({mode:f.literal("source-batch"),minRelevanceScore:f.number().min(0).max(1).optional()})]);class GvA{refs=new Map;add(A){this.refs.set(`${A.entityType}:${A.entityId}`,A)}drain(){let A=Array.from(this.refs.values());return this.refs.clear(),A}}function CX1(A){let{context:Q,logger:B,config:w}=A;return{process:async($)=>{if($.mode==="derive")return await A.extractAllTopics(),{success:!0};if($.mode==="rebuild")return await A.rebuildAllTopics(),{success:!0};return kH2({context:Q,logger:B,config:w,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:$.minRelevanceScore??w.minRelevanceScore})},validateAndParse:($)=>{let I=jH2.safeParse($??{});return I.success?I.data:null}}}async function kH2(A){let Q=A.sourceBatch.drain(),B=await Promise.all(Q.map(async(W)=>({ref:W,entity:await A.context.entityService.getEntity({entityType:W.entityType,id:W.entityId})}))),w=0,$=0,I=0,D=0,Y=[];for(let{ref:W,entity:U}of B){if(!U){$++;continue}if(U.contentHash!==W.contentHash){w++;continue}if(!A.isEntityPublished(U)){I++;continue}if(!i3(U.visibility,A.config.extractionVisibility)){D++;continue}Y.push(U)}if(Y.length===0)return{success:!0,sources:Q.length,created:0,merged:0,skipped:0,batches:0,stale:w,missing:$,unpublished:I,hidden:D};let X=await VV(Y,A.context,A.logger,{minRelevanceScore:A.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});return{success:!0,sources:Q.length,...X,stale:w,missing:$,unpublished:I,hidden:D}}function OX1(){return{priority:5,source:GwA,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:EV}}}async function RX1(A){let Q=await PX1(A);if(Q.length===0){A.logger.info("No entities to extract topics from");return}A.logger.info(`Batch topic extraction: ${Q.length} entities`);let B=await VV(Q,A.context,A.logger,{minRelevanceScore:A.config.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});A.logger.info("Batch topic extraction complete",B)}async function bX1(A){let Q=await PX1(A),B=await KvA(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",B)}async function KvA(A,Q,B,w){let $=new QH(Q.entityService,B),I=await $.listTopics({visibility:w.extractionVisibility});for(let Y of I)await $.deleteTopic(Y.id);if(A.length===0)return{deleted:I.length,created:0,merged:0,skipped:0,batches:0};let D=await VV(A,Q,B,{minRelevanceScore:w.minRelevanceScore,autoMerge:w.autoMerge,mergeSimilarityThreshold:w.mergeSimilarityThreshold,targetVisibility:w.extractionVisibility});return{deleted:I.length,...D}}async function PX1(A){let Q=_H2(A),B=[];for(let w of Q){let $=await A.context.entityService.listEntities({entityType:w,options:{filter:{visibilityScope:A.config.extractionVisibility}}});for(let I of $){if(!A.isEntityPublished(I))continue;B.push(I)}}return B}function _H2(A){return A.context.entityService.getEntityTypes().filter((B)=>A.shouldProcessEntityType(B))}var Nk=f.object({entityType:f.string(),content:f.string(),metadata:f.record(f.unknown()).optional()}),vH2=Nk.extend({minRelevanceScore:f.number().optional()}),xH2=f.object({contentA:Nk,contentB:Nk,minRelevanceScore:f.number().optional(),threshold:f.number().min(0).max(1).optional()}),nc=f.object({title:f.string(),content:f.string()}),yH2=f.object({existingTopics:f.array(nc),incomingTopic:nc,threshold:f.number().optional()}),TH2=f.object({existingTopics:f.array(nc).default([]),incomingTopic:nc.extend({relevanceScore:f.number().min(0).max(1).optional()}),threshold:f.number().optional()}),SH2=f.object({entities:f.array(Nk).min(1),minRelevanceScore:f.number().optional()}),gH2=f.object({existingTopics:f.array(nc).optional(),entities:f.array(Nk)}),hH2=f.object({entities:f.array(Nk)});function zk(A,Q=""){return{id:`eval${Q}-${Date.now()}`,entityType:A.entityType,content:A.content,contentHash:RB(A.content),visibility:"public",metadata:A.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}}function jX1(A){return{title:A.title,relevanceScore:A.relevanceScore}}function mH2(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function uH2(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:mH2(Q)}]}}async function MV(A){let Q=await A.entityService.listEntities({entityType:nB});await Promise.all(Q.map((B)=>A.entityService.deleteEntity({entityType:nB,id:B.id})))}async function cH2(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise((B)=>setTimeout(B,100))}}function kX1(A){let{context:Q,logger:B,config:w}=A,$=new UvA(Q,B),I=async(D,Y,X="")=>{let W=zk(D,X);return $.extractFromEntity(W,Y)};Q.eval.registerHandler("extractFromEntity",async(D)=>{await MV(Q);let Y=vH2.parse(D),X=Y.minRelevanceScore??w.minRelevanceScore,W=zk(Y);return(await $.extractFromEntity(W,X)).map((K)=>uH2(K,W))}),Q.eval.registerHandler("checkMergeSimilarity",async(D)=>{await MV(Q);let Y=xH2.parse(D),X=Y.minRelevanceScore??w.minRelevanceScore,W=Y.threshold??w.mergeSimilarityThreshold,[U,K]=await Promise.all([I(Y.contentA,X,"-a"),I(Y.contentB,X,"-b")]),F=new QH(Q.entityService,B),Z=[];for(let L of U){let R=await F.createTopic(L);if(R)Z.push(R)}let q=(await Promise.all(K.map(async(L)=>{let R=await F.findMergeCandidate({incoming:L,threshold:W,additionalCandidates:Z});if(!R)return null;return{incomingTitle:L.title,candidateTitle:R.title,candidateScore:R.score}}))).filter((L)=>L!==null),E=q.map((L)=>L.candidateTitle);return{topicsA:U.map(jX1),topicsB:K.map(jX1),matchingTitles:E,mergeCandidates:q,wouldMerge:q.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(D)=>{await MV(Q);let Y=yH2.parse(D),X=Y.threshold??w.mergeSimilarityThreshold,W=new QH(Q.entityService,B),U=[];for(let F of Y.existingTopics){let Z=await W.createTopic(F);if(Z)U.push(Z)}let K=await W.findMergeCandidate({incoming:{title:Y.incomingTopic.title},threshold:X,additionalCandidates:U});return{found:K!==null,candidateTitle:K?.title,candidateScore:K?.score}}),Q.eval.registerHandler("processTopicWithAutoMerge",async(D)=>{await MV(Q);let Y=TH2.parse(D),X=new QH(Q.entityService,B);for(let F of Y.existingTopics)await X.createTopic({title:F.title,content:F.content});await cH2(Q);let W=zk({entityType:"post",content:Y.incomingTopic.content,metadata:{title:Y.incomingTopic.title}},"-source"),U=await VV([W],Q,B,{minRelevanceScore:0,autoMerge:!0,mergeSimilarityThreshold:Y.threshold??w.mergeSimilarityThreshold}),K=await Q.entityService.listEntities({entityType:nB});return{...U,topicCount:K.length,topics:K.map(WvA)}}),Q.eval.registerHandler("rebuildTopics",async(D)=>{await MV(Q);let Y=gH2.parse(D),X=new QH(Q.entityService,B);for(let F of Y.existingTopics??[])await X.createTopic(F);let W=Y.entities.map((F,Z)=>zk(F,`-rebuild-${Z}`)),U=await KvA(W,Q,B,w),K=await Q.entityService.listEntities({entityType:nB});return{...U,topicCount:K.length,topics:K.map(WvA)}}),Q.eval.registerHandler("extractSequentially",async(D)=>{await MV(Q);let Y=SH2.parse(D),X=Y.minRelevanceScore??w.minRelevanceScore,W=new QH(Q.entityService,B),U=[];for(let[F,Z]of Y.entities.entries()){let q=zk(Z,`-sequential-${F}`),E=await $.extractFromEntity(q,X);for(let L of E)await W.createTopic({title:L.title,content:L.content});U.push({extractedTitles:E.map((L)=>L.title)})}let K=await Q.entityService.listEntities({entityType:nB});return{totalTopics:K.length,perEntity:U,topics:K.map(Zk)}}),Q.eval.registerHandler("batchExtract",async(D)=>{await MV(Q);let X=hH2.parse(D).entities.map((K,F)=>zk(K,`-batch-${F}`)),W=await VV(X,Q,B,{minRelevanceScore:w.minRelevanceScore}),U=await Q.entityService.listEntities({entityType:nB});return{...W,topics:U.map(Zk)}})}var _X1={name:"@brains/topics",private:!0,version:"0.2.0-alpha.92",description:"Extract and manage topics from conversations",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var lH2=new Lf;class vX1 extends V2{entityType=nB;schema=JwA;adapter=lH2;sourceBatch=new GvA;constructor(A={}){super(EV,_X1,A,BX1)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:XX1,"merge-synthesis":WX1,"topic-list":HX1,"topic-detail":UX1}}getDataSources(){return[new HvA(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:DvA,targetType:nB,job:{type:$X1,handler:CX1({context:A,logger:this.logger,config:this.config,extractAllTopics:()=>this.extractAllTopics(A),rebuildAllTopics:()=>this.rebuildAllTopics(A),sourceBatch:this.sourceBatch,isEntityPublished:(Q)=>this.isEntityPublished(Q)})},initialSync:{shouldEnqueue:async()=>!await r3(A,nB,{visibility:this.config.extractionVisibility}),jobData:{mode:"derive",reason:"initial-sync"},jobOptions:OX1()},sourceChange:{sourceTypes:this.config.includeEntityTypes,requireInitialSync:!0,jobData:(Q)=>{let B=Q.entity;if(!B)return null;if(!this.shouldProcessEntityType(B.entityType,A.entityService))return null;if(!this.isEntityPublished(B))return null;if(!i3(B.visibility,this.config.extractionVisibility))return null;return this.sourceBatch.add({entityId:B.id,entityType:B.entityType,contentHash:B.contentHash}),{mode:"source-batch"}},jobOptions:()=>({priority:5,source:GwA,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:DX1,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:EV}})}}]}async onRegister(A){A.insights.register("topic-distribution",KX1()),fX1({context:A,pluginId:this.id}),kX1({context:A,logger:this.logger,config:this.config})}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(DvA)?.hasQueuedInitialSync()??!1}shouldProcessEntityType(A,Q){if(A===nB)return!1;if(!this.config.includeEntityTypes.includes(A))return!1;return Q.getEntityTypeConfig(A).projectionSource!==!1}isEntityPublished(A){let B=A.metadata.status;if(B===void 0||B===null)return!0;if(typeof B!=="string")return!1;return this.config.extractableStatuses.includes(B)}async extractAllTopics(A){await RX1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await bX1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function qwA(A){return new vX1(A)}eA();fA();eA();var xX1=f.enum(["linkedin"]),yX1=f.enum(["draft","queued","published","failed"]),TX1=f.enum(["post","deck"]),SX1=f.object({id:f.string().min(1).describe("Document entity ID")}),rY=f.object({title:f.string().describe("Short descriptive title (3-6 words) for file naming"),platform:xX1.describe("Target platform"),status:yX1,coverImageId:f.string().optional().describe("Image entity ID for post image"),documents:f.array(SX1).optional().describe("Document attachments for publishing"),publishedAt:f.string().datetime().optional(),platformPostId:f.string().optional().describe("ID from platform after publishing"),sourceEntityId:f.string().optional().describe("Source entity ID if auto-generated"),sourceEntityType:TX1.optional().describe("Source entity type (post, deck)")}),gX1=rY.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:f.string().describe("URL-friendly identifier: {platform}-{title}")}),qk=a1.extend({entityType:f.literal("social-post"),metadata:gX1}),LwA=qk.extend({frontmatter:rY,body:f.string()}),EwA=LwA.extend({url:f.string().optional(),listUrl:f.string().optional(),listLabel:f.string().optional(),typeLabel:f.string().optional(),coverImageUrl:f.string().optional(),coverImageWidth:f.number().optional(),coverImageHeight:f.number().optional()});eA();fA();class fvA extends zQ{constructor(){super({entityType:"social-post",schema:qk,frontmatterSchema:rY,supportsCoverImage:!0})}toMarkdown(A){let Q="",B={};try{B=this.parseFrontMatter(A.content,rY),Q=this.extractBody(A.content)}catch{Q=A.content}let w={...B,title:A.metadata.title,platform:A.metadata.platform,status:A.metadata.status,...A.metadata.publishedAt!==void 0&&{publishedAt:A.metadata.publishedAt},...A.metadata.platformPostId!==void 0&&{platformPostId:A.metadata.platformPostId}};return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,rY),B=`${Q.platform}-${XQ(Q.title)}`;return{content:A,entityType:"social-post",metadata:{title:Q.title,slug:B,platform:Q.platform,status:Q.status,publishedAt:Q.publishedAt,platformPostId:Q.platformPostId}}}parsePostFrontmatter(A){return this.parseFrontMatter(A.content,rY)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}}var II=new fvA;eA();eA();fA();var iH2=oH.extend({platform:f.enum(["linkedin"]).optional(),status:f.enum(["draft","queued","published","failed"]).optional(),sortByQueue:f.boolean().optional(),nextInQueue:f.boolean().optional()}),dH2=sH.extend({query:iH2.optional()});function hX1(A){let Q=$2(A.content,rY);return LwA.parse({...A,frontmatter:Q.metadata,body:Q.content})}class VwA extends f5{id="social-media:posts";name="Social Post DataSource";description="Fetches and transforms social post entities for queue management and publishing";config={entityType:"social-post",defaultSort:[{field:"publishedAt",direction:"desc",nullsFirst:!0},{field:"created",direction:"desc"}],defaultLimit:100};constructor(A){super(A);this.logger.debug("SocialPostDataSource initialized")}parseQuery(A){let Q=dH2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return hX1(A)}buildDetailResult(A,Q){return{post:A}}buildListResult(A,Q,B){return{posts:A,totalCount:Q?.totalItems??A.length,pagination:Q,baseUrl:B.baseUrl}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A),$=B.entityService;if(w.nextInQueue)return this.fetchNextInQueue(Q,$);if(w.id){let{item:U}=await this.fetchDetail(w.id,$);return Q.parse(this.buildDetailResult(U,null))}let I={};if(w.platform)I.platform=w.platform;if(w.status)I.status=w.status;let D=Object.keys(I).length>0,Y=w.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:X,pagination:W}=await this.fetchList(w,$,{...D&&{filter:{metadata:I}},sortFields:Y});return Q.parse(this.buildListResult(X,W,w))}async fetchNextInQueue(A,Q){let w=(await Q.listEntities({entityType:this.config.entityType,options:{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}}))[0],$=w?hX1(w):null;return A.parse({post:$})}}fA();var mX1=f.object({accessToken:f.string().optional(),refreshToken:f.string().optional(),organizationId:f.string().optional(),apiVersion:f.string().regex(/^\d{6}$/).optional()}),FvA=f.object({linkedin:mX1.optional(),publishInterval:f.number().default(3600000),enabled:f.boolean().default(!0),defaultPrompt:f.string().default("Create an engaging social media post that drives engagement"),maxRetries:f.number().default(3),autoGenerateOnBlogPublish:f.boolean().default(!1)});eA();fA();r$();zvA();import{jsxDEV as r6,Fragment as oH2}from"preact/jsx-dev-runtime";function rH2(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function nH2(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var CwA=({posts:A,pageTitle:Q,pagination:B,baseUrl:w="/social-posts"})=>{let $=Q??"Social Posts",I=B?.totalItems??A.length,D=`Browse all ${I} social ${I===1?"post":"posts"}`;return r6(oH2,{children:[r6(Z2,{title:$,description:D},void 0,!1,void 0,this),r6("div",{className:"social-post-list bg-theme",children:r6("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[r6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:$},void 0,!1,void 0,this),A.length===0?r6("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):r6("ul",{className:"space-y-6",children:A.map((Y)=>r6("li",{children:r6(zB,{href:Y.url,variant:"horizontal",children:r6("div",{className:"flex flex-col sm:flex-row gap-4",children:[Y.coverImageUrl&&r6("img",{src:Y.coverImageUrl,alt:Y.frontmatter.title,className:"w-full sm:w-24 h-48 sm:h-24 object-cover rounded-lg shrink-0"},void 0,!1,void 0,this),r6("div",{className:"flex-1 min-w-0",children:[r6("div",{className:"flex items-start justify-between gap-4 mb-2",children:[r6("h2",{className:"text-lg font-semibold text-heading",children:Y.frontmatter.title},void 0,!1,void 0,this),r6("time",{className:"text-sm text-theme-muted shrink-0",children:nH2(Y.frontmatter.publishedAt??Y.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r6("div",{className:"flex items-center gap-2 mb-3",children:[r6(BI,{status:Y.frontmatter.status},void 0,!1,void 0,this),r6("span",{className:"text-xs text-theme-muted uppercase",children:Y.frontmatter.platform},void 0,!1,void 0,this),r6("span",{className:"text-xs text-theme-muted font-mono",children:Y.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r6("p",{className:"text-theme leading-relaxed",children:rH2(Y.body,200)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},Y.id,!1,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&r6(If,{currentPage:B.currentPage,totalPages:B.totalPages,baseUrl:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as n6,Fragment as sH2}from"preact/jsx-dev-runtime";function uX1(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var OwA=({post:A})=>{let Q=`Social Post - ${A.frontmatter.platform}`,B=A.body.slice(0,160),w=[{label:"Home",href:"/"},{label:A.listLabel??"Social Posts",href:A.listUrl??"/social-posts"},{label:A.frontmatter.platform}];return n6(sH2,{children:[n6(Z2,{title:Q,description:B},void 0,!1,void 0,this),n6("section",{className:"social-post-detail",children:n6("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:n6("div",{className:"max-w-3xl mx-auto",children:[n6(wJ,{items:w},void 0,!1,void 0,this),n6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),n6("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[n6(BI,{status:A.frontmatter.status},void 0,!1,void 0,this),n6("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),n6("span",{className:"text-sm text-theme-muted font-mono",children:A.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.coverImageUrl&&A.coverImageWidth&&A.coverImageHeight&&n6(wf,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),n6(zB,{className:"p-8 mb-8",children:n6("p",{className:"text-lg text-theme leading-relaxed whitespace-pre-wrap",children:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),n6("div",{className:"space-y-4 text-sm text-theme-muted",children:[n6("div",{children:[n6("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",uX1(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&n6("div",{children:[n6("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",uX1(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&n6("div",{children:n6("a",{href:`https://www.linkedin.com/feed/update/${A.frontmatter.platformPostId}`,target:"_blank",rel:"noopener noreferrer",className:"text-brand hover:underline",children:"View on LinkedIn \u2192"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};function oc(A){return`social-media:${A}`}var aH2=f.union([f.boolean(),f.object({generate:f.boolean().optional(),prompt:f.string().optional()})]),NvA=f.object({prompt:f.string().optional(),platform:f.enum(["linkedin"]).optional(),sourceEntityType:f.enum(["post","deck"]).optional(),sourceEntityId:f.string().optional(),title:f.string().optional().describe("Required when content is provided directly"),content:f.string().optional(),addToQueue:f.boolean().optional(),generateImage:f.boolean().optional().describe("Auto-generate cover image for post"),coverImage:aH2.optional().describe("Generic cover image generation request")}),tH2=xI.extend({slug:f.string().optional()});class CV extends S9{constructor(A,Q){super(A,Q,{schema:NvA,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let B=A.platform??"linkedin",w=A.addToQueue??!1,{prompt:$,sourceEntityType:I,sourceEntityId:D}=A,{content:Y,title:X}=A;if(Y&&X)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(Y&&!X){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let L=await this.context.ai.generate({prompt:Y,templateName:oc(B)});X=L.title,Y=L.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(D&&I){await this.reportProgress(Q,{progress:10,message:`Fetching source ${I}`});let L=await this.context.entityService.getEntity({entityType:I,id:D});if(!L)this.failEarly(`Source entity not found: ${I}/${D}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let _=f.object({slug:f.string()}).safeParse(L.metadata),O=_.success?_.data.slug:D,r=await this.context.ai.generate({prompt:`Create an engaging ${B} post to promote this ${I}:
|
|
5169
|
+
`)}async function VV(A,Q,B,w={}){if(A.length===0)return{created:0,merged:0,skipped:0,batches:0};let $=w.minRelevanceScore??0,I=w.autoMerge??!1,D=w.mergeSimilarityThreshold??0.85,Y=w.targetVisibility??"public",X=NX1(A),W=new QH(Q.entityService,B),U=w.topicMergeSynthesizer??new JvA(Q,B),K=await zwA(Q.entityService,void 0,Y),F=new Map,Z=0,q=0,E=0;for(let R of X){B.info(`Processing batch of ${R.length} entities`);let _=PH2(R),O=NwA({entityTitle:`Batch of ${R.length} entities`,entityType:"batch",content:_,existingTopicTitles:K});try{let n=(await Q.ai.generate({prompt:O,templateName:"topics:extraction"})).topics.filter((S)=>S.relevanceScore>=$);for(let S of n)try{if(I){let g=await W.findMergeCandidate({incoming:S,threshold:D,additionalCandidates:Array.from(F.values()),targetVisibility:Y});if(g){let e=await U.synthesize({existingTopic:g.topic,incomingTopic:S}),h=await W.applySynthesizedMerge({existingId:g.topic.id,synthesized:{...e,title:g.title},visibility:Y});if(!h)throw Error(`Failed to merge topic: ${S.title}`);F.set(h.id,h),q++;continue}}let x=W.getTopicIdForTitle(S.title,Y);if(F.has(x)){E++;continue}let T=await W.createTopicOptimistic({title:S.title,content:S.content,visibility:Y});if(T.topic)F.set(T.topic.id,T.topic);if(T.created)Z++;else E++}catch(x){B.error("Topic batch item failed",{title:S.title,error:S0(x)})}}catch(r){B.error("Batch topic extraction failed",{batchSize:R.length,promptChars:O.length,error:S0(r)})}}let L={created:Z,merged:q,skipped:E,batches:X.length};if(Z>0||q>0)await Q.messaging.send({type:IX1,payload:L,broadcast:!0});return L}eA();fA();var jH2=f.discriminatedUnion("mode",[f.object({mode:f.literal("derive"),reason:f.string().optional()}),f.object({mode:f.literal("rebuild"),reason:f.string().optional()}),f.object({mode:f.literal("source-batch"),minRelevanceScore:f.number().min(0).max(1).optional()})]);class GvA{refs=new Map;add(A){this.refs.set(`${A.entityType}:${A.entityId}`,A)}drain(){let A=Array.from(this.refs.values());return this.refs.clear(),A}}function CX1(A){let{context:Q,logger:B,config:w}=A;return{process:async($)=>{if($.mode==="derive")return await A.extractAllTopics(),{success:!0};if($.mode==="rebuild")return await A.rebuildAllTopics(),{success:!0};return kH2({context:Q,logger:B,config:w,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:$.minRelevanceScore??w.minRelevanceScore})},validateAndParse:($)=>{let I=jH2.safeParse($??{});return I.success?I.data:null}}}async function kH2(A){let Q=A.sourceBatch.drain(),B=await Promise.all(Q.map(async(W)=>({ref:W,entity:await A.context.entityService.getEntity({entityType:W.entityType,id:W.entityId})}))),w=0,$=0,I=0,D=0,Y=[];for(let{ref:W,entity:U}of B){if(!U){$++;continue}if(U.contentHash!==W.contentHash){w++;continue}if(!A.isEntityPublished(U)){I++;continue}if(!i3(U.visibility,A.config.extractionVisibility)){D++;continue}Y.push(U)}if(Y.length===0)return{success:!0,sources:Q.length,created:0,merged:0,skipped:0,batches:0,stale:w,missing:$,unpublished:I,hidden:D};let X=await VV(Y,A.context,A.logger,{minRelevanceScore:A.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});return{success:!0,sources:Q.length,...X,stale:w,missing:$,unpublished:I,hidden:D}}function OX1(){return{priority:5,source:GwA,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:EV}}}async function RX1(A){let Q=await PX1(A);if(Q.length===0){A.logger.info("No entities to extract topics from");return}A.logger.info(`Batch topic extraction: ${Q.length} entities`);let B=await VV(Q,A.context,A.logger,{minRelevanceScore:A.config.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});A.logger.info("Batch topic extraction complete",B)}async function bX1(A){let Q=await PX1(A),B=await KvA(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",B)}async function KvA(A,Q,B,w){let $=new QH(Q.entityService,B),I=await $.listTopics({visibility:w.extractionVisibility});for(let Y of I)await $.deleteTopic(Y.id);if(A.length===0)return{deleted:I.length,created:0,merged:0,skipped:0,batches:0};let D=await VV(A,Q,B,{minRelevanceScore:w.minRelevanceScore,autoMerge:w.autoMerge,mergeSimilarityThreshold:w.mergeSimilarityThreshold,targetVisibility:w.extractionVisibility});return{deleted:I.length,...D}}async function PX1(A){let Q=_H2(A),B=[];for(let w of Q){let $=await A.context.entityService.listEntities({entityType:w,options:{filter:{visibilityScope:A.config.extractionVisibility}}});for(let I of $){if(!A.isEntityPublished(I))continue;B.push(I)}}return B}function _H2(A){return A.context.entityService.getEntityTypes().filter((B)=>A.shouldProcessEntityType(B))}var Nk=f.object({entityType:f.string(),content:f.string(),metadata:f.record(f.unknown()).optional()}),vH2=Nk.extend({minRelevanceScore:f.number().optional()}),xH2=f.object({contentA:Nk,contentB:Nk,minRelevanceScore:f.number().optional(),threshold:f.number().min(0).max(1).optional()}),nc=f.object({title:f.string(),content:f.string()}),yH2=f.object({existingTopics:f.array(nc),incomingTopic:nc,threshold:f.number().optional()}),TH2=f.object({existingTopics:f.array(nc).default([]),incomingTopic:nc.extend({relevanceScore:f.number().min(0).max(1).optional()}),threshold:f.number().optional()}),SH2=f.object({entities:f.array(Nk).min(1),minRelevanceScore:f.number().optional()}),gH2=f.object({existingTopics:f.array(nc).optional(),entities:f.array(Nk)}),hH2=f.object({entities:f.array(Nk)});function zk(A,Q=""){return{id:`eval${Q}-${Date.now()}`,entityType:A.entityType,content:A.content,contentHash:RB(A.content),visibility:"public",metadata:A.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}}function jX1(A){return{title:A.title,relevanceScore:A.relevanceScore}}function mH2(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function uH2(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:mH2(Q)}]}}async function MV(A){let Q=await A.entityService.listEntities({entityType:nB});await Promise.all(Q.map((B)=>A.entityService.deleteEntity({entityType:nB,id:B.id})))}async function cH2(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise((B)=>setTimeout(B,100))}}function kX1(A){let{context:Q,logger:B,config:w}=A,$=new UvA(Q,B),I=async(D,Y,X="")=>{let W=zk(D,X);return $.extractFromEntity(W,Y)};Q.eval.registerHandler("extractFromEntity",async(D)=>{await MV(Q);let Y=vH2.parse(D),X=Y.minRelevanceScore??w.minRelevanceScore,W=zk(Y);return(await $.extractFromEntity(W,X)).map((K)=>uH2(K,W))}),Q.eval.registerHandler("checkMergeSimilarity",async(D)=>{await MV(Q);let Y=xH2.parse(D),X=Y.minRelevanceScore??w.minRelevanceScore,W=Y.threshold??w.mergeSimilarityThreshold,[U,K]=await Promise.all([I(Y.contentA,X,"-a"),I(Y.contentB,X,"-b")]),F=new QH(Q.entityService,B),Z=[];for(let L of U){let R=await F.createTopic(L);if(R)Z.push(R)}let q=(await Promise.all(K.map(async(L)=>{let R=await F.findMergeCandidate({incoming:L,threshold:W,additionalCandidates:Z});if(!R)return null;return{incomingTitle:L.title,candidateTitle:R.title,candidateScore:R.score}}))).filter((L)=>L!==null),E=q.map((L)=>L.candidateTitle);return{topicsA:U.map(jX1),topicsB:K.map(jX1),matchingTitles:E,mergeCandidates:q,wouldMerge:q.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(D)=>{await MV(Q);let Y=yH2.parse(D),X=Y.threshold??w.mergeSimilarityThreshold,W=new QH(Q.entityService,B),U=[];for(let F of Y.existingTopics){let Z=await W.createTopic(F);if(Z)U.push(Z)}let K=await W.findMergeCandidate({incoming:{title:Y.incomingTopic.title},threshold:X,additionalCandidates:U});return{found:K!==null,candidateTitle:K?.title,candidateScore:K?.score}}),Q.eval.registerHandler("processTopicWithAutoMerge",async(D)=>{await MV(Q);let Y=TH2.parse(D),X=new QH(Q.entityService,B);for(let F of Y.existingTopics)await X.createTopic({title:F.title,content:F.content});await cH2(Q);let W=zk({entityType:"post",content:Y.incomingTopic.content,metadata:{title:Y.incomingTopic.title}},"-source"),U=await VV([W],Q,B,{minRelevanceScore:0,autoMerge:!0,mergeSimilarityThreshold:Y.threshold??w.mergeSimilarityThreshold}),K=await Q.entityService.listEntities({entityType:nB});return{...U,topicCount:K.length,topics:K.map(WvA)}}),Q.eval.registerHandler("rebuildTopics",async(D)=>{await MV(Q);let Y=gH2.parse(D),X=new QH(Q.entityService,B);for(let F of Y.existingTopics??[])await X.createTopic(F);let W=Y.entities.map((F,Z)=>zk(F,`-rebuild-${Z}`)),U=await KvA(W,Q,B,w),K=await Q.entityService.listEntities({entityType:nB});return{...U,topicCount:K.length,topics:K.map(WvA)}}),Q.eval.registerHandler("extractSequentially",async(D)=>{await MV(Q);let Y=SH2.parse(D),X=Y.minRelevanceScore??w.minRelevanceScore,W=new QH(Q.entityService,B),U=[];for(let[F,Z]of Y.entities.entries()){let q=zk(Z,`-sequential-${F}`),E=await $.extractFromEntity(q,X);for(let L of E)await W.createTopic({title:L.title,content:L.content});U.push({extractedTitles:E.map((L)=>L.title)})}let K=await Q.entityService.listEntities({entityType:nB});return{totalTopics:K.length,perEntity:U,topics:K.map(Zk)}}),Q.eval.registerHandler("batchExtract",async(D)=>{await MV(Q);let X=hH2.parse(D).entities.map((K,F)=>zk(K,`-batch-${F}`)),W=await VV(X,Q,B,{minRelevanceScore:w.minRelevanceScore}),U=await Q.entityService.listEntities({entityType:nB});return{...W,topics:U.map(Zk)}})}var _X1={name:"@brains/topics",private:!0,version:"0.2.0-alpha.93",description:"Extract and manage topics from conversations",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var lH2=new Lf;class vX1 extends V2{entityType=nB;schema=JwA;adapter=lH2;sourceBatch=new GvA;constructor(A={}){super(EV,_X1,A,BX1)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:XX1,"merge-synthesis":WX1,"topic-list":HX1,"topic-detail":UX1}}getDataSources(){return[new HvA(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:DvA,targetType:nB,job:{type:$X1,handler:CX1({context:A,logger:this.logger,config:this.config,extractAllTopics:()=>this.extractAllTopics(A),rebuildAllTopics:()=>this.rebuildAllTopics(A),sourceBatch:this.sourceBatch,isEntityPublished:(Q)=>this.isEntityPublished(Q)})},initialSync:{shouldEnqueue:async()=>!await r3(A,nB,{visibility:this.config.extractionVisibility}),jobData:{mode:"derive",reason:"initial-sync"},jobOptions:OX1()},sourceChange:{sourceTypes:this.config.includeEntityTypes,requireInitialSync:!0,jobData:(Q)=>{let B=Q.entity;if(!B)return null;if(!this.shouldProcessEntityType(B.entityType,A.entityService))return null;if(!this.isEntityPublished(B))return null;if(!i3(B.visibility,this.config.extractionVisibility))return null;return this.sourceBatch.add({entityId:B.id,entityType:B.entityType,contentHash:B.contentHash}),{mode:"source-batch"}},jobOptions:()=>({priority:5,source:GwA,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:DX1,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:EV}})}}]}async onRegister(A){A.insights.register("topic-distribution",KX1()),fX1({context:A,pluginId:this.id}),kX1({context:A,logger:this.logger,config:this.config})}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(DvA)?.hasQueuedInitialSync()??!1}shouldProcessEntityType(A,Q){if(A===nB)return!1;if(!this.config.includeEntityTypes.includes(A))return!1;return Q.getEntityTypeConfig(A).projectionSource!==!1}isEntityPublished(A){let B=A.metadata.status;if(B===void 0||B===null)return!0;if(typeof B!=="string")return!1;return this.config.extractableStatuses.includes(B)}async extractAllTopics(A){await RX1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await bX1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function qwA(A){return new vX1(A)}eA();fA();eA();var xX1=f.enum(["linkedin"]),yX1=f.enum(["draft","queued","published","failed"]),TX1=f.enum(["post","deck"]),SX1=f.object({id:f.string().min(1).describe("Document entity ID")}),rY=f.object({title:f.string().describe("Short descriptive title (3-6 words) for file naming"),platform:xX1.describe("Target platform"),status:yX1,coverImageId:f.string().optional().describe("Image entity ID for post image"),documents:f.array(SX1).optional().describe("Document attachments for publishing"),publishedAt:f.string().datetime().optional(),platformPostId:f.string().optional().describe("ID from platform after publishing"),sourceEntityId:f.string().optional().describe("Source entity ID if auto-generated"),sourceEntityType:TX1.optional().describe("Source entity type (post, deck)")}),gX1=rY.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:f.string().describe("URL-friendly identifier: {platform}-{title}")}),qk=a1.extend({entityType:f.literal("social-post"),metadata:gX1}),LwA=qk.extend({frontmatter:rY,body:f.string()}),EwA=LwA.extend({url:f.string().optional(),listUrl:f.string().optional(),listLabel:f.string().optional(),typeLabel:f.string().optional(),coverImageUrl:f.string().optional(),coverImageWidth:f.number().optional(),coverImageHeight:f.number().optional()});eA();fA();class fvA extends zQ{constructor(){super({entityType:"social-post",schema:qk,frontmatterSchema:rY,supportsCoverImage:!0})}toMarkdown(A){let Q="",B={};try{B=this.parseFrontMatter(A.content,rY),Q=this.extractBody(A.content)}catch{Q=A.content}let w={...B,title:A.metadata.title,platform:A.metadata.platform,status:A.metadata.status,...A.metadata.publishedAt!==void 0&&{publishedAt:A.metadata.publishedAt},...A.metadata.platformPostId!==void 0&&{platformPostId:A.metadata.platformPostId}};return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,rY),B=`${Q.platform}-${XQ(Q.title)}`;return{content:A,entityType:"social-post",metadata:{title:Q.title,slug:B,platform:Q.platform,status:Q.status,publishedAt:Q.publishedAt,platformPostId:Q.platformPostId}}}parsePostFrontmatter(A){return this.parseFrontMatter(A.content,rY)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}}var II=new fvA;eA();eA();fA();var iH2=oH.extend({platform:f.enum(["linkedin"]).optional(),status:f.enum(["draft","queued","published","failed"]).optional(),sortByQueue:f.boolean().optional(),nextInQueue:f.boolean().optional()}),dH2=sH.extend({query:iH2.optional()});function hX1(A){let Q=$2(A.content,rY);return LwA.parse({...A,frontmatter:Q.metadata,body:Q.content})}class VwA extends f5{id="social-media:posts";name="Social Post DataSource";description="Fetches and transforms social post entities for queue management and publishing";config={entityType:"social-post",defaultSort:[{field:"publishedAt",direction:"desc",nullsFirst:!0},{field:"created",direction:"desc"}],defaultLimit:100};constructor(A){super(A);this.logger.debug("SocialPostDataSource initialized")}parseQuery(A){let Q=dH2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return hX1(A)}buildDetailResult(A,Q){return{post:A}}buildListResult(A,Q,B){return{posts:A,totalCount:Q?.totalItems??A.length,pagination:Q,baseUrl:B.baseUrl}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A),$=B.entityService;if(w.nextInQueue)return this.fetchNextInQueue(Q,$);if(w.id){let{item:U}=await this.fetchDetail(w.id,$);return Q.parse(this.buildDetailResult(U,null))}let I={};if(w.platform)I.platform=w.platform;if(w.status)I.status=w.status;let D=Object.keys(I).length>0,Y=w.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:X,pagination:W}=await this.fetchList(w,$,{...D&&{filter:{metadata:I}},sortFields:Y});return Q.parse(this.buildListResult(X,W,w))}async fetchNextInQueue(A,Q){let w=(await Q.listEntities({entityType:this.config.entityType,options:{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}}))[0],$=w?hX1(w):null;return A.parse({post:$})}}fA();var mX1=f.object({accessToken:f.string().optional(),refreshToken:f.string().optional(),organizationId:f.string().optional(),apiVersion:f.string().regex(/^\d{6}$/).optional()}),FvA=f.object({linkedin:mX1.optional(),publishInterval:f.number().default(3600000),enabled:f.boolean().default(!0),defaultPrompt:f.string().default("Create an engaging social media post that drives engagement"),maxRetries:f.number().default(3),autoGenerateOnBlogPublish:f.boolean().default(!1)});eA();fA();r$();zvA();import{jsxDEV as r6,Fragment as oH2}from"preact/jsx-dev-runtime";function rH2(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function nH2(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var CwA=({posts:A,pageTitle:Q,pagination:B,baseUrl:w="/social-posts"})=>{let $=Q??"Social Posts",I=B?.totalItems??A.length,D=`Browse all ${I} social ${I===1?"post":"posts"}`;return r6(oH2,{children:[r6(Z2,{title:$,description:D},void 0,!1,void 0,this),r6("div",{className:"social-post-list bg-theme",children:r6("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[r6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:$},void 0,!1,void 0,this),A.length===0?r6("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):r6("ul",{className:"space-y-6",children:A.map((Y)=>r6("li",{children:r6(zB,{href:Y.url,variant:"horizontal",children:r6("div",{className:"flex flex-col sm:flex-row gap-4",children:[Y.coverImageUrl&&r6("img",{src:Y.coverImageUrl,alt:Y.frontmatter.title,className:"w-full sm:w-24 h-48 sm:h-24 object-cover rounded-lg shrink-0"},void 0,!1,void 0,this),r6("div",{className:"flex-1 min-w-0",children:[r6("div",{className:"flex items-start justify-between gap-4 mb-2",children:[r6("h2",{className:"text-lg font-semibold text-heading",children:Y.frontmatter.title},void 0,!1,void 0,this),r6("time",{className:"text-sm text-theme-muted shrink-0",children:nH2(Y.frontmatter.publishedAt??Y.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r6("div",{className:"flex items-center gap-2 mb-3",children:[r6(BI,{status:Y.frontmatter.status},void 0,!1,void 0,this),r6("span",{className:"text-xs text-theme-muted uppercase",children:Y.frontmatter.platform},void 0,!1,void 0,this),r6("span",{className:"text-xs text-theme-muted font-mono",children:Y.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),r6("p",{className:"text-theme leading-relaxed",children:rH2(Y.body,200)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},Y.id,!1,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&r6(If,{currentPage:B.currentPage,totalPages:B.totalPages,baseUrl:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as n6,Fragment as sH2}from"preact/jsx-dev-runtime";function uX1(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var OwA=({post:A})=>{let Q=`Social Post - ${A.frontmatter.platform}`,B=A.body.slice(0,160),w=[{label:"Home",href:"/"},{label:A.listLabel??"Social Posts",href:A.listUrl??"/social-posts"},{label:A.frontmatter.platform}];return n6(sH2,{children:[n6(Z2,{title:Q,description:B},void 0,!1,void 0,this),n6("section",{className:"social-post-detail",children:n6("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:n6("div",{className:"max-w-3xl mx-auto",children:[n6(wJ,{items:w},void 0,!1,void 0,this),n6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),n6("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[n6(BI,{status:A.frontmatter.status},void 0,!1,void 0,this),n6("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),n6("span",{className:"text-sm text-theme-muted font-mono",children:A.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.coverImageUrl&&A.coverImageWidth&&A.coverImageHeight&&n6(wf,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),n6(zB,{className:"p-8 mb-8",children:n6("p",{className:"text-lg text-theme leading-relaxed whitespace-pre-wrap",children:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),n6("div",{className:"space-y-4 text-sm text-theme-muted",children:[n6("div",{children:[n6("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",uX1(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&n6("div",{children:[n6("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",uX1(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&n6("div",{children:n6("a",{href:`https://www.linkedin.com/feed/update/${A.frontmatter.platformPostId}`,target:"_blank",rel:"noopener noreferrer",className:"text-brand hover:underline",children:"View on LinkedIn \u2192"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};function oc(A){return`social-media:${A}`}var aH2=f.union([f.boolean(),f.object({generate:f.boolean().optional(),prompt:f.string().optional()})]),NvA=f.object({prompt:f.string().optional(),platform:f.enum(["linkedin"]).optional(),sourceEntityType:f.enum(["post","deck"]).optional(),sourceEntityId:f.string().optional(),title:f.string().optional().describe("Required when content is provided directly"),content:f.string().optional(),addToQueue:f.boolean().optional(),generateImage:f.boolean().optional().describe("Auto-generate cover image for post"),coverImage:aH2.optional().describe("Generic cover image generation request")}),tH2=xI.extend({slug:f.string().optional()});class CV extends S9{constructor(A,Q){super(A,Q,{schema:NvA,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let B=A.platform??"linkedin",w=A.addToQueue??!1,{prompt:$,sourceEntityType:I,sourceEntityId:D}=A,{content:Y,title:X}=A;if(Y&&X)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(Y&&!X){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let L=await this.context.ai.generate({prompt:Y,templateName:oc(B)});X=L.title,Y=L.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(D&&I){await this.reportProgress(Q,{progress:10,message:`Fetching source ${I}`});let L=await this.context.entityService.getEntity({entityType:I,id:D});if(!L)this.failEarly(`Source entity not found: ${I}/${D}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let _=f.object({slug:f.string()}).safeParse(L.metadata),O=_.success?_.data.slug:D,r=await this.context.ai.generate({prompt:`Create an engaging ${B} post to promote this ${I}:
|
|
5158
5170
|
|
|
5159
5171
|
Source: ${I}/${O}
|
|
5160
5172
|
|
|
5161
5173
|
${L.content}`,templateName:oc(B)});X=r.title,Y=r.content,await this.reportProgress(Q,{progress:50,message:"Social post generated from source"})}else if($){await this.reportProgress(Q,{progress:10,message:"Generating social post with AI"});let L=await this.context.ai.generate({prompt:$,templateName:oc(B)});X=L.title,Y=L.content,await this.reportProgress(Q,{progress:50,message:"Social post generated"})}else this.failEarly("No content source provided (prompt, sourceEntityId, or content)");if(!Y||!X)this.failEarly("Content or title was not generated");let U={title:X,platform:B,status:w?"queued":"draft",...D&&{sourceEntityId:D},...I&&{sourceEntityType:I}},K=II.createPostContent(U,Y),Z=II.fromMarkdown(K).metadata;if(!Z)this.failEarly("Failed to parse social post metadata");let q=await PG({entityType:"social-post",title:X,deriveId:(L)=>`${B}-${XQ(L)}`,regeneratePrompt:"Generate a different social media post title on the same topic.",context:this.context}),E=K;if(q!==X){Z.title=q,Z.slug=`${B}-${XQ(q)}`;let L={...U,title:q};E=II.createPostContent(L,Y)}return{id:Z.slug,content:E,metadata:Z,title:q,resultExtras:{slug:Z.slug},createOptions:{deduplicateId:!0}}}async onGenerationFailure(A,Q){await this.context.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:Q}})}async afterCreate(A,Q,B,w){if(A.generateImage){await this.reportProgress(B,{progress:90,message:"Queueing image generation"});let $=w.title??"Social Post";await this.context.jobs.enqueue({type:"image:image-generate",data:{prompt:`Social media graphic for: ${$}`,title:`${$} Image`,aspectRatio:"16:9",targetEntityType:"social-post",targetEntityId:Q},toolContext:{interfaceType:"job",userId:"system"}})}await this.context.messaging.send({type:"generate:report:success",payload:{entityType:"social-post",entityId:Q}})}summarizeDataForLog(A){return{platform:A.platform??"linkedin",hasPrompt:!!A.prompt,sourceEntityType:A.sourceEntityType,addToQueue:A.addToQueue??!1,generateImage:A.generateImage??!1,coverImage:!!A.coverImage}}}function sc(A){if(A.length<=200)return A;return`${A.slice(0,200)}\u2026 (truncated, ${A.length} bytes)`}function eH2(A){let Q={status:"READY",media:A.urn};if(A.title)Q.title={text:A.title};return Q}function AU2(A){if(!qvA(A))return null;let Q=RwA(A,"value");if(!Q)return null;let B=RwA(Q,"uploadMechanism");if(!B)return null;let w=RwA(B,"com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest");if(!w)return null;let $=w.uploadUrl,I=Q.asset;if(typeof $!=="string"||typeof I!=="string")return null;return{uploadUrl:$,assetUrn:I}}function QU2(A){if(!qvA(A))return null;let Q=RwA(A,"value");if(!Q)return null;let{uploadUrl:B,document:w}=Q;if(typeof B!=="string"||typeof w!=="string")return null;return{uploadUrl:B,documentUrn:w}}function RwA(A,Q){let B=A[Q];return qvA(B)?B:null}function qvA(A){return typeof A==="object"&&A!==null}var BU2="202604";class LvA{config;logger;name="linkedin";apiBaseUrl="https://api.linkedin.com/v2";restApiBaseUrl="https://api.linkedin.com/rest";fetch;cachedUserId=null;constructor(A,Q,B={}){this.config=A;this.logger=Q;this.fetch=B.fetch??globalThis.fetch.bind(globalThis)}async publish(A,Q,B,w){if(!this.config.accessToken)throw Error("LinkedIn access token not configured");let $=await this.getAuthor(),I=w?.[0];if(w&&w.length>1)this.logger.warn("LinkedIn document publishing supports one PDF",{count:w.length});let D=null;if(I){let K=await this.uploadDocument($,I);return this.publishDocumentPost($,A,K,I.filename)}else if(B){let K=await this.uploadImage($,B);if(K)D={category:"IMAGE",urn:K}}let Y={shareCommentary:{text:A},shareMediaCategory:D?.category??"NONE",...D&&{media:[eH2(D)]}},X=await this.fetch(`${this.apiBaseUrl}/ugcPosts`,{method:"POST",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:$,lifecycleState:"PUBLISHED",specificContent:{"com.linkedin.ugc.ShareContent":Y},visibility:{"com.linkedin.ugc.MemberNetworkVisibility":"PUBLIC"}})});if(!X.ok){let K=sc(await X.text());throw this.logger.error("LinkedIn API error",{status:X.status,error:K}),Error(`LinkedIn API error: ${X.status} - ${K}`)}let W=X.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn post created",{postId:W,mediaCategory:D?.category??"NONE"});let U={id:W};if(W)U.url=`https://www.linkedin.com/feed/update/${W}`;return U}getRestHeaders(){return{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","Linkedin-Version":this.config.apiVersion??BU2,"X-Restli-Protocol-Version":"2.0.0"}}async uploadImage(A,Q){try{let B=await this.fetch(`${this.apiBaseUrl}/assets?action=registerUpload`,{method:"POST",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({registerUploadRequest:{recipes:["urn:li:digitalmediaRecipe:feedshare-image"],owner:A,serviceRelationships:[{relationshipType:"OWNER",identifier:"urn:li:userGeneratedContent"}]}})});if(!B.ok){let Y=sc(await B.text());return this.logger.warn("LinkedIn image upload registration failed",{status:B.status,error:Y}),null}let w=AU2(await B.json());if(!w)return this.logger.warn("LinkedIn image upload registration was malformed"),null;let{uploadUrl:$,assetUrn:I}=w,D=await this.fetch($,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!D.ok)return this.logger.warn("LinkedIn image binary upload failed",{status:D.status}),null;return this.logger.info("LinkedIn image uploaded",{assetUrn:I}),I}catch(B){return this.logger.warn("LinkedIn image upload error",{error:B}),null}}async uploadDocument(A,Q){let B=await this.fetch(`${this.restApiBaseUrl}/documents?action=initializeUpload`,{method:"POST",headers:this.getRestHeaders(),body:JSON.stringify({initializeUploadRequest:{owner:A}})});if(!B.ok){let I=sc(await B.text());throw Error(`LinkedIn document upload initialization failed: ${B.status} - ${I}`)}let w=QU2(await B.json());if(!w)throw Error("LinkedIn document upload initialization was malformed");let $=await this.fetch(w.uploadUrl,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!$.ok)throw Error(`LinkedIn document binary upload failed: ${$.status}`);return this.logger.info("LinkedIn document uploaded",{documentUrn:w.documentUrn,filename:Q.filename}),w.documentUrn}async publishDocumentPost(A,Q,B,w){let $=await this.fetch(`${this.restApiBaseUrl}/posts`,{method:"POST",headers:this.getRestHeaders(),body:JSON.stringify({author:A,commentary:Q,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},content:{media:{id:B,title:w}},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1})});if(!$.ok){let Y=sc(await $.text());throw this.logger.error("LinkedIn document post API error",{status:$.status,error:Y}),Error(`LinkedIn document post API error: ${$.status} - ${Y}`)}let I=$.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn document post created",{postId:I,documentUrn:B});let D={id:I};if(I)D.url=`https://www.linkedin.com/feed/update/${I}`;return D}async validateCredentials(){if(!this.config.accessToken)return!1;try{if(this.config.organizationId)return(await this.fetch(`${this.apiBaseUrl}/organizations/${this.config.organizationId}`,{headers:{Authorization:`Bearer ${this.config.accessToken}`}})).ok;return await this.getUserId(),!0}catch{return!1}}async getAuthor(){if(this.config.organizationId)return`urn:li:organization:${this.config.organizationId}`;return this.getUserId()}async getUserId(){if(this.cachedUserId)return this.cachedUserId;if(!this.config.accessToken)throw Error("LinkedIn access token not configured");try{let B=await this.fetch("https://api.linkedin.com/v2/userinfo",{headers:{Authorization:`Bearer ${this.config.accessToken}`}});if(B.ok){let w=await B.json();return this.cachedUserId=`urn:li:person:${w.sub}`,this.cachedUserId}}catch{}let A=await this.fetch("https://api.linkedin.com/v2/me",{headers:{Authorization:`Bearer ${this.config.accessToken}`}});if(!A.ok){let B=sc(await A.text());throw Error(`Failed to get LinkedIn user ID: ${A.status} - ${B}`)}let Q=await A.json();return this.cachedUserId=`urn:li:person:${Q.id}`,this.cachedUserId}}function EvA(A,Q,B={}){return new LvA(A,Q,B)}eA();fA();nw();zvA();var wU2=f.object({posts:f.array(EwA),totalCount:f.number().optional(),pagination:T9.nullable(),baseUrl:f.string().optional()}),$U2=f.object({post:EwA});function cX1(){return{linkedin:MwA,"social-post-list":R1({name:"social-post-list",description:"Social post list page template",schema:wU2,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:CwA}}),"social-post-detail":R1({name:"social-post-detail",description:"Individual social post template",schema:$U2,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:OwA}})}}fA();var IU2=f.object({prompt:f.string().optional(),content:f.string().optional(),platform:f.enum(["linkedin"]).default("linkedin")}),DU2=f.object({prompt:f.string().optional(),content:f.string().optional(),title:f.string().optional(),platform:f.enum(["linkedin"]).optional()});function pX1(A){A.eval.registerHandler("generation",async(Q)=>{let B=IU2.parse(Q),w=B.content?`Create an engaging LinkedIn post to share this content:
|
|
5162
5174
|
|
|
5163
|
-
${B.content}`:B.prompt??"Write an engaging LinkedIn post";return A.ai.generate({prompt:w,templateName:`social-media:${B.platform}`})}),A.eval.registerHandler("create",async(Q)=>{let B=DU2.parse(Q),w=[],$=p$.from(async(W)=>{let U={progress:W.progress};if(W.message!==void 0)U.message=W.message;w.push(U)});if(!$)throw Error("Failed to create progress reporter");let D=await new CV(A.logger,A).process(B,`eval-${Date.now()}`,$),Y=!1,X;if(D.success&&D.entityId){let W=await A.entityService.getEntity({entityType:"social-post",id:D.entityId});Y=!!W,X=W?.content.slice(0,300)}return{...D,entityExists:Y,entityPreview:X,progressSteps:w}})}fA();eA();class ac{sendMessage;logger;entityService;providers;resolveAttachment;constructor(A){this.sendMessage=A.sendMessage,this.logger=A.logger,this.entityService=A.entityService,this.providers=A.providers,this.resolveAttachment=A.resolveAttachment}async handle(A){let{entityType:Q,entityId:B}=A;if(Q!=="social-post")return;this.logger.debug("Handling publish:execute",{entityId:B});try{let w=await this.entityService.getEntity({entityType:"social-post",id:B});if(!w){await this.reportFailure(Q,B,`Post not found: ${B}`);return}if(w.metadata.status==="published"){this.logger.debug("Post already published, skipping",{entityId:B});return}let $=w.metadata.platform,I=this.providers.get($);if(!I){await this.reportFailure(Q,B,`No provider configured for platform: ${$}`);return}let D=$2(w.content,rY),Y;if(D.metadata.coverImageId)Y=await this.fetchImageData(D.metadata.coverImageId);let X=D.metadata.documents??[],W=await this.fetchDocumentData(X);try{if(X.length>0&&W.length===0)throw Error(`Refusing to publish: ${X.length} document(s) referenced but none could be fetched`);let U=X.length===0?await this.resolveSourceAttachment(D.metadata):[],K=W.length>0?W:U,F=K.length?await I.publish(D.content,w.metadata,Y,K):await I.publish(D.content,w.metadata,Y),Z=new Date().toISOString(),q=F.id||void 0,E={...D.metadata,status:"published",publishedAt:Z,...q&&{platformPostId:q}},L=II.createPostContent(E,D.content);await this.entityService.updateEntity({entity:{...w,content:L,metadata:{...w.metadata,status:"published",publishedAt:Z,platformPostId:q}}}),await this.reportSuccess(Q,B,F.id),this.logger.info(`Post published successfully: ${B}`,{platform:$,platformPostId:q})}catch(U){let K=U instanceof Error?U.message:String(U),F={...D.metadata,status:"failed"},Z=II.createPostContent(F,D.content);await this.entityService.updateEntity({entity:{...w,content:Z,metadata:{...w.metadata,status:"failed"}}}),await this.reportFailure(Q,B,K),this.logger.error(`Post publish failed: ${B}`,{platform:$,error:K})}}catch(w){let $=S0(w);this.logger.error("Unexpected error in publish handler",{entityId:B,error:$}),await this.reportFailure(Q,B,$)}}async reportSuccess(A,Q,B){await this.sendMessage({type:"publish:report:success",payload:{entityType:A,entityId:Q,result:{id:B}}})}async reportFailure(A,Q,B){await this.sendMessage({type:"publish:report:failure",payload:{entityType:A,entityId:Q,error:B}})}async resolveSourceAttachment(A){if(!this.resolveAttachment||!A.sourceEntityType||!A.sourceEntityId)return[];let Q=await this.resolveAttachment({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:"carousel"});return Q?[Q]:[]}async fetchDocumentData(A){if(!A?.length)return[];let Q=[];for(let B of A){let w=await this.fetchSingleDocumentData(B.id);if(w)Q.push(w)}return Q}async fetchSingleDocumentData(A){try{let Q=await this.entityService.getEntity({entityType:"document",id:A});if(!Q){this.logger.warn("Document not found",{documentId:A});return}let B=Q.content.match(/^data:application\/pdf;base64,(.+)$/);if(!B?.[1]){this.logger.warn("Invalid document data URL format",{documentId:A});return}let w=typeof Q.metadata.filename==="string"?Q.metadata.filename:`${A}.pdf`;return{type:"document",data:Buffer.from(B[1],"base64"),mimeType:"application/pdf",filename:w}}catch(Q){this.logger.warn("Failed to fetch document",{documentId:A,error:Q});return}}async fetchImageData(A){try{let Q=await this.entityService.getEntity({entityType:"image",id:A});if(!Q){this.logger.warn("Cover image not found",{imageId:A});return}let w=Q.content.match(/^data:([^;]+);base64,(.+)$/);if(!w?.[1]||!w[2]){this.logger.warn("Invalid image data URL format",{imageId:A});return}let $=w[1],I=w[2];return{data:Buffer.from(I,"base64"),mimeType:$}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function lX1(A,Q,B){if(Q.size===0){B.debug("No providers configured, skipping publish-pipeline registration");return}A.messaging.subscribe("system:plugins:ready",async()=>{let w=Q.values().next().value;return await A.messaging.send({type:"publish:register",payload:{entityType:"social-post",provider:w}}),B.info("Registered social-post with publish-pipeline"),{success:!0}})}function iX1(A,Q,B){let w=new ac({sendMessage:A.messaging.send,logger:B.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q,resolveAttachment:A.attachments.resolve});A.messaging.subscribe("publish:execute",async($)=>{return await w.handle($.payload),{success:!0}}),B.debug("Subscribed to publish:execute messages")}fA();function dX1(A,Q){A.messaging.subscribe("entity:updated",async(B)=>{let{entityType:w,entityId:$,entity:I}=B.payload;if(w!=="post")return{success:!0};if(I.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:$}},limit:1}})).length>0)return Q.debug(`Social post already exists for ${$}, skipping auto-generate`),{success:!0};return await A.messaging.send({type:"social:auto-generate",payload:{sourceEntityType:w,sourceEntityId:$,platform:"linkedin"}}),Q.info(`Auto-generate social post triggered for queued post ${$}`),{success:!0}}catch(Y){let X=S0(Y);return Q.error(`Failed to trigger auto-generate for ${$}:`,{error:X}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function rX1(A,Q){A.messaging.subscribe("social:auto-generate",async(B)=>{let{sourceEntityType:w,sourceEntityId:$,platform:I}=B.payload;try{let D=await A.jobs.enqueue({type:`${II.entityType}:generation`,data:{sourceEntityType:w,sourceEntityId:$,platform:I,addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info(`Social post generation job enqueued for ${w}/${$}`,{jobId:D}),{success:!0,jobId:D}}catch(D){let Y=S0(D);return Q.error(`Failed to enqueue social post generation for ${$}:`,{error:Y}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function nX1(A,Q){A.messaging.subscribe("generate:execute",async(B)=>{let{entityType:w}=B.payload;if(w!=="social-post")return{success:!0};Q.info("Received generate:execute for social-post");try{let $=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:5}});if($.length===0)return Q.info("No published posts found for social post generation"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"No published posts available for social post generation"}}),{success:!0};let I=null;for(let Y of $)if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:Y.id}},limit:1}})).length===0){I=Y;break}if(!I)return Q.info("All recent posts already have social posts"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"All recent posts already have social posts generated"}}),{success:!0};let D=await A.jobs.enqueue({type:`${II.entityType}:generation`,data:{sourceEntityType:"post",sourceEntityId:I.id,platform:"linkedin",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info("Social post generation job queued",{jobId:D,sourcePostId:I.id}),{success:!0}}catch($){let I=S0($);return Q.error("Failed to handle generate:execute:",{error:I}),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:I}}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}var oX1={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.92",description:"Multi-provider social media posting with queue-based publishing",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class VvA extends V2{entityType=II.entityType;schema=qk;adapter=II;providers=new Map;constructor(A){super("social-media",oX1,A,FvA)}createGenerationHandler(A){return new CV(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return cX1()}getDataSources(){return[new VwA(this.logger.child("SocialPostDataSource"))]}async onRegister(A){if(this.initializeProviders(),lX1(A,this.providers,this.logger),iX1(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)dX1(A,this.logger),rX1(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");nX1(A,this.logger),pX1(A),this.logger.info("Social media plugin registered successfully")}initializeProviders(){if(this.config.linkedin?.accessToken){let A=EvA(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function tc(A){return new VvA(A)}fA();var XU2=f.enum(["draft","queued","published","failed"]),D_w=f.object({status:XU2.default("draft"),queueOrder:f.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:f.string().datetime().optional()});class MvA{name="internal";async publish(A,Q){return{id:"internal"}}}var I7={REGISTER:"publish:register",QUEUE:"publish:queue",DIRECT:"publish:direct",REMOVE:"publish:remove",REORDER:"publish:reorder",LIST:"publish:list",REPORT_SUCCESS:"publish:report:success",REPORT_FAILURE:"publish:report:failure",EXECUTE:"publish:execute",QUEUED:"publish:queued",COMPLETED:"publish:completed",FAILED:"publish:failed",LIST_RESPONSE:"publish:list:response"},FN={REGISTER:"generate:register",REPORT_SUCCESS:"generate:report:success",REPORT_FAILURE:"generate:report:failure",EXECUTE:"generate:execute",COMPLETED:"generate:completed",FAILED:"generate:failed",SKIPPED:"generate:skipped"};fA();var WU2=f.object({skipIfDraftExists:f.boolean().optional(),minSourceEntities:f.number().optional(),maxUnpublishedDrafts:f.number().optional(),sourceEntityType:f.string().optional()}),sX1=f.object({entitySchedules:f.record(f.string(),f.string()).optional(),generationSchedules:f.record(f.string(),f.string()).optional(),generationConditions:f.record(f.string(),WU2).optional(),maxRetries:f.number().optional().default(3),retryBaseDelayMs:f.number().optional().default(5000)});class NJ{static instance=null;queues=new Map;static getInstance(){return NJ.instance??=new NJ,NJ.instance}static resetInstance(){NJ.instance=null}static createFresh(){return new NJ}constructor(){}async add(A,Q){let B=this.getOrCreateQueue(A),w=B.find((D)=>D.entityId===Q);if(w)return{position:w.position};let $=B.length+1,I={entityId:Q,entityType:A,position:$,queuedAt:new Date().toISOString()};return B.push(I),{position:$}}async remove(A,Q){let B=this.queues.get(A);if(!B)return;let w=B.findIndex(($)=>$.entityId===Q);if(w===-1)return;B.splice(w,1),this.recalculatePositions(B)}async reorder(A,Q,B){let w=this.queues.get(A);if(!w)return;let $=w.findIndex((Y)=>Y.entityId===Q);if($===-1)return;let[I]=w.splice($,1);if(!I)return;let D=Math.max(0,Math.min(B-1,w.length));w.splice(D,0,I),this.recalculatePositions(w)}async list(A){let Q=this.queues.get(A);if(!Q)return[];return[...Q]}async getNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;return Q[0]??null}async getNextAcrossTypes(){let A=null;for(let Q of this.queues.values()){let B=Q[0];if(!B)continue;if(!A||B.queuedAt<A.queuedAt)A=B}return A}async popNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let B=Q.shift()??null;if(B)this.recalculatePositions(Q);return B}getRegisteredTypes(){return Array.from(this.queues.keys())}async getQueuedEntityTypes(){let A=[];for(let[Q,B]of this.queues.entries())if(B.length>0)A.push(Q);return A}getOrCreateQueue(A){let Q=this.queues.get(A);if(!Q)Q=[],this.queues.set(A,Q);return Q}recalculatePositions(A){A.forEach((Q,B)=>{Q.position=B+1})}}class qJ{static instance=null;providers=new Map;defaultProvider=new MvA;static getInstance(){return qJ.instance??=new qJ,qJ.instance}static resetInstance(){qJ.instance=null}static createFresh(){return new qJ}constructor(){}register(A,Q){this.providers.set(A,Q)}get(A){return this.providers.get(A)??this.defaultProvider}has(A){return this.providers.has(A)}unregister(A){this.providers.delete(A)}getRegisteredTypes(){return Array.from(this.providers.keys())}}fA();fA();async function aX1(A,Q){let B={entityType:A.entityType,entityId:A.entityId};if(Q.messageBus)await Q.messageBus.send({type:I7.EXECUTE,payload:B,sender:"publish-service"});Q.onExecute?.(B)}async function tX1(A,Q){let B=Q.providerRegistry.get(A.entityType);if(!Q.entityService){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"EntityService not available for provider mode",retryCount:0,willRetry:!1});return}let w=await Q.entityService.getEntity({entityType:A.entityType,id:A.entityId});if(!w){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:`Entity not found: ${A.entityType}/${A.entityId}`,retryCount:0,willRetry:!1});return}try{let $=await B.publish(w.content,w.metadata);Q.retryTracker.clearRetries(A.entityId),Q.onPublish?.({entityType:A.entityType,entityId:A.entityId,result:$})}catch($){let I=S0($);Q.retryTracker.recordFailure(A.entityId,I);let D=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:I,retryCount:D?.retryCount??1,willRetry:D?.willRetry??!1})}}function eX1(A,Q,B,w){if(w.retryTracker.clearRetries(Q),w.messageBus)w.messageBus.send({type:I7.COMPLETED,payload:{entityType:A,entityId:Q,result:B},sender:"publish-service"});w.onPublish?.({entityType:A,entityId:Q,result:B})}function AW1(A,Q,B,w){w.retryTracker.recordFailure(Q,B);let $=w.retryTracker.getRetryInfo(Q),I={entityType:A,entityId:Q,error:B,retryCount:$?.retryCount??1,willRetry:$?.willRetry??!1};if(w.messageBus)w.messageBus.send({type:I7.FAILED,payload:I,sender:"publish-service"});w.onFailed?.(I)}async function QW1(A,Q){let B=Q.generationConditions[A];if(B&&Q.onCheckGenerationConditions){let $=await Q.onCheckGenerationConditions(A,B);if(!$.shouldGenerate){if(Q.messageBus)Q.messageBus.send({type:FN.SKIPPED,payload:{entityType:A,reason:$.reason??"Conditions not met"},sender:"content-pipeline"});return}}let w={entityType:A};if(Q.messageBus)await Q.messageBus.send({type:FN.EXECUTE,payload:w,sender:"content-pipeline"});Q.onGenerate?.(w)}function BW1(A,Q,B){if(B)B.send({type:FN.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function wW1(A,Q,B){if(B)B.send({type:FN.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var HU2=1000;class CvA{deps;publishJobs=new Map;immediateIntervalJob=null;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.entitySchedules)){let B=this.deps.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,B)}this.immediateIntervalJob=this.deps.config.backend.scheduleInterval(HU2,()=>this.processUnscheduledTypes())}stop(){if(UU2(this.publishJobs),this.immediateIntervalJob)this.immediateIntervalJob.stop(),this.immediateIntervalJob=null}async processEntityType(A){if(!this.deps.isRunning())return;try{let Q=await this.deps.config.queueManager.getNext(A);if(Q)await this.processEntry(Q)}catch(Q){this.deps.config.logger.error(`Scheduler error for ${A}:`,Q)}}async processUnscheduledTypes(){if(!this.deps.isRunning())return;try{let A=await this.deps.config.queueManager.getQueuedEntityTypes();for(let Q of A)if(!this.entitySchedules[Q]){let B=await this.deps.config.queueManager.getNext(Q);if(B){await this.processEntry(B);break}}}catch(A){this.deps.config.logger.error("Scheduler error for unscheduled types:",A)}}async processEntry(A){if(await this.deps.config.queueManager.remove(A.entityType,A.entityId),this.deps.config.messageBus!==void 0)await aX1(A,this.deps.getPublishDeps());else await tX1(A,this.deps.getPublishDeps())}get entitySchedules(){return this.deps.config.entitySchedules}}function UU2(A){for(let Q of A.values())Q.stop();A.clear()}class OvA{deps;generationJobs=new Map;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.generationSchedules)){let B=this.deps.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,B)}}stop(){JU2(this.generationJobs)}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await QW1(A,this.deps.getGenerationDeps())}catch(Q){this.deps.config.logger.error(`Generation trigger error for ${A}:`,Q)}}get generationSchedules(){return this.deps.config.generationSchedules}}function JU2(A){for(let Q of A.values())Q.stop();A.clear()}class BH{static instance=null;config;publishRunner;generationRunner;running=!1;static getInstance(A){return BH.instance??=new BH(A),BH.instance}static resetInstance(){if(BH.instance)BH.instance.stop();BH.instance=null}static createFresh(A){return new BH(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new CvA({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new OvA({config:this.config,getGenerationDeps:()=>this.generationDeps,isRunning:()=>this.running})}async start(){if(this.running)return;this.running=!0,this.publishRunner.start(),this.generationRunner.start()}async stop(){this.running=!1,this.publishRunner.stop(),this.generationRunner.stop()}isRunning(){return this.running}completePublish(A,Q,B){eX1(A,Q,B,this.publishDeps)}failPublish(A,Q,B){AW1(A,Q,B,this.publishDeps)}async publishDirect(A,Q,B,w){return this.config.providerRegistry.get(A).publish(B,w)}completeGeneration(A,Q){BW1(A,Q,this.config.messageBus)}failGeneration(A,Q){wW1(A,Q,this.config.messageBus)}get entitySchedules(){return this.config.entitySchedules}get generationSchedules(){return this.config.generationSchedules}get publishDeps(){return{providerRegistry:this.config.providerRegistry,retryTracker:this.config.retryTracker,messageBus:this.config.messageBus,entityService:this.config.entityService,onExecute:this.config.onExecute,onPublish:this.config.onPublish,onFailed:this.config.onFailed}}get generationDeps(){return{logger:this.config.logger,messageBus:this.config.messageBus,generationConditions:this.config.generationConditions,onCheckGenerationConditions:this.config.onCheckGenerationConditions,onGenerate:this.config.onGenerate}}validateCronExpressions(){for(let[A,Q]of Object.entries(this.entitySchedules))this.validateCronExpression(A,Q,"publish");for(let[A,Q]of Object.entries(this.generationSchedules))this.validateCronExpression(A,Q,"generation")}validateCronExpression(A,Q,B){try{this.config.backend.validateCron(Q)}catch(w){throw Error(`Invalid ${B} cron expression for ${A}: "${Q}" - ${S0(w)}`)}}}var $W1={maxRetries:3,baseDelayMs:5000};class LJ{static instance=null;retries=new Map;config;static getInstance(A){return LJ.instance??=new LJ(A??$W1),LJ.instance}static resetInstance(){LJ.instance=null}static createFresh(A){return new LJ(A??$W1)}constructor(A){this.config=A}recordFailure(A,Q){let w=(this.retries.get(A)?.retryCount??0)+1,$=this.config.baseDelayMs*Math.pow(2,w-1),I=Date.now()+$;this.retries.set(A,{entityId:A,retryCount:w,lastError:Q,nextRetryAt:I})}shouldRetry(A){let Q=this.retries.get(A);if(!Q)return!1;return Q.retryCount<this.config.maxRetries}isReadyForRetry(A){let Q=this.retries.get(A);if(!Q)return!1;return Date.now()>=Q.nextRetryAt}clearRetries(A){this.retries.delete(A)}getRetryInfo(A){let Q=this.retries.get(A);if(!Q)return null;return{entityId:Q.entityId,retryCount:Q.retryCount,lastError:Q.lastError,nextRetryAt:Q.nextRetryAt,willRetry:Q.retryCount<this.config.maxRetries}}}function D7(A,Q,B,w,$,I,D,Y){return D7.fromTZ(D7.tp(A,Q,B,w,$,I,D),Y)}D7.fromTZISO=(A,Q,B)=>D7.fromTZ(GU2(A,Q),B);D7.fromTZ=function(A,Q){let B=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),w=RvA(A.tz,B),$=new Date(B.getTime()-w),I=RvA(A.tz,$);if(I-w===0)return $;{let D=new Date(B.getTime()-I),Y=RvA(A.tz,D);if(Y-I===0)return D;if(!Q&&Y-I>0)return D;if(Q)throw Error("Invalid date passed to fromTZ()");return $}};D7.toTZ=function(A,Q){let B=A.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),w=new Date(B);return{y:w.getFullYear(),m:w.getMonth()+1,d:w.getDate(),h:w.getHours(),i:w.getMinutes(),s:w.getSeconds(),tz:Q}};D7.tp=(A,Q,B,w,$,I,D)=>({y:A,m:Q,d:B,h:w,i:$,s:I,tz:D});function RvA(A,Q=new Date){let B=Q.toLocaleString("en-US",{timeZone:A,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],w=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${w} GMT`)-Date.parse(`${w} ${B}`)}function GU2(A,Q){let B=new Date(Date.parse(A));if(isNaN(B))throw Error("minitz: Invalid ISO8601 passed to parser.");let w=A.substring(9);return A.includes("Z")||w.includes("-")||w.includes("+")?D7.tp(B.getUTCFullYear(),B.getUTCMonth()+1,B.getUTCDate(),B.getUTCHours(),B.getUTCMinutes(),B.getUTCSeconds(),"Etc/UTC"):D7.tp(B.getFullYear(),B.getMonth()+1,B.getDate(),B.getHours(),B.getMinutes(),B.getSeconds(),Q)}D7.minitz=D7;var bvA=32,Ap=31|bvA,XW1=[1,2,4,8,16],IW1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(A,Q){this.pattern=A,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let A=this.pattern.replace(/\s+/g," ").split(" ");if(A.length<5||A.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(A.length===5&&A.unshift("0"),A[3].indexOf("L")>=0&&(A[3]=A[3].replace("L",""),this.lastDayOfMonth=!0),A[3]=="*"&&(this.starDOM=!0),A[4].length>=3&&(A[4]=this.replaceAlphaMonths(A[4])),A[5].length>=3&&(A[5]=this.replaceAlphaDays(A[5])),A[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new nY(new Date,this.timezone).getDate(!0);A[0]=A[0].replace("?",Q.getSeconds().toString()),A[1]=A[1].replace("?",Q.getMinutes().toString()),A[2]=A[2].replace("?",Q.getHours().toString()),this.starDOM||(A[3]=A[3].replace("?",Q.getDate().toString())),A[4]=A[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(A[5]=A[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(A),this.partToArray("second",A[0],0,1),this.partToArray("minute",A[1],0,1),this.partToArray("hour",A[2],0,1),this.partToArray("day",A[3],-1,1),this.partToArray("month",A[4],-1,1),this.partToArray("dayOfWeek",A[5],0,Ap),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(A,Q,B,w){let $=this[A],I=A==="day"&&this.lastDayOfMonth;if(Q===""&&!I)throw TypeError("CronPattern: configuration entry "+A+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return $.fill(w);let D=Q.split(",");if(D.length>1)for(let Y=0;Y<D.length;Y++)this.partToArray(A,D[Y],B,w);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,A,B,w):Q.indexOf("-")!==-1?this.handleRange(Q,A,B,w):Q.indexOf("/")!==-1?this.handleStepping(Q,A,B,w):Q!==""&&this.handleNumber(Q,A,B,w)}throwAtIllegalCharacters(A){for(let Q=0;Q<A.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(A[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+A[Q]+") contains illegal characters.")}handleNumber(A,Q,B,w){let $=this.extractNth(A,Q),I=parseInt($[0],10)+B;if(isNaN(I))throw TypeError("CronPattern: "+Q+" is not a number: '"+A+"'");this.setPart(Q,I,$[1]||w)}setPart(A,Q,B){if(!Object.prototype.hasOwnProperty.call(this,A))throw TypeError("CronPattern: Invalid part specified: "+A);if(A==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,B);return}if(A==="second"||A==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+A+": "+Q)}else if(A==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+A+": "+Q)}else if(A==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+A+": "+Q)}else if(A==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+A+": "+Q);this[A][Q]=B}handleRangeWithStepping(A,Q,B,w){let $=this.extractNth(A,Q),I=$[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(I===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+A+"'");let[,D,Y,X]=I,W=parseInt(D,10)+B,U=parseInt(Y,10)+B,K=parseInt(X,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(U))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(K===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(K>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if(W>U)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let F=W;F<=U;F+=K)this.setPart(Q,F,$[1]||w)}extractNth(A,Q){let B=A,w;if(B.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");w=B.split("#")[1],B=B.split("#")[0]}return[B,w]}handleRange(A,Q,B,w){let $=this.extractNth(A,Q),I=$[0].split("-");if(I.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+A+"'");let D=parseInt(I[0],10)+B,Y=parseInt(I[1],10)+B;if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(D>Y)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let X=D;X<=Y;X++)this.setPart(Q,X,$[1]||w)}handleStepping(A,Q,B,w){let $=this.extractNth(A,Q),I=$[0].split("/");if(I.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+A+"'");I[0]===""&&(I[0]="*");let D=0;I[0]!=="*"&&(D=parseInt(I[0],10)+B);let Y=parseInt(I[1],10);if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Y===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Y>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let X=D;X<this[Q].length;X+=Y)this.setPart(Q,X,$[1]||w)}replaceAlphaDays(A){return A.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(A){return A.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(A){let Q=A.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":A}setNthWeekdayOfMonth(A,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[A]=this.dayOfWeek[A]|bvA;else if(Q===Ap)this.dayOfWeek[A]=Ap;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|XW1[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},DW1=[31,28,31,30,31,30,31,31,30,31,30,31],Ef=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],nY=class A{tz;ms;second;minute;hour;day;month;year;constructor(Q,B){if(this.tz=B,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof A)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,B,w,$){let I=new Date(Date.UTC(Q,B,w)).getUTCDay(),D=0;for(let Y=1;Y<=w;Y++)new Date(Date.UTC(Q,B,Y)).getUTCDay()===I&&D++;if($&Ap&&XW1[D-1]&$)return!0;if($&bvA){let Y=new Date(Date.UTC(Q,B+1,0)).getUTCDate();for(let X=w+1;X<=Y;X++)if(new Date(Date.UTC(Q,B,X)).getUTCDay()===I)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let B=D7.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=B.s,this.minute=B.i,this.hour=B.h,this.day=B.d,this.month=B.m-1,this.year=B.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>DW1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let B=D7.fromTZISO(Q);this.ms=B.getUTCMilliseconds(),this.second=B.getUTCSeconds(),this.minute=B.getUTCMinutes(),this.hour=B.getUTCHours(),this.day=B.getUTCDate(),this.month=B.getUTCMonth(),this.year=B.getUTCFullYear(),this.apply()}else return this.fromDate(D7.fromTZISO(Q,this.tz))}findNext(Q,B,w,$){let I=this[B],D;w.lastDayOfMonth&&(this.month!==1?D=DW1[this.month]:D=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Y=!w.starDOW&&B=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let X=this[B]+$;X<w[B].length;X++){let W=w[B][X];if(B==="day"&&w.lastDayOfMonth&&X-$==D&&(W=1),B==="day"&&!w.starDOW){let U=w.dayOfWeek[(Y+(X-$-1))%7];if(U&&U&Ap)U=this.isNthWeekdayOfMonth(this.year,this.month,X-$,U)?1:0;else if(U)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${U}`);Q.legacyMode&&!w.starDOM?W=W||U:W=W&&U}if(W)return this[B]=X-$,I!==this[B]?2:1}return 3}recurse(Q,B,w){let $=this.findNext(B,Ef[w][0],Q,Ef[w][2]);if($>1){let I=w+1;for(;I<Ef.length;)this[Ef[I][0]]=-Ef[I][2],I++;if($===3)return this[Ef[w][1]]++,this[Ef[w][0]]=-Ef[w][2],this.apply(),this.recurse(Q,B,0);if(this.apply())return this.recurse(Q,B,w-1)}return w+=1,w>=Ef.length?this:this.year>=3000?null:this.recurse(Q,B,w)}increment(Q,B,w){return this.second+=B.interval!==void 0&&B.interval>1&&w?B.interval:1,this.ms=0,this.apply(),this.recurse(Q,B,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):D7.fromTZ(D7.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function KU2(A){if(A===void 0&&(A={}),delete A.name,A.legacyMode=A.legacyMode===void 0?!0:A.legacyMode,A.paused=A.paused===void 0?!1:A.paused,A.maxRuns=A.maxRuns===void 0?1/0:A.maxRuns,A.catch=A.catch===void 0?!1:A.catch,A.interval=A.interval===void 0?0:parseInt(A.interval.toString(),10),A.utcOffset=A.utcOffset===void 0?void 0:parseInt(A.utcOffset.toString(),10),A.unref=A.unref===void 0?!1:A.unref,A.startAt&&(A.startAt=new nY(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new nY(A.stopAt,A.timezone)),A.interval!==null){if(isNaN(A.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(A.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(A.utcOffset!==void 0){if(isNaN(A.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(A.utcOffset<-870||A.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(A.utcOffset!==void 0&&A.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(A.unref!==!0&&A.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return A}function ec(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function fU2(A){return ec(A)}function FU2(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var YW1=30000,bwA=[],PvA=class{name;options;_states;fn;constructor(A,Q,B){let w,$;if(ec(Q))$=Q;else if(typeof Q=="object")w=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(ec(B))$=B;else if(typeof B=="object")w=B;else if(B!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=w?.name,this.options=KU2(w),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:w?w.maxRuns:void 0,paused:w?w.paused:!1,pattern:new IW1("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new nY(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new IW1(A,this.options.timezone),this.name){if(bwA.find((I)=>I.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");bwA.push(this)}return $!==void 0&&fU2($)&&(this.fn=$,this.schedule()),this}nextRun(A){let Q=this._next(A);return Q?Q.getDate(!1):null}nextRuns(A,Q){this._states.maxRuns!==void 0&&A>this._states.maxRuns&&(A=this._states.maxRuns);let B=[],w=Q||this._states.currentRun||void 0;for(;A--&&(w=this.nextRun(w));)B.push(w);return B}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let A=this.nextRun(this._states.currentRun),Q=!this._states.paused,B=this.fn!==void 0,w=!this._states.kill;return Q&&B&&w&&A!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(A){let Q=this._next(A);return Q?A instanceof nY||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new nY(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=bwA.indexOf(this);A>=0&&bwA.splice(A,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(A){if(A&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");A&&(this.fn=A);let Q=this.msToNext(),B=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||B===null?this:(Q>YW1&&(Q=YW1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(B),Q),this._states.currentTimeout&&this.options.unref&&FU2(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new nY(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){ec(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new nY(A,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(A){let Q=new Date,B=!this._states.paused&&Q.getTime()>=A.getTime(),w=this._states.blocking&&this.options.protect;B&&!w?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):B&&w&&ec(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(A){let Q=!!(A||this._states.currentRun),B=!1;!A&&this.options.startAt&&this.options.interval&&([A,Q]=this._calculatePreviousRun(A,Q),B=!A),A=new nY(A,this.options.timezone||this.options.utcOffset),this.options.startAt&&A&&A.getTime()<this.options.startAt.getTime()&&(A=this.options.startAt);let w=this._states.once||new nY(A,this.options.timezone||this.options.utcOffset);return!B&&w!==this._states.once&&(w=w.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=A.getTime()||w===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&w.getTime()>=this.options.stopAt.getTime()?null:w}_calculatePreviousRun(A,Q){let B=new nY(void 0,this.options.timezone||this.options.utcOffset),w=A;if(this.options.startAt.getTime()<=B.getTime()){w=this.options.startAt;let $=w.getTime()+this.options.interval*1000;for(;$<=B.getTime();)w=new nY(w,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),$=w.getTime()+this.options.interval*1000;Q=!0}return w===null&&(w=void 0),[w,Q]}};class PwA{scheduleCron(A,Q){let B=new PvA(A,()=>{Q()});return{stop:()=>B.stop()}}scheduleInterval(A,Q){let B=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(B)}}validateCron(A){new PvA(A).stop()}}eA();fA();var jvA=f.object({action:f.enum(["list","add","remove","reorder"]).describe("Queue action to perform"),entityType:f.string().optional().describe("Entity type (required for add/remove/reorder, optional for list)"),entityId:f.string().optional().describe("Entity ID (required for add/remove/reorder)"),position:f.number().optional().describe("New position for reorder action (1-based)")}),kvA=f.object({position:f.number(),entityType:f.string(),entityId:f.string(),queuedAt:f.string()}),ZU2=f.object({success:f.literal(!0),message:f.string().optional(),data:f.object({queue:f.array(kvA).optional(),entityType:f.string().optional(),entityId:f.string().optional(),position:f.number().optional()}).optional()}),zU2=f.object({success:f.literal(!1),error:f.string(),code:f.string().optional()}),_vA=f.union([ZU2,zU2]);function jwA(A,Q,B){return{...j2(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",jvA,async($)=>{let{action:I,entityType:D,entityId:Y,position:X}=$;switch(I){case"list":return NU2(B,D);case"add":return qU2(B,D,Y);case"remove":return LU2(B,D,Y);case"reorder":return EU2(B,D,Y,X);default:return{success:!1,error:`Unknown action: ${I}`}}}),outputSchema:_vA}}async function NU2(A,Q){let B=[];if(Q)B=await A.list(Q);else{let $=A.getRegisteredTypes();for(let I of $){let D=await A.list(I);B.push(...D)}B.sort((I,D)=>new Date(I.queuedAt).getTime()-new Date(D.queuedAt).getTime())}if(B.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:B.map(($,I)=>({position:I+1,entityType:$.entityType,entityId:$.entityId,queuedAt:$.queuedAt}))},message:`${B.length} items in queue`}}async function qU2(A,Q,B){let w=vvA("add",Q,B);if(!w.success)return w.error;let $=await A.add(w.entityType,w.entityId);return{success:!0,data:{entityType:w.entityType,entityId:w.entityId,position:$.position},message:`Added to queue at position ${$.position}`}}async function LU2(A,Q,B){let w=vvA("remove",Q,B);if(!w.success)return w.error;return await A.remove(w.entityType,w.entityId),{success:!0,data:{entityType:w.entityType,entityId:w.entityId},message:"Removed from queue"}}async function EU2(A,Q,B,w){let $=vvA("reorder",Q,B);if(!$.success)return $.error;let I=VU2(w);if(!I.success)return I.error;return await A.reorder($.entityType,$.entityId,I.position),{success:!0,data:{entityType:$.entityType,entityId:$.entityId,position:I.position},message:`Moved to position ${I.position}`}}function vvA(A,Q,B){if(!Q)return{success:!1,error:{success:!1,error:`entityType is required for ${A} action`}};if(!B)return{success:!1,error:{success:!1,error:`entityId is required for ${A} action`}};return{success:!0,entityType:Q,entityId:B}}function VU2(A){if(A===void 0)return{success:!1,error:{success:!1,error:"position is required for reorder action"}};if(A<1)return{success:!1,error:{success:!1,error:"position must be a positive number"}};return{success:!0,position:A}}eA();fA();eA();fA();var MU2=f.object({id:f.string().min(1)});async function HW1(A,Q){let{bodyContent:B,coverImageId:w,documents:$,sourceEntityType:I,sourceEntityId:D}=CU2(Q.content),Y=w?await bU2(A,w):void 0,X;if($&&$.length>0){let U=await PU2(A,$);if(U.length>0)X=U}X??=await RU2(A,I,D);let W={bodyContent:B};if(Y)W.imageData=Y;if(X&&X.length>0)W.documentData=X;return W}function CU2(A){try{let Q=$2(A,f.record(f.unknown())),B=Q.metadata.coverImageId,w=typeof B==="string"?B:void 0,$=OU2(Q.metadata.documents),I=WW1(Q.metadata.sourceEntityType),D=WW1(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...w&&{coverImageId:w},...$.length>0&&{documents:$},...I&&{sourceEntityType:I},...D&&{sourceEntityId:D}}}catch{return{bodyContent:A}}}function OU2(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let B=MU2.safeParse(Q);return B.success?[B.data]:[]})}function WW1(A){return typeof A==="string"&&A.length>0?A:void 0}async function RU2(A,Q,B){if(!Q||!B)return;let w=await A.attachments.resolve({sourceEntityType:Q,sourceEntityId:B,attachmentType:"carousel"});return w?[w]:void 0}async function bU2(A,Q){let B=await A.entityService.getEntity({entityType:"image",id:Q});if(!B?.content)return;let w=UW1(B.content);if(!w?.mimeType.startsWith("image/"))return;return{data:w.data,mimeType:w.mimeType}}async function PU2(A,Q){return(await Promise.all(Q.map((w)=>jU2(A,w)))).filter((w)=>w!==void 0)}async function jU2(A,Q){let B=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!B?.content)return;let w=UW1(B.content);if(w?.mimeType!=="application/pdf")return;return{type:"document",data:w.data,mimeType:"application/pdf",filename:kU2(B,Q.id)}}function UW1(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function kU2(A,Q){let B=A.metadata.filename;return typeof B==="string"&&B.length>0?B:`${Q}.pdf`}var xvA=f.object({entityType:f.string().describe("Entity type to publish (e.g., social-post, post, deck)"),id:f.string().optional().describe("Entity ID to publish"),slug:f.string().optional().describe("Entity slug to publish")}),_U2=f.object({success:f.literal(!0),message:f.string().optional(),data:f.object({entityType:f.string().optional(),entityId:f.string().optional(),platformId:f.string().optional(),url:f.string().optional()}).optional()}),vU2=f.object({success:f.literal(!1),error:f.string(),code:f.string().optional()}),yvA=f.union([_U2,vU2]);function kwA(A,Q,B){return{...j2(Q,"publish","Publish an entity directly to its platform. Works with any registered entity type (social-post, post, deck, etc.)",xvA,async($)=>{let{entityType:I,id:D,slug:Y}=$;if(!D&&!Y)return{success:!1,error:"Either 'id' or 'slug' must be provided"};let X=await xU2(A,I,D,Y);if(!X)return{success:!1,error:`Entity not found: ${I}:${D??Y}`};if(X.visibility!=="public")return{success:!1,error:`Cannot publish ${I}:${X.id} to a public provider because visibility is ${X.visibility}`};if(X.metadata.status==="published")return{success:!1,error:"Entity is already published"};if(!B.has(I))return{success:!1,error:`No publish provider registered for ${I}. Check that the required credentials are configured.`};let W=B.get(I),{bodyContent:U,imageData:K,documentData:F}=await HW1(A,X),Z=await W.publish(U,X.metadata,K,F);return await A.entityService.updateEntity({entity:{...X,metadata:{...X.metadata,status:"published",publishedAt:new Date().toISOString(),platformId:Z.id}}}),{success:!0,data:{entityType:I,entityId:X.id,platformId:Z.id,url:Z.url},message:`Published ${I}:${X.id}`}}),outputSchema:yvA}}async function xU2(A,Q,B,w){if(B)return A.entityService.getEntity({entityType:Q,id:B});if(!w)return null;return(await A.entityService.listEntities({entityType:Q,options:{filter:{metadata:{slug:w}},limit:1}}))[0]??null}eA();fA();function JW1(A,Q){yU2(A,Q),TU2(A,Q)}function yU2(A,Q){A.messaging.subscribe(I7.REGISTER,async(B)=>SU2(Q,B.payload)),A.messaging.subscribe(I7.QUEUE,async(B)=>gU2(A,Q,B.payload)),A.messaging.subscribe(I7.DIRECT,async(B)=>hU2(A,Q,B.payload)),A.messaging.subscribe(I7.REMOVE,async(B)=>mU2(Q,B.payload)),A.messaging.subscribe(I7.REORDER,async(B)=>uU2(Q,B.payload)),A.messaging.subscribe(I7.LIST,async(B)=>cU2(A,Q,B.payload)),A.messaging.subscribe(I7.REPORT_SUCCESS,async(B)=>pU2(Q,B.payload)),A.messaging.subscribe(I7.REPORT_FAILURE,async(B)=>lU2(Q,B.payload)),Q.logger.debug("Subscribed to publish messages")}function TU2(A,Q){A.messaging.subscribe(FN.REPORT_SUCCESS,async(B)=>iU2(Q,B.payload)),A.messaging.subscribe(FN.REPORT_FAILURE,async(B)=>dU2(Q,B.payload)),Q.logger.debug("Subscribed to generation messages")}async function SU2(A,Q){let{entityType:B,provider:w}=Q;try{if(w)A.providerRegistry.register(B,w),A.logger.info(`Registered provider for entity type: ${B}`,{providerName:w.name});return{success:!0}}catch($){let I=S0($);return A.logger.error(`Failed to register provider: ${I}`),{success:!1}}}async function gU2(A,Q,B){let{entityType:w,entityId:$}=B;try{let I=await Q.queueManager.add(w,$);return await A.messaging.send({type:I7.QUEUED,payload:{entityType:w,entityId:$,position:I.position}}),Q.logger.debug(`Entity queued: ${$}`,{entityType:w,position:I.position}),{success:!0}}catch(I){let D=S0(I);return Q.logger.error(`Failed to queue entity: ${D}`),{success:!1}}}async function hU2(A,Q,B){let{entityType:w,entityId:$}=B;return await A.messaging.send({type:I7.EXECUTE,payload:{entityType:w,entityId:$}}),Q.logger.debug(`Direct publish requested: ${$}`,{entityType:w}),{success:!0}}async function mU2(A,Q){let{entityType:B,entityId:w}=Q;try{return await A.queueManager.remove(B,w),A.logger.debug(`Entity removed from queue: ${w}`,{entityType:B}),{success:!0}}catch($){let I=S0($);return A.logger.error(`Failed to remove entity: ${I}`),{success:!1}}}async function uU2(A,Q){let{entityType:B,entityId:w,position:$}=Q;try{return await A.queueManager.reorder(B,w,$),A.logger.debug(`Entity reordered: ${w}`,{entityType:B,newPosition:$}),{success:!0}}catch(I){let D=S0(I);return A.logger.error(`Failed to reorder entity: ${D}`),{success:!1}}}async function cU2(A,Q,B){let{entityType:w}=B;try{let $=await Q.queueManager.list(w);return await A.messaging.send({type:I7.LIST_RESPONSE,payload:{entityType:w,queue:$.map((I)=>({entityId:I.entityId,position:I.position,queuedAt:I.queuedAt}))}}),{success:!0}}catch($){let I=S0($);return Q.logger.error(`Failed to list queue: ${I}`),{success:!1}}}async function pU2(A,Q){let{entityType:B,entityId:w,result:$}=Q;return A.scheduler.completePublish(B,w,$),A.logger.info(`Publish reported success: ${w}`,{entityType:B}),{success:!0}}async function lU2(A,Q){let{entityType:B,entityId:w,error:$}=Q;A.scheduler.failPublish(B,w,$);let I=A.retryTracker.getRetryInfo(w);return A.logger.info(`Publish reported failure: ${w}`,{entityType:B,error:$,retryCount:I?.retryCount,willRetry:I?.willRetry}),{success:!0}}async function iU2(A,Q){let{entityType:B,entityId:w}=Q;return A.scheduler.completeGeneration(B,w),A.logger.info("Generation completed",{entityType:B,entityId:w}),{success:!0}}async function dU2(A,Q){let{entityType:B,error:w}=Q;return A.scheduler.failGeneration(B,w),A.logger.warn("Generation failed",{entityType:B,error:w}),{success:!0}}fA();async function GW1(A,Q,B,w){try{if(w.skipIfDraftExists!==!1){if((await A.listEntities({entityType:B,options:{filter:{metadata:{status:"draft"}},limit:1}})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(w.maxUnpublishedDrafts!==void 0){let $=await A.listEntities({entityType:B,options:{filter:{metadata:{status:"draft"}},limit:w.maxUnpublishedDrafts+1}});if($.length>=w.maxUnpublishedDrafts)return{shouldGenerate:!1,reason:`Max unpublished drafts reached (${$.length}/${w.maxUnpublishedDrafts})`}}if(w.minSourceEntities!==void 0&&w.sourceEntityType){let $=await A.listEntities({entityType:w.sourceEntityType,options:{publishedOnly:!0,limit:w.minSourceEntities}});if($.length<w.minSourceEntities)return{shouldGenerate:!1,reason:`Not enough source entities (${$.length}/${w.minSourceEntities} ${w.sourceEntityType})`}}return{shouldGenerate:!0}}catch($){return Q.error("Failed to check generation conditions",{entityType:B,error:S0($)}),{shouldGenerate:!1,reason:`Condition check failed: ${S0($)}`}}}function KW1(A){let{context:Q,config:B,queueManager:w,providerRegistry:$,retryTracker:I,logger:D}=A,Y=rU2(Q);return BH.createFresh({queueManager:w,providerRegistry:$,retryTracker:I,logger:D,backend:new PwA,...B.entitySchedules&&{entitySchedules:B.entitySchedules},...B.generationSchedules&&{generationSchedules:B.generationSchedules},...B.generationConditions&&{generationConditions:B.generationConditions},messageBus:Y,entityService:Q.entityService,onCheckGenerationConditions:(X,W)=>GW1(Q.entityService,D,X,W)})}function rU2(A){return{send:async($)=>{return A.messaging.send({type:$.type,payload:$.payload,...$.target!==void 0?{target:$.target}:{},...$.metadata!==void 0?{metadata:$.metadata}:{},...$.broadcast!==void 0?{broadcast:$.broadcast}:{}})},subscribe:()=>()=>{},unsubscribe:()=>{}}}async function fW1(A,Q,B){let w=A.getEntityTypes();for(let I of w){let D=await A.listEntities({entityType:I,options:{filter:{metadata:{status:"queued"}}}});for(let Y of D)await Q.add(Y.entityType,Y.id)}let $=0;for(let I of w){let D=await Q.list(I);$+=D.length}if($>0)B.info(`Rebuilt queue with ${$} queued entities`)}var nU2=["draft","queued","published","failed"];async function FW1(A,Q){await A.messaging.send({type:"dashboard:register-widget",payload:{id:"publication-pipeline",pluginId:Q,title:"Publication Pipeline",section:"secondary",priority:100,rendererName:"PipelineWidget",visibility:"anchor",dataProvider:()=>oU2(A)}})}async function oU2(A){let Q=A.entityService.getEntityTypes(),B=[],w={draft:0,queued:0,published:0,failed:0};for(let $ of Q){let I=await A.entityService.listEntities({entityType:$});for(let D of I){let Y=sU2(D.metadata.status);if(!Y)continue;w[Y]++,B.push({id:D.id,title:aU2(D.id,D.metadata.title),type:$,status:Y})}}return{summary:w,items:B}}function sU2(A){return nU2.find((Q)=>Q===A)}function aU2(A,Q){return typeof Q==="string"?Q:A}var ZW1={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.92",description:"Content pipeline plugin for managing entity publishing queues, scheduling, and generation",type:"module",main:"src/index.ts",types:"src/index.ts",scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",croner:"^9.1.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",typescript:"^5.3.3"},exports:{".":{types:"./src/index.ts",default:"./src/index.ts"}},files:["src"]};class TvA extends qB{pluginContext;queueManager;providerRegistry;retryTracker;scheduler;constructor(A){super("content-pipeline",ZW1,A??{},sX1)}async onRegister(A){this.pluginContext=A,this.queueManager=NJ.createFresh(),this.providerRegistry=qJ.createFresh(),this.retryTracker=LJ.createFresh({maxRetries:this.config.maxRetries,baseDelayMs:this.config.retryBaseDelayMs}),this.scheduler=KW1({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,logger:this.logger}),JW1(A,{queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,scheduler:this.scheduler,logger:this.logger})}async onReady(A){await fW1(A.entityService,this.queueManager,this.logger),await FW1(A,this.id),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[jwA(this.pluginContext,this.id,this.queueManager),kwA(this.pluginContext,this.id,this.providerRegistry)]}async getInstructions(){return'## Publishing\n- Use `content-pipeline_queue` to manage the publish queue \u2014 list queued items, add entities to the queue, remove them, or reorder.\n- Use `content-pipeline_publish` to publish an entity directly to its platform (e.g. LinkedIn, Buttondown).\n- When users ask about their "publish queue", "publishing queue", or "what\'s queued", use `content-pipeline_queue`.'}getQueueManager(){return this.queueManager}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getScheduler(){return this.scheduler}async onShutdown(){await this.scheduler.stop(),NJ.resetInstance(),qJ.resetInstance(),LJ.resetInstance()}}function SvA(A){return new TvA(A)}eA();fA();var zW1=f.object({accountId:f.string().describe("Cloudflare account ID"),apiToken:f.string().describe("Cloudflare API token with Analytics:Read permission"),siteTag:f.string().describe("Cloudflare Web Analytics site tag")}),gvA=f.object({cloudflare:zW1.optional()});eA();fA();var eU2=f.object({date:f.string().describe("Single date in YYYY-MM-DD format").optional(),days:f.number().min(1).max(365).describe("Number of days back from yesterday (e.g., 7 for last week)").optional(),startDate:f.string().describe("Start date in YYYY-MM-DD format (use with endDate)").optional(),endDate:f.string().describe("End date in YYYY-MM-DD format (use with startDate)").optional(),limit:f.number().min(1).max(100).default(20).describe("Maximum items for breakdowns (pages, referrers, countries)")});function AJ2(A){if(A.date&&(A.days||A.startDate||A.endDate))return"Cannot combine 'date' with 'days' or 'startDate'/'endDate'";if(A.days&&(A.startDate||A.endDate))return"Cannot combine 'days' with 'startDate'/'endDate'";if(A.startDate&&!A.endDate||!A.startDate&&A.endDate)return"Both 'startDate' and 'endDate' must be provided for custom range";return null}function NW1(A,Q,B){let w=[];if(!B)return w;return w.push(j2(A,"query",`Query website analytics from Cloudflare.
|
|
5175
|
+
${B.content}`:B.prompt??"Write an engaging LinkedIn post";return A.ai.generate({prompt:w,templateName:`social-media:${B.platform}`})}),A.eval.registerHandler("create",async(Q)=>{let B=DU2.parse(Q),w=[],$=p$.from(async(W)=>{let U={progress:W.progress};if(W.message!==void 0)U.message=W.message;w.push(U)});if(!$)throw Error("Failed to create progress reporter");let D=await new CV(A.logger,A).process(B,`eval-${Date.now()}`,$),Y=!1,X;if(D.success&&D.entityId){let W=await A.entityService.getEntity({entityType:"social-post",id:D.entityId});Y=!!W,X=W?.content.slice(0,300)}return{...D,entityExists:Y,entityPreview:X,progressSteps:w}})}fA();eA();class ac{sendMessage;logger;entityService;providers;resolveAttachment;constructor(A){this.sendMessage=A.sendMessage,this.logger=A.logger,this.entityService=A.entityService,this.providers=A.providers,this.resolveAttachment=A.resolveAttachment}async handle(A){let{entityType:Q,entityId:B}=A;if(Q!=="social-post")return;this.logger.debug("Handling publish:execute",{entityId:B});try{let w=await this.entityService.getEntity({entityType:"social-post",id:B});if(!w){await this.reportFailure(Q,B,`Post not found: ${B}`);return}if(w.metadata.status==="published"){this.logger.debug("Post already published, skipping",{entityId:B});return}let $=w.metadata.platform,I=this.providers.get($);if(!I){await this.reportFailure(Q,B,`No provider configured for platform: ${$}`);return}let D=$2(w.content,rY),Y;if(D.metadata.coverImageId)Y=await this.fetchImageData(D.metadata.coverImageId);let X=D.metadata.documents??[],W=await this.fetchDocumentData(X);try{if(X.length>0&&W.length===0)throw Error(`Refusing to publish: ${X.length} document(s) referenced but none could be fetched`);let U=X.length===0?await this.resolveSourceAttachment(D.metadata):[],K=W.length>0?W:U,F=K.length?await I.publish(D.content,w.metadata,Y,K):await I.publish(D.content,w.metadata,Y),Z=new Date().toISOString(),q=F.id||void 0,E={...D.metadata,status:"published",publishedAt:Z,...q&&{platformPostId:q}},L=II.createPostContent(E,D.content);await this.entityService.updateEntity({entity:{...w,content:L,metadata:{...w.metadata,status:"published",publishedAt:Z,platformPostId:q}}}),await this.reportSuccess(Q,B,F.id),this.logger.info(`Post published successfully: ${B}`,{platform:$,platformPostId:q})}catch(U){let K=U instanceof Error?U.message:String(U),F={...D.metadata,status:"failed"},Z=II.createPostContent(F,D.content);await this.entityService.updateEntity({entity:{...w,content:Z,metadata:{...w.metadata,status:"failed"}}}),await this.reportFailure(Q,B,K),this.logger.error(`Post publish failed: ${B}`,{platform:$,error:K})}}catch(w){let $=S0(w);this.logger.error("Unexpected error in publish handler",{entityId:B,error:$}),await this.reportFailure(Q,B,$)}}async reportSuccess(A,Q,B){await this.sendMessage({type:"publish:report:success",payload:{entityType:A,entityId:Q,result:{id:B}}})}async reportFailure(A,Q,B){await this.sendMessage({type:"publish:report:failure",payload:{entityType:A,entityId:Q,error:B}})}async resolveSourceAttachment(A){if(!this.resolveAttachment||!A.sourceEntityType||!A.sourceEntityId)return[];let Q=await this.resolveAttachment({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:"carousel"});return Q?[Q]:[]}async fetchDocumentData(A){if(!A?.length)return[];let Q=[];for(let B of A){let w=await this.fetchSingleDocumentData(B.id);if(w)Q.push(w)}return Q}async fetchSingleDocumentData(A){try{let Q=await this.entityService.getEntity({entityType:"document",id:A});if(!Q){this.logger.warn("Document not found",{documentId:A});return}let B=Q.content.match(/^data:application\/pdf;base64,(.+)$/);if(!B?.[1]){this.logger.warn("Invalid document data URL format",{documentId:A});return}let w=typeof Q.metadata.filename==="string"?Q.metadata.filename:`${A}.pdf`;return{type:"document",data:Buffer.from(B[1],"base64"),mimeType:"application/pdf",filename:w}}catch(Q){this.logger.warn("Failed to fetch document",{documentId:A,error:Q});return}}async fetchImageData(A){try{let Q=await this.entityService.getEntity({entityType:"image",id:A});if(!Q){this.logger.warn("Cover image not found",{imageId:A});return}let w=Q.content.match(/^data:([^;]+);base64,(.+)$/);if(!w?.[1]||!w[2]){this.logger.warn("Invalid image data URL format",{imageId:A});return}let $=w[1],I=w[2];return{data:Buffer.from(I,"base64"),mimeType:$}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function lX1(A,Q,B){if(Q.size===0){B.debug("No providers configured, skipping publish-pipeline registration");return}A.messaging.subscribe("system:plugins:ready",async()=>{let w=Q.values().next().value;return await A.messaging.send({type:"publish:register",payload:{entityType:"social-post",provider:w}}),B.info("Registered social-post with publish-pipeline"),{success:!0}})}function iX1(A,Q,B){let w=new ac({sendMessage:A.messaging.send,logger:B.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q,resolveAttachment:A.attachments.resolve});A.messaging.subscribe("publish:execute",async($)=>{return await w.handle($.payload),{success:!0}}),B.debug("Subscribed to publish:execute messages")}fA();function dX1(A,Q){A.messaging.subscribe("entity:updated",async(B)=>{let{entityType:w,entityId:$,entity:I}=B.payload;if(w!=="post")return{success:!0};if(I.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:$}},limit:1}})).length>0)return Q.debug(`Social post already exists for ${$}, skipping auto-generate`),{success:!0};return await A.messaging.send({type:"social:auto-generate",payload:{sourceEntityType:w,sourceEntityId:$,platform:"linkedin"}}),Q.info(`Auto-generate social post triggered for queued post ${$}`),{success:!0}}catch(Y){let X=S0(Y);return Q.error(`Failed to trigger auto-generate for ${$}:`,{error:X}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function rX1(A,Q){A.messaging.subscribe("social:auto-generate",async(B)=>{let{sourceEntityType:w,sourceEntityId:$,platform:I}=B.payload;try{let D=await A.jobs.enqueue({type:`${II.entityType}:generation`,data:{sourceEntityType:w,sourceEntityId:$,platform:I,addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info(`Social post generation job enqueued for ${w}/${$}`,{jobId:D}),{success:!0,jobId:D}}catch(D){let Y=S0(D);return Q.error(`Failed to enqueue social post generation for ${$}:`,{error:Y}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function nX1(A,Q){A.messaging.subscribe("generate:execute",async(B)=>{let{entityType:w}=B.payload;if(w!=="social-post")return{success:!0};Q.info("Received generate:execute for social-post");try{let $=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:5}});if($.length===0)return Q.info("No published posts found for social post generation"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"No published posts available for social post generation"}}),{success:!0};let I=null;for(let Y of $)if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:Y.id}},limit:1}})).length===0){I=Y;break}if(!I)return Q.info("All recent posts already have social posts"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"All recent posts already have social posts generated"}}),{success:!0};let D=await A.jobs.enqueue({type:`${II.entityType}:generation`,data:{sourceEntityType:"post",sourceEntityId:I.id,platform:"linkedin",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info("Social post generation job queued",{jobId:D,sourcePostId:I.id}),{success:!0}}catch($){let I=S0($);return Q.error("Failed to handle generate:execute:",{error:I}),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:I}}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}var oX1={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.93",description:"Multi-provider social media posting with queue-based publishing",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class VvA extends V2{entityType=II.entityType;schema=qk;adapter=II;providers=new Map;constructor(A){super("social-media",oX1,A,FvA)}createGenerationHandler(A){return new CV(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return cX1()}getDataSources(){return[new VwA(this.logger.child("SocialPostDataSource"))]}async onRegister(A){if(this.initializeProviders(),lX1(A,this.providers,this.logger),iX1(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)dX1(A,this.logger),rX1(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");nX1(A,this.logger),pX1(A),this.logger.info("Social media plugin registered successfully")}initializeProviders(){if(this.config.linkedin?.accessToken){let A=EvA(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function tc(A){return new VvA(A)}fA();var XU2=f.enum(["draft","queued","published","failed"]),D_w=f.object({status:XU2.default("draft"),queueOrder:f.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:f.string().datetime().optional()});class MvA{name="internal";async publish(A,Q){return{id:"internal"}}}var I7={REGISTER:"publish:register",QUEUE:"publish:queue",DIRECT:"publish:direct",REMOVE:"publish:remove",REORDER:"publish:reorder",LIST:"publish:list",REPORT_SUCCESS:"publish:report:success",REPORT_FAILURE:"publish:report:failure",EXECUTE:"publish:execute",QUEUED:"publish:queued",COMPLETED:"publish:completed",FAILED:"publish:failed",LIST_RESPONSE:"publish:list:response"},FN={REGISTER:"generate:register",REPORT_SUCCESS:"generate:report:success",REPORT_FAILURE:"generate:report:failure",EXECUTE:"generate:execute",COMPLETED:"generate:completed",FAILED:"generate:failed",SKIPPED:"generate:skipped"};fA();var WU2=f.object({skipIfDraftExists:f.boolean().optional(),minSourceEntities:f.number().optional(),maxUnpublishedDrafts:f.number().optional(),sourceEntityType:f.string().optional()}),sX1=f.object({entitySchedules:f.record(f.string(),f.string()).optional(),generationSchedules:f.record(f.string(),f.string()).optional(),generationConditions:f.record(f.string(),WU2).optional(),maxRetries:f.number().optional().default(3),retryBaseDelayMs:f.number().optional().default(5000)});class NJ{static instance=null;queues=new Map;static getInstance(){return NJ.instance??=new NJ,NJ.instance}static resetInstance(){NJ.instance=null}static createFresh(){return new NJ}constructor(){}async add(A,Q){let B=this.getOrCreateQueue(A),w=B.find((D)=>D.entityId===Q);if(w)return{position:w.position};let $=B.length+1,I={entityId:Q,entityType:A,position:$,queuedAt:new Date().toISOString()};return B.push(I),{position:$}}async remove(A,Q){let B=this.queues.get(A);if(!B)return;let w=B.findIndex(($)=>$.entityId===Q);if(w===-1)return;B.splice(w,1),this.recalculatePositions(B)}async reorder(A,Q,B){let w=this.queues.get(A);if(!w)return;let $=w.findIndex((Y)=>Y.entityId===Q);if($===-1)return;let[I]=w.splice($,1);if(!I)return;let D=Math.max(0,Math.min(B-1,w.length));w.splice(D,0,I),this.recalculatePositions(w)}async list(A){let Q=this.queues.get(A);if(!Q)return[];return[...Q]}async getNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;return Q[0]??null}async getNextAcrossTypes(){let A=null;for(let Q of this.queues.values()){let B=Q[0];if(!B)continue;if(!A||B.queuedAt<A.queuedAt)A=B}return A}async popNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let B=Q.shift()??null;if(B)this.recalculatePositions(Q);return B}getRegisteredTypes(){return Array.from(this.queues.keys())}async getQueuedEntityTypes(){let A=[];for(let[Q,B]of this.queues.entries())if(B.length>0)A.push(Q);return A}getOrCreateQueue(A){let Q=this.queues.get(A);if(!Q)Q=[],this.queues.set(A,Q);return Q}recalculatePositions(A){A.forEach((Q,B)=>{Q.position=B+1})}}class qJ{static instance=null;providers=new Map;defaultProvider=new MvA;static getInstance(){return qJ.instance??=new qJ,qJ.instance}static resetInstance(){qJ.instance=null}static createFresh(){return new qJ}constructor(){}register(A,Q){this.providers.set(A,Q)}get(A){return this.providers.get(A)??this.defaultProvider}has(A){return this.providers.has(A)}unregister(A){this.providers.delete(A)}getRegisteredTypes(){return Array.from(this.providers.keys())}}fA();fA();async function aX1(A,Q){let B={entityType:A.entityType,entityId:A.entityId};if(Q.messageBus)await Q.messageBus.send({type:I7.EXECUTE,payload:B,sender:"publish-service"});Q.onExecute?.(B)}async function tX1(A,Q){let B=Q.providerRegistry.get(A.entityType);if(!Q.entityService){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"EntityService not available for provider mode",retryCount:0,willRetry:!1});return}let w=await Q.entityService.getEntity({entityType:A.entityType,id:A.entityId});if(!w){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:`Entity not found: ${A.entityType}/${A.entityId}`,retryCount:0,willRetry:!1});return}try{let $=await B.publish(w.content,w.metadata);Q.retryTracker.clearRetries(A.entityId),Q.onPublish?.({entityType:A.entityType,entityId:A.entityId,result:$})}catch($){let I=S0($);Q.retryTracker.recordFailure(A.entityId,I);let D=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:I,retryCount:D?.retryCount??1,willRetry:D?.willRetry??!1})}}function eX1(A,Q,B,w){if(w.retryTracker.clearRetries(Q),w.messageBus)w.messageBus.send({type:I7.COMPLETED,payload:{entityType:A,entityId:Q,result:B},sender:"publish-service"});w.onPublish?.({entityType:A,entityId:Q,result:B})}function AW1(A,Q,B,w){w.retryTracker.recordFailure(Q,B);let $=w.retryTracker.getRetryInfo(Q),I={entityType:A,entityId:Q,error:B,retryCount:$?.retryCount??1,willRetry:$?.willRetry??!1};if(w.messageBus)w.messageBus.send({type:I7.FAILED,payload:I,sender:"publish-service"});w.onFailed?.(I)}async function QW1(A,Q){let B=Q.generationConditions[A];if(B&&Q.onCheckGenerationConditions){let $=await Q.onCheckGenerationConditions(A,B);if(!$.shouldGenerate){if(Q.messageBus)Q.messageBus.send({type:FN.SKIPPED,payload:{entityType:A,reason:$.reason??"Conditions not met"},sender:"content-pipeline"});return}}let w={entityType:A};if(Q.messageBus)await Q.messageBus.send({type:FN.EXECUTE,payload:w,sender:"content-pipeline"});Q.onGenerate?.(w)}function BW1(A,Q,B){if(B)B.send({type:FN.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function wW1(A,Q,B){if(B)B.send({type:FN.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var HU2=1000;class CvA{deps;publishJobs=new Map;immediateIntervalJob=null;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.entitySchedules)){let B=this.deps.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,B)}this.immediateIntervalJob=this.deps.config.backend.scheduleInterval(HU2,()=>this.processUnscheduledTypes())}stop(){if(UU2(this.publishJobs),this.immediateIntervalJob)this.immediateIntervalJob.stop(),this.immediateIntervalJob=null}async processEntityType(A){if(!this.deps.isRunning())return;try{let Q=await this.deps.config.queueManager.getNext(A);if(Q)await this.processEntry(Q)}catch(Q){this.deps.config.logger.error(`Scheduler error for ${A}:`,Q)}}async processUnscheduledTypes(){if(!this.deps.isRunning())return;try{let A=await this.deps.config.queueManager.getQueuedEntityTypes();for(let Q of A)if(!this.entitySchedules[Q]){let B=await this.deps.config.queueManager.getNext(Q);if(B){await this.processEntry(B);break}}}catch(A){this.deps.config.logger.error("Scheduler error for unscheduled types:",A)}}async processEntry(A){if(await this.deps.config.queueManager.remove(A.entityType,A.entityId),this.deps.config.messageBus!==void 0)await aX1(A,this.deps.getPublishDeps());else await tX1(A,this.deps.getPublishDeps())}get entitySchedules(){return this.deps.config.entitySchedules}}function UU2(A){for(let Q of A.values())Q.stop();A.clear()}class OvA{deps;generationJobs=new Map;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.generationSchedules)){let B=this.deps.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,B)}}stop(){JU2(this.generationJobs)}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await QW1(A,this.deps.getGenerationDeps())}catch(Q){this.deps.config.logger.error(`Generation trigger error for ${A}:`,Q)}}get generationSchedules(){return this.deps.config.generationSchedules}}function JU2(A){for(let Q of A.values())Q.stop();A.clear()}class BH{static instance=null;config;publishRunner;generationRunner;running=!1;static getInstance(A){return BH.instance??=new BH(A),BH.instance}static resetInstance(){if(BH.instance)BH.instance.stop();BH.instance=null}static createFresh(A){return new BH(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new CvA({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new OvA({config:this.config,getGenerationDeps:()=>this.generationDeps,isRunning:()=>this.running})}async start(){if(this.running)return;this.running=!0,this.publishRunner.start(),this.generationRunner.start()}async stop(){this.running=!1,this.publishRunner.stop(),this.generationRunner.stop()}isRunning(){return this.running}completePublish(A,Q,B){eX1(A,Q,B,this.publishDeps)}failPublish(A,Q,B){AW1(A,Q,B,this.publishDeps)}async publishDirect(A,Q,B,w){return this.config.providerRegistry.get(A).publish(B,w)}completeGeneration(A,Q){BW1(A,Q,this.config.messageBus)}failGeneration(A,Q){wW1(A,Q,this.config.messageBus)}get entitySchedules(){return this.config.entitySchedules}get generationSchedules(){return this.config.generationSchedules}get publishDeps(){return{providerRegistry:this.config.providerRegistry,retryTracker:this.config.retryTracker,messageBus:this.config.messageBus,entityService:this.config.entityService,onExecute:this.config.onExecute,onPublish:this.config.onPublish,onFailed:this.config.onFailed}}get generationDeps(){return{logger:this.config.logger,messageBus:this.config.messageBus,generationConditions:this.config.generationConditions,onCheckGenerationConditions:this.config.onCheckGenerationConditions,onGenerate:this.config.onGenerate}}validateCronExpressions(){for(let[A,Q]of Object.entries(this.entitySchedules))this.validateCronExpression(A,Q,"publish");for(let[A,Q]of Object.entries(this.generationSchedules))this.validateCronExpression(A,Q,"generation")}validateCronExpression(A,Q,B){try{this.config.backend.validateCron(Q)}catch(w){throw Error(`Invalid ${B} cron expression for ${A}: "${Q}" - ${S0(w)}`)}}}var $W1={maxRetries:3,baseDelayMs:5000};class LJ{static instance=null;retries=new Map;config;static getInstance(A){return LJ.instance??=new LJ(A??$W1),LJ.instance}static resetInstance(){LJ.instance=null}static createFresh(A){return new LJ(A??$W1)}constructor(A){this.config=A}recordFailure(A,Q){let w=(this.retries.get(A)?.retryCount??0)+1,$=this.config.baseDelayMs*Math.pow(2,w-1),I=Date.now()+$;this.retries.set(A,{entityId:A,retryCount:w,lastError:Q,nextRetryAt:I})}shouldRetry(A){let Q=this.retries.get(A);if(!Q)return!1;return Q.retryCount<this.config.maxRetries}isReadyForRetry(A){let Q=this.retries.get(A);if(!Q)return!1;return Date.now()>=Q.nextRetryAt}clearRetries(A){this.retries.delete(A)}getRetryInfo(A){let Q=this.retries.get(A);if(!Q)return null;return{entityId:Q.entityId,retryCount:Q.retryCount,lastError:Q.lastError,nextRetryAt:Q.nextRetryAt,willRetry:Q.retryCount<this.config.maxRetries}}}function D7(A,Q,B,w,$,I,D,Y){return D7.fromTZ(D7.tp(A,Q,B,w,$,I,D),Y)}D7.fromTZISO=(A,Q,B)=>D7.fromTZ(GU2(A,Q),B);D7.fromTZ=function(A,Q){let B=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),w=RvA(A.tz,B),$=new Date(B.getTime()-w),I=RvA(A.tz,$);if(I-w===0)return $;{let D=new Date(B.getTime()-I),Y=RvA(A.tz,D);if(Y-I===0)return D;if(!Q&&Y-I>0)return D;if(Q)throw Error("Invalid date passed to fromTZ()");return $}};D7.toTZ=function(A,Q){let B=A.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),w=new Date(B);return{y:w.getFullYear(),m:w.getMonth()+1,d:w.getDate(),h:w.getHours(),i:w.getMinutes(),s:w.getSeconds(),tz:Q}};D7.tp=(A,Q,B,w,$,I,D)=>({y:A,m:Q,d:B,h:w,i:$,s:I,tz:D});function RvA(A,Q=new Date){let B=Q.toLocaleString("en-US",{timeZone:A,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],w=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${w} GMT`)-Date.parse(`${w} ${B}`)}function GU2(A,Q){let B=new Date(Date.parse(A));if(isNaN(B))throw Error("minitz: Invalid ISO8601 passed to parser.");let w=A.substring(9);return A.includes("Z")||w.includes("-")||w.includes("+")?D7.tp(B.getUTCFullYear(),B.getUTCMonth()+1,B.getUTCDate(),B.getUTCHours(),B.getUTCMinutes(),B.getUTCSeconds(),"Etc/UTC"):D7.tp(B.getFullYear(),B.getMonth()+1,B.getDate(),B.getHours(),B.getMinutes(),B.getSeconds(),Q)}D7.minitz=D7;var bvA=32,Ap=31|bvA,XW1=[1,2,4,8,16],IW1=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(A,Q){this.pattern=A,this.timezone=Q,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern=="string"||this.pattern instanceof String))throw TypeError("CronPattern: Pattern has to be of type string.");this.pattern.indexOf("@")>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let A=this.pattern.replace(/\s+/g," ").split(" ");if(A.length<5||A.length>6)throw TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exactly five or six space separated parts are required.");if(A.length===5&&A.unshift("0"),A[3].indexOf("L")>=0&&(A[3]=A[3].replace("L",""),this.lastDayOfMonth=!0),A[3]=="*"&&(this.starDOM=!0),A[4].length>=3&&(A[4]=this.replaceAlphaMonths(A[4])),A[5].length>=3&&(A[5]=this.replaceAlphaDays(A[5])),A[5]=="*"&&(this.starDOW=!0),this.pattern.indexOf("?")>=0){let Q=new nY(new Date,this.timezone).getDate(!0);A[0]=A[0].replace("?",Q.getSeconds().toString()),A[1]=A[1].replace("?",Q.getMinutes().toString()),A[2]=A[2].replace("?",Q.getHours().toString()),this.starDOM||(A[3]=A[3].replace("?",Q.getDate().toString())),A[4]=A[4].replace("?",(Q.getMonth()+1).toString()),this.starDOW||(A[5]=A[5].replace("?",Q.getDay().toString()))}this.throwAtIllegalCharacters(A),this.partToArray("second",A[0],0,1),this.partToArray("minute",A[1],0,1),this.partToArray("hour",A[2],0,1),this.partToArray("day",A[3],-1,1),this.partToArray("month",A[4],-1,1),this.partToArray("dayOfWeek",A[5],0,Ap),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(A,Q,B,w){let $=this[A],I=A==="day"&&this.lastDayOfMonth;if(Q===""&&!I)throw TypeError("CronPattern: configuration entry "+A+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return $.fill(w);let D=Q.split(",");if(D.length>1)for(let Y=0;Y<D.length;Y++)this.partToArray(A,D[Y],B,w);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,A,B,w):Q.indexOf("-")!==-1?this.handleRange(Q,A,B,w):Q.indexOf("/")!==-1?this.handleStepping(Q,A,B,w):Q!==""&&this.handleNumber(Q,A,B,w)}throwAtIllegalCharacters(A){for(let Q=0;Q<A.length;Q++)if((Q===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(A[Q]))throw TypeError("CronPattern: configuration entry "+Q+" ("+A[Q]+") contains illegal characters.")}handleNumber(A,Q,B,w){let $=this.extractNth(A,Q),I=parseInt($[0],10)+B;if(isNaN(I))throw TypeError("CronPattern: "+Q+" is not a number: '"+A+"'");this.setPart(Q,I,$[1]||w)}setPart(A,Q,B){if(!Object.prototype.hasOwnProperty.call(this,A))throw TypeError("CronPattern: Invalid part specified: "+A);if(A==="dayOfWeek"){if(Q===7&&(Q=0),Q<0||Q>6)throw RangeError("CronPattern: Invalid value for dayOfWeek: "+Q);this.setNthWeekdayOfMonth(Q,B);return}if(A==="second"||A==="minute"){if(Q<0||Q>=60)throw RangeError("CronPattern: Invalid value for "+A+": "+Q)}else if(A==="hour"){if(Q<0||Q>=24)throw RangeError("CronPattern: Invalid value for "+A+": "+Q)}else if(A==="day"){if(Q<0||Q>=31)throw RangeError("CronPattern: Invalid value for "+A+": "+Q)}else if(A==="month"&&(Q<0||Q>=12))throw RangeError("CronPattern: Invalid value for "+A+": "+Q);this[A][Q]=B}handleRangeWithStepping(A,Q,B,w){let $=this.extractNth(A,Q),I=$[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(I===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+A+"'");let[,D,Y,X]=I,W=parseInt(D,10)+B,U=parseInt(Y,10)+B,K=parseInt(X,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(U))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(K))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(K===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(K>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if(W>U)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let F=W;F<=U;F+=K)this.setPart(Q,F,$[1]||w)}extractNth(A,Q){let B=A,w;if(B.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");w=B.split("#")[1],B=B.split("#")[0]}return[B,w]}handleRange(A,Q,B,w){let $=this.extractNth(A,Q),I=$[0].split("-");if(I.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+A+"'");let D=parseInt(I[0],10)+B,Y=parseInt(I[1],10)+B;if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(D>Y)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let X=D;X<=Y;X++)this.setPart(Q,X,$[1]||w)}handleStepping(A,Q,B,w){let $=this.extractNth(A,Q),I=$[0].split("/");if(I.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+A+"'");I[0]===""&&(I[0]="*");let D=0;I[0]!=="*"&&(D=parseInt(I[0],10)+B);let Y=parseInt(I[1],10);if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Y===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Y>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let X=D;X<this[Q].length;X+=Y)this.setPart(Q,X,$[1]||w)}replaceAlphaDays(A){return A.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")}replaceAlphaMonths(A){return A.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")}handleNicknames(A){let Q=A.trim().toLowerCase();return Q==="@yearly"||Q==="@annually"?"0 0 1 1 *":Q==="@monthly"?"0 0 1 * *":Q==="@weekly"?"0 0 * * 0":Q==="@daily"?"0 0 * * *":Q==="@hourly"?"0 * * * *":A}setNthWeekdayOfMonth(A,Q){if(typeof Q!="number"&&Q==="L")this.dayOfWeek[A]=this.dayOfWeek[A]|bvA;else if(Q===Ap)this.dayOfWeek[A]=Ap;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|XW1[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},DW1=[31,28,31,30,31,30,31,31,30,31,30,31],Ef=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],nY=class A{tz;ms;second;minute;hour;day;month;year;constructor(Q,B){if(this.tz=B,Q&&Q instanceof Date)if(!isNaN(Q))this.fromDate(Q);else throw TypeError("CronDate: Invalid date passed to CronDate constructor");else if(Q===void 0)this.fromDate(new Date);else if(Q&&typeof Q=="string")this.fromString(Q);else if(Q instanceof A)this.fromCronDate(Q);else throw TypeError("CronDate: Invalid type ("+typeof Q+") passed to CronDate constructor")}isNthWeekdayOfMonth(Q,B,w,$){let I=new Date(Date.UTC(Q,B,w)).getUTCDay(),D=0;for(let Y=1;Y<=w;Y++)new Date(Date.UTC(Q,B,Y)).getUTCDay()===I&&D++;if($&Ap&&XW1[D-1]&$)return!0;if($&bvA){let Y=new Date(Date.UTC(Q,B+1,0)).getUTCDate();for(let X=w+1;X<=Y;X++)if(new Date(Date.UTC(Q,B,X)).getUTCDay()===I)return!1;return!0}return!1}fromDate(Q){if(this.tz!==void 0)if(typeof this.tz=="number")this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes()+this.tz,this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),this.apply();else{let B=D7.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=B.s,this.minute=B.i,this.hour=B.h,this.day=B.d,this.month=B.m-1,this.year=B.y}else this.ms=Q.getMilliseconds(),this.second=Q.getSeconds(),this.minute=Q.getMinutes(),this.hour=Q.getHours(),this.day=Q.getDate(),this.month=Q.getMonth(),this.year=Q.getFullYear()}fromCronDate(Q){this.tz=Q.tz,this.year=Q.year,this.month=Q.month,this.day=Q.day,this.hour=Q.hour,this.minute=Q.minute,this.second=Q.second,this.ms=Q.ms}apply(){if(this.month>11||this.day>DW1[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let Q=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=Q.getUTCMilliseconds(),this.second=Q.getUTCSeconds(),this.minute=Q.getUTCMinutes(),this.hour=Q.getUTCHours(),this.day=Q.getUTCDate(),this.month=Q.getUTCMonth(),this.year=Q.getUTCFullYear(),!0}else return!1}fromString(Q){if(typeof this.tz=="number"){let B=D7.fromTZISO(Q);this.ms=B.getUTCMilliseconds(),this.second=B.getUTCSeconds(),this.minute=B.getUTCMinutes(),this.hour=B.getUTCHours(),this.day=B.getUTCDate(),this.month=B.getUTCMonth(),this.year=B.getUTCFullYear(),this.apply()}else return this.fromDate(D7.fromTZISO(Q,this.tz))}findNext(Q,B,w,$){let I=this[B],D;w.lastDayOfMonth&&(this.month!==1?D=DW1[this.month]:D=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let Y=!w.starDOW&&B=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let X=this[B]+$;X<w[B].length;X++){let W=w[B][X];if(B==="day"&&w.lastDayOfMonth&&X-$==D&&(W=1),B==="day"&&!w.starDOW){let U=w.dayOfWeek[(Y+(X-$-1))%7];if(U&&U&Ap)U=this.isNthWeekdayOfMonth(this.year,this.month,X-$,U)?1:0;else if(U)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${U}`);Q.legacyMode&&!w.starDOM?W=W||U:W=W&&U}if(W)return this[B]=X-$,I!==this[B]?2:1}return 3}recurse(Q,B,w){let $=this.findNext(B,Ef[w][0],Q,Ef[w][2]);if($>1){let I=w+1;for(;I<Ef.length;)this[Ef[I][0]]=-Ef[I][2],I++;if($===3)return this[Ef[w][1]]++,this[Ef[w][0]]=-Ef[w][2],this.apply(),this.recurse(Q,B,0);if(this.apply())return this.recurse(Q,B,w-1)}return w+=1,w>=Ef.length?this:this.year>=3000?null:this.recurse(Q,B,w)}increment(Q,B,w){return this.second+=B.interval!==void 0&&B.interval>1&&w?B.interval:1,this.ms=0,this.apply(),this.recurse(Q,B,0)}getDate(Q){return Q||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz=="number"?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):D7.fromTZ(D7.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function KU2(A){if(A===void 0&&(A={}),delete A.name,A.legacyMode=A.legacyMode===void 0?!0:A.legacyMode,A.paused=A.paused===void 0?!1:A.paused,A.maxRuns=A.maxRuns===void 0?1/0:A.maxRuns,A.catch=A.catch===void 0?!1:A.catch,A.interval=A.interval===void 0?0:parseInt(A.interval.toString(),10),A.utcOffset=A.utcOffset===void 0?void 0:parseInt(A.utcOffset.toString(),10),A.unref=A.unref===void 0?!1:A.unref,A.startAt&&(A.startAt=new nY(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new nY(A.stopAt,A.timezone)),A.interval!==null){if(isNaN(A.interval))throw Error("CronOptions: Supplied value for interval is not a number");if(A.interval<0)throw Error("CronOptions: Supplied value for interval can not be negative")}if(A.utcOffset!==void 0){if(isNaN(A.utcOffset))throw Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");if(A.utcOffset<-870||A.utcOffset>870)throw Error("CronOptions: utcOffset out of bounds.");if(A.utcOffset!==void 0&&A.timezone)throw Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}if(A.unref!==!0&&A.unref!==!1)throw Error("CronOptions: Unref should be either true, false or undefined(false).");return A}function ec(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function fU2(A){return ec(A)}function FU2(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var YW1=30000,bwA=[],PvA=class{name;options;_states;fn;constructor(A,Q,B){let w,$;if(ec(Q))$=Q;else if(typeof Q=="object")w=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(ec(B))$=B;else if(typeof B=="object")w=B;else if(B!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=w?.name,this.options=KU2(w),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:w?w.maxRuns:void 0,paused:w?w.paused:!1,pattern:new IW1("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new nY(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new IW1(A,this.options.timezone),this.name){if(bwA.find((I)=>I.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");bwA.push(this)}return $!==void 0&&fU2($)&&(this.fn=$,this.schedule()),this}nextRun(A){let Q=this._next(A);return Q?Q.getDate(!1):null}nextRuns(A,Q){this._states.maxRuns!==void 0&&A>this._states.maxRuns&&(A=this._states.maxRuns);let B=[],w=Q||this._states.currentRun||void 0;for(;A--&&(w=this.nextRun(w));)B.push(w);return B}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let A=this.nextRun(this._states.currentRun),Q=!this._states.paused,B=this.fn!==void 0,w=!this._states.kill;return Q&&B&&w&&A!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(A){let Q=this._next(A);return Q?A instanceof nY||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new nY(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=bwA.indexOf(this);A>=0&&bwA.splice(A,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(A){if(A&&this.fn)throw Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");A&&(this.fn=A);let Q=this.msToNext(),B=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||B===null?this:(Q>YW1&&(Q=YW1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(B),Q),this._states.currentTimeout&&this.options.unref&&FU2(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new nY(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(Q){ec(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new nY(A,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(A){let Q=new Date,B=!this._states.paused&&Q.getTime()>=A.getTime(),w=this._states.blocking&&this.options.protect;B&&!w?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):B&&w&&ec(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(A){let Q=!!(A||this._states.currentRun),B=!1;!A&&this.options.startAt&&this.options.interval&&([A,Q]=this._calculatePreviousRun(A,Q),B=!A),A=new nY(A,this.options.timezone||this.options.utcOffset),this.options.startAt&&A&&A.getTime()<this.options.startAt.getTime()&&(A=this.options.startAt);let w=this._states.once||new nY(A,this.options.timezone||this.options.utcOffset);return!B&&w!==this._states.once&&(w=w.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=A.getTime()||w===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&w.getTime()>=this.options.stopAt.getTime()?null:w}_calculatePreviousRun(A,Q){let B=new nY(void 0,this.options.timezone||this.options.utcOffset),w=A;if(this.options.startAt.getTime()<=B.getTime()){w=this.options.startAt;let $=w.getTime()+this.options.interval*1000;for(;$<=B.getTime();)w=new nY(w,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),$=w.getTime()+this.options.interval*1000;Q=!0}return w===null&&(w=void 0),[w,Q]}};class PwA{scheduleCron(A,Q){let B=new PvA(A,()=>{Q()});return{stop:()=>B.stop()}}scheduleInterval(A,Q){let B=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(B)}}validateCron(A){new PvA(A).stop()}}eA();fA();var jvA=f.object({action:f.enum(["list","add","remove","reorder"]).describe("Queue action to perform"),entityType:f.string().optional().describe("Entity type (required for add/remove/reorder, optional for list)"),entityId:f.string().optional().describe("Entity ID (required for add/remove/reorder)"),position:f.number().optional().describe("New position for reorder action (1-based)")}),kvA=f.object({position:f.number(),entityType:f.string(),entityId:f.string(),queuedAt:f.string()}),ZU2=f.object({success:f.literal(!0),message:f.string().optional(),data:f.object({queue:f.array(kvA).optional(),entityType:f.string().optional(),entityId:f.string().optional(),position:f.number().optional()}).optional()}),zU2=f.object({success:f.literal(!1),error:f.string(),code:f.string().optional()}),_vA=f.union([ZU2,zU2]);function jwA(A,Q,B){return{...j2(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",jvA,async($)=>{let{action:I,entityType:D,entityId:Y,position:X}=$;switch(I){case"list":return NU2(B,D);case"add":return qU2(B,D,Y);case"remove":return LU2(B,D,Y);case"reorder":return EU2(B,D,Y,X);default:return{success:!1,error:`Unknown action: ${I}`}}}),outputSchema:_vA}}async function NU2(A,Q){let B=[];if(Q)B=await A.list(Q);else{let $=A.getRegisteredTypes();for(let I of $){let D=await A.list(I);B.push(...D)}B.sort((I,D)=>new Date(I.queuedAt).getTime()-new Date(D.queuedAt).getTime())}if(B.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:B.map(($,I)=>({position:I+1,entityType:$.entityType,entityId:$.entityId,queuedAt:$.queuedAt}))},message:`${B.length} items in queue`}}async function qU2(A,Q,B){let w=vvA("add",Q,B);if(!w.success)return w.error;let $=await A.add(w.entityType,w.entityId);return{success:!0,data:{entityType:w.entityType,entityId:w.entityId,position:$.position},message:`Added to queue at position ${$.position}`}}async function LU2(A,Q,B){let w=vvA("remove",Q,B);if(!w.success)return w.error;return await A.remove(w.entityType,w.entityId),{success:!0,data:{entityType:w.entityType,entityId:w.entityId},message:"Removed from queue"}}async function EU2(A,Q,B,w){let $=vvA("reorder",Q,B);if(!$.success)return $.error;let I=VU2(w);if(!I.success)return I.error;return await A.reorder($.entityType,$.entityId,I.position),{success:!0,data:{entityType:$.entityType,entityId:$.entityId,position:I.position},message:`Moved to position ${I.position}`}}function vvA(A,Q,B){if(!Q)return{success:!1,error:{success:!1,error:`entityType is required for ${A} action`}};if(!B)return{success:!1,error:{success:!1,error:`entityId is required for ${A} action`}};return{success:!0,entityType:Q,entityId:B}}function VU2(A){if(A===void 0)return{success:!1,error:{success:!1,error:"position is required for reorder action"}};if(A<1)return{success:!1,error:{success:!1,error:"position must be a positive number"}};return{success:!0,position:A}}eA();fA();eA();fA();var MU2=f.object({id:f.string().min(1)});async function HW1(A,Q){let{bodyContent:B,coverImageId:w,documents:$,sourceEntityType:I,sourceEntityId:D}=CU2(Q.content),Y=w?await bU2(A,w):void 0,X;if($&&$.length>0){let U=await PU2(A,$);if(U.length>0)X=U}X??=await RU2(A,I,D);let W={bodyContent:B};if(Y)W.imageData=Y;if(X&&X.length>0)W.documentData=X;return W}function CU2(A){try{let Q=$2(A,f.record(f.unknown())),B=Q.metadata.coverImageId,w=typeof B==="string"?B:void 0,$=OU2(Q.metadata.documents),I=WW1(Q.metadata.sourceEntityType),D=WW1(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...w&&{coverImageId:w},...$.length>0&&{documents:$},...I&&{sourceEntityType:I},...D&&{sourceEntityId:D}}}catch{return{bodyContent:A}}}function OU2(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let B=MU2.safeParse(Q);return B.success?[B.data]:[]})}function WW1(A){return typeof A==="string"&&A.length>0?A:void 0}async function RU2(A,Q,B){if(!Q||!B)return;let w=await A.attachments.resolve({sourceEntityType:Q,sourceEntityId:B,attachmentType:"carousel"});return w?[w]:void 0}async function bU2(A,Q){let B=await A.entityService.getEntity({entityType:"image",id:Q});if(!B?.content)return;let w=UW1(B.content);if(!w?.mimeType.startsWith("image/"))return;return{data:w.data,mimeType:w.mimeType}}async function PU2(A,Q){return(await Promise.all(Q.map((w)=>jU2(A,w)))).filter((w)=>w!==void 0)}async function jU2(A,Q){let B=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!B?.content)return;let w=UW1(B.content);if(w?.mimeType!=="application/pdf")return;return{type:"document",data:w.data,mimeType:"application/pdf",filename:kU2(B,Q.id)}}function UW1(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function kU2(A,Q){let B=A.metadata.filename;return typeof B==="string"&&B.length>0?B:`${Q}.pdf`}var xvA=f.object({entityType:f.string().describe("Entity type to publish (e.g., social-post, post, deck)"),id:f.string().optional().describe("Entity ID to publish"),slug:f.string().optional().describe("Entity slug to publish")}),_U2=f.object({success:f.literal(!0),message:f.string().optional(),data:f.object({entityType:f.string().optional(),entityId:f.string().optional(),platformId:f.string().optional(),url:f.string().optional()}).optional()}),vU2=f.object({success:f.literal(!1),error:f.string(),code:f.string().optional()}),yvA=f.union([_U2,vU2]);function kwA(A,Q,B){return{...j2(Q,"publish","Publish an entity directly to its platform. Works with any registered entity type (social-post, post, deck, etc.)",xvA,async($)=>{let{entityType:I,id:D,slug:Y}=$;if(!D&&!Y)return{success:!1,error:"Either 'id' or 'slug' must be provided"};let X=await xU2(A,I,D,Y);if(!X)return{success:!1,error:`Entity not found: ${I}:${D??Y}`};if(X.visibility!=="public")return{success:!1,error:`Cannot publish ${I}:${X.id} to a public provider because visibility is ${X.visibility}`};if(X.metadata.status==="published")return{success:!1,error:"Entity is already published"};if(!B.has(I))return{success:!1,error:`No publish provider registered for ${I}. Check that the required credentials are configured.`};let W=B.get(I),{bodyContent:U,imageData:K,documentData:F}=await HW1(A,X),Z=await W.publish(U,X.metadata,K,F);return await A.entityService.updateEntity({entity:{...X,metadata:{...X.metadata,status:"published",publishedAt:new Date().toISOString(),platformId:Z.id}}}),{success:!0,data:{entityType:I,entityId:X.id,platformId:Z.id,url:Z.url},message:`Published ${I}:${X.id}`}}),outputSchema:yvA}}async function xU2(A,Q,B,w){if(B)return A.entityService.getEntity({entityType:Q,id:B});if(!w)return null;return(await A.entityService.listEntities({entityType:Q,options:{filter:{metadata:{slug:w}},limit:1}}))[0]??null}eA();fA();function JW1(A,Q){yU2(A,Q),TU2(A,Q)}function yU2(A,Q){A.messaging.subscribe(I7.REGISTER,async(B)=>SU2(Q,B.payload)),A.messaging.subscribe(I7.QUEUE,async(B)=>gU2(A,Q,B.payload)),A.messaging.subscribe(I7.DIRECT,async(B)=>hU2(A,Q,B.payload)),A.messaging.subscribe(I7.REMOVE,async(B)=>mU2(Q,B.payload)),A.messaging.subscribe(I7.REORDER,async(B)=>uU2(Q,B.payload)),A.messaging.subscribe(I7.LIST,async(B)=>cU2(A,Q,B.payload)),A.messaging.subscribe(I7.REPORT_SUCCESS,async(B)=>pU2(Q,B.payload)),A.messaging.subscribe(I7.REPORT_FAILURE,async(B)=>lU2(Q,B.payload)),Q.logger.debug("Subscribed to publish messages")}function TU2(A,Q){A.messaging.subscribe(FN.REPORT_SUCCESS,async(B)=>iU2(Q,B.payload)),A.messaging.subscribe(FN.REPORT_FAILURE,async(B)=>dU2(Q,B.payload)),Q.logger.debug("Subscribed to generation messages")}async function SU2(A,Q){let{entityType:B,provider:w}=Q;try{if(w)A.providerRegistry.register(B,w),A.logger.info(`Registered provider for entity type: ${B}`,{providerName:w.name});return{success:!0}}catch($){let I=S0($);return A.logger.error(`Failed to register provider: ${I}`),{success:!1}}}async function gU2(A,Q,B){let{entityType:w,entityId:$}=B;try{let I=await Q.queueManager.add(w,$);return await A.messaging.send({type:I7.QUEUED,payload:{entityType:w,entityId:$,position:I.position}}),Q.logger.debug(`Entity queued: ${$}`,{entityType:w,position:I.position}),{success:!0}}catch(I){let D=S0(I);return Q.logger.error(`Failed to queue entity: ${D}`),{success:!1}}}async function hU2(A,Q,B){let{entityType:w,entityId:$}=B;return await A.messaging.send({type:I7.EXECUTE,payload:{entityType:w,entityId:$}}),Q.logger.debug(`Direct publish requested: ${$}`,{entityType:w}),{success:!0}}async function mU2(A,Q){let{entityType:B,entityId:w}=Q;try{return await A.queueManager.remove(B,w),A.logger.debug(`Entity removed from queue: ${w}`,{entityType:B}),{success:!0}}catch($){let I=S0($);return A.logger.error(`Failed to remove entity: ${I}`),{success:!1}}}async function uU2(A,Q){let{entityType:B,entityId:w,position:$}=Q;try{return await A.queueManager.reorder(B,w,$),A.logger.debug(`Entity reordered: ${w}`,{entityType:B,newPosition:$}),{success:!0}}catch(I){let D=S0(I);return A.logger.error(`Failed to reorder entity: ${D}`),{success:!1}}}async function cU2(A,Q,B){let{entityType:w}=B;try{let $=await Q.queueManager.list(w);return await A.messaging.send({type:I7.LIST_RESPONSE,payload:{entityType:w,queue:$.map((I)=>({entityId:I.entityId,position:I.position,queuedAt:I.queuedAt}))}}),{success:!0}}catch($){let I=S0($);return Q.logger.error(`Failed to list queue: ${I}`),{success:!1}}}async function pU2(A,Q){let{entityType:B,entityId:w,result:$}=Q;return A.scheduler.completePublish(B,w,$),A.logger.info(`Publish reported success: ${w}`,{entityType:B}),{success:!0}}async function lU2(A,Q){let{entityType:B,entityId:w,error:$}=Q;A.scheduler.failPublish(B,w,$);let I=A.retryTracker.getRetryInfo(w);return A.logger.info(`Publish reported failure: ${w}`,{entityType:B,error:$,retryCount:I?.retryCount,willRetry:I?.willRetry}),{success:!0}}async function iU2(A,Q){let{entityType:B,entityId:w}=Q;return A.scheduler.completeGeneration(B,w),A.logger.info("Generation completed",{entityType:B,entityId:w}),{success:!0}}async function dU2(A,Q){let{entityType:B,error:w}=Q;return A.scheduler.failGeneration(B,w),A.logger.warn("Generation failed",{entityType:B,error:w}),{success:!0}}fA();async function GW1(A,Q,B,w){try{if(w.skipIfDraftExists!==!1){if((await A.listEntities({entityType:B,options:{filter:{metadata:{status:"draft"}},limit:1}})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(w.maxUnpublishedDrafts!==void 0){let $=await A.listEntities({entityType:B,options:{filter:{metadata:{status:"draft"}},limit:w.maxUnpublishedDrafts+1}});if($.length>=w.maxUnpublishedDrafts)return{shouldGenerate:!1,reason:`Max unpublished drafts reached (${$.length}/${w.maxUnpublishedDrafts})`}}if(w.minSourceEntities!==void 0&&w.sourceEntityType){let $=await A.listEntities({entityType:w.sourceEntityType,options:{publishedOnly:!0,limit:w.minSourceEntities}});if($.length<w.minSourceEntities)return{shouldGenerate:!1,reason:`Not enough source entities (${$.length}/${w.minSourceEntities} ${w.sourceEntityType})`}}return{shouldGenerate:!0}}catch($){return Q.error("Failed to check generation conditions",{entityType:B,error:S0($)}),{shouldGenerate:!1,reason:`Condition check failed: ${S0($)}`}}}function KW1(A){let{context:Q,config:B,queueManager:w,providerRegistry:$,retryTracker:I,logger:D}=A,Y=rU2(Q);return BH.createFresh({queueManager:w,providerRegistry:$,retryTracker:I,logger:D,backend:new PwA,...B.entitySchedules&&{entitySchedules:B.entitySchedules},...B.generationSchedules&&{generationSchedules:B.generationSchedules},...B.generationConditions&&{generationConditions:B.generationConditions},messageBus:Y,entityService:Q.entityService,onCheckGenerationConditions:(X,W)=>GW1(Q.entityService,D,X,W)})}function rU2(A){return{send:async($)=>{return A.messaging.send({type:$.type,payload:$.payload,...$.target!==void 0?{target:$.target}:{},...$.metadata!==void 0?{metadata:$.metadata}:{},...$.broadcast!==void 0?{broadcast:$.broadcast}:{}})},subscribe:()=>()=>{},unsubscribe:()=>{}}}async function fW1(A,Q,B){let w=A.getEntityTypes();for(let I of w){let D=await A.listEntities({entityType:I,options:{filter:{metadata:{status:"queued"}}}});for(let Y of D)await Q.add(Y.entityType,Y.id)}let $=0;for(let I of w){let D=await Q.list(I);$+=D.length}if($>0)B.info(`Rebuilt queue with ${$} queued entities`)}var nU2=["draft","queued","published","failed"];async function FW1(A,Q){await A.messaging.send({type:"dashboard:register-widget",payload:{id:"publication-pipeline",pluginId:Q,title:"Publication Pipeline",section:"secondary",priority:100,rendererName:"PipelineWidget",visibility:"anchor",dataProvider:()=>oU2(A)}})}async function oU2(A){let Q=A.entityService.getEntityTypes(),B=[],w={draft:0,queued:0,published:0,failed:0};for(let $ of Q){let I=await A.entityService.listEntities({entityType:$});for(let D of I){let Y=sU2(D.metadata.status);if(!Y)continue;w[Y]++,B.push({id:D.id,title:aU2(D.id,D.metadata.title),type:$,status:Y})}}return{summary:w,items:B}}function sU2(A){return nU2.find((Q)=>Q===A)}function aU2(A,Q){return typeof Q==="string"?Q:A}var ZW1={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.93",description:"Content pipeline plugin for managing entity publishing queues, scheduling, and generation",type:"module",main:"src/index.ts",types:"src/index.ts",scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",croner:"^9.1.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",typescript:"^5.3.3"},exports:{".":{types:"./src/index.ts",default:"./src/index.ts"}},files:["src"]};class TvA extends qB{pluginContext;queueManager;providerRegistry;retryTracker;scheduler;constructor(A){super("content-pipeline",ZW1,A??{},sX1)}async onRegister(A){this.pluginContext=A,this.queueManager=NJ.createFresh(),this.providerRegistry=qJ.createFresh(),this.retryTracker=LJ.createFresh({maxRetries:this.config.maxRetries,baseDelayMs:this.config.retryBaseDelayMs}),this.scheduler=KW1({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,logger:this.logger}),JW1(A,{queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,scheduler:this.scheduler,logger:this.logger})}async onReady(A){await fW1(A.entityService,this.queueManager,this.logger),await FW1(A,this.id),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[jwA(this.pluginContext,this.id,this.queueManager),kwA(this.pluginContext,this.id,this.providerRegistry)]}async getInstructions(){return'## Publishing\n- Use `content-pipeline_queue` to manage the publish queue \u2014 list queued items, add entities to the queue, remove them, or reorder.\n- Use `content-pipeline_publish` to publish an entity directly to its platform (e.g. LinkedIn, Buttondown).\n- When users ask about their "publish queue", "publishing queue", or "what\'s queued", use `content-pipeline_queue`.'}getQueueManager(){return this.queueManager}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getScheduler(){return this.scheduler}async onShutdown(){await this.scheduler.stop(),NJ.resetInstance(),qJ.resetInstance(),LJ.resetInstance()}}function SvA(A){return new TvA(A)}eA();fA();var zW1=f.object({accountId:f.string().describe("Cloudflare account ID"),apiToken:f.string().describe("Cloudflare API token with Analytics:Read permission"),siteTag:f.string().describe("Cloudflare Web Analytics site tag")}),gvA=f.object({cloudflare:zW1.optional()});eA();fA();var eU2=f.object({date:f.string().describe("Single date in YYYY-MM-DD format").optional(),days:f.number().min(1).max(365).describe("Number of days back from yesterday (e.g., 7 for last week)").optional(),startDate:f.string().describe("Start date in YYYY-MM-DD format (use with endDate)").optional(),endDate:f.string().describe("End date in YYYY-MM-DD format (use with startDate)").optional(),limit:f.number().min(1).max(100).default(20).describe("Maximum items for breakdowns (pages, referrers, countries)")});function AJ2(A){if(A.date&&(A.days||A.startDate||A.endDate))return"Cannot combine 'date' with 'days' or 'startDate'/'endDate'";if(A.days&&(A.startDate||A.endDate))return"Cannot combine 'days' with 'startDate'/'endDate'";if(A.startDate&&!A.endDate||!A.startDate&&A.endDate)return"Both 'startDate' and 'endDate' must be provided for custom range";return null}function NW1(A,Q,B){let w=[];if(!B)return w;return w.push(j2(A,"query",`Query website analytics from Cloudflare.
|
|
5164
5176
|
|
|
5165
5177
|
Date range options (use only one):
|
|
5166
5178
|
- No params: yesterday only
|
|
@@ -5298,7 +5310,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,eU2,
|
|
|
5298
5310
|
}
|
|
5299
5311
|
}
|
|
5300
5312
|
}
|
|
5301
|
-
`,variables:B})});if(!w.ok){let D=await w.text();throw Error(`Cloudflare API error: ${w.status} - ${D}`)}let $=await w.json();if($.errors&&$.errors.length>0)throw Error(`Cloudflare GraphQL error: ${$.errors.map((D)=>D.message).join(", ")}`);return($.data.viewer.accounts[0]?.rumPageloadEventsAdaptiveGroups??[]).map((D)=>({country:D.dimensions.countryName,visits:D.sum.visits}))}}fA();var mvA=7,QJ2=10;function LW1(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=$C(),B=ei(mvA),w=_F(B),$=_F(Q);try{let[I,D]=await Promise.all([A.getWebsiteStats({startDate:w,endDate:$}),A.getTopPages({startDate:w,endDate:$,limit:QJ2})]);return{days:mvA,startDate:w,endDate:$,pageviews:I.pageviews,visitors:I.visitors,topPages:D}}catch(I){return{error:I instanceof Error?I.message:"Failed to fetch analytics",days:mvA}}}}var EW1={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.
|
|
5313
|
+
`,variables:B})});if(!w.ok){let D=await w.text();throw Error(`Cloudflare API error: ${w.status} - ${D}`)}let $=await w.json();if($.errors&&$.errors.length>0)throw Error(`Cloudflare GraphQL error: ${$.errors.map((D)=>D.message).join(", ")}`);return($.data.viewer.accounts[0]?.rumPageloadEventsAdaptiveGroups??[]).map((D)=>({country:D.dimensions.countryName,visits:D.sum.visits}))}}fA();var mvA=7,QJ2=10;function LW1(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=$C(),B=ei(mvA),w=_F(B),$=_F(Q);try{let[I,D]=await Promise.all([A.getWebsiteStats({startDate:w,endDate:$}),A.getTopPages({startDate:w,endDate:$,limit:QJ2})]);return{days:mvA,startDate:w,endDate:$,pageviews:I.pageviews,visitors:I.visitors,topPages:D}}catch(I){return{error:I instanceof Error?I.message:"Failed to fetch analytics",days:mvA}}}}var EW1={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.93",description:"Analytics plugin for collecting website and social media metrics",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class VW1 extends qB{cloudflareClient;constructor(A={}){super("analytics",EW1,A,gvA)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new hvA(this.config.cloudflare):void 0,A.insights.register("traffic-overview",LW1(this.cloudflareClient))}async onReady(A){let Q=this.config.cloudflare?.siteTag;if(!Q)return;await A.messaging.send({type:"plugin:site-builder:head-script:register",payload:{pluginId:this.id,script:qW1(Q)}})}async getTools(){return NW1(this.id,this.getContext(),this.cloudflareClient)}}function wJ2(A={}){return new VW1(A)}var _wA=wJ2;eA();fA();Aw();var $J2=new Set(["description","excerpt","summary","tagline","story"]);function IJ2(A){if(A.endsWith("s"))return A;return vI(A)}function uvA(A,Q=!1,B){let w=A._def.typeName;if(w==="ZodOptional"||w==="ZodNullable")return uvA(A._def.innerType,!0,B);if(w==="ZodDefault")return uvA(A._def.innerType,Q,A._def.defaultValue());return{inner:A,isOptional:Q,defaultValue:B}}function cvA(A,Q){let{inner:B,isOptional:w,defaultValue:$}=uvA(Q),I=B._def.typeName,D={name:A,label:SH(A),widget:"string",...w&&{required:!1},...$!==void 0&&{default:$}};switch(I){case"ZodString":{if((B._def.checks??[]).some((X)=>X.kind==="datetime"))return{...D,widget:"datetime"};if($J2.has(A))return{...D,widget:"text"};return{...D,widget:"string"}}case"ZodNumber":return{...D,widget:"number"};case"ZodBoolean":return{...D,widget:"boolean"};case"ZodEnum":{let Y=B._def.values;return{...D,widget:"select",options:Y}}case"ZodArray":{let Y=B._def.type,X=cvA("item",Y);if(X.widget==="object"&&X.fields)return{...D,widget:"list",fields:X.fields};return{...D,widget:"list",field:{name:A,label:SH(A),widget:X.widget}}}case"ZodObject":{let Y=B.shape,X=Object.entries(Y).map(([W,U])=>cvA(W,U));return{...D,widget:"object",fields:X}}default:return{...D,widget:"string"}}}function MW1(A,Q){let B=Object.entries(A.shape).map(([w,$])=>cvA(w,$));if(Q)B.push({name:"body",label:"Body",widget:"markdown"});return B}function CW1(A){let Q=[],B=[];for(let w of A.entityTypes){let $=A.getFrontmatterSchema(w);if(!$)continue;let I=A.getAdapter(w),D=I?.hasBody!==!1,Y=A.entityDisplay?.[w],X=w===td?"Note":SH(w),W=Y?.label??X,U=Y?.pluralName??IJ2(W);if(I?.isSingleton){B.push({name:w,label:W,file:`${w}/${w}.md`,fields:MW1($,D)});continue}if(w===td){Q.push({name:w,label:U,folder:".",create:!0,extension:"md",format:"raw",fields:[{name:"body",label:"Body",widget:"markdown"}]});continue}Q.push({name:w,label:U,folder:w,create:!0,extension:"md",format:"frontmatter",fields:MW1($,D)})}if(B.length>0)Q.push({name:"settings",label:"Settings",files:B});return{backend:{name:"github",repo:A.repo,branch:A.branch,...A.baseUrl&&{base_url:A.baseUrl}},media_folder:"image",public_folder:"/images",collections:Q}}function pvA(A){return`<!doctype html>
|
|
5302
5314
|
<html>
|
|
5303
5315
|
<head>
|
|
5304
5316
|
<meta charset="utf-8" />
|
|
@@ -5309,7 +5321,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,eU2,
|
|
|
5309
5321
|
</head>
|
|
5310
5322
|
<body></body>
|
|
5311
5323
|
</html>
|
|
5312
|
-
`}fA();var OW1={name:"@brains/cms",private:!0,version:"0.2.0-alpha.
|
|
5324
|
+
`}fA();var OW1={name:"@brains/cms",private:!0,version:"0.2.0-alpha.93",description:"CMS plugin for config and browser authoring routes",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/cms-config":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var YJ2=f.object({label:f.string().optional(),pluralName:f.string().optional()}).passthrough(),XJ2=f.object({entityDisplay:f.record(YJ2).optional(),routePath:f.string().default("/cms")});function WJ2(A){return`${A.endsWith("/")?A:`${A}/`}config.yml`}function HJ2(A,Q){let B=A.entityDisplay??Q?.entityDisplay;return B?{entityDisplay:B}:{}}async function UJ2(A){let Q=await A.messaging.send({type:"git-sync:get-repo-info",payload:{}});if("noop"in Q||!Q.success||!Q.data)throw Error("CMS config unavailable: git-sync repo info unavailable");let{repo:B,branch:w}=Q.data;if(!B||!w)throw Error("CMS config unavailable: git-sync repo info incomplete");return{repo:B,branch:w}}async function JJ2(A,Q={}){let{repo:B,branch:w}=await UJ2(A);return CW1({repo:B,branch:w,...A.siteUrl&&{baseUrl:A.siteUrl},entityTypes:A.entityService.getEntityTypes(),getFrontmatterSchema:($)=>A.entities.getEffectiveFrontmatterSchema($),getAdapter:($)=>A.entities.getAdapter($),...Q.entityDisplay&&{entityDisplay:Q.entityDisplay}})}async function RW1(A,Q={}){return TH(await JJ2(A,Q))}class lvA extends qB{constructor(A={}){super("cms",OW1,A,XJ2)}async onRegister(A){await super.onRegister(A),A.endpoints.register({label:"CMS",url:this.config.routePath,priority:40,visibility:"anchor"}),A.interactions.register({id:"cms",label:"CMS",description:"Edit and manage content through the browser CMS.",href:this.config.routePath,kind:"admin",priority:40,visibility:"anchor"})}getWebRoutes(){let A=WJ2(this.config.routePath);return[{path:this.config.routePath,method:"GET",public:!0,handler:async()=>{return new Response(pvA({cmsConfigPath:A}),{headers:{"Content-Type":"text/html; charset=utf-8"}})}},{path:A,method:"GET",public:!0,handler:async()=>{try{let Q=await RW1(this.getContext(),HJ2(this.config,this.getContext()));return new Response(Q,{headers:{"Content-Type":"application/yaml; charset=utf-8"}})}catch(Q){return new Response(Q instanceof Error?Q.message:"CMS unavailable",{status:503,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}}]}}function OV(A){return new lvA(A)}eA();fA();eA();fA();var vwA=["StatsWidget","ListWidget","CustomWidget","PipelineWidget","IdentityWidget","ProfileWidget","SystemWidget"],GJ2=new Set(vwA);function ivA(A){return GJ2.has(A)}var bW1=f.object({id:f.string(),pluginId:f.string(),title:f.string(),description:f.string().optional(),priority:f.number().default(50),section:f.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:f.string(),visibility:b7.default("public")});class xwA{widgets=new Map;logger;constructor(A){this.logger=A.child("DashboardWidgetRegistry")}register(A){let Q={...A,...bW1.parse(A)},B=`${Q.pluginId}:${Q.id}`;this.widgets.set(B,Q),this.logger.debug("Dashboard widget registered",{key:B,title:Q.title,rendererName:Q.rendererName})}unregister(A,Q){if(Q){this.widgets.delete(`${A}:${Q}`);return}for(let B of this.widgets.keys())if(B.startsWith(`${A}:`))this.widgets.delete(B)}get(A,Q){return this.widgets.get(`${A}:${Q}`)}list(A={}){let Q=typeof A==="string"?{section:A}:A,B=Q.permissionLevel??"public";return Array.from(this.widgets.values()).filter((w)=>!Q.section||w.section===Q.section).filter((w)=>i$.hasPermission(B,w.visibility)).sort((w,$)=>w.priority-$.priority)}get size(){return this.widgets.size}}fA();class ywA{id="dashboard:dashboard";name="Dashboard DataSource";description="Aggregates dashboard widgets from all plugins";registry;logger;constructor(A,Q){this.registry=A,this.logger=Q.child("DashboardDataSource")}async getDashboardData(A={}){let Q={},B=A.widgets??this.registry.list({...A.permissionLevel!==void 0&&{permissionLevel:A.permissionLevel}}),w=await Promise.allSettled(B.map(async($)=>{let I=await $.dataProvider(),{dataProvider:D,component:Y,clientScript:X,visibility:W="public",...U}=$;return{key:`${$.pluginId}:${$.id}`,widget:{...U,visibility:W},data:I}}));for(let $=0;$<w.length;$++){let I=w[$],D=B[$];if(!I||!D)continue;if(I.status==="fulfilled")Q[I.value.key]={widget:I.value.widget,data:I.value.data};else this.logger.error("Widget data provider failed",{widgetId:D.id,pluginId:D.pluginId,error:S0(I.reason)})}return{widgets:Q}}async fetch(A,Q,B){return await this.getDashboardData()}}import{render as cJ2}from"preact-render-to-string";var PW1=`
|
|
5313
5325
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
5314
5326
|
html, body { min-height: 100%; max-width: 100%; }
|
|
5315
5327
|
body {
|
|
@@ -6549,7 +6561,7 @@ ${PW1}`;import{jsxDEV as wH,Fragment as _W1}from"preact/jsx-dev-runtime";functio
|
|
|
6549
6561
|
}
|
|
6550
6562
|
});
|
|
6551
6563
|
})();`;function rJ2({input:A}){let Q=A.appInfo.entities,B=A.appInfo.entityCounts,w=lJ2(A.widgets),$=Boolean(A.character.role)||Boolean(A.character.purpose)||A.character.values.length>0,I=A.appInfo.interactions,D=`layout${$?" has-identity":""}`,Y=A.operatorAccess&&!A.operatorAccess.isOperator&&A.operatorAccess.hiddenWidgetCount>0,X=new Date;return wB("html",{lang:"en","data-theme":"dark",children:[wB("head",{children:[wB("meta",{charSet:"utf-8"},void 0,!1,void 0,this),wB("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0"},void 0,!1,void 0,this),wB("title",{children:A.title},void 0,!1,void 0,this),wB("link",{rel:"preconnect",href:"https://fonts.googleapis.com"},void 0,!1,void 0,this),wB("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"},void 0,!1,void 0,this),wB("link",{href:pJ2,rel:"stylesheet"},void 0,!1,void 0,this),A.themeCSS!==void 0&&wB("style",{"data-dashboard-theme":!0,dangerouslySetInnerHTML:{__html:A.themeCSS}},void 0,!1,void 0,this),wB("style",{"data-dashboard-styles":!0,dangerouslySetInnerHTML:{__html:kW1}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),wB("body",{children:[wB("main",{class:"console","data-component":"dashboard:dashboard",children:[wB(vW1,{title:A.title,tagline:A.profile.description,operatorAccess:A.operatorAccess},void 0,!1,void 0,this),wB("section",{class:D,children:[$&&wB("div",{class:"identity-column",children:[wB(yW1,{character:A.character},void 0,!1,void 0,this),wB(dvA,{interactions:I,baseUrl:A.baseUrl},void 0,!1,void 0,this),Y&&A.operatorAccess&&wB(cW1,{hiddenWidgetCount:A.operatorAccess.hiddenWidgetCount,loginUrl:A.operatorAccess.loginUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),wB("div",{class:"main-column",children:[wB(xW1,{total:Q,entityCounts:B},void 0,!1,void 0,this),!$&&Y&&A.operatorAccess&&wB(cW1,{hiddenWidgetCount:A.operatorAccess.hiddenWidgetCount,loginUrl:A.operatorAccess.loginUrl},void 0,!1,void 0,this),w.primary.map((W)=>wB(TwA,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this)),w.secondary.map((W)=>wB(TwA,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this))]},void 0,!0,void 0,this),wB("div",{class:"sidebar-column",children:[!$&&wB(dvA,{interactions:I,baseUrl:A.baseUrl},void 0,!1,void 0,this),w.sidebar.map((W)=>wB(TwA,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this)),wB(TW1,{endpoints:A.appInfo.endpoints,baseUrl:A.baseUrl},void 0,!1,void 0,this),wB(mW1,{appInfo:A.appInfo,now:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),wB(uW1,{title:A.title,appInfo:A.appInfo,baseUrl:A.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),wB("script",{dangerouslySetInnerHTML:{__html:iJ2}},void 0,!1,void 0,this),wB("script",{dangerouslySetInnerHTML:{__html:dJ2}},void 0,!1,void 0,this),A.widgetScripts.map((W,U)=>wB("script",{dangerouslySetInnerHTML:{__html:W}},`widget-script:${U}`,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function pW1(A){return`<!doctype html>
|
|
6552
|
-
${cJ2(wB(rJ2,{input:A},void 0,!1,void 0,this))}`}function lW1(A,Q){let B={},w=new Set;for(let[$,I]of Object.entries(A)){let D=Q?.get(I.widget.pluginId,I.widget.id);if(B[$]={...I,...D?.component?{component:D.component}:{}},D?.clientScript)w.add(D.clientScript)}return{widgets:B,widgetScripts:Array.from(w)}}var iW1={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.
|
|
6564
|
+
${cJ2(wB(rJ2,{input:A},void 0,!1,void 0,this))}`}function lW1(A,Q){let B={},w=new Set;for(let[$,I]of Object.entries(A)){let D=Q?.get(I.widget.pluginId,I.widget.id);if(B[$]={...I,...D?.component?{component:D.component}:{}},D?.clientScript)w.add(D.clientScript)}return{widgets:B,widgetScripts:Array.from(w)}}var iW1={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.93",description:"Dashboard plugin with extensible widget system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var oJ2=f.object({version:f.string().default("1.0.0"),routePath:f.string().default("/dashboard"),themeCSS:f.string().optional()}),sJ2=f.object({id:f.string(),pluginId:f.string(),title:f.string(),description:f.string().optional(),priority:f.number().default(50),section:f.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:f.string(),visibility:b7.default("public"),component:f.custom().optional(),clientScript:f.string().optional(),dataProvider:f.function().returns(f.promise(f.unknown()))}).superRefine((A,Q)=>{if(!ivA(A.rendererName)&&!A.component)Q.addIssue({code:f.ZodIssueCode.custom,message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),aJ2=f.object({pluginId:f.string(),widgetId:f.string().optional()});function tJ2(A){return{id:A.id,pluginId:A.pluginId,title:A.title,...A.description?{description:A.description}:{},priority:A.priority,section:A.section,rendererName:A.rendererName,visibility:A.visibility,...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider}}class nvA extends qB{widgetRegistry=null;datasource=null;siteUrl;ctx;constructor(A){super("dashboard",iW1,A??{},oJ2)}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new xwA(this.logger),this.datasource=new ywA(this.widgetRegistry,this.logger),A.entities.registerDataSource(this.datasource),A.endpoints.register({label:"Dashboard",url:this.config.routePath,priority:30,visibility:"public"}),A.interactions.register({id:"dashboard",label:"Dashboard",description:"Inspect runtime status, endpoints, and dashboard widgets.",href:this.config.routePath,kind:"admin",priority:30,visibility:"public"}),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let B=sJ2.parse(Q.payload),w=tJ2(B);return this.widgetRegistry?.register(w),this.logger.debug("Widget registered via messaging",{widgetId:B.id,pluginId:B.pluginId,rendererName:B.rendererName,builtIn:vwA.includes(B.rendererName)}),{success:!0}}catch(B){return this.logger.error("Failed to register widget",{error:S0(B),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{let B=aJ2.parse(Q.payload);return this.widgetRegistry?.unregister(B.pluginId,B.widgetId),this.logger.debug("Widget unregistered via messaging",{pluginId:B.pluginId,widgetId:B.widgetId}),{success:!0}}),this.logger.info("Dashboard plugin registered")}getWebRoutes(){return[{path:this.config.routePath,method:"GET",public:!0,handler:async(A)=>{if(!this.datasource||!this.ctx)return new Response("Dashboard unavailable",{status:503,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Q=this.ctx,B=await MK()?.getOperatorSession(A),w=Boolean(B),$=w?"anchor":"public",I=this.widgetRegistry?.list({permissionLevel:"anchor"})??[],D=I.filter((r)=>i$.hasPermission($,r.visibility)),Y=I.length-D.length,[X,W]=await Promise.all([this.datasource.getDashboardData({permissionLevel:$,widgets:D}),Q.appInfo()]),U=Q.identity.get(),K=Q.identity.getProfile(),F=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),Z={...W,endpoints:W.endpoints.filter((r)=>i$.hasPermission($,r.visibility)),interactions:W.interactions.filter((r)=>i$.hasPermission($,r.visibility))},q=K.name||W.model||"Brain Dashboard",E=new URL(A.url),L=`${E.pathname}${E.search}`,R=encodeURIComponent(L),_=lW1(X.widgets,this.widgetRegistry),O={title:q,baseUrl:F,widgets:_.widgets,widgetScripts:_.widgetScripts,character:U,profile:K,appInfo:Z,...this.config.themeCSS!==void 0&&{themeCSS:this.config.themeCSS},operatorAccess:{isOperator:w,hiddenWidgetCount:Y,loginUrl:`/login?return_to=${R}`,logoutUrl:`/logout?return_to=${R}`}};return new Response(pW1(O),{headers:{"Content-Type":"text/html; charset=utf-8"}})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function zN(A){return new nvA(A)}eA();fA();var eJ2=f.object({id:f.string(),pluginId:f.string(),title:f.string(),description:f.string().optional(),priority:f.number(),section:f.enum(["primary","secondary","sidebar"]),rendererName:f.string(),visibility:b7,component:f.custom().optional()}),AG2=f.object({widget:eJ2,data:f.unknown()}),QG2=f.object({widgets:f.record(AG2)});fA();eA();fA();import{h as fG2}from"preact";fA();YY();eA();var Lk=f.enum(["draft","queued","published","failed"]),Bp=f.object({subject:f.string(),status:Lk,entityIds:f.array(f.string()).optional(),scheduledFor:f.string().datetime().optional(),sentAt:f.string().datetime().optional(),buttondownId:f.string().optional(),sourceEntityType:f.string().optional()}),dW1=Bp.pick({subject:!0,status:!0,entityIds:!0,scheduledFor:!0,sentAt:!0,buttondownId:!0,sourceEntityType:!0}),wp=a1.extend({entityType:f.literal("newsletter"),metadata:dW1});eA();class rW1 extends zQ{constructor(){super({entityType:"newsletter",schema:wp,frontmatterSchema:Bp})}toMarkdown(A){let Q=this.extractBody(A.content);return this.buildMarkdown(Q,A.metadata)}fromMarkdown(A){let Q=this.parseFrontmatter(A);return{entityType:"newsletter",content:A,metadata:Q}}}var nW1=new rW1;eA();eA();fA();var BG2=oH.extend({status:f.enum(["draft","queued","published","failed"]).optional()}),wG2=sH.extend({query:BG2.optional()});function oW1(A){try{let{content:Q}=$2(A.content,Bp);return Q}catch{return A.content}}class ovA extends f5{id="newsletter:entities";name="Newsletter Entity DataSource";description="Fetches and transforms newsletter entities for rendering";config={entityType:"newsletter",defaultSort:[{field:"created",direction:"desc"}],defaultLimit:10,lookupField:"id",enableNavigation:!0};constructor(A){super(A);this.logger.debug("NewsletterDataSource initialized")}parseQuery(A){let Q=wG2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=oW1(A),B={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:hH(Q,150),created:A.created,url:`/newsletters/${A.id}`};if(A.metadata.sentAt)B.sentAt=A.metadata.sentAt;return B}buildListResult(A,Q,B){return{newsletters:A,totalCount:Q?.totalItems??A.length,pagination:Q}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A),$=B.entityService;if(w.id)return this.fetchSingleNewsletter(w.id,Q,$);let I=w.status,D=I?{filter:{metadata:{status:I}}}:void 0,{items:Y,pagination:X}=await this.fetchList(w,$,D);return Q.parse(this.buildListResult(Y,X,w))}async fetchSingleNewsletter(A,Q,B){let w=await B.getEntity({entityType:this.config.entityType,id:A});if(!w)throw Error(`Newsletter not found: ${A}`);let $=await this.resolveNavigation(w,B),I=[];if(w.metadata.entityIds?.length){let X=w.metadata.sourceEntityType??"post";I=(await Promise.all(w.metadata.entityIds.map(async(U)=>{let K=await B.getEntity({entityType:X,id:U});if(K){let F=K.metadata;return{id:U,title:F.title??U,url:`/${X}s/${F.slug??U}`}}return null}))).filter((U)=>U!==null)}let D=oW1(w),Y={id:w.id,subject:w.metadata.subject,status:w.metadata.status,content:D,created:w.created,updated:w.updated,sentAt:w.metadata.sentAt,scheduledFor:w.metadata.scheduledFor,newsletter:w,prevNewsletter:$.prev?{id:$.prev.id,subject:$.prev.subject,url:$.prev.url}:null,nextNewsletter:$.next?{id:$.next.id,subject:$.next.subject,url:$.next.url}:null,sourceEntities:I.length>0?I:void 0};return Q.parse(Y)}}eA();fA();var $G2=f.object({prompt:f.string().optional().describe("AI generation prompt"),sourceEntityIds:f.array(f.string()).optional().describe("Entity IDs to include in newsletter (e.g., blog posts)"),sourceEntityType:f.enum(["post"]).optional().describe("Type of source entities"),content:f.string().optional().describe("Direct content (skip AI)"),subject:f.string().optional().describe("Newsletter subject (AI-generated if not provided)"),addToQueue:f.boolean().optional().describe("Create as queued (true) or draft (false)")});class svA extends S9{constructor(A,Q){super(A,Q,{schema:$G2,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let B=A.addToQueue??!1,{prompt:w,sourceEntityIds:$,sourceEntityType:I}=A,{content:D,subject:Y}=A;if(D){if(!Y)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if($&&$.length>0){let F=I??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${$.length} source entities`});let q=(await Promise.all($.map((O)=>this.context.entityService.getEntity({entityType:F,id:O})))).filter((O)=>O!=null);if(q.length===0)this.failEarly(`No source entities found for IDs: ${$.join(", ")}`);await this.reportProgress(Q,{progress:30,message:`Generating newsletter from ${q.length} posts`});let L=`Create an engaging newsletter that highlights these blog posts:
|
|
6553
6565
|
|
|
6554
6566
|
${q.map((O)=>`## ${O.metadata.title}
|
|
6555
6567
|
|
|
@@ -6618,14 +6630,14 @@ Newsletter-specific guidelines:
|
|
|
6618
6630
|
- "Reply and let me know..."
|
|
6619
6631
|
- "Until next time..."
|
|
6620
6632
|
|
|
6621
|
-
The goal is to build a relationship with readers through valuable, authentic content.`});fA();eA();import{jsxDEV as D4,Fragment as WG2}from"preact/jsx-dev-runtime";var DG2=f.object({id:f.string(),subject:f.string(),status:Lk,excerpt:f.string(),created:f.string(),sentAt:f.string().optional(),url:f.string()}),YG2=f.object({newsletters:f.array(DG2),totalCount:f.number(),pagination:T9.nullable()}),XG2=({newsletters:A,totalCount:Q,pageTitle:B,pagination:w,baseUrl:$="/newsletters"})=>{let I=B??"Newsletters",D=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return D4(WG2,{children:[D4(Z2,{title:I,description:D},void 0,!1,void 0,this),D4("div",{className:"newsletter-list bg-theme",children:D4("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[D4("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:I},void 0,!1,void 0,this),A.length===0?D4("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):D4("div",{className:"space-y-4",children:A.map((Y)=>D4(zB,{href:Y.url,children:[D4(k$,{className:"text-lg",children:Y.subject},void 0,!1,void 0,this),D4(W9,{children:D4("div",{className:"flex items-center gap-3",children:[D4(BI,{status:Y.status},void 0,!1,void 0,this),D4("span",{className:"text-sm text-theme-muted",children:M6(Y.sentAt??Y.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y.excerpt&&D4("p",{className:"text-theme-muted line-clamp-2",children:Y.excerpt},void 0,!1,void 0,this)]},Y.id,!0,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&D4(If,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},aW1=R1({name:"newsletter-list",description:"Newsletter list page template",schema:YG2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:XG2}});fA();eA();import{jsxDEV as $8,Fragment as GG2}from"preact/jsx-dev-runtime";var HG2=f.object({id:f.string(),title:f.string(),url:f.string()}),tW1=f.object({id:f.string(),subject:f.string(),url:f.string()}),UG2=f.object({id:f.string(),subject:f.string(),status:Lk,content:f.string(),created:f.string(),updated:f.string(),sentAt:f.string().optional(),scheduledFor:f.string().optional(),sourceEntities:f.array(HG2).optional(),prevNewsletter:tW1.nullable().optional(),nextNewsletter:tW1.nullable().optional()}),JG2=({subject:A,status:Q,content:B,created:w,sentAt:$,scheduledFor:I,sourceEntities:D,prevNewsletter:Y,nextNewsletter:X})=>{let W=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],U=$??w,K=$?"Sent":"Created";return $8(GG2,{children:[$8(Z2,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),$8("section",{className:"newsletter-detail-section",children:$8("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:$8("div",{className:"max-w-3xl mx-auto",children:[$8(wJ,{items:W},void 0,!1,void 0,this),$8("h1",{className:"text-3xl md:text-4xl font-bold text-heading leading-tight tracking-tight mb-4",children:A},void 0,!1,void 0,this),$8("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[$8(BI,{status:Q},void 0,!1,void 0,this),$8("span",{children:[K,": ",M6(U,{style:"long"})]},void 0,!0,void 0,this),I&&Q==="queued"&&$8("span",{children:["Scheduled for: ",M6(I,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D&&D.length>0&&$8(zB,{variant:"compact",className:"mb-8",children:[$8("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),$8("ul",{className:"space-y-1",children:D.map((F)=>$8("li",{children:$8("a",{href:F.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:F.title},void 0,!1,void 0,this)},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$8(CD,{markdown:B},void 0,!1,void 0,this),(Y??X)&&$8("nav",{className:"mt-12 pt-8 border-t border-theme",children:$8("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Y?$8(zB,{href:Y.url,variant:"compact",children:[$8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),$8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:Y.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$8("div",{},void 0,!1,void 0,this),X&&$8(zB,{href:X.url,variant:"compact",className:"md:text-right",children:[$8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),$8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:X.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},eW1=R1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:UG2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:JG2}});var AH1={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.
|
|
6633
|
+
The goal is to build a relationship with readers through valuable, authentic content.`});fA();eA();import{jsxDEV as D4,Fragment as WG2}from"preact/jsx-dev-runtime";var DG2=f.object({id:f.string(),subject:f.string(),status:Lk,excerpt:f.string(),created:f.string(),sentAt:f.string().optional(),url:f.string()}),YG2=f.object({newsletters:f.array(DG2),totalCount:f.number(),pagination:T9.nullable()}),XG2=({newsletters:A,totalCount:Q,pageTitle:B,pagination:w,baseUrl:$="/newsletters"})=>{let I=B??"Newsletters",D=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return D4(WG2,{children:[D4(Z2,{title:I,description:D},void 0,!1,void 0,this),D4("div",{className:"newsletter-list bg-theme",children:D4("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[D4("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:I},void 0,!1,void 0,this),A.length===0?D4("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):D4("div",{className:"space-y-4",children:A.map((Y)=>D4(zB,{href:Y.url,children:[D4(k$,{className:"text-lg",children:Y.subject},void 0,!1,void 0,this),D4(W9,{children:D4("div",{className:"flex items-center gap-3",children:[D4(BI,{status:Y.status},void 0,!1,void 0,this),D4("span",{className:"text-sm text-theme-muted",children:M6(Y.sentAt??Y.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y.excerpt&&D4("p",{className:"text-theme-muted line-clamp-2",children:Y.excerpt},void 0,!1,void 0,this)]},Y.id,!0,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&D4(If,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},aW1=R1({name:"newsletter-list",description:"Newsletter list page template",schema:YG2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:XG2}});fA();eA();import{jsxDEV as $8,Fragment as GG2}from"preact/jsx-dev-runtime";var HG2=f.object({id:f.string(),title:f.string(),url:f.string()}),tW1=f.object({id:f.string(),subject:f.string(),url:f.string()}),UG2=f.object({id:f.string(),subject:f.string(),status:Lk,content:f.string(),created:f.string(),updated:f.string(),sentAt:f.string().optional(),scheduledFor:f.string().optional(),sourceEntities:f.array(HG2).optional(),prevNewsletter:tW1.nullable().optional(),nextNewsletter:tW1.nullable().optional()}),JG2=({subject:A,status:Q,content:B,created:w,sentAt:$,scheduledFor:I,sourceEntities:D,prevNewsletter:Y,nextNewsletter:X})=>{let W=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],U=$??w,K=$?"Sent":"Created";return $8(GG2,{children:[$8(Z2,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),$8("section",{className:"newsletter-detail-section",children:$8("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:$8("div",{className:"max-w-3xl mx-auto",children:[$8(wJ,{items:W},void 0,!1,void 0,this),$8("h1",{className:"text-3xl md:text-4xl font-bold text-heading leading-tight tracking-tight mb-4",children:A},void 0,!1,void 0,this),$8("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[$8(BI,{status:Q},void 0,!1,void 0,this),$8("span",{children:[K,": ",M6(U,{style:"long"})]},void 0,!0,void 0,this),I&&Q==="queued"&&$8("span",{children:["Scheduled for: ",M6(I,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D&&D.length>0&&$8(zB,{variant:"compact",className:"mb-8",children:[$8("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),$8("ul",{className:"space-y-1",children:D.map((F)=>$8("li",{children:$8("a",{href:F.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:F.title},void 0,!1,void 0,this)},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$8(CD,{markdown:B},void 0,!1,void 0,this),(Y??X)&&$8("nav",{className:"mt-12 pt-8 border-t border-theme",children:$8("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Y?$8(zB,{href:Y.url,variant:"compact",children:[$8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),$8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:Y.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$8("div",{},void 0,!1,void 0,this),X&&$8(zB,{href:X.url,variant:"compact",className:"md:text-right",children:[$8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),$8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:X.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},eW1=R1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:UG2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:JG2}});var AH1={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.93",description:"Newsletter entity type with AI generation and publish pipeline",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts,.tsx","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var FG2=f.object({});class avA extends V2{entityType="newsletter";schema=wp;adapter=nW1;constructor(A={}){super("newsletter",AH1,A,FG2)}createGenerationHandler(A){return new svA(this.logger,A)}getTemplates(){return{generation:sW1,"newsletter-list":aW1,"newsletter-detail":eW1}}getDataSources(){return[new ovA(this.logger.child("NewsletterDataSource"))]}async onRegister(A){this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.subscribeToGenerateExecute(A),this.registerEvalHandlers(A),A.messaging.subscribe("system:plugins:ready",async()=>{let Q=await A.messaging.send({type:"buttondown:is-configured",payload:{}});if(!("noop"in Q)&&Q.success)await A.messaging.send({type:"plugin:site-builder:slot:register",payload:{pluginId:this.id,slotName:"footer-top",render:()=>fG2(SPA,{variant:"inline"})}});return{success:!0}}),this.logger.debug("Newsletter plugin registered")}deferPublishRegistration(A){let Q={name:"internal",publish:async()=>({id:"internal"})};A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"newsletter",provider:Q}}),{success:!0}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:B,entityId:w}=Q.payload;if(B!=="newsletter")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"newsletter",id:w});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:B,entityId:w,error:`Newsletter not found: ${w}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let I=await A.messaging.send({type:"buttondown:send",payload:{entityId:w,subject:$.metadata.subject,content:$.content}}),D=new Date().toISOString(),Y=!("noop"in I)&&I.data?I.data.emailId:void 0;return await A.entityService.updateEntity({entity:{...$,metadata:{...$.metadata,status:"published",sentAt:D,buttondownId:Y}}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:B,entityId:w,sentAt:D}}),this.logger.info(`Published newsletter: ${w}`),{success:!0}}catch($){let I=S0($);return await A.messaging.send({type:"publish:report:failure",payload:{entityType:B,entityId:w,error:I}}),{success:!0}}})}subscribeToGenerateExecute(A){A.messaging.subscribe("generate:execute",async(Q)=>{if(Q.payload.entityType!=="newsletter")return{success:!0};try{let B=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:10}});if(B.length===0)return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:"No published posts available for newsletter"}}),{success:!0};return await A.jobs.enqueue({type:"newsletter:generation",data:{sourceEntityIds:B.map((w)=>w.id),sourceEntityType:"post",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}}),{success:!0}}catch(B){return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:S0(B)}}),{success:!0}}})}registerEvalHandlers(A){let Q=f.object({prompt:f.string().optional(),content:f.string().optional()});A.eval.registerHandler("generation",async(B)=>{let w=Q.parse(B),$=w.content?`Create an engaging newsletter based on this content:
|
|
6622
6634
|
|
|
6623
|
-
${w.content}`:w.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function tvA(A={}){return new avA(A)}eA();fA();class Ek{config;logger;constructor(A,Q){this.config=A;this.logger=Q}async request(A,Q={}){let B=`https://api.buttondown.email/v1${A}`;this.logger.debug("Buttondown API request",{endpoint:A,method:Q.method??"GET"});let w=await fetch(B,{...Q,headers:{Authorization:`Token ${this.config.apiKey}`,"Content-Type":"application/json",...Q.headers}});if(!w.ok){let $=await w.json().catch(()=>({})),I=$.detail??$.message??`HTTP ${w.status}`;throw this.logger.error("Buttondown API error",{endpoint:A,status:w.status,error:I}),Error(`Buttondown API error: ${I}`)}return w.json()}async createSubscriber(A){let Q={email_address:A.email,type:this.config.doubleOptIn?"unactivated":"regular"};if(A.name)Q.metadata={name:A.name};if(A.tags&&A.tags.length>0)Q.tags=A.tags;this.logger.info("Creating subscriber",{email:A.email});try{return await this.request("/subscribers",{method:"POST",body:JSON.stringify(Q)})}catch(B){if(B instanceof Error&&B.message.includes("already subscribed")){let w=B.message.match(/id=([a-f0-9-]+)/);return this.logger.info("Subscriber already exists",{email:A.email}),{id:w?.[1]??"existing",email:A.email,subscriber_type:"already_subscribed"}}throw B}}async unsubscribe(A){this.logger.info("Unsubscribing",{email:A}),await this.request(`/subscribers/${encodeURIComponent(A)}`,{method:"DELETE"})}async listSubscribers(A){let Q=new URLSearchParams;if(A?.type)Q.set("type",A.type);if(A?.limit)Q.set("page_size",String(A.limit));let B=Q.toString(),w=B?`/subscribers?${B}`:"/subscribers";return this.request(w)}async createEmail(A){let Q={subject:A.subject,body:A.body,status:A.status??"draft"};if(A.publish_date)Q.publish_date=A.publish_date;return this.logger.info("Creating email",{subject:A.subject,status:A.status??"draft"}),this.request("/emails",{method:"POST",body:JSON.stringify(Q)})}async getEmail(A){return this.request(`/emails/${A}`)}async validateCredentials(){try{return await this.request("/subscribers?page_size=1"),!0}catch{return!1}}}eA();fA();var ZG2=f.object({email:f.string().email().describe("Email address to subscribe"),name:f.string().optional().describe("Subscriber name (optional)"),tags:f.array(f.string()).optional().describe("Tags to apply to subscriber (optional)")}),zG2=f.object({email:f.string().email().describe("Email address to unsubscribe")}),NG2=f.object({type:f.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:f.number().optional().describe("Maximum number of results")});function QH1(A,Q,B){let w=new Ek(Q,B);return[j2(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",ZG2,async($)=>{try{let I=await w.createSubscriber({email:$.email,...$.name&&{name:$.name},...$.tags&&{tags:$.tags}}),D=I.subscriber_type==="already_subscribed";return J8({subscriberId:I.id,email:I.email,status:I.subscriber_type,message:D?"already_subscribed":"subscribed"},D?`${$.email} is already subscribed`:`Subscribed ${$.email} successfully`)}catch(I){return h5(S0(I))}}),j2(A,"unsubscribe","Unsubscribe an email address from the newsletter.",zG2,async($)=>{try{return await w.unsubscribe($.email),J8({email:$.email},`Unsubscribed ${$.email} successfully`)}catch(I){return h5(S0(I))}}),j2(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",NG2,async($)=>{try{let I=await w.listSubscribers({...$.type&&{type:$.type},...$.limit&&{limit:$.limit}});return J8({subscribers:I.results.map((D)=>({id:D.id,email:D.email,status:D.subscriber_type})),count:I.count},`Found ${I.count} subscribers`)}catch(I){return h5(S0(I))}})]}fA();async function BH1(A,Q,B,w){if(A.entityType!=="post")return{success:!0,skipped:!0,reason:"Only post entity types trigger auto-send"};let $=await B.getEntity({entityType:"post",id:A.entityId});if(!$)return{success:!1,error:`Post ${A.entityId} not found`};w.info("Auto-sending newsletter for published post",{postId:$.id,title:$.metadata.title});try{let I=await Q.createEmail({subject:$.metadata.title,body:$.content,status:"about_to_send"});return w.info("Newsletter sent for post",{postId:$.id,emailId:I.id}),{success:!0,emailId:I.id}}catch(I){let D=S0(I);return w.error("Failed to send newsletter for post",{postId:$.id,error:D}),{success:!1,error:D}}}var wH1={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.
|
|
6635
|
+
${w.content}`:w.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function tvA(A={}){return new avA(A)}eA();fA();class Ek{config;logger;constructor(A,Q){this.config=A;this.logger=Q}async request(A,Q={}){let B=`https://api.buttondown.email/v1${A}`;this.logger.debug("Buttondown API request",{endpoint:A,method:Q.method??"GET"});let w=await fetch(B,{...Q,headers:{Authorization:`Token ${this.config.apiKey}`,"Content-Type":"application/json",...Q.headers}});if(!w.ok){let $=await w.json().catch(()=>({})),I=$.detail??$.message??`HTTP ${w.status}`;throw this.logger.error("Buttondown API error",{endpoint:A,status:w.status,error:I}),Error(`Buttondown API error: ${I}`)}return w.json()}async createSubscriber(A){let Q={email_address:A.email,type:this.config.doubleOptIn?"unactivated":"regular"};if(A.name)Q.metadata={name:A.name};if(A.tags&&A.tags.length>0)Q.tags=A.tags;this.logger.info("Creating subscriber",{email:A.email});try{return await this.request("/subscribers",{method:"POST",body:JSON.stringify(Q)})}catch(B){if(B instanceof Error&&B.message.includes("already subscribed")){let w=B.message.match(/id=([a-f0-9-]+)/);return this.logger.info("Subscriber already exists",{email:A.email}),{id:w?.[1]??"existing",email:A.email,subscriber_type:"already_subscribed"}}throw B}}async unsubscribe(A){this.logger.info("Unsubscribing",{email:A}),await this.request(`/subscribers/${encodeURIComponent(A)}`,{method:"DELETE"})}async listSubscribers(A){let Q=new URLSearchParams;if(A?.type)Q.set("type",A.type);if(A?.limit)Q.set("page_size",String(A.limit));let B=Q.toString(),w=B?`/subscribers?${B}`:"/subscribers";return this.request(w)}async createEmail(A){let Q={subject:A.subject,body:A.body,status:A.status??"draft"};if(A.publish_date)Q.publish_date=A.publish_date;return this.logger.info("Creating email",{subject:A.subject,status:A.status??"draft"}),this.request("/emails",{method:"POST",body:JSON.stringify(Q)})}async getEmail(A){return this.request(`/emails/${A}`)}async validateCredentials(){try{return await this.request("/subscribers?page_size=1"),!0}catch{return!1}}}eA();fA();var ZG2=f.object({email:f.string().email().describe("Email address to subscribe"),name:f.string().optional().describe("Subscriber name (optional)"),tags:f.array(f.string()).optional().describe("Tags to apply to subscriber (optional)")}),zG2=f.object({email:f.string().email().describe("Email address to unsubscribe")}),NG2=f.object({type:f.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:f.number().optional().describe("Maximum number of results")});function QH1(A,Q,B){let w=new Ek(Q,B);return[j2(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",ZG2,async($)=>{try{let I=await w.createSubscriber({email:$.email,...$.name&&{name:$.name},...$.tags&&{tags:$.tags}}),D=I.subscriber_type==="already_subscribed";return J8({subscriberId:I.id,email:I.email,status:I.subscriber_type,message:D?"already_subscribed":"subscribed"},D?`${$.email} is already subscribed`:`Subscribed ${$.email} successfully`)}catch(I){return h5(S0(I))}}),j2(A,"unsubscribe","Unsubscribe an email address from the newsletter.",zG2,async($)=>{try{return await w.unsubscribe($.email),J8({email:$.email},`Unsubscribed ${$.email} successfully`)}catch(I){return h5(S0(I))}}),j2(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",NG2,async($)=>{try{let I=await w.listSubscribers({...$.type&&{type:$.type},...$.limit&&{limit:$.limit}});return J8({subscribers:I.results.map((D)=>({id:D.id,email:D.email,status:D.subscriber_type})),count:I.count},`Found ${I.count} subscribers`)}catch(I){return h5(S0(I))}})]}fA();async function BH1(A,Q,B,w){if(A.entityType!=="post")return{success:!0,skipped:!0,reason:"Only post entity types trigger auto-send"};let $=await B.getEntity({entityType:"post",id:A.entityId});if(!$)return{success:!1,error:`Post ${A.entityId} not found`};w.info("Auto-sending newsletter for published post",{postId:$.id,title:$.metadata.title});try{let I=await Q.createEmail({subject:$.metadata.title,body:$.content,status:"about_to_send"});return w.info("Newsletter sent for post",{postId:$.id,emailId:I.id}),{success:!0,emailId:I.id}}catch(I){let D=S0(I);return w.error("Failed to send newsletter for post",{postId:$.id,error:D}),{success:!1,error:D}}}var wH1={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.93",description:"Buttondown newsletter integration \u2014 subscriber management and API routes",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var LG2=f.object({apiKey:f.string().optional().describe("Buttondown API key"),doubleOptIn:f.boolean().default(!0).describe("Require email confirmation for new subscribers"),autoSendOnPublish:f.boolean().default(!1).describe("Automatically send newsletter when a blog post is published")});class evA extends qB{constructor(A={}){super("buttondown",wH1,A,LG2)}async onRegister(A){if(A.messaging.subscribe("buttondown:is-configured",async()=>{return{success:!!this.config.apiKey}}),this.config.apiKey){let Q=new Ek({apiKey:this.config.apiKey,doubleOptIn:this.config.doubleOptIn},this.logger);if(A.messaging.subscribe("buttondown:send",async(B)=>{try{return{success:!0,data:{emailId:(await Q.createEmail({subject:B.payload.subject,body:B.payload.content,status:"about_to_send"})).id}}}catch(w){return this.logger.error("Buttondown send failed",{error:S0(w)}),{success:!1}}}),this.config.autoSendOnPublish)A.messaging.subscribe("publish:completed",async(B)=>{return await BH1(B.payload,Q,A.entityService,this.logger),{success:!0}}),this.logger.info("Buttondown auto-send on publish enabled")}}async getTools(){if(!this.config.apiKey)return[];return QH1(this.id,{apiKey:this.config.apiKey,doubleOptIn:this.config.doubleOptIn},this.logger)}getApiRoutes(){if(!this.config.apiKey)return[];return[{path:"/subscribe",method:"POST",tool:"subscribe",public:!0,successRedirect:"/subscribe/thanks",errorRedirect:"/subscribe/error"}]}}function AxA(A={}){return new evA(A)}var EG2=f.object({apiKey:f.string().optional().describe("Buttondown API key"),doubleOptIn:f.boolean().optional().describe("Require email confirmation for new subscribers"),autoSendOnPublish:f.boolean().optional().describe("Automatically send newsletter when a blog post is published")});function $H1(A={}){let Q=EG2.parse(A);return[tvA({}),AxA({...Q.apiKey!==void 0&&{apiKey:Q.apiKey},...Q.doubleOptIn!==void 0&&{doubleOptIn:Q.doubleOptIn},...Q.autoSendOnPublish!==void 0&&{autoSendOnPublish:Q.autoSendOnPublish}})]}eA();fA();import{existsSync as xG2,mkdirSync as yG2,writeFileSync as TG2}from"fs";import{join as Mf}from"path";fA();var QxA=f.object({baseFolder:f.string().default("_obsidian")});fA();function VG2(A){let Q=A,B=!0,w=void 0,$=!1,I=!0;while(I){if(I=!1,Q instanceof f.ZodOptional)B=!1,Q=Q._def.innerType,I=!0;if(Q instanceof f.ZodDefault)B=!1,$=!0,w=Q._def.defaultValue(),Q=Q._def.innerType,I=!0;if(Q instanceof f.ZodNullable)B=!1,Q=Q._def.innerType,I=!0}let D={inner:Q,required:B};if($)D.defaultValue=w;return D}function MG2(A){if(A instanceof f.ZodEnum)return{type:"enum",enumValues:A._def.values};if(A instanceof f.ZodLiteral)return{type:"string",defaultValue:A._def.value};if(A instanceof f.ZodString)return{type:"string"};if(A instanceof f.ZodNumber)return{type:"number"};if(A instanceof f.ZodBoolean)return{type:"boolean"};if(A instanceof f.ZodArray)return{type:"array"};if(A instanceof f.ZodDate)return{type:"date"};if(A instanceof f.ZodPipeline){if(A._def.out instanceof f.ZodDate)return{type:"date"}}return{type:"unknown"}}function IH1(A){let Q=A.shape,B=[];for(let[w,$]of Object.entries(Q)){let{inner:I,required:D,defaultValue:Y}=VG2($),X=MG2(I),W={name:w,type:X.type,required:D},U=Y!==void 0?Y:X.defaultValue;if(U!==void 0)W.defaultValue=U;if(X.enumValues)W.enumValues=X.enumValues;B.push(W)}return B}function CG2(A,Q){if(A.name==="entityType")return String(A.defaultValue??Q);if(A.name==="title")return'"{{title}}"';if(A.type==="date"&&(A.name==="created"||A.name==="updated"))return'"{{date}}"';if(A.defaultValue!==void 0){if(Array.isArray(A.defaultValue))return"[]";if(typeof A.defaultValue==="boolean")return String(A.defaultValue);if(typeof A.defaultValue==="number")return String(A.defaultValue);return String(A.defaultValue)}if(A.type==="enum"&&A.enumValues&&A.enumValues.length>0)return A.enumValues[0]??"";switch(A.type){case"string":return'""';case"number":return"";case"boolean":return"false";case"array":return"[]";case"date":return'""';default:return'""'}}function DH1(A,Q,B=""){let w=["---"];for(let $ of Q){let I=CG2($,A);if(I==="")w.push(`${$.name}:`);else w.push(`${$.name}: ${I}`)}if(w.push("---"),w.push(""),B)w.push(B);else w.push("<!-- Write your content here -->"),w.push("");return w.join(`
|
|
6624
6636
|
`)}fA();var OG2={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function RG2(A){let Q={name:A.name,id:A.name,type:OG2[A.type]};if(A.type==="enum"&&A.enumValues){let B={};A.enumValues.forEach((w,$)=>{B[String($)]=w}),Q.options=B}return Q}function YH1(A,Q){let B={filesPaths:A,fields:Q.map(RG2)};return`---
|
|
6625
6637
|
${TH(B)}---
|
|
6626
|
-
`}fA();var bG2=new Set(["entityType"]),PG2={base:"Notes"},jG2=new Set(["base"]);function kG2(A){let Q=["file.name"];for(let B of A)if(!bG2.has(B.name))Q.push(B.name);return Q}function _G2(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function XH1(A,Q){let B=PG2[A]??ai(A),w=_G2(Q),$=kG2(Q),I=[{type:"table",name:`All ${B}`,order:$}];if(w)I.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:$});let Y={filters:{and:[jG2.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:I};return{filename:`${B}.base`,content:TH(Y),hasStatus:w}}function WH1(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w}")`),B={filters:{and:[Q.length===1?Q[0]:{or:Q}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return TH(B)}function HH1(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w.entityType}")`),B={filters:{and:[Q.length===1?Q[0]:{or:Q},'status != "published"']},views:[{type:"table",name:"Pipeline",groupBy:{property:"status",direction:"ASC"},order:["file.name","file.folder","status"]}]};return TH(B)}var UH1={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.92",description:"Obsidian vault integration \u2014 generates templates from entity schemas",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var SG2={mkdir:yG2,writeFile:TG2,existsFile:xG2},gG2=f.object({entityTypes:f.array(f.string()).optional().describe("Entity types to generate templates for (default: all)")});class BxA extends qB{deps;constructor(A={},Q={}){super("obsidian-vault",UH1,A,QxA);this.deps={...SG2,...Q}}async onReady(A){this.logger.info("Auto-syncing Obsidian templates, fileClasses, and bases"),await this.sync(A)}async getTools(){let A=this.getContext();return[j2(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",gG2,async(Q)=>{return this.sync(A,Q.entityTypes)})]}async sync(A,Q){try{let B=A.entityService.getEntityTypes(),w=Q?B.filter((L)=>Q.includes(L)):B,$=Mf(A.dataDir,this.config.baseFolder),I=Mf($,"templates"),D=Mf($,"fileClasses"),Y=Mf($,"bases");this.deps.mkdir(I,{recursive:!0}),this.deps.mkdir(D,{recursive:!0}),this.deps.mkdir(Y,{recursive:!0});let X=[],W=[],U=[],K=[],F=[],Z=[];for(let L of w){let R=A.entities.getEffectiveFrontmatterSchema(L);if(!R){this.logger.debug(`Skipping ${L}: no frontmatter schema`),W.push(L);continue}let _=IH1(R),O=A.entities.getAdapter(L),r=O?.isSingleton===!0,n=YH1(L,_);if(this.deps.writeFile(Mf(D,`${L}.md`),n),U.push(L),r){F.push(L),this.logger.debug(`Generated fileClass (singleton): ${L}`);continue}let S=O?.getBodyTemplate()??"",x=DH1(L,_,S);this.deps.writeFile(Mf(I,`${L}.md`),x),X.push(L);let T=XH1(L,_),g=Mf(Y,T.filename);if(!this.deps.existsFile(g))this.deps.writeFile(g,T.content),K.push(L),this.logger.debug(`Generated base: ${T.filename}`);if(T.hasStatus)Z.push({entityType:L,fields:_});this.logger.debug(`Generated template + fileClass: ${L}`)}let q=WH1(F);if(q){let L=Mf(Y,"Settings.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,q),K.push("Settings"),this.logger.debug("Generated Settings.base")}let E=HH1(Z);if(E){let L=Mf(Y,"Pipeline.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,E),K.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${X.length} templates, ${U.length} fileClasses, ${K.length} bases (${W.length} skipped)`),J8({generated:X,skipped:W,fileClasses:U,bases:K})}catch(B){return this.logger.error("Failed to sync",{error:B}),h5(B instanceof Error?B.message:"Unknown error")}}}function wxA(A,Q){return new BxA(A,Q)}eA();fA();eA();var $xA=f.enum(["new","planned","in-progress","done","declined"]),IxA=f.enum(["low","medium","high","critical"]),$p=f.object({title:f.string(),status:$xA,priority:IxA.default("medium"),requested:f.number().int().default(1),declinedReason:f.string().optional()}),JH1=f.object({title:f.string(),status:$xA,priority:IxA,requested:f.number().int(),slug:f.string()}),Ip=a1.extend({entityType:f.literal("wish"),metadata:JH1}),DxA=f.object({});eA();fA();class Dp extends zQ{constructor(){super({entityType:"wish",schema:Ip,frontmatterSchema:$p})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,$p);return{frontmatter:$p.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),B=XQ(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:B}}}}var YxA=new Dp;fA();fA();async function GH1(A,Q){let B=`${Q.title}: ${Q.description}`,$=(await A.search({query:B,options:{types:["wish"],limit:1}}))[0];if($&&$.score>=A.similarityThreshold)return $.entity;let I=XQ(Q.title);return A.getEntity({entityType:"wish",id:I})}class SwA{logger;context;adapter=new Dp;constructor(A,Q){this.logger=A;this.context=Q}async process(A,Q,B){let w=A.title??A.prompt??"Untitled wish",$=A.content??A.prompt??"",I=await GH1({search:(W)=>this.context.entityService.search(W),getEntity:(W)=>this.context.entityService.getEntity(W),similarityThreshold:0.85},{title:w,description:$});if(I){let{frontmatter:W,description:U}=this.adapter.parseWishContent(I.content),K=W.requested+1,F=this.adapter.createWishContent({...W,requested:K},U);return await this.context.entityService.updateEntity({entity:{...I,content:F,metadata:{...I.metadata,requested:K}}}),this.logger.info("Incremented wish request count",{id:I.id,requested:K}),{success:!0,entityId:I.id,existed:!0,requested:K}}let D=XQ(w),Y=A.options?.priority??"medium",X=this.adapter.createWishContent({title:w,status:"new",priority:Y,requested:1},$);return await this.context.entityService.createEntity({entity:{id:D,entityType:"wish",content:X,metadata:{title:w,status:"new",priority:Y,requested:1,slug:D}}}),this.logger.info("Created new wish",{id:D,title:w}),{success:!0,entityId:D,existed:!1,requested:1}}}var KH1={critical:0,high:1,medium:2,low:3};function fH1(A){A.sort((Q,B)=>{let w=B.metadata.requested-Q.metadata.requested;if(w!==0)return w;return KH1[Q.metadata.priority]-KH1[B.metadata.priority]})}var FH1={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.92",description:"Wishlist plugin for tracking unfulfilled user requests",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class ZH1 extends V2{entityType=YxA.entityType;schema=Ip;adapter=YxA;constructor(A={}){super("wishlist",FH1,A,DxA)}async interceptCreate(A,Q,B){let w=await new SwA(this.logger,B).process({...A.title?{title:A.title}:{},...A.prompt?{prompt:A.prompt}:{},...A.content?{content:A.content}:{}},`wish-create-${Date.now()}`,{});if(!w.success)return{kind:"handled",result:{success:!1,error:w.error??"Failed to create wish"}};return{kind:"handled",result:{success:!0,data:{...w.entityId?{entityId:w.entityId}:{},status:w.existed?"updated":"created"}}}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"top-wishes",pluginId:this.id,title:"Top Wishes",section:"secondary",priority:30,rendererName:"ListWidget",dataProvider:async()=>{let B=await A.entityService.listEntities({entityType:"wish",options:{limit:10}});return fH1(B),{items:B.map((w)=>({id:w.id,name:w.metadata.title,count:w.metadata.requested,priority:w.metadata.priority,status:w.metadata.status}))}}}}),{success:!0}});let Q=new SwA(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:(B)=>B})}async getInstructions(){return"**CRITICAL \u2014 Wishlist exclusions**: A2A agent-contact requests are never wishlist cases. "+'If a request asks you to ask, message, contact, call, or reach out to an agent, and the target is missing, ambiguous, archived, URL-only, unsaved-domain, or not-yet-saved in the local agent directory, do not call any create tool for a wish. Tell the user to add/save or clarify the agent first. This includes requests that contain a full agent URL, a bare domain like unknown-agent.io, or phrasing like "message this agent URL for me". Only create or save an agent entry if the user explicitly asks you to add or save that agent. '+"**CRITICAL \u2014 Unfulfilled requests**: For other unfulfillable requests, ALWAYS call `system_create` with entityType "+`"wish" BEFORE responding when you cannot fulfill a user's request. This applies to physical actions, non-agent missing integrations, and any non-agent capability `+"you lack. Physical-world requests like making food, driving somewhere, or doing chores are always wishlist cases. Do NOT just explain you can't do it \u2014 create the wish first, THEN respond. "+"Never claim the request was added to the wishlist unless you actually called system_create for the wish. In your response, tell the user their request has been added to the wishlist."}}function mG2(A={}){return new ZH1(A)}var gwA=mG2;eA();fA();eA();var Yp=f.object({title:f.string(),target:f.string()}),zH1=f.object({title:f.string(),target:f.string(),slug:f.string().optional()}),Xp=a1.extend({entityType:f.literal("prompt"),metadata:zH1});eA();fA();class XxA extends zQ{constructor(){super({entityType:"prompt",schema:Xp,frontmatterSchema:Yp})}toMarkdown(A){let Q=this.extractBody(A.content),B=this.parseFrontMatter(A.content,Yp);return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Yp),B=XQ(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:B}}}}var hwA=new XxA;var NH1={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.92",description:"Prompt entity type \u2014 AI prompts as editable markdown entities",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};class WxA extends V2{entityType=hwA.entityType;schema=Xp;adapter=hwA;constructor(){super("prompt",NH1,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function RV(){return new WxA}eA();fA();class mwA{apiKey;fetchFn;baseUrl="https://api.unsplash.com";constructor(A,Q){this.apiKey=A,this.fetchFn=Q}async searchPhotos(A,Q){let B=new URL(`${this.baseUrl}/search/photos`);B.searchParams.set("query",A),B.searchParams.set("page",String(Q.page)),B.searchParams.set("per_page",String(Q.perPage));let w=await this.fetchFn(B.toString(),{headers:{Authorization:`Client-ID ${this.apiKey}`}});if(!w.ok)throw Error(`Unsplash API error: ${w.status} ${w.statusText}`);let $=await w.json();return{photos:$.results.map(cG2),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function cG2(A){return{id:A.id,description:A.description,altDescription:A.alt_description,thumbnailUrl:A.urls.thumb,imageUrl:A.urls.regular,photographerName:A.user.name,photographerUrl:A.user.links.html,sourceUrl:A.links.html,downloadLocation:A.links.download_location,width:A.width,height:A.height}}fA();v4();var qH1={query:f.string().describe("Search terms for stock photos"),perPage:f.number().min(1).max(30).default(10).describe("Results per page (1-30)"),page:f.number().min(1).default(1).describe("Page number")},LH1={photoId:f.string().describe("Photo ID from search results"),downloadLocation:f.string().url().describe("Download tracking URL (required by provider ToS)"),photographerName:f.string().describe("Photographer name for attribution"),photographerUrl:f.string().url().describe("Photographer profile URL for attribution"),sourceUrl:f.string().url().describe("Photo page URL on provider"),imageUrl:f.string().url().describe("Image URL to download"),title:f.string().optional().describe("Image entity title"),alt:f.string().optional().describe("Alt text for the image"),targetEntityType:f.string().optional().describe("Entity type to set cover image on"),targetEntityId:f.string().optional().describe("Entity ID to set cover image on")};function VH1(A,Q){return[pG2(A,Q),lG2(A,Q)]}function pG2(A,Q){return{name:`${A}_search`,description:"Search for stock photos. Returns photo candidates with preview URLs and metadata. Use stock-photo_select to materialize a chosen photo into an image entity.",inputSchema:qH1,handler:async(B)=>{let w=f.object(qH1).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};try{return{success:!0,data:await Q.provider.searchPhotos(w.data.query,{page:w.data.page,perPage:w.data.perPage})}}catch($){return{success:!1,error:$ instanceof Error?$.message:"Search failed"}}}}}function lG2(A,Q){return{name:`${A}_select`,description:"Select a stock photo from search results and materialize it as an image entity. Triggers provider download tracking per ToS. Optionally sets as cover image on a target entity.",inputSchema:LH1,handler:async(B)=>{let w=f.object(LH1).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{photoId:$,downloadLocation:I,photographerName:D,photographerUrl:Y,sourceUrl:X,imageUrl:W,title:U,alt:K,targetEntityType:F,targetEntityId:Z}=w.data,q={photographerName:D,photographerUrl:Y,sourceUrl:X},E=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:W}}}});if(E[0]){let S={imageEntityId:E[0].id,alreadyExisted:!0,attribution:q};if(F&&Z)await EH1(Q.entityService,F,Z,E[0].id),S.coverSet=!0;return{success:!0,data:S}}Q.provider.triggerDownload(I).catch(()=>{});let L;try{L=await Q.fetchImage(W)}catch(S){return{success:!1,error:S instanceof Error?S.message:"Image download failed"}}let R=U??`Stock photo ${$}`,_=YZ.createImageEntity({dataUrl:L,title:R,alt:K??R}),O={id:$,..._,metadata:{..._.metadata,sourceUrl:W}},{entityId:r}=await Q.entityService.createEntity({entity:O}),n={imageEntityId:r,alreadyExisted:!1,attribution:q};if(F&&Z)await EH1(Q.entityService,F,Z,r),n.coverSet=!0;return{success:!0,data:n}}}}async function EH1(A,Q,B,w){let $=await A.getEntity({entityType:Q,id:B});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:w}}})}v4();var MH1={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.92",description:"Stock photo search and selection \u2014 Unsplash provider",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var dG2=f.object({provider:f.enum(["unsplash"]).default("unsplash"),apiKey:f.string().optional().describe("Stock photo provider API key")});class HxA extends qB{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",MH1,A,dG2);this.deps=Q}async getTools(){if(!this.config.apiKey)return[];if(this.cachedTools)return this.cachedTools;let A=this.getContext(),Q=new mwA(this.config.apiKey,this.deps.fetch??globalThis.fetch);return this.cachedTools=VH1(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??wW}),this.cachedTools}}function UxA(A={},Q={}){return new HxA(A,Q)}eA();fA();eA();eA();fA();var CH1=f.enum(["ai","foundation","work"]),OH1=f.object({suffix:CH1,title:f.string(),body:f.string(),linkLabel:f.string(),linkHref:f.string()}),Wp=f.object({eyebrow:f.string(),headline:f.string(),cards:f.array(OH1).min(1)}),uwA=f.object({title:f.string(),slug:f.string(),status:f.enum(["draft","published"])}),Hp=a1.extend({entityType:f.literal("ecosystem-section"),metadata:uwA});class RH1 extends zQ{constructor(){super({entityType:"ecosystem-section",schema:Hp,frontmatterSchema:uwA})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var JxA=new RH1;fA();function rG2(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function GxA(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function Up(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function cwA(A){let Q=rG2(A),w=GxA(Q,"Cards").split(/^### Card \d+\s*$/m).map(($)=>$.trim()).filter(Boolean);return Wp.parse({eyebrow:GxA(Q,"Eyebrow"),headline:GxA(Q,"Headline"),cards:w.map(($)=>({suffix:Up($,"Suffix"),title:Up($,"Title"),body:Up($,"Body"),linkLabel:Up($,"Link Label"),linkHref:Up($,"Link Href")}))})}function bH1(A){return["# Ecosystem Section","","## Eyebrow",A.eyebrow,"","## Headline",A.headline,"","## Cards","",...A.cards.flatMap((Q,B)=>[`### Card ${B+1}`,"","#### Suffix",Q.suffix,"","#### Title",Q.title,"","#### Body",Q.body,"","#### Link Label",Q.linkLabel,"","#### Link Href",Q.linkHref,""])].join(`
|
|
6638
|
+
`}fA();var bG2=new Set(["entityType"]),PG2={base:"Notes"},jG2=new Set(["base"]);function kG2(A){let Q=["file.name"];for(let B of A)if(!bG2.has(B.name))Q.push(B.name);return Q}function _G2(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function XH1(A,Q){let B=PG2[A]??ai(A),w=_G2(Q),$=kG2(Q),I=[{type:"table",name:`All ${B}`,order:$}];if(w)I.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:$});let Y={filters:{and:[jG2.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:I};return{filename:`${B}.base`,content:TH(Y),hasStatus:w}}function WH1(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w}")`),B={filters:{and:[Q.length===1?Q[0]:{or:Q}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return TH(B)}function HH1(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w.entityType}")`),B={filters:{and:[Q.length===1?Q[0]:{or:Q},'status != "published"']},views:[{type:"table",name:"Pipeline",groupBy:{property:"status",direction:"ASC"},order:["file.name","file.folder","status"]}]};return TH(B)}var UH1={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.93",description:"Obsidian vault integration \u2014 generates templates from entity schemas",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var SG2={mkdir:yG2,writeFile:TG2,existsFile:xG2},gG2=f.object({entityTypes:f.array(f.string()).optional().describe("Entity types to generate templates for (default: all)")});class BxA extends qB{deps;constructor(A={},Q={}){super("obsidian-vault",UH1,A,QxA);this.deps={...SG2,...Q}}async onReady(A){this.logger.info("Auto-syncing Obsidian templates, fileClasses, and bases"),await this.sync(A)}async getTools(){let A=this.getContext();return[j2(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",gG2,async(Q)=>{return this.sync(A,Q.entityTypes)})]}async sync(A,Q){try{let B=A.entityService.getEntityTypes(),w=Q?B.filter((L)=>Q.includes(L)):B,$=Mf(A.dataDir,this.config.baseFolder),I=Mf($,"templates"),D=Mf($,"fileClasses"),Y=Mf($,"bases");this.deps.mkdir(I,{recursive:!0}),this.deps.mkdir(D,{recursive:!0}),this.deps.mkdir(Y,{recursive:!0});let X=[],W=[],U=[],K=[],F=[],Z=[];for(let L of w){let R=A.entities.getEffectiveFrontmatterSchema(L);if(!R){this.logger.debug(`Skipping ${L}: no frontmatter schema`),W.push(L);continue}let _=IH1(R),O=A.entities.getAdapter(L),r=O?.isSingleton===!0,n=YH1(L,_);if(this.deps.writeFile(Mf(D,`${L}.md`),n),U.push(L),r){F.push(L),this.logger.debug(`Generated fileClass (singleton): ${L}`);continue}let S=O?.getBodyTemplate()??"",x=DH1(L,_,S);this.deps.writeFile(Mf(I,`${L}.md`),x),X.push(L);let T=XH1(L,_),g=Mf(Y,T.filename);if(!this.deps.existsFile(g))this.deps.writeFile(g,T.content),K.push(L),this.logger.debug(`Generated base: ${T.filename}`);if(T.hasStatus)Z.push({entityType:L,fields:_});this.logger.debug(`Generated template + fileClass: ${L}`)}let q=WH1(F);if(q){let L=Mf(Y,"Settings.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,q),K.push("Settings"),this.logger.debug("Generated Settings.base")}let E=HH1(Z);if(E){let L=Mf(Y,"Pipeline.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,E),K.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${X.length} templates, ${U.length} fileClasses, ${K.length} bases (${W.length} skipped)`),J8({generated:X,skipped:W,fileClasses:U,bases:K})}catch(B){return this.logger.error("Failed to sync",{error:B}),h5(B instanceof Error?B.message:"Unknown error")}}}function wxA(A,Q){return new BxA(A,Q)}eA();fA();eA();var $xA=f.enum(["new","planned","in-progress","done","declined"]),IxA=f.enum(["low","medium","high","critical"]),$p=f.object({title:f.string(),status:$xA,priority:IxA.default("medium"),requested:f.number().int().default(1),declinedReason:f.string().optional()}),JH1=f.object({title:f.string(),status:$xA,priority:IxA,requested:f.number().int(),slug:f.string()}),Ip=a1.extend({entityType:f.literal("wish"),metadata:JH1}),DxA=f.object({});eA();fA();class Dp extends zQ{constructor(){super({entityType:"wish",schema:Ip,frontmatterSchema:$p})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,$p);return{frontmatter:$p.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),B=XQ(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:B}}}}var YxA=new Dp;fA();fA();async function GH1(A,Q){let B=`${Q.title}: ${Q.description}`,$=(await A.search({query:B,options:{types:["wish"],limit:1}}))[0];if($&&$.score>=A.similarityThreshold)return $.entity;let I=XQ(Q.title);return A.getEntity({entityType:"wish",id:I})}class SwA{logger;context;adapter=new Dp;constructor(A,Q){this.logger=A;this.context=Q}async process(A,Q,B){let w=A.title??A.prompt??"Untitled wish",$=A.content??A.prompt??"",I=await GH1({search:(W)=>this.context.entityService.search(W),getEntity:(W)=>this.context.entityService.getEntity(W),similarityThreshold:0.85},{title:w,description:$});if(I){let{frontmatter:W,description:U}=this.adapter.parseWishContent(I.content),K=W.requested+1,F=this.adapter.createWishContent({...W,requested:K},U);return await this.context.entityService.updateEntity({entity:{...I,content:F,metadata:{...I.metadata,requested:K}}}),this.logger.info("Incremented wish request count",{id:I.id,requested:K}),{success:!0,entityId:I.id,existed:!0,requested:K}}let D=XQ(w),Y=A.options?.priority??"medium",X=this.adapter.createWishContent({title:w,status:"new",priority:Y,requested:1},$);return await this.context.entityService.createEntity({entity:{id:D,entityType:"wish",content:X,metadata:{title:w,status:"new",priority:Y,requested:1,slug:D}}}),this.logger.info("Created new wish",{id:D,title:w}),{success:!0,entityId:D,existed:!1,requested:1}}}var KH1={critical:0,high:1,medium:2,low:3};function fH1(A){A.sort((Q,B)=>{let w=B.metadata.requested-Q.metadata.requested;if(w!==0)return w;return KH1[Q.metadata.priority]-KH1[B.metadata.priority]})}var FH1={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.93",description:"Wishlist plugin for tracking unfulfilled user requests",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class ZH1 extends V2{entityType=YxA.entityType;schema=Ip;adapter=YxA;constructor(A={}){super("wishlist",FH1,A,DxA)}async interceptCreate(A,Q,B){let w=await new SwA(this.logger,B).process({...A.title?{title:A.title}:{},...A.prompt?{prompt:A.prompt}:{},...A.content?{content:A.content}:{}},`wish-create-${Date.now()}`,{});if(!w.success)return{kind:"handled",result:{success:!1,error:w.error??"Failed to create wish"}};return{kind:"handled",result:{success:!0,data:{...w.entityId?{entityId:w.entityId}:{},status:w.existed?"updated":"created"}}}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"top-wishes",pluginId:this.id,title:"Top Wishes",section:"secondary",priority:30,rendererName:"ListWidget",dataProvider:async()=>{let B=await A.entityService.listEntities({entityType:"wish",options:{limit:10}});return fH1(B),{items:B.map((w)=>({id:w.id,name:w.metadata.title,count:w.metadata.requested,priority:w.metadata.priority,status:w.metadata.status}))}}}}),{success:!0}});let Q=new SwA(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:(B)=>B})}async getInstructions(){return"**CRITICAL \u2014 Wishlist exclusions**: A2A agent-contact requests are never wishlist cases. "+'If a request asks you to ask, message, contact, call, or reach out to an agent, and the target is missing, ambiguous, archived, URL-only, unsaved-domain, or not-yet-saved in the local agent directory, do not call any create tool for a wish. Tell the user to add/save or clarify the agent first. This includes requests that contain a full agent URL, a bare domain like unknown-agent.io, or phrasing like "message this agent URL for me". Only create or save an agent entry if the user explicitly asks you to add or save that agent. '+"**CRITICAL \u2014 Unfulfilled requests**: For other unfulfillable requests, ALWAYS call `system_create` with entityType "+`"wish" BEFORE responding when you cannot fulfill a user's request. This applies to physical actions, non-agent missing integrations, and any non-agent capability `+"you lack. Physical-world requests like making food, driving somewhere, or doing chores are always wishlist cases. Do NOT just explain you can't do it \u2014 create the wish first, THEN respond. "+"Never claim the request was added to the wishlist unless you actually called system_create for the wish. In your response, tell the user their request has been added to the wishlist."}}function mG2(A={}){return new ZH1(A)}var gwA=mG2;eA();fA();eA();var Yp=f.object({title:f.string(),target:f.string()}),zH1=f.object({title:f.string(),target:f.string(),slug:f.string().optional()}),Xp=a1.extend({entityType:f.literal("prompt"),metadata:zH1});eA();fA();class XxA extends zQ{constructor(){super({entityType:"prompt",schema:Xp,frontmatterSchema:Yp})}toMarkdown(A){let Q=this.extractBody(A.content),B=this.parseFrontMatter(A.content,Yp);return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Yp),B=XQ(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:B}}}}var hwA=new XxA;var NH1={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.93",description:"Prompt entity type \u2014 AI prompts as editable markdown entities",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};class WxA extends V2{entityType=hwA.entityType;schema=Xp;adapter=hwA;constructor(){super("prompt",NH1,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function RV(){return new WxA}eA();fA();class mwA{apiKey;fetchFn;baseUrl="https://api.unsplash.com";constructor(A,Q){this.apiKey=A,this.fetchFn=Q}async searchPhotos(A,Q){let B=new URL(`${this.baseUrl}/search/photos`);B.searchParams.set("query",A),B.searchParams.set("page",String(Q.page)),B.searchParams.set("per_page",String(Q.perPage));let w=await this.fetchFn(B.toString(),{headers:{Authorization:`Client-ID ${this.apiKey}`}});if(!w.ok)throw Error(`Unsplash API error: ${w.status} ${w.statusText}`);let $=await w.json();return{photos:$.results.map(cG2),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function cG2(A){return{id:A.id,description:A.description,altDescription:A.alt_description,thumbnailUrl:A.urls.thumb,imageUrl:A.urls.regular,photographerName:A.user.name,photographerUrl:A.user.links.html,sourceUrl:A.links.html,downloadLocation:A.links.download_location,width:A.width,height:A.height}}fA();v4();var qH1={query:f.string().describe("Search terms for stock photos"),perPage:f.number().min(1).max(30).default(10).describe("Results per page (1-30)"),page:f.number().min(1).default(1).describe("Page number")},LH1={photoId:f.string().describe("Photo ID from search results"),downloadLocation:f.string().url().describe("Download tracking URL (required by provider ToS)"),photographerName:f.string().describe("Photographer name for attribution"),photographerUrl:f.string().url().describe("Photographer profile URL for attribution"),sourceUrl:f.string().url().describe("Photo page URL on provider"),imageUrl:f.string().url().describe("Image URL to download"),title:f.string().optional().describe("Image entity title"),alt:f.string().optional().describe("Alt text for the image"),targetEntityType:f.string().optional().describe("Entity type to set cover image on"),targetEntityId:f.string().optional().describe("Entity ID to set cover image on")};function VH1(A,Q){return[pG2(A,Q),lG2(A,Q)]}function pG2(A,Q){return{name:`${A}_search`,description:"Search for stock photos. Returns photo candidates with preview URLs and metadata. Use stock-photo_select to materialize a chosen photo into an image entity.",inputSchema:qH1,handler:async(B)=>{let w=f.object(qH1).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};try{return{success:!0,data:await Q.provider.searchPhotos(w.data.query,{page:w.data.page,perPage:w.data.perPage})}}catch($){return{success:!1,error:$ instanceof Error?$.message:"Search failed"}}}}}function lG2(A,Q){return{name:`${A}_select`,description:"Select a stock photo from search results and materialize it as an image entity. Triggers provider download tracking per ToS. Optionally sets as cover image on a target entity.",inputSchema:LH1,handler:async(B)=>{let w=f.object(LH1).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{photoId:$,downloadLocation:I,photographerName:D,photographerUrl:Y,sourceUrl:X,imageUrl:W,title:U,alt:K,targetEntityType:F,targetEntityId:Z}=w.data,q={photographerName:D,photographerUrl:Y,sourceUrl:X},E=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:W}}}});if(E[0]){let S={imageEntityId:E[0].id,alreadyExisted:!0,attribution:q};if(F&&Z)await EH1(Q.entityService,F,Z,E[0].id),S.coverSet=!0;return{success:!0,data:S}}Q.provider.triggerDownload(I).catch(()=>{});let L;try{L=await Q.fetchImage(W)}catch(S){return{success:!1,error:S instanceof Error?S.message:"Image download failed"}}let R=U??`Stock photo ${$}`,_=YZ.createImageEntity({dataUrl:L,title:R,alt:K??R}),O={id:$,..._,metadata:{..._.metadata,sourceUrl:W}},{entityId:r}=await Q.entityService.createEntity({entity:O}),n={imageEntityId:r,alreadyExisted:!1,attribution:q};if(F&&Z)await EH1(Q.entityService,F,Z,r),n.coverSet=!0;return{success:!0,data:n}}}}async function EH1(A,Q,B,w){let $=await A.getEntity({entityType:Q,id:B});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:w}}})}v4();var MH1={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.93",description:"Stock photo search and selection \u2014 Unsplash provider",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var dG2=f.object({provider:f.enum(["unsplash"]).default("unsplash"),apiKey:f.string().optional().describe("Stock photo provider API key")});class HxA extends qB{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",MH1,A,dG2);this.deps=Q}async getTools(){if(!this.config.apiKey)return[];if(this.cachedTools)return this.cachedTools;let A=this.getContext(),Q=new mwA(this.config.apiKey,this.deps.fetch??globalThis.fetch);return this.cachedTools=VH1(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??wW}),this.cachedTools}}function UxA(A={},Q={}){return new HxA(A,Q)}eA();fA();eA();eA();fA();var CH1=f.enum(["ai","foundation","work"]),OH1=f.object({suffix:CH1,title:f.string(),body:f.string(),linkLabel:f.string(),linkHref:f.string()}),Wp=f.object({eyebrow:f.string(),headline:f.string(),cards:f.array(OH1).min(1)}),uwA=f.object({title:f.string(),slug:f.string(),status:f.enum(["draft","published"])}),Hp=a1.extend({entityType:f.literal("ecosystem-section"),metadata:uwA});class RH1 extends zQ{constructor(){super({entityType:"ecosystem-section",schema:Hp,frontmatterSchema:uwA})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var JxA=new RH1;fA();function rG2(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function GxA(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function Up(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function cwA(A){let Q=rG2(A),w=GxA(Q,"Cards").split(/^### Card \d+\s*$/m).map(($)=>$.trim()).filter(Boolean);return Wp.parse({eyebrow:GxA(Q,"Eyebrow"),headline:GxA(Q,"Headline"),cards:w.map(($)=>({suffix:Up($,"Suffix"),title:Up($,"Title"),body:Up($,"Body"),linkLabel:Up($,"Link Label"),linkHref:Up($,"Link Href")}))})}function bH1(A){return["# Ecosystem Section","","## Eyebrow",A.eyebrow,"","## Headline",A.headline,"","## Cards","",...A.cards.flatMap((Q,B)=>[`### Card ${B+1}`,"","#### Suffix",Q.suffix,"","#### Title",Q.title,"","#### Body",Q.body,"","#### Link Label",Q.linkLabel,"","#### Link Href",Q.linkHref,""])].join(`
|
|
6627
6639
|
`)}var nG2=f.object({query:f.object({id:f.string().optional()}).optional()}).passthrough();class pwA{id="rizom-ecosystem:entities";name="Rizom Ecosystem";description="Fetches an ecosystem-section entity for rendering";async fetch(A,Q,B){let $=nG2.parse(A??{}).query?.id??"rizom-ecosystem",I=await B.entityService.getEntity({entityType:"ecosystem-section",id:$});if(!I)throw Error(`Ecosystem section not found: ${$}`);return Q.parse(cwA(I.content))}}eA();var oG2=UQA({extend:{classGroups:{"font-size":[{text:["display-2xl","display-xl","display-lg","display-md","display-sm","heading-lg","heading-md","heading-sm","body-xl","body-lg","body-md","body-sm","body-xs","label-md","label-sm","label-xs"]}]}}});function EJ(...A){return oG2(Xj(A))}import{jsxDEV as Vgw}from"preact/jsx-dev-runtime";import{jsxDEV as Rgw}from"preact/jsx-dev-runtime";import{jsxDEV as kgw}from"preact/jsx-dev-runtime";import{jsxDEV as aG2}from"preact/jsx-dev-runtime";var KxA="px-6 md:px-10 xl:px-20",sG2=`${KxA} relative z-[1]`,fxA=({id:A,className:Q,children:B})=>aG2("section",{id:A,className:EJ(sG2,Q),children:B},void 0,!1,void 0,this);import{jsxDEV as lwA}from"preact/jsx-dev-runtime";var tG2={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},Jp=({name:A="rizom",brandSuffix:Q,className:B,dotClassName:w,suffixClassName:$})=>{let I=tG2[Q];return lwA("span",{className:EJ("inline-flex items-baseline gap-0 font-display font-medium tracking-[-0.015em] [font-variation-settings:'opsz'_24]",B),children:[lwA("span",{className:"text-theme",children:A},void 0,!1,void 0,this),lwA("span",{className:EJ(I??"text-accent",w),children:"."},void 0,!1,void 0,this),lwA("span",{className:EJ("italic font-normal text-theme-muted",$),children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as pgw}from"preact/jsx-dev-runtime";import{jsxDEV as rgw}from"preact/jsx-dev-runtime";import{jsxDEV as agw,Fragment as sgw}from"preact/jsx-dev-runtime";import{jsxDEV as Ahw}from"preact/jsx-dev-runtime";import{Fragment as FxA}from"preact";import{jsxDEV as Gp}from"preact/jsx-dev-runtime";var eG2=/(\*[^*]+\*)/;function ZxA(A,Q){let B=A.split(`
|
|
6628
|
-
`);return Gp(FxA,{children:B.map((w,$)=>Gp(FxA,{children:[$>0&&Gp("br",{},void 0,!1,void 0,this),w.split(eG2).map((I,D)=>{if(I.length>=3&&I.startsWith("*")&&I.endsWith("*"))return Gp("span",{className:Q,children:I.slice(1,-1)},D,!1,void 0,this);return Gp(FxA,{children:I},D,!1,void 0,this)})]},$,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as YI,Fragment as HK2}from"preact/jsx-dev-runtime";var AK2="italic text-accent font-normal",QK2="You are here",BK2={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},wK2={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},$K2={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},IK2="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",DK2="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",YK2="font-label text-[10.5px] uppercase tracking-[0.22em] text-theme-muted self-start mt-[18px] pb-1 border-b border-white/10 transition-colors hover:text-theme",XK2="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",WK2=({card:A})=>{let Q=A.linkLabel===QK2,B=A.linkHref.trim().length===0,w=YI(HK2,{children:[YI(Jp,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),YI("span",{className:`${IK2} ${BK2[A.suffix]}`,children:A.title},void 0,!1,void 0,this),YI("p",{className:DK2,children:A.body},void 0,!1,void 0,this),Q?YI("span",{className:XK2,children:A.linkLabel},void 0,!1,void 0,this):YI("span",{className:YK2,children:A.linkLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$=`flex flex-col gap-[14px] border-t pt-7 ${Q?wK2[A.suffix]:"border-white/10"}`;return Q||B?YI("div",{className:$,children:w},void 0,!1,void 0,this):YI("a",{href:A.linkHref,className:`${$} text-inherit no-underline transition-colors ${$K2[A.suffix]}`,children:w},void 0,!1,void 0,this)},zxA=({eyebrow:A,headline:Q,cards:B})=>YI(fxA,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[YI("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[YI("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),YI("h2",{className:"mt-5 font-display text-[clamp(34px,4.4vw,60px)] font-[380] leading-[1.04] tracking-[-0.02em] text-heading [font-variation-settings:'opsz'_96]",children:ZxA(Q,AK2)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YI("div",{className:"mx-auto grid max-w-[1180px] grid-cols-3 gap-16 max-[768px]:grid-cols-1 max-[768px]:gap-7",children:B.map((w)=>YI(WK2,{card:w},w.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);var UK2=[{suffix:"work",title:"The service",body:"Workshops and consulting that apply the methodology in live engagements.",linkLabel:"Visit rizom.work \u2192",linkHref:"https://rizom.work"},{suffix:"foundation",title:"The source",body:"The non-profit that holds the IP and stewards the methodology independently.",linkLabel:"Read the manifesto \u2192",linkHref:"https://rizom.foundation"},{suffix:"ai",title:"The tools",body:"Open-source AI agents built on the methodology, the technical layer underneath.",linkLabel:"See the platform \u2192",linkHref:"https://rizom.ai"}];function PH1(A){return{eyebrow:"The Ecosystem",headline:"One practice. *Three faces.*",cards:UK2.map((Q)=>Q.suffix===A?{...Q,linkLabel:"You are here",linkHref:""}:Q)}}var JK2=PH1();var NxA=R1({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:Wp,formatter:{parse:cwA,format:bH1},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:zxA}});var jH1={name:"@brains/rizom-ecosystem",private:!0,version:"0.2.0-alpha.
|
|
6640
|
+
`);return Gp(FxA,{children:B.map((w,$)=>Gp(FxA,{children:[$>0&&Gp("br",{},void 0,!1,void 0,this),w.split(eG2).map((I,D)=>{if(I.length>=3&&I.startsWith("*")&&I.endsWith("*"))return Gp("span",{className:Q,children:I.slice(1,-1)},D,!1,void 0,this);return Gp(FxA,{children:I},D,!1,void 0,this)})]},$,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as YI,Fragment as HK2}from"preact/jsx-dev-runtime";var AK2="italic text-accent font-normal",QK2="You are here",BK2={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},wK2={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},$K2={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},IK2="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",DK2="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",YK2="font-label text-[10.5px] uppercase tracking-[0.22em] text-theme-muted self-start mt-[18px] pb-1 border-b border-white/10 transition-colors hover:text-theme",XK2="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",WK2=({card:A})=>{let Q=A.linkLabel===QK2,B=A.linkHref.trim().length===0,w=YI(HK2,{children:[YI(Jp,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),YI("span",{className:`${IK2} ${BK2[A.suffix]}`,children:A.title},void 0,!1,void 0,this),YI("p",{className:DK2,children:A.body},void 0,!1,void 0,this),Q?YI("span",{className:XK2,children:A.linkLabel},void 0,!1,void 0,this):YI("span",{className:YK2,children:A.linkLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$=`flex flex-col gap-[14px] border-t pt-7 ${Q?wK2[A.suffix]:"border-white/10"}`;return Q||B?YI("div",{className:$,children:w},void 0,!1,void 0,this):YI("a",{href:A.linkHref,className:`${$} text-inherit no-underline transition-colors ${$K2[A.suffix]}`,children:w},void 0,!1,void 0,this)},zxA=({eyebrow:A,headline:Q,cards:B})=>YI(fxA,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[YI("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[YI("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),YI("h2",{className:"mt-5 font-display text-[clamp(34px,4.4vw,60px)] font-[380] leading-[1.04] tracking-[-0.02em] text-heading [font-variation-settings:'opsz'_96]",children:ZxA(Q,AK2)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YI("div",{className:"mx-auto grid max-w-[1180px] grid-cols-3 gap-16 max-[768px]:grid-cols-1 max-[768px]:gap-7",children:B.map((w)=>YI(WK2,{card:w},w.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);var UK2=[{suffix:"work",title:"The service",body:"Workshops and consulting that apply the methodology in live engagements.",linkLabel:"Visit rizom.work \u2192",linkHref:"https://rizom.work"},{suffix:"foundation",title:"The source",body:"The non-profit that holds the IP and stewards the methodology independently.",linkLabel:"Read the manifesto \u2192",linkHref:"https://rizom.foundation"},{suffix:"ai",title:"The tools",body:"Open-source AI agents built on the methodology, the technical layer underneath.",linkLabel:"See the platform \u2192",linkHref:"https://rizom.ai"}];function PH1(A){return{eyebrow:"The Ecosystem",headline:"One practice. *Three faces.*",cards:UK2.map((Q)=>Q.suffix===A?{...Q,linkLabel:"You are here",linkHref:""}:Q)}}var JK2=PH1();var NxA=R1({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:Wp,formatter:{parse:cwA,format:bH1},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:zxA}});var jH1={name:"@brains/rizom-ecosystem",private:!0,version:"0.2.0-alpha.93",description:"Entity-backed Rizom ecosystem section",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@rizom/ui":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class qxA extends V2{entityType="ecosystem-section";schema=Hp;adapter=JxA;constructor(A={}){super("rizom-ecosystem",jH1,A,f.object({}).default({}))}getTemplates(){return{ecosystem:NxA}}getDataSources(){return[new pwA]}}function bV(A={}){return new qxA(A)}fA();eA();eA();fA();Z$();fA();eA();var f9="agent",kH1="agent-discovery",_H1="agent:generation",vH1="agent-network",xH1="AgentNetworkWidget",Kp="agent-discovery:entities",LxA="agent-list",ExA="agent-detail",O6="skill",yH1="skill",iwA="skill-derivation",TH1="skill:project",SH1="skill-derivation",gH1="skill:skill-derivation",hH1="skills";var Vk=f.object({name:f.string(),description:f.string(),tags:f.array(f.string())}),oY=f.enum(["discovered","approved"]).describe("Discovered for review or approved for calling"),$H=uX.pick({name:!0,kind:!0,organization:!0}).extend({brainName:f.string().describe("Name of the brain instance"),url:f.string().url().describe("Brain endpoint URL"),did:f.string().optional().describe("Decentralized identifier (public)"),status:oY,discoveredAt:f.string().datetime().describe("When this agent was first discovered")}),mH1=$H.pick({name:!0,url:!0,status:!0}).extend({discoveredAt:f.string().datetime().optional(),slug:f.string()}),Mk=a1.extend({entityType:f.literal(f9),metadata:mH1}),fp=Mk.extend({frontmatter:$H,about:f.string(),skills:f.array(Vk),notes:f.string()}),Ck=fp.extend({url:f.string().optional(),typeLabel:f.string().optional()}),KK2=fp.extend({url:f.string(),typeLabel:f.string()});fA();var fK2=f.array(Vk);function uH1(A){let Q=fK2.safeParse(A);if(!Q.success||Q.data.length===0)return"";return Q.data.map((B)=>{let w=B.tags.length>0?` [${B.tags.join(", ")}]`:"";return`- ${B.name}: ${B.description}${w}`}).join(`
|
|
6629
6641
|
`)}function cH1(A){if(!A.trim())return[];let Q=[];for(let B of A.split(`
|
|
6630
6642
|
`)){let w=B.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/);if(!w)continue;let $=w[1]??"",I=w[2]??"",D=w[3],Y=D?D.split(",").map((X)=>X.trim()).filter(Boolean):[];Q.push({name:$,description:I,tags:Y})}return Q}var FK2=f.object({about:f.string(),skills:f.array(Vk),notes:f.string()}),pH1=new vB(FK2,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:uH1,parser:cH1},{key:"notes",label:"Notes",type:"string"}]});class sY extends zQ{constructor(){super({entityType:f9,schema:Mk,frontmatterSchema:$H})}fromMarkdown(A){let Q=this.parseFrontMatter(A,$H),B=QC(Q.url);return{content:A,entityType:f9,metadata:{name:Q.name,url:Q.url,status:Q.status,discoveredAt:Q.discoveredAt,slug:B}}}createAgentContent(A){let Q={name:A.name,kind:A.kind,...A.organization&&{organization:A.organization},brainName:A.brainName,url:A.url,...A.did&&{did:A.did},status:oY.parse(A.status),discoveredAt:A.discoveredAt},B=pH1.format({about:A.about,skills:A.skills,notes:A.notes});return this.buildMarkdown(B,Q)}parseAgentContent(A){let Q=this.extractBody(A);if(!Q.trim())return{about:"",skills:[],notes:""};try{let B=pH1.parse(Q);return{about:B.about,skills:B.skills,notes:B.notes}}catch{return{about:"",skills:[],notes:""}}}parseEntity(A){return{frontmatter:this.parseFrontMatter(A.content,$H),body:this.parseAgentContent(A.content)}}}eA();var ZK2=new sY,zK2=oH.extend({status:oY.optional()}),NK2=sH.extend({query:zK2.optional()});function qK2(A){let Q=$2(A.content,$H),B=ZK2.parseAgentContent(A.content);return fp.parse({...A,frontmatter:Q.metadata,about:B.about,skills:B.skills,notes:B.notes})}class dwA extends f5{id=Kp;name="Agent Directory DataSource";description="Fetches and transforms agent entities for rendering";config={entityType:f9,defaultSort:[{field:"discoveredAt",direction:"desc"}],defaultLimit:50,lookupField:"slug",enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return qK2(A)}buildDetailResult(A,Q){return{agent:A,prevAgent:Q?.prev??null,nextAgent:Q?.next??null}}parseQuery(A){let Q=NK2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}buildListResult(A,Q,B){let w=oY.safeParse(B.status);return{agents:A,pagination:Q,baseUrl:B.baseUrl,selectedStatus:w.success?w.data:"all"}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A);if(w.id)return super.fetch(A,Q,B);let{items:$,pagination:I}=await this.fetchList(w,B.entityService,w.status?{filter:{metadata:{status:w.status}}}:void 0);return Q.parse(this.buildListResult($,I,w))}}eA();fA();r$();eA();async function lH1(A,Q){let w=`${(A.startsWith("http")?A:`https://${A}`).replace(/\/$/,"")}/.well-known/agent-card.json`;try{let $=await Q(w);if(!$.ok)return null;let I=await $.json();return zx(I)}catch{return null}}function rwA(A){let Q=A.trim();if(Q.startsWith("http://")||Q.startsWith("https://"))try{return new URL(Q).hostname}catch{return Q}let B=Q.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(B)try{return new URL(B[0]).hostname}catch{return B[0]}if(/^[^\s]+\.[^\s]+$/.test(Q))return Q;return""}fA();var LK2=new sY;function iH1(A){return A.trim().toLowerCase().replace(/[_\s]+/g,"-")}function NN(A){let Q=new Set,B=[];for(let w of A){let $=iH1(w);if(!$||Q.has($))continue;Q.add($),B.push($)}return B}function EK2(A,Q){if(Q.count!==A.count)return Q.count-A.count;return A.tag.localeCompare(Q.tag)}async function dH1(A,Q={}){let B=Q.minCount??1,w=Q.topN??12,$=Q.visibilityScope??"public",I=new Map,[D,Y]=await Promise.all([A.entityService.listEntities({entityType:O6,options:{filter:{visibilityScope:$}}}),A.entityService.listEntities({entityType:f9,options:{filter:{visibilityScope:$}}})]),X=(W)=>{for(let U of NN(W))I.set(U,(I.get(U)??0)+1)};for(let W of D)X(W.metadata.tags);for(let W of Y){let U=LK2.parseAgentContent(W.content);X(U.skills.flatMap((K)=>K.tags))}return Array.from(I.entries()).map(([W,U])=>({tag:W,count:U})).filter((W)=>W.count>=B).sort(EK2).slice(0,w)}function rH1(A){if(A.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...A.map(({tag:Q,count:B})=>`- ${Q} (${B})`)].join(`
|
|
6631
6643
|
`)}var VK2=new sY;function nH1(A,Q={}){let B=A.anchor?.name??A.brainName,w=A.anchor?.kind??"professional",$=[];if(A.anchor?.description)$.push(A.anchor.description);if(A.description)$.push(A.description);let I=Q.status??"discovered",D=new Date().toISOString();return{content:VK2.createAgentContent({name:B,kind:w,...A.anchor?.organization&&{organization:A.anchor.organization},brainName:A.brainName,url:A.url,status:I,discoveredAt:D,about:$.join(`
|
|
@@ -6725,7 +6737,7 @@ ${TH(B)}---
|
|
|
6725
6737
|
setView("agents");
|
|
6726
6738
|
setTagFilter("all");
|
|
6727
6739
|
});
|
|
6728
|
-
})();`;import{jsxDEV as m2}from"preact/jsx-dev-runtime";function _K2({item:A}){return m2("li",{class:"list-item",children:[m2("div",{class:"list-main",children:[m2("span",{class:"list-name",children:A.name},void 0,!1,void 0,this),m2("span",{class:"list-desc",children:A.description},void 0,!1,void 0,this),A.tags.length>0&&m2("div",{class:"list-tags",children:A.tags.map((Q)=>m2("span",{class:"tag",children:Q},`${A.id}:${Q}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m2("div",{class:"list-meta",children:A.status==="discovered"&&m2("span",{class:"pill pill--warn",children:"review"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function vK2({item:A}){return m2("li",{class:"list-item agent-network-skill-row","data-agent-network-skill-row":!0,"data-agent-network-tags":JSON.stringify(A.tags),children:[m2("div",{class:"list-main",children:m2("span",{class:"list-name",children:A.name},void 0,!1,void 0,this)},void 0,!1,void 0,this),m2("div",{class:"list-meta",children:m2("span",{class:`agent-network-source${A.sourceType==="brain"?" is-brain":""}`,children:A.sourceLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xK2({kind:A,items:Q,active:B}){return m2("div",{class:`agent-network-panel${B?" is-active":""}`,"data-agent-network-panel":A,children:Q.length>0?m2("ul",{class:"list agent-network-list",children:Q.map((w)=>m2(_K2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):m2("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function yK2({skills:A,count:Q,filters:B}){return m2("div",{class:"agent-network-panel","data-agent-network-panel":"skills",children:[m2("div",{class:"agent-network-filter-row",role:"tablist","aria-label":"Filter skills by tag",children:[m2("button",{class:"agent-network-filter is-active",type:"button","data-agent-network-tag-filter":"all","aria-pressed":"true",children:[m2("span",{class:"count",children:Q},void 0,!1,void 0,this),m2("span",{class:"label",children:"all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B.map((w)=>m2("button",{class:`agent-network-filter${w.variant==="gap"?" is-gap":""}`,type:"button","data-agent-network-tag-filter":w.tag,"aria-pressed":"false",children:[m2("span",{class:"count",children:w.count},void 0,!1,void 0,this),m2("span",{class:"label",children:w.tag},void 0,!1,void 0,this)]},w.tag,!0,void 0,this))]},void 0,!0,void 0,this),A.length>0?m2("ul",{class:"list agent-network-list agent-network-skills-list",children:A.map((w)=>m2(vK2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):m2("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function CxA({data:A}){let Q=AU1.safeParse(A);if(!Q.success)return m2("p",{class:"muted",children:"Nothing to show yet."},void 0,!1,void 0,this);let B=Q.data;return m2("div",{"data-agent-network-widget":!0,"data-agent-network-view":"agents",children:[m2("div",{class:"agent-network-view-tabs",role:"tablist","aria-label":"Browse the agent network",children:[m2("button",{class:"agent-network-view-tab is-active",type:"button","data-agent-network-view-tab":"agents","aria-pressed":"true",children:["Agents",m2("span",{class:"agent-network-view-count",children:B.counts.agents},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m2("button",{class:"agent-network-view-tab",type:"button","data-agent-network-view-tab":"skills","aria-pressed":"false",children:["Skills",m2("span",{class:"agent-network-view-count",children:B.counts.skills},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m2("div",{class:"agent-network-kind-tabs",role:"tablist","aria-label":"Filter agents by kind",children:MxA.map((w)=>{let $=w==="all";return m2("button",{class:`agent-network-kind-tab${$?" is-active":""}`,type:"button","data-agent-network-kind-tab":w,"aria-pressed":$?"true":"false",children:[m2("span",{class:"agent-network-kind-count",children:B.agents[w].length},void 0,!1,void 0,this),m2("span",{class:"agent-network-kind-label",children:w},void 0,!1,void 0,this)]},w,!0,void 0,this)})},void 0,!1,void 0,this),MxA.map((w)=>m2(xK2,{kind:w,items:B.agents[w],active:w==="all"},w,!1,void 0,this)),m2(yK2,{skills:B.skills,count:B.counts.skills,filters:B.skillFilters},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function BU1(A,Q){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:vH1,pluginId:Q,title:"Agent Network",section:"secondary",priority:15,rendererName:xH1,component:CxA,clientScript:owA,dataProvider:async()=>QU1(A)}}),{success:!0}})}function wU1(){return'## Agent directory\n- Add a new agent contact with `system_create` using `entityType: "agent"` and pass the domain or URL in `url`.\n- List saved agents with `system_list` using `entityType: "agent"`.\n- Approve a discovered agent with `system_update` on the `agent` entity using `fields` (for example `fields: { status: "approved" }`). Do not replace the full content just to change status.\n- When the user explicitly says `approve`, `approve it`, `yes approve`, or `approve <agent-id>`, call `system_update` immediately with `fields: { status: "approved" }` and let the standard confirmation flow ask the user to confirm. Never pass `confirmed: true` on the initial approval request.\n- If the previous turn identified one specific discovered agent, treat a short follow-up like `approve`, `approve it`, or `yes approve` as referring to that same agent id.\n- If `system_update` succeeds for an approval request, answer plainly that the agent is now approved. Do not say the operation failed, and do not ask to retry, unless the tool actually failed.\n- If `system_update` says to use `fields`, or says full content replacement is invalid/empty, retry once immediately with `fields` instead of surfacing that error to the user.\n- If the user gives an exact saved agent id like `old-agent.io`, call that single `system_update` directly instead of listing/searching first.\n- If the previous turn identified one specific unsaved agent domain and offered to add/save it, treat a short affirmative follow-up like `yes`, `yes please`, `please do`, `go ahead`, `do that`, or `save it` as consent to save that same agent immediately with `system_create`.\n- Calling and saving agents are separate actions: if an agent is not saved yet, tell the user it is not saved in the local agent directory yet and ask them to add/save it first. Prefer the words `add/save it first` in that response.\n- Treat phrases like `what does <agent> have to say`, `what would <agent> say/think`, and asking a saved agent for its own skills/capabilities as contact requests. For an exact saved local agent id such as `yeehaa.io`, use `a2a_call` rather than answering from local saved agent metadata, unless the user explicitly asks for directory/profile details.\n- If the user asks to `call`, `talk to`, `ask`, or contact an unsaved domain/URL, do not call `system_create` on that first request. First explain that it is not saved and ask whether to add/save it first. Only save it after explicit add/save intent or an affirmative follow-up to your save offer.\n- If a user gives an agent URL, do not call it directly. Save the agent first, then use its local agent id.\n- A URL-based or unsaved-domain agent contact request is a save-first directory case, not a wishlist case.\n- If a saved agent is archived/removed, do not call it and do not create a wish. Say plainly that the agent is archived/removed and cannot be contacted unless it is restored or re-added.\n- If more than one saved agent could match the user\u2019s name-based reference, ask which saved agent they mean before calling anything.\n- Do not create a wish or any other entity for a missing, archived/removed, or ambiguous agent unless the user explicitly asks you to add or save that agent.'}eA();nw();fA();import{jsxDEV as $U1}from"preact/jsx-dev-runtime";function swA(A){try{return new URL(A).hostname}catch{return A}}var awA=({name:A,className:Q=""})=>{let B=A.charAt(0).toUpperCase(),w=0;for(let I=0;I<A.length;I++)w=A.charCodeAt(I)+((w<<5)-w);let $=Math.abs(w)%360;return $U1("div",{className:`flex items-center justify-center rounded-full text-white font-bold flex-shrink-0 ${Q}`,style:{backgroundColor:`hsl(${$}, 55%, 45%)`},children:B},void 0,!1,void 0,this)},twA=({kind:A,size:Q="md"})=>{let w={professional:"bg-status-success text-status-success",team:"bg-status-info text-status-info",collective:"bg-brand/10 text-brand"}[A]??"bg-status-neutral text-status-neutral";return $U1("span",{className:`inline-flex items-center rounded-full font-medium ${Q==="sm"?"px-2 py-0.5 text-xs":"px-2.5 py-0.5 text-[13px]"} ${w}`,children:A},void 0,!1,void 0,this)};import{jsxDEV as NQ,Fragment as gK2}from"preact/jsx-dev-runtime";var TK2=({skills:A})=>{if(A.length===0)return null;return NQ("div",{className:"flex gap-1.5 flex-wrap mt-2",children:A.map((Q)=>NQ("span",{className:"text-[11px] px-2 py-0.5 bg-theme-subtle rounded-md text-theme-muted",children:Q.name},Q.name,!1,void 0,this))},void 0,!1,void 0,this)};function SK2(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function IU1(A,Q,B){let w=new URLSearchParams({status:Q});if(B>1)w.set("page",String(B));return`${A}?${w.toString()}`}var OxA=({agent:A})=>{let{frontmatter:Q,about:B,skills:w,url:$}=A,I=Q.status==="approved";return NQ("a",{href:$,className:`flex items-start gap-5 p-6 rounded-xl border border-theme bg-theme-subtle hover:shadow-lg transition-shadow ${I?"":"opacity-70"}`,children:[NQ(awA,{name:Q.name,className:"w-12 h-12 text-lg"},void 0,!1,void 0,this),NQ("div",{className:"flex-1 min-w-0",children:[NQ("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[NQ("span",{className:"text-lg font-semibold text-heading",children:Q.name},void 0,!1,void 0,this),NQ(twA,{kind:Q.kind,size:"sm"},void 0,!1,void 0,this),Q.organization&&NQ("span",{className:"text-xs text-theme-muted",children:["\xB7 ",Q.organization]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"text-sm text-theme-muted mb-1",children:Q.brainName},void 0,!1,void 0,this),B&&NQ("p",{className:"text-sm text-theme-muted line-clamp-2 mb-0",children:B},void 0,!1,void 0,this),I&&NQ(TK2,{skills:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col items-end gap-1 flex-shrink-0 text-right",children:[NQ("span",{className:"text-xs text-theme-muted",children:swA(Q.url)},void 0,!1,void 0,this),NQ("span",{className:"text-[11px] text-theme-muted opacity-60",children:I?`Discovered ${SK2(Q.discoveredAt)}`:"Discovered \xB7 approve before calling"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},DU1=({agents:A,pageTitle:Q,pagination:B,baseUrl:w="/agents",selectedStatus:$})=>{let I=Q??"Agent Directory",D=B?.totalItems??A.length,Y=A.filter((F)=>F.frontmatter.status==="approved"),X=A.filter((F)=>F.frontmatter.status==="discovered"),W=Y.length,U=X.length,K=`Your network of ${D} ${D===1?"brain":"brains"} and their anchors`;return NQ(gK2,{children:[NQ(Z2,{title:I,description:K},void 0,!1,void 0,this),NQ("div",{className:"agent-list bg-theme",children:NQ("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[NQ("div",{className:"mb-8 pb-6 border-b border-theme",children:[NQ("h1",{className:"text-4xl font-bold text-heading mb-2",children:I},void 0,!1,void 0,this),NQ("p",{className:"text-theme-muted mb-4",children:K},void 0,!1,void 0,this),NQ("div",{className:"flex flex-wrap gap-2 text-sm mb-4",children:[NQ("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-heading",children:[D," total"]},void 0,!0,void 0,this),NQ("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-status-success",children:[W," approved"]},void 0,!0,void 0,this),NQ("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-theme-muted",children:[U," discovered"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-wrap gap-2 text-sm",children:[NQ("a",{href:w,className:`px-3 py-1 rounded-full border transition-colors ${$==="all"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"All"},void 0,!1,void 0,this),NQ("a",{href:`${w}?status=approved`,className:`px-3 py-1 rounded-full border transition-colors ${$==="approved"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Approved"},void 0,!1,void 0,this),NQ("a",{href:`${w}?status=discovered`,className:`px-3 py-1 rounded-full border transition-colors ${$==="discovered"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Discovered"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$==="all"&&Y.length>0&&NQ("section",{className:"mb-10",children:[NQ("div",{className:"flex items-center justify-between mb-4",children:[NQ("h2",{className:"text-lg font-semibold text-heading",children:"Approved brains"},void 0,!1,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:Y.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col gap-4",children:Y.map((F)=>NQ(OxA,{agent:F},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$==="all"&&X.length>0&&NQ("section",{children:[NQ("div",{className:"flex items-center justify-between mb-4",children:[NQ("div",{children:[NQ("h2",{className:"text-lg font-semibold text-heading",children:"Discovered brains"},void 0,!1,void 0,this),NQ("p",{className:"text-sm text-theme-muted",children:"Review and approve these before calling them."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:X.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col gap-4",children:X.map((F)=>NQ(OxA,{agent:F},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$!=="all"&&A.length>0&&NQ("section",{children:[NQ("div",{className:"flex items-center justify-between mb-4",children:[NQ("h2",{className:"text-lg font-semibold text-heading",children:$==="approved"?"Approved brains":"Discovered brains"},void 0,!1,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:A.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col gap-4",children:A.map((F)=>NQ(OxA,{agent:F},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.length===0&&NQ("p",{className:"text-center text-theme-muted py-16",children:"No agents in your directory yet."},void 0,!1,void 0,this),B&&B.totalPages>1&&$==="all"&&NQ("div",{className:"mt-12",children:NQ(If,{currentPage:B.currentPage,totalPages:B.totalPages,baseUrl:w},void 0,!1,void 0,this)},void 0,!1,void 0,this),B&&B.totalPages>1&&$!=="all"&&NQ("nav",{"aria-label":"Pagination",className:"flex items-center justify-center gap-3 mt-12",children:[B.hasPrevPage?NQ("a",{href:IU1(w,$,B.currentPage-1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"\u2190 Prev"},void 0,!1,void 0,this):NQ("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"\u2190 Prev"},void 0,!1,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:["Page ",B.currentPage," of ",B.totalPages]},void 0,!0,void 0,this),B.hasNextPage?NQ("a",{href:IU1(w,$,B.currentPage+1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"Next \u2192"},void 0,!1,void 0,this):NQ("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"Next \u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as YQ,Fragment as cK2}from"preact/jsx-dev-runtime";function hK2(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}var Fp=({children:A})=>YQ("h2",{className:"text-sm font-semibold text-theme-muted uppercase tracking-wide mb-3",children:A},void 0,!1,void 0,this),mK2=({skill:A})=>YQ("div",{className:"flex items-start gap-3 px-4 py-3 bg-theme-subtle rounded-lg",children:[YQ("div",{className:"flex-1",children:[YQ("div",{className:"text-sm font-semibold text-heading",children:A.name},void 0,!1,void 0,this),YQ("div",{className:"text-[13px] text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.tags.length>0&&YQ("div",{className:"flex gap-1 flex-shrink-0",children:A.tags.map((Q)=>YQ("span",{className:"text-[11px] px-2 py-0.5 bg-theme rounded-md text-theme-muted",children:Q},Q,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),uK2=({label:A,value:Q,valueClassName:B})=>YQ("div",{className:"flex justify-between text-[13px]",children:[YQ("span",{className:"text-theme-muted",children:A},void 0,!1,void 0,this),YQ("span",{className:B??"text-heading",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YU1=({agent:A,prevAgent:Q,nextAgent:B})=>{let{frontmatter:w,about:$,skills:I,notes:D}=A,Y=swA(w.url),X=w.status==="approved";return YQ(cK2,{children:[YQ(Z2,{title:w.name,description:$||`Agent profile for ${w.name}`},void 0,!1,void 0,this),YQ("article",{className:"agent-detail",children:YQ("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:[YQ("a",{href:"/agents",className:"text-sm text-theme-muted hover:text-brand transition-colors mb-6 inline-block",children:"\u2190 Back to Directory"},void 0,!1,void 0,this),YQ("div",{className:"flex items-start gap-6 mb-8",children:[YQ(awA,{name:w.name,className:"w-[72px] h-[72px] text-3xl"},void 0,!1,void 0,this),YQ("div",{children:[YQ("div",{className:"flex items-center gap-3 mb-1",children:[YQ("h1",{className:"text-3xl md:text-4xl font-bold text-heading",children:w.name},void 0,!1,void 0,this),YQ(twA,{kind:w.kind},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YQ("div",{className:"text-base text-theme-muted mb-2",children:w.brainName},void 0,!1,void 0,this),YQ("div",{className:"flex items-center gap-3 text-theme-muted",children:[w.organization&&YQ("span",{className:"text-[15px]",children:w.organization},void 0,!1,void 0,this),w.organization&&YQ("span",{className:"text-theme-muted opacity-40",children:"\xB7"},void 0,!1,void 0,this),YQ("span",{className:"text-sm",children:["Discovered ",hK2(w.discoveredAt)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("div",{className:"border-b border-theme mb-8"},void 0,!1,void 0,this),!X&&YQ("div",{className:"mb-8 rounded-xl border border-theme bg-theme-subtle px-5 py-4",children:[YQ("div",{className:"text-sm font-semibold text-heading mb-1",children:"Saved for review"},void 0,!1,void 0,this),YQ("p",{className:"text-sm text-theme-muted",children:"This brain is discovered but not approved yet, so it cannot be called until you approve it."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YQ("div",{className:"flex flex-col md:flex-row gap-12",children:[YQ("div",{className:"flex-[2] min-w-0",children:[$&&YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"About"},void 0,!1,void 0,this),YQ("p",{className:"text-[15px] text-theme leading-relaxed",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I.length>0&&YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Skills"},void 0,!1,void 0,this),YQ("div",{className:"flex flex-col gap-2.5",children:I.map((W)=>YQ(mK2,{skill:W},W.name,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D&&YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Notes"},void 0,!1,void 0,this),YQ("p",{className:"text-[15px] text-theme leading-relaxed",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("aside",{className:"flex-1 md:pl-8 md:border-l border-theme-muted/20",children:[YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Brain"},void 0,!1,void 0,this),YQ("div",{className:"p-4 bg-theme-subtle rounded-xl",children:[YQ("div",{className:"text-[15px] font-semibold text-heading mb-1",children:w.brainName},void 0,!1,void 0,this),w.did&&YQ("div",{className:"text-xs text-theme-muted font-mono",children:w.did},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Connection"},void 0,!1,void 0,this),YQ("div",{className:"flex flex-col gap-3",children:[YQ("div",{children:[YQ("div",{className:"text-[13px] text-theme-muted mb-0.5",children:"Endpoint"},void 0,!1,void 0,this),YQ("div",{className:"text-xs text-heading font-mono",children:w.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YQ(uK2,{label:"Status",value:w.status==="approved"?"Approved":"Discovered",valueClassName:w.status==="approved"?"text-status-success font-medium":"text-theme-muted"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("a",{href:w.url.replace(/\/a2a\/?$/,""),target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center px-5 py-3 bg-theme-dark text-theme-inverse rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:["Visit ",Y," \u2197"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(Q??B)&&YQ("nav",{className:"mt-12 pt-6 border-t border-theme flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[YQ("div",{className:"min-h-[1px]",children:Q&&YQ("a",{href:Q.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[YQ("span",{children:"\u2190 Previous"},void 0,!1,void 0,this),YQ("span",{className:"text-heading font-medium",children:Q.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),YQ("div",{className:"min-h-[1px] md:text-right",children:B&&YQ("a",{href:B.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[YQ("span",{children:"Next \u2192"},void 0,!1,void 0,this),YQ("span",{className:"text-heading font-medium",children:B.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};var pK2=f.object({agents:f.array(Ck),pageTitle:f.string().optional(),pagination:T9.nullable(),baseUrl:f.string().optional(),selectedStatus:f.union([f.literal("all"),oY])});function XU1(){return{[LxA]:R1({name:LxA,description:"Agent directory list page template",schema:pK2,dataSourceId:Kp,requiredPermission:"public",layout:{component:DU1}}),[ExA]:R1({name:ExA,description:"Individual agent profile template",schema:f.object({agent:Ck,prevAgent:Ck.nullable(),nextAgent:Ck.nullable()}),dataSourceId:Kp,requiredPermission:"public",layout:{component:YU1}})}}var ewA={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.92",description:"Agent discovery \u2014 brain+anchor contacts and skills",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var iK2=new sY;class RxA extends V2{entityType=f9;schema=Mk;adapter=iK2;constructor(){super(kH1,ewA)}interceptCreate(A,Q,B){return oH1(A,Q,B,this.id)}createGenerationHandler(A){return new VxA(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return XU1()}getDataSources(){return[new dwA(this.logger.child("AgentDataSource"))]}async onRegister(A){BU1(A,this.id)}async getInstructions(){return wU1()}}function bxA(){return new RxA}eA();fA();eA();var Ok=uI,WU1=uI,Zp=a1.extend({entityType:f.literal(O6),metadata:WU1});eA();class Rk extends zQ{constructor(){super({entityType:O6,schema:Zp,frontmatterSchema:Ok})}fromMarkdown(A){let Q=this.parseFrontMatter(A,Ok);return{content:A,entityType:O6,metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}eA();fA();var dK2=f.object({skills:f.array(Ok).max(8)}),HU1=R1({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:dK2,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
|
|
6740
|
+
})();`;import{jsxDEV as m2}from"preact/jsx-dev-runtime";function _K2({item:A}){return m2("li",{class:"list-item",children:[m2("div",{class:"list-main",children:[m2("span",{class:"list-name",children:A.name},void 0,!1,void 0,this),m2("span",{class:"list-desc",children:A.description},void 0,!1,void 0,this),A.tags.length>0&&m2("div",{class:"list-tags",children:A.tags.map((Q)=>m2("span",{class:"tag",children:Q},`${A.id}:${Q}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m2("div",{class:"list-meta",children:A.status==="discovered"&&m2("span",{class:"pill pill--warn",children:"review"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function vK2({item:A}){return m2("li",{class:"list-item agent-network-skill-row","data-agent-network-skill-row":!0,"data-agent-network-tags":JSON.stringify(A.tags),children:[m2("div",{class:"list-main",children:m2("span",{class:"list-name",children:A.name},void 0,!1,void 0,this)},void 0,!1,void 0,this),m2("div",{class:"list-meta",children:m2("span",{class:`agent-network-source${A.sourceType==="brain"?" is-brain":""}`,children:A.sourceLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function xK2({kind:A,items:Q,active:B}){return m2("div",{class:`agent-network-panel${B?" is-active":""}`,"data-agent-network-panel":A,children:Q.length>0?m2("ul",{class:"list agent-network-list",children:Q.map((w)=>m2(_K2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):m2("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function yK2({skills:A,count:Q,filters:B}){return m2("div",{class:"agent-network-panel","data-agent-network-panel":"skills",children:[m2("div",{class:"agent-network-filter-row",role:"tablist","aria-label":"Filter skills by tag",children:[m2("button",{class:"agent-network-filter is-active",type:"button","data-agent-network-tag-filter":"all","aria-pressed":"true",children:[m2("span",{class:"count",children:Q},void 0,!1,void 0,this),m2("span",{class:"label",children:"all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B.map((w)=>m2("button",{class:`agent-network-filter${w.variant==="gap"?" is-gap":""}`,type:"button","data-agent-network-tag-filter":w.tag,"aria-pressed":"false",children:[m2("span",{class:"count",children:w.count},void 0,!1,void 0,this),m2("span",{class:"label",children:w.tag},void 0,!1,void 0,this)]},w.tag,!0,void 0,this))]},void 0,!0,void 0,this),A.length>0?m2("ul",{class:"list agent-network-list agent-network-skills-list",children:A.map((w)=>m2(vK2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):m2("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function CxA({data:A}){let Q=AU1.safeParse(A);if(!Q.success)return m2("p",{class:"muted",children:"Nothing to show yet."},void 0,!1,void 0,this);let B=Q.data;return m2("div",{"data-agent-network-widget":!0,"data-agent-network-view":"agents",children:[m2("div",{class:"agent-network-view-tabs",role:"tablist","aria-label":"Browse the agent network",children:[m2("button",{class:"agent-network-view-tab is-active",type:"button","data-agent-network-view-tab":"agents","aria-pressed":"true",children:["Agents",m2("span",{class:"agent-network-view-count",children:B.counts.agents},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m2("button",{class:"agent-network-view-tab",type:"button","data-agent-network-view-tab":"skills","aria-pressed":"false",children:["Skills",m2("span",{class:"agent-network-view-count",children:B.counts.skills},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m2("div",{class:"agent-network-kind-tabs",role:"tablist","aria-label":"Filter agents by kind",children:MxA.map((w)=>{let $=w==="all";return m2("button",{class:`agent-network-kind-tab${$?" is-active":""}`,type:"button","data-agent-network-kind-tab":w,"aria-pressed":$?"true":"false",children:[m2("span",{class:"agent-network-kind-count",children:B.agents[w].length},void 0,!1,void 0,this),m2("span",{class:"agent-network-kind-label",children:w},void 0,!1,void 0,this)]},w,!0,void 0,this)})},void 0,!1,void 0,this),MxA.map((w)=>m2(xK2,{kind:w,items:B.agents[w],active:w==="all"},w,!1,void 0,this)),m2(yK2,{skills:B.skills,count:B.counts.skills,filters:B.skillFilters},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function BU1(A,Q){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:vH1,pluginId:Q,title:"Agent Network",section:"secondary",priority:15,rendererName:xH1,component:CxA,clientScript:owA,dataProvider:async()=>QU1(A)}}),{success:!0}})}function wU1(){return'## Agent directory\n- Add a new agent contact with `system_create` using `entityType: "agent"` and pass the domain or URL in `url`.\n- List saved agents with `system_list` using `entityType: "agent"`.\n- Approve a discovered agent with `system_update` on the `agent` entity using `fields` (for example `fields: { status: "approved" }`). Do not replace the full content just to change status.\n- When the user explicitly says `approve`, `approve it`, `yes approve`, or `approve <agent-id>`, call `system_update` immediately with `fields: { status: "approved" }` and let the standard confirmation flow ask the user to confirm. Never pass `confirmed: true` on the initial approval request.\n- If the previous turn identified one specific discovered agent, treat a short follow-up like `approve`, `approve it`, or `yes approve` as referring to that same agent id.\n- If `system_update` succeeds for an approval request, answer plainly that the agent is now approved. Do not say the operation failed, and do not ask to retry, unless the tool actually failed.\n- If `system_update` says to use `fields`, or says full content replacement is invalid/empty, retry once immediately with `fields` instead of surfacing that error to the user.\n- If the user gives an exact saved agent id like `old-agent.io`, call that single `system_update` directly instead of listing/searching first.\n- If the previous turn identified one specific unsaved agent domain and offered to add/save it, treat a short affirmative follow-up like `yes`, `yes please`, `please do`, `go ahead`, `do that`, or `save it` as consent to save that same agent immediately with `system_create`.\n- Calling and saving agents are separate actions: if an agent is not saved yet, tell the user it is not saved in the local agent directory yet and ask them to add/save it first. Prefer the words `add/save it first` in that response.\n- Treat phrases like `what does <agent> have to say`, `what would <agent> say/think`, and asking a saved agent for its own skills/capabilities as contact requests. For an exact saved local agent id such as `yeehaa.io`, use `a2a_call` rather than answering from local saved agent metadata, unless the user explicitly asks for directory/profile details.\n- If the user asks to `call`, `talk to`, `ask`, or contact an unsaved domain/URL, do not call `system_create` on that first request. First explain that it is not saved and ask whether to add/save it first. Only save it after explicit add/save intent or an affirmative follow-up to your save offer.\n- If a user gives an agent URL, do not call it directly. Save the agent first, then use its local agent id.\n- A URL-based or unsaved-domain agent contact request is a save-first directory case, not a wishlist case.\n- If a saved agent is archived/removed, do not call it and do not create a wish. Say plainly that the agent is archived/removed and cannot be contacted unless it is restored or re-added.\n- If more than one saved agent could match the user\u2019s name-based reference, ask which saved agent they mean before calling anything.\n- Do not create a wish or any other entity for a missing, archived/removed, or ambiguous agent unless the user explicitly asks you to add or save that agent.'}eA();nw();fA();import{jsxDEV as $U1}from"preact/jsx-dev-runtime";function swA(A){try{return new URL(A).hostname}catch{return A}}var awA=({name:A,className:Q=""})=>{let B=A.charAt(0).toUpperCase(),w=0;for(let I=0;I<A.length;I++)w=A.charCodeAt(I)+((w<<5)-w);let $=Math.abs(w)%360;return $U1("div",{className:`flex items-center justify-center rounded-full text-white font-bold flex-shrink-0 ${Q}`,style:{backgroundColor:`hsl(${$}, 55%, 45%)`},children:B},void 0,!1,void 0,this)},twA=({kind:A,size:Q="md"})=>{let w={professional:"bg-status-success text-status-success",team:"bg-status-info text-status-info",collective:"bg-brand/10 text-brand"}[A]??"bg-status-neutral text-status-neutral";return $U1("span",{className:`inline-flex items-center rounded-full font-medium ${Q==="sm"?"px-2 py-0.5 text-xs":"px-2.5 py-0.5 text-[13px]"} ${w}`,children:A},void 0,!1,void 0,this)};import{jsxDEV as NQ,Fragment as gK2}from"preact/jsx-dev-runtime";var TK2=({skills:A})=>{if(A.length===0)return null;return NQ("div",{className:"flex gap-1.5 flex-wrap mt-2",children:A.map((Q)=>NQ("span",{className:"text-[11px] px-2 py-0.5 bg-theme-subtle rounded-md text-theme-muted",children:Q.name},Q.name,!1,void 0,this))},void 0,!1,void 0,this)};function SK2(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function IU1(A,Q,B){let w=new URLSearchParams({status:Q});if(B>1)w.set("page",String(B));return`${A}?${w.toString()}`}var OxA=({agent:A})=>{let{frontmatter:Q,about:B,skills:w,url:$}=A,I=Q.status==="approved";return NQ("a",{href:$,className:`flex items-start gap-5 p-6 rounded-xl border border-theme bg-theme-subtle hover:shadow-lg transition-shadow ${I?"":"opacity-70"}`,children:[NQ(awA,{name:Q.name,className:"w-12 h-12 text-lg"},void 0,!1,void 0,this),NQ("div",{className:"flex-1 min-w-0",children:[NQ("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[NQ("span",{className:"text-lg font-semibold text-heading",children:Q.name},void 0,!1,void 0,this),NQ(twA,{kind:Q.kind,size:"sm"},void 0,!1,void 0,this),Q.organization&&NQ("span",{className:"text-xs text-theme-muted",children:["\xB7 ",Q.organization]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"text-sm text-theme-muted mb-1",children:Q.brainName},void 0,!1,void 0,this),B&&NQ("p",{className:"text-sm text-theme-muted line-clamp-2 mb-0",children:B},void 0,!1,void 0,this),I&&NQ(TK2,{skills:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col items-end gap-1 flex-shrink-0 text-right",children:[NQ("span",{className:"text-xs text-theme-muted",children:swA(Q.url)},void 0,!1,void 0,this),NQ("span",{className:"text-[11px] text-theme-muted opacity-60",children:I?`Discovered ${SK2(Q.discoveredAt)}`:"Discovered \xB7 approve before calling"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},DU1=({agents:A,pageTitle:Q,pagination:B,baseUrl:w="/agents",selectedStatus:$})=>{let I=Q??"Agent Directory",D=B?.totalItems??A.length,Y=A.filter((F)=>F.frontmatter.status==="approved"),X=A.filter((F)=>F.frontmatter.status==="discovered"),W=Y.length,U=X.length,K=`Your network of ${D} ${D===1?"brain":"brains"} and their anchors`;return NQ(gK2,{children:[NQ(Z2,{title:I,description:K},void 0,!1,void 0,this),NQ("div",{className:"agent-list bg-theme",children:NQ("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[NQ("div",{className:"mb-8 pb-6 border-b border-theme",children:[NQ("h1",{className:"text-4xl font-bold text-heading mb-2",children:I},void 0,!1,void 0,this),NQ("p",{className:"text-theme-muted mb-4",children:K},void 0,!1,void 0,this),NQ("div",{className:"flex flex-wrap gap-2 text-sm mb-4",children:[NQ("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-heading",children:[D," total"]},void 0,!0,void 0,this),NQ("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-status-success",children:[W," approved"]},void 0,!0,void 0,this),NQ("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-theme-muted",children:[U," discovered"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-wrap gap-2 text-sm",children:[NQ("a",{href:w,className:`px-3 py-1 rounded-full border transition-colors ${$==="all"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"All"},void 0,!1,void 0,this),NQ("a",{href:`${w}?status=approved`,className:`px-3 py-1 rounded-full border transition-colors ${$==="approved"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Approved"},void 0,!1,void 0,this),NQ("a",{href:`${w}?status=discovered`,className:`px-3 py-1 rounded-full border transition-colors ${$==="discovered"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Discovered"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$==="all"&&Y.length>0&&NQ("section",{className:"mb-10",children:[NQ("div",{className:"flex items-center justify-between mb-4",children:[NQ("h2",{className:"text-lg font-semibold text-heading",children:"Approved brains"},void 0,!1,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:Y.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col gap-4",children:Y.map((F)=>NQ(OxA,{agent:F},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$==="all"&&X.length>0&&NQ("section",{children:[NQ("div",{className:"flex items-center justify-between mb-4",children:[NQ("div",{children:[NQ("h2",{className:"text-lg font-semibold text-heading",children:"Discovered brains"},void 0,!1,void 0,this),NQ("p",{className:"text-sm text-theme-muted",children:"Review and approve these before calling them."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:X.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col gap-4",children:X.map((F)=>NQ(OxA,{agent:F},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$!=="all"&&A.length>0&&NQ("section",{children:[NQ("div",{className:"flex items-center justify-between mb-4",children:[NQ("h2",{className:"text-lg font-semibold text-heading",children:$==="approved"?"Approved brains":"Discovered brains"},void 0,!1,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:A.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),NQ("div",{className:"flex flex-col gap-4",children:A.map((F)=>NQ(OxA,{agent:F},F.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.length===0&&NQ("p",{className:"text-center text-theme-muted py-16",children:"No agents in your directory yet."},void 0,!1,void 0,this),B&&B.totalPages>1&&$==="all"&&NQ("div",{className:"mt-12",children:NQ(If,{currentPage:B.currentPage,totalPages:B.totalPages,baseUrl:w},void 0,!1,void 0,this)},void 0,!1,void 0,this),B&&B.totalPages>1&&$!=="all"&&NQ("nav",{"aria-label":"Pagination",className:"flex items-center justify-center gap-3 mt-12",children:[B.hasPrevPage?NQ("a",{href:IU1(w,$,B.currentPage-1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"\u2190 Prev"},void 0,!1,void 0,this):NQ("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"\u2190 Prev"},void 0,!1,void 0,this),NQ("span",{className:"text-sm text-theme-muted",children:["Page ",B.currentPage," of ",B.totalPages]},void 0,!0,void 0,this),B.hasNextPage?NQ("a",{href:IU1(w,$,B.currentPage+1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"Next \u2192"},void 0,!1,void 0,this):NQ("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"Next \u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as YQ,Fragment as cK2}from"preact/jsx-dev-runtime";function hK2(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}var Fp=({children:A})=>YQ("h2",{className:"text-sm font-semibold text-theme-muted uppercase tracking-wide mb-3",children:A},void 0,!1,void 0,this),mK2=({skill:A})=>YQ("div",{className:"flex items-start gap-3 px-4 py-3 bg-theme-subtle rounded-lg",children:[YQ("div",{className:"flex-1",children:[YQ("div",{className:"text-sm font-semibold text-heading",children:A.name},void 0,!1,void 0,this),YQ("div",{className:"text-[13px] text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.tags.length>0&&YQ("div",{className:"flex gap-1 flex-shrink-0",children:A.tags.map((Q)=>YQ("span",{className:"text-[11px] px-2 py-0.5 bg-theme rounded-md text-theme-muted",children:Q},Q,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),uK2=({label:A,value:Q,valueClassName:B})=>YQ("div",{className:"flex justify-between text-[13px]",children:[YQ("span",{className:"text-theme-muted",children:A},void 0,!1,void 0,this),YQ("span",{className:B??"text-heading",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YU1=({agent:A,prevAgent:Q,nextAgent:B})=>{let{frontmatter:w,about:$,skills:I,notes:D}=A,Y=swA(w.url),X=w.status==="approved";return YQ(cK2,{children:[YQ(Z2,{title:w.name,description:$||`Agent profile for ${w.name}`},void 0,!1,void 0,this),YQ("article",{className:"agent-detail",children:YQ("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:[YQ("a",{href:"/agents",className:"text-sm text-theme-muted hover:text-brand transition-colors mb-6 inline-block",children:"\u2190 Back to Directory"},void 0,!1,void 0,this),YQ("div",{className:"flex items-start gap-6 mb-8",children:[YQ(awA,{name:w.name,className:"w-[72px] h-[72px] text-3xl"},void 0,!1,void 0,this),YQ("div",{children:[YQ("div",{className:"flex items-center gap-3 mb-1",children:[YQ("h1",{className:"text-3xl md:text-4xl font-bold text-heading",children:w.name},void 0,!1,void 0,this),YQ(twA,{kind:w.kind},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YQ("div",{className:"text-base text-theme-muted mb-2",children:w.brainName},void 0,!1,void 0,this),YQ("div",{className:"flex items-center gap-3 text-theme-muted",children:[w.organization&&YQ("span",{className:"text-[15px]",children:w.organization},void 0,!1,void 0,this),w.organization&&YQ("span",{className:"text-theme-muted opacity-40",children:"\xB7"},void 0,!1,void 0,this),YQ("span",{className:"text-sm",children:["Discovered ",hK2(w.discoveredAt)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("div",{className:"border-b border-theme mb-8"},void 0,!1,void 0,this),!X&&YQ("div",{className:"mb-8 rounded-xl border border-theme bg-theme-subtle px-5 py-4",children:[YQ("div",{className:"text-sm font-semibold text-heading mb-1",children:"Saved for review"},void 0,!1,void 0,this),YQ("p",{className:"text-sm text-theme-muted",children:"This brain is discovered but not approved yet, so it cannot be called until you approve it."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YQ("div",{className:"flex flex-col md:flex-row gap-12",children:[YQ("div",{className:"flex-[2] min-w-0",children:[$&&YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"About"},void 0,!1,void 0,this),YQ("p",{className:"text-[15px] text-theme leading-relaxed",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I.length>0&&YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Skills"},void 0,!1,void 0,this),YQ("div",{className:"flex flex-col gap-2.5",children:I.map((W)=>YQ(mK2,{skill:W},W.name,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D&&YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Notes"},void 0,!1,void 0,this),YQ("p",{className:"text-[15px] text-theme leading-relaxed",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("aside",{className:"flex-1 md:pl-8 md:border-l border-theme-muted/20",children:[YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Brain"},void 0,!1,void 0,this),YQ("div",{className:"p-4 bg-theme-subtle rounded-xl",children:[YQ("div",{className:"text-[15px] font-semibold text-heading mb-1",children:w.brainName},void 0,!1,void 0,this),w.did&&YQ("div",{className:"text-xs text-theme-muted font-mono",children:w.did},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("section",{className:"mb-8",children:[YQ(Fp,{children:"Connection"},void 0,!1,void 0,this),YQ("div",{className:"flex flex-col gap-3",children:[YQ("div",{children:[YQ("div",{className:"text-[13px] text-theme-muted mb-0.5",children:"Endpoint"},void 0,!1,void 0,this),YQ("div",{className:"text-xs text-heading font-mono",children:w.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this),YQ(uK2,{label:"Status",value:w.status==="approved"?"Approved":"Discovered",valueClassName:w.status==="approved"?"text-status-success font-medium":"text-theme-muted"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),YQ("a",{href:w.url.replace(/\/a2a\/?$/,""),target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center px-5 py-3 bg-theme-dark text-theme-inverse rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:["Visit ",Y," \u2197"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(Q??B)&&YQ("nav",{className:"mt-12 pt-6 border-t border-theme flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[YQ("div",{className:"min-h-[1px]",children:Q&&YQ("a",{href:Q.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[YQ("span",{children:"\u2190 Previous"},void 0,!1,void 0,this),YQ("span",{className:"text-heading font-medium",children:Q.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),YQ("div",{className:"min-h-[1px] md:text-right",children:B&&YQ("a",{href:B.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[YQ("span",{children:"Next \u2192"},void 0,!1,void 0,this),YQ("span",{className:"text-heading font-medium",children:B.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};var pK2=f.object({agents:f.array(Ck),pageTitle:f.string().optional(),pagination:T9.nullable(),baseUrl:f.string().optional(),selectedStatus:f.union([f.literal("all"),oY])});function XU1(){return{[LxA]:R1({name:LxA,description:"Agent directory list page template",schema:pK2,dataSourceId:Kp,requiredPermission:"public",layout:{component:DU1}}),[ExA]:R1({name:ExA,description:"Individual agent profile template",schema:f.object({agent:Ck,prevAgent:Ck.nullable(),nextAgent:Ck.nullable()}),dataSourceId:Kp,requiredPermission:"public",layout:{component:YU1}})}}var ewA={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.93",description:"Agent discovery \u2014 brain+anchor contacts and skills",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var iK2=new sY;class RxA extends V2{entityType=f9;schema=Mk;adapter=iK2;constructor(){super(kH1,ewA)}interceptCreate(A,Q,B){return oH1(A,Q,B,this.id)}createGenerationHandler(A){return new VxA(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return XU1()}getDataSources(){return[new dwA(this.logger.child("AgentDataSource"))]}async onRegister(A){BU1(A,this.id)}async getInstructions(){return wU1()}}function bxA(){return new RxA}eA();fA();eA();var Ok=uI,WU1=uI,Zp=a1.extend({entityType:f.literal(O6),metadata:WU1});eA();class Rk extends zQ{constructor(){super({entityType:O6,schema:Zp,frontmatterSchema:Ok})}fromMarkdown(A){let Q=this.parseFrontMatter(A,Ok);return{content:A,entityType:O6,metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}eA();fA();var dK2=f.object({skills:f.array(Ok).max(8)}),HU1=R1({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:dK2,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
|
|
6729
6741
|
|
|
6730
6742
|
Given knowledge domains, CONSOLIDATE related topics into broader skills.
|
|
6731
6743
|
There should be FEWER skills than topics \u2014 combine related domains.
|
|
@@ -6875,9 +6887,9 @@ Context:
|
|
|
6875
6887
|
${JSON.stringify(w,null,2)}
|
|
6876
6888
|
|
|
6877
6889
|
Draft SWOT:
|
|
6878
|
-
${JSON.stringify(B,null,2)}`}function Y8A(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function Kf2(A,Q){let B=["strengths","weaknesses","opportunities","threats"];for(let w of B){let $=new Set(A[w].map((I)=>I.theme.trim().toLowerCase()));for(let I of Q[w]){let D=I.sourceTheme.trim().toLowerCase();if(!$.has(D))throw Error(`SWOT refinement invented theme "${I.sourceTheme}" in ${w}`)}}}class X8A{logger;context;adapter=new Cf;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=kxA.safeParse(A??{});return Q.success?Q.data:null}async process(A,Q,B){await B.report({progress:0.2,message:"Building SWOT context"});let w=await TxA(this.context),$;if(w.summary.brainSkillCount+w.summary.approvedAgentCount+w.summary.discoveredAgentCount===0)$={strengths:[],weaknesses:[],opportunities:[],threats:[]};else{await B.report({progress:0.6,message:"Synthesizing SWOT analysis"});let{object:W}=await this.context.ai.generateObject(await Uf2(this.context,w),_xA),U=_xA.parse(W);await B.report({progress:0.75,message:"Refining SWOT language"});let K=await this.context.ai.generateObject(await Gf2(this.context,w,U),$8A);$=$8A.parse(K.object),Kf2(U,$)}let D=new Date().toISOString(),Y=this.adapter.createSwotContent({strengths:Y8A($.strengths),weaknesses:Y8A($.weaknesses),opportunities:Y8A($.opportunities),threats:Y8A($.threats),derivedAt:D});await B.report({progress:0.9,message:"Saving SWOT entity"});let X=await this.context.entityService.getEntity({entityType:"swot",id:"swot"});if(X)await this.context.entityService.updateEntity({entity:{...X,content:Y,metadata:{derivedAt:D}}});else await this.context.entityService.createEntity({entity:{id:"swot",entityType:"swot",content:Y,metadata:{derivedAt:D}}});return this.logger.info("SWOT derivation complete",{derivedAt:D,brainSkillCount:w.summary.brainSkillCount,approvedAgentCount:w.summary.approvedAgentCount,discoveredAgentCount:w.summary.discoveredAgentCount}),{entityId:"swot"}}}fA();import{jsxDEV as Y7}from"preact/jsx-dev-runtime";var W8A=f.object({title:f.string(),detail:f.string().optional()}),ff2=f.discriminatedUnion("status",[f.object({status:f.literal("generating")}),f.object({status:f.literal("ready"),strengths:f.array(W8A).default([]),weaknesses:f.array(W8A).default([]),opportunities:f.array(W8A).default([]),threats:f.array(W8A).default([]),derivedAt:f.string()})]);function Ff2({items:A}){if(A.length===0)return Y7("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return Y7("ul",{class:"swot-list",children:A.map((Q)=>Y7("li",{class:"swot-item",children:[Y7("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?Y7("span",{children:[" \u2014 ",Q.detail]},void 0,!0,void 0,this):null]},`${Q.title}:${Q.detail??""}`,!0,void 0,this))},void 0,!1,void 0,this)}function H8A({title:A,tone:Q,items:B}){return Y7("section",{class:`swot-cell is-${Q}`,children:[Y7("div",{class:"swot-head",children:A},void 0,!1,void 0,this),Y7(Ff2,{items:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function hxA({data:A}){let Q=ff2.safeParse(A);if(!Q.success||Q.data.status==="generating")return Y7("div",{"data-swot-widget":!0,children:Y7("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let B=Q.data;return Y7("div",{"data-swot-widget":!0,children:Y7("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[Y7(H8A,{title:"Strengths",tone:"s",items:B.strengths},void 0,!1,void 0,this),Y7(H8A,{title:"Weaknesses",tone:"w",items:B.weaknesses},void 0,!1,void 0,this),Y7(H8A,{title:"Opportunities",tone:"o",items:B.opportunities},void 0,!1,void 0,this),Y7(H8A,{title:"Threats",tone:"t",items:B.threats},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}fA();var mxA={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.
|
|
6890
|
+
${JSON.stringify(B,null,2)}`}function Y8A(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function Kf2(A,Q){let B=["strengths","weaknesses","opportunities","threats"];for(let w of B){let $=new Set(A[w].map((I)=>I.theme.trim().toLowerCase()));for(let I of Q[w]){let D=I.sourceTheme.trim().toLowerCase();if(!$.has(D))throw Error(`SWOT refinement invented theme "${I.sourceTheme}" in ${w}`)}}}class X8A{logger;context;adapter=new Cf;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=kxA.safeParse(A??{});return Q.success?Q.data:null}async process(A,Q,B){await B.report({progress:0.2,message:"Building SWOT context"});let w=await TxA(this.context),$;if(w.summary.brainSkillCount+w.summary.approvedAgentCount+w.summary.discoveredAgentCount===0)$={strengths:[],weaknesses:[],opportunities:[],threats:[]};else{await B.report({progress:0.6,message:"Synthesizing SWOT analysis"});let{object:W}=await this.context.ai.generateObject(await Uf2(this.context,w),_xA),U=_xA.parse(W);await B.report({progress:0.75,message:"Refining SWOT language"});let K=await this.context.ai.generateObject(await Gf2(this.context,w,U),$8A);$=$8A.parse(K.object),Kf2(U,$)}let D=new Date().toISOString(),Y=this.adapter.createSwotContent({strengths:Y8A($.strengths),weaknesses:Y8A($.weaknesses),opportunities:Y8A($.opportunities),threats:Y8A($.threats),derivedAt:D});await B.report({progress:0.9,message:"Saving SWOT entity"});let X=await this.context.entityService.getEntity({entityType:"swot",id:"swot"});if(X)await this.context.entityService.updateEntity({entity:{...X,content:Y,metadata:{derivedAt:D}}});else await this.context.entityService.createEntity({entity:{id:"swot",entityType:"swot",content:Y,metadata:{derivedAt:D}}});return this.logger.info("SWOT derivation complete",{derivedAt:D,brainSkillCount:w.summary.brainSkillCount,approvedAgentCount:w.summary.approvedAgentCount,discoveredAgentCount:w.summary.discoveredAgentCount}),{entityId:"swot"}}}fA();import{jsxDEV as Y7}from"preact/jsx-dev-runtime";var W8A=f.object({title:f.string(),detail:f.string().optional()}),ff2=f.discriminatedUnion("status",[f.object({status:f.literal("generating")}),f.object({status:f.literal("ready"),strengths:f.array(W8A).default([]),weaknesses:f.array(W8A).default([]),opportunities:f.array(W8A).default([]),threats:f.array(W8A).default([]),derivedAt:f.string()})]);function Ff2({items:A}){if(A.length===0)return Y7("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return Y7("ul",{class:"swot-list",children:A.map((Q)=>Y7("li",{class:"swot-item",children:[Y7("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?Y7("span",{children:[" \u2014 ",Q.detail]},void 0,!0,void 0,this):null]},`${Q.title}:${Q.detail??""}`,!0,void 0,this))},void 0,!1,void 0,this)}function H8A({title:A,tone:Q,items:B}){return Y7("section",{class:`swot-cell is-${Q}`,children:[Y7("div",{class:"swot-head",children:A},void 0,!1,void 0,this),Y7(Ff2,{items:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function hxA({data:A}){let Q=ff2.safeParse(A);if(!Q.success||Q.data.status==="generating")return Y7("div",{"data-swot-widget":!0,children:Y7("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let B=Q.data;return Y7("div",{"data-swot-widget":!0,children:Y7("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[Y7(H8A,{title:"Strengths",tone:"s",items:B.strengths},void 0,!1,void 0,this),Y7(H8A,{title:"Weaknesses",tone:"w",items:B.weaknesses},void 0,!1,void 0,this),Y7(H8A,{title:"Opportunities",tone:"o",items:B.opportunities},void 0,!1,void 0,this),Y7(H8A,{title:"Threats",tone:"t",items:B.threats},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}fA();var mxA={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.93",description:"Assessment outputs and capability-profile analysis",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var uxA=new Cf;class cxA extends V2{entityType="swot";schema=bk;adapter=uxA;initialSyncComplete=!1;constructor(){super("swot",mxA)}async onRegister(A){let Q=new X8A(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q),A.eval.registerHandler("deriveSwot",async()=>{let I=p$.from(async()=>{});if(!I)throw Error("Expected progress reporter to be created");await Q.process({reason:"eval"},"eval-swot-derive",I);let D=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!D)throw Error("Expected SWOT entity to be created during eval");return uxA.parseSwotContent(D.content).frontmatter});let B=async(I)=>{try{return await A.jobs.enqueue({type:"derive",data:{reason:I},options:{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${I}`}}})}catch(D){return this.logger.error("Failed to queue SWOT derivation",{error:D,reason:I}),null}},w=async(I)=>{if(!await A.entityService.getEntity({entityType:"swot",id:"swot"}))await B(I)};A.messaging.subscribe("sync:initial:completed",async()=>{return this.initialSyncComplete=!0,await w("initial-missing-entity"),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"swot",pluginId:this.id,title:"SWOT",section:"secondary",priority:14,rendererName:"SwotWidget",component:hxA,dataProvider:async()=>{let I=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!I)return{status:"generating"};let{frontmatter:D}=uxA.parseSwotContent(I.content);return{status:"ready",...D}}}}),{success:!0}});let $=async(I)=>{let{entityType:D}=I.payload;if(!this.initialSyncComplete)return{success:!0};if(D!=="agent"&&D!=="skill")return{success:!0};return await B("entity-change"),{success:!0}};A.messaging.subscribe("entity:created",$),A.messaging.subscribe("entity:updated",$),A.messaging.subscribe("entity:deleted",$)}}function pxA(){return new cxA}eA();Z$();fA();var fpw=new Cf,MU1=f.object({name:f.string(),description:f.string(),tags:f.array(f.string())}),lxA=f.enum(["discovered","approved"]),zf2=f.object({name:f.string(),kind:f.enum(["professional","team","collective"]),organization:f.string().optional(),brainName:f.string(),url:f.string().url(),did:f.string().optional(),status:lxA,discoveredAt:f.string().datetime()}),Nf2=a1.extend({entityType:f.literal("agent"),metadata:f.object({name:f.string(),url:f.string().url(),status:lxA,slug:f.string()})}),qf2=a1.extend({entityType:f.literal("skill"),metadata:uI}),Lf2=f.object({about:f.string(),skills:f.array(MU1),notes:f.string()});function Ef2(A){if(!Array.isArray(A)||A.length===0)return"";return A.map((B)=>{let w=B.tags.length>0?` [${B.tags.join(", ")}]`:"";return`- ${B.name}: ${B.description}${w}`}).join(`
|
|
6879
6891
|
`)}function Vf2(A){if(!A.trim())return[];return A.split(`
|
|
6880
|
-
`).map((Q)=>Q.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/)).filter((Q)=>Q!==null).map((Q)=>({name:Q[1]??"",description:Q[2]??"",tags:Q[3]?Q[3].split(",").map((B)=>B.trim()).filter(Boolean):[]}))}var Mf2=new vB(Lf2,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:Ef2,parser:Vf2},{key:"notes",label:"Notes",type:"string"}]});class CU1 extends zQ{constructor(){super({entityType:"agent",schema:Nf2,frontmatterSchema:zf2})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=Mf2.format({about:A.about,skills:A.skills,notes:A.notes});return this.buildMarkdown(Q,{name:A.name,kind:A.kind,...A.organization?{organization:A.organization}:{},brainName:A.brainName,url:A.url,...A.did?{did:A.did}:{},status:A.status,discoveredAt:A.discoveredAt})}}class OU1 extends zQ{constructor(){super({entityType:"skill",schema:qf2,frontmatterSchema:uI})}fromMarkdown(A){let Q=this.parseFrontMatter(A,uI);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var Fpw=new CU1,Zpw=new OU1,zpw=f.object({skills:f.array(uI),agents:f.array(f.object({id:f.string().optional(),name:f.string(),kind:f.enum(["professional","team","collective"]),organization:f.string().optional(),brainName:f.string(),url:f.string().url(),did:f.string().optional(),status:lxA,discoveredAt:f.string().datetime().optional(),about:f.string(),skills:f.array(MU1),notes:f.string().default("")}))});var Cf2=f.object({}).strict();function U8A(A={}){return Cf2.parse(A),[pxA()]}eA();fA();nw();y6();fA();eA();var J8A=Hr.extend({expertise:f.array(f.string()).optional().describe("Skills, domains, areas of focus"),currentFocus:f.string().optional().describe("What you're currently working on"),availability:f.string().optional().describe("What you're open to (consulting, speaking, etc.)")}),qN=uX.extend(J8A.shape);eA();kG();fA();var Of2=new aH;class G8A{postsListUrl;decksListUrl;id="professional:homepage-list";name="Homepage List DataSource";description="Fetches profile, blog posts, and presentation decks for homepage";constructor(A,Q){this.postsListUrl=A;this.decksListUrl=Q}async fetch(A,Q,B){let w=B.entityService,[$,I,D,Y]=await Promise.all([cC(w),w.listEntities({entityType:"post",options:{limit:20}}),w.listEntities({entityType:"deck",options:{limit:20}}),Pc(w)]),X=Of2.parseProfileBody($,qN),W=I.sort(Vv).slice(0,3).map(vc),U=D.sort(Vv).slice(0,3).map(gc);if(!Y.cta)throw Error("CTA not configured in site-info");let K={profile:X,posts:W,decks:U,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:Y.cta,sections:Y.sections??{}};return Q.parse(K)}}eA();kG();var Rf2=new aH;class K8A{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,B){let w=await cC(B.entityService),I={profile:Rf2.parseProfileBody(w,qN)};return Q.parse(I)}}import{jsxDEV as pw,Fragment as jf2}from"preact/jsx-dev-runtime";var bf2="grid md:grid-cols-[14rem_1px_1fr] gap-y-2 gap-x-0 md:gap-16 items-start",Pf2="border-t md:border-t-0 md:border-l border-rule-strong md:self-stretch",ixA=({number:A,title:Q,blurb:B,children:w})=>pw("section",{className:"py-20 border-b border-rule px-6 md:px-12",children:pw("div",{className:"max-w-6xl mx-auto",children:pw("div",{className:bf2,children:[pw(kPA,{title:Q,number:A,blurb:B},void 0,!1,void 0,this),pw("div",{className:Pf2,"aria-hidden":"true"},void 0,!1,void 0,this),pw("div",{className:"mt-6 md:mt-0",children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),dxA=({profile:A,posts:Q,decks:B,postsListUrl:w,decksListUrl:$,cta:I,sections:D})=>{let Y=A.tagline||A.description,X=Q.map((Z)=>({id:Z.id,url:Z.url,title:Z.metadata.title,date:Z.metadata.publishedAt||Z.created,description:Z.frontmatter.excerpt,series:Z.frontmatter.seriesName&&Z.frontmatter.seriesIndex?{name:Z.frontmatter.seriesName,index:Z.frontmatter.seriesIndex}:void 0})),W=B.map((Z)=>({id:Z.id,url:Z.url,title:Z.frontmatter.title||Z.id,date:Z.frontmatter.publishedAt??Z.created,description:Z.frontmatter.description})),U=A.name||"Home",K=A.intro||A.description||Y||"Professional site",F=Boolean(A.description)||A.expertise!==void 0&&A.expertise.length>0;return pw(jf2,{children:[pw(Z2,{title:U,description:K,ogType:"website"},void 0,!1,void 0,this),pw("div",{className:"homepage-list bg-theme",children:[pw("header",{className:"hero-bg-pattern relative w-full px-6 md:px-12 pt-28 pb-24 md:pt-28 md:pb-24 overflow-hidden border-b border-rule",children:pw("div",{className:"relative z-10 max-w-6xl mx-auto w-full",children:[A.name&&pw("div",{className:"flex items-center gap-[0.6rem] mb-6 font-mono text-[0.7rem] font-medium uppercase tracking-[0.22em] text-accent",children:[pw("span",{className:"w-[18px] h-px bg-accent","aria-hidden":"true"},void 0,!1,void 0,this),pw("span",{children:A.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y&&pw("h1",{className:"font-heading text-[clamp(2.75rem,6.5vw,5.5rem)] font-normal text-heading leading-[1.02] tracking-[-0.025em] max-w-[18ch] [font-variation-settings:'opsz'_144,'SOFT'_30]",children:I2A(Y,"italic font-normal text-accent [font-variation-settings:'opsz'_144,'SOFT'_80]")},void 0,!1,void 0,this),A.intro&&pw("p",{className:"font-heading font-light text-[clamp(1.1rem,1.8vw,1.4rem)] leading-[1.5] text-theme-muted max-w-[42ch] mt-8 [font-variation-settings:'opsz'_24]",children:I2A(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),pw(ixA,{number:"01",title:"Essays",blurb:D.essays?.blurb,children:pw($2A,{items:X,viewAllUrl:w,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.length>0&&pw(ixA,{number:"02",title:"Presentations",blurb:D.presentations?.blurb,children:pw($2A,{items:W,viewAllUrl:$,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),F&&pw(ixA,{number:"03",title:"About",blurb:D.about?.blurb,children:pw("div",{className:"flex flex-col gap-8",children:[A.description&&pw("p",{className:"font-heading font-light text-[1.25rem] leading-[1.55] text-theme max-w-[55ch] [font-variation-settings:'opsz'_24,'SOFT'_50]",children:A.description},void 0,!1,void 0,this),A.expertise&&A.expertise.length>0&&pw(_PA,{subjects:A.expertise},void 0,!1,void 0,this),pw("a",{href:"/about",className:"mt-6 inline-flex items-center gap-2 font-mono text-[0.7rem] font-medium uppercase tracking-[0.18em] text-accent pb-1 relative before:content-[''] before:absolute before:left-0 before:right-full before:bottom-0 before:h-px before:bg-accent before:transition-[right] before:duration-300 hover:before:right-0",children:["Learn more",pw("span",{"aria-hidden":"true",children:"\u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),pw(FPA,{cta:I,variant:"editorial",socialLinks:A.socialLinks},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as ww,Fragment as kf2}from"preact/jsx-dev-runtime";var rxA=({profile:A})=>{let Q=`About ${A.name||"Me"}`,B=A.description||A.intro||"About page",w=A.expertise&&A.expertise.length>0||A.currentFocus||A.availability||A.email||A.website||A.socialLinks&&A.socialLinks.length>0;return ww(kf2,{children:[ww(Z2,{title:Q,description:B,ogType:"profile"},void 0,!1,void 0,this),ww("div",{className:"about-page bg-theme",children:[ww("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:ww("div",{className:"relative z-10 max-w-4xl mx-auto",children:[ww("h1",{className:"text-5xl md:text-6xl font-semibold mb-6 text-heading",children:["About ",A.name||"Me"]},void 0,!0,void 0,this),A.description&&ww("p",{className:"text-xl md:text-2xl text-theme-muted leading-relaxed",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),ww("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&ww("section",{className:"content-section-reveal mb-20 md:mb-28",children:ww(CD,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&ww("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),ww("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map(($,I)=>ww("li",{className:ku({variant:"accent",size:"lg"}),children:$},I,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),ww("p",{className:"text-lg text-theme leading-relaxed",children:A.currentFocus},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.availability&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),ww("p",{className:"text-lg text-theme leading-relaxed",children:A.availability},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(A.email||A.website||A.socialLinks&&A.socialLinks.length>0)&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),ww("div",{className:"space-y-4",children:[A.email&&ww("p",{className:"text-lg",children:ww("a",{href:`mailto:${A.email}`,className:"text-brand hover:text-brand-dark transition-colors",children:A.email},void 0,!1,void 0,this)},void 0,!1,void 0,this),A.website&&ww("p",{className:"text-lg",children:ww("a",{href:A.website,target:"_blank",rel:"noopener noreferrer",className:"text-brand hover:text-brand-dark transition-colors",children:A.website},void 0,!1,void 0,this)},void 0,!1,void 0,this),A.socialLinks&&A.socialLinks.length>0&&ww("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map(($,I)=>ww(o5,{href:$.url,external:!0,variant:"secondary",size:"md",children:$.label||$.platform},I,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as X7,Fragment as RU1}from"preact/jsx-dev-runtime";var nxA=()=>{return X7(RU1,{children:[X7(Z2,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),X7("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:X7("div",{className:"text-center max-w-md",children:[X7("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),X7("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),X7("p",{className:"text-lg text-theme-muted mb-8",children:"You'll receive a confirmation email shortly. Check your inbox to confirm your subscription."},void 0,!1,void 0,this),X7(o5,{href:"/",variant:"primary",children:"Back to Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},oxA=()=>{return X7(RU1,{children:[X7(Z2,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),X7("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:X7("div",{className:"text-center max-w-md",children:[X7("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),X7("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),X7("p",{className:"text-lg text-theme-muted mb-8",children:"We couldn't process your subscription. Please try again or contact us if the problem persists."},void 0,!1,void 0,this),X7(o5,{href:"/",variant:"primary",children:"Back to Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};fA();var bU1=f.object({label:f.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:f.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')")}),PU1=f.object({entityDisplay:f.object({post:bU1,deck:bU1}).describe("Display metadata for post and deck entity types (required for homepage)")});var jU1={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.92",description:"Professional site composition package",type:"module",exports:{".":"./src/index.ts"},files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/blog":"workspace:*","@brains/decks":"workspace:*","@brains/identity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/site-info":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class sxA extends qB{dependencies=["blog","decks"];constructor(A){super("professional-site",jU1,A,PU1)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",J8A);let Q=this.config.entityDisplay.post,B=this.config.entityDisplay.deck,w=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,$=`/${B.pluralName??B.label.toLowerCase()+"s"}`,I=new G8A(w,$);A.entities.registerDataSource(I);let D=new K8A;A.entities.registerDataSource(D);let Y=f.object({profile:qN,posts:f.array(Nf),decks:f.array(Tc),postsListUrl:f.string(),decksListUrl:f.string(),cta:ekA,sections:f.record(f.string(),Nd)}),X=f.object({profile:qN}),W=f.object({});A.templates.register({"homepage-list":R1({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:Y,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:dxA}}),about:R1({name:"about",description:"About page with full profile information",schema:X,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:rxA}}),"subscribe-thanks":R1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:W,requiredPermission:"public",layout:{component:nxA}}),"subscribe-error":R1({name:"subscribe-error",description:"Newsletter subscription error page",schema:W,requiredPermission:"public",layout:{component:oxA}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function kU1(A){return new sxA(A??{})}var _U1=[{id:"home",path:"/",title:"Home",description:"Professional site homepage",layout:"default",navigation:{show:!0,label:"Home",slot:"secondary",priority:10},sections:[{id:"homepage",template:"professional-site:homepage-list",dataQuery:{}}]},{id:"about",path:"/about",title:"About",description:"About page",layout:"default",navigation:{show:!0,label:"About",slot:"primary",priority:90},sections:[{id:"about",template:"professional-site:about",dataQuery:{}}]},{id:"subscribe-thanks",path:"/subscribe/thanks",title:"Thanks for subscribing",description:"Newsletter subscription confirmation",layout:"default",navigation:{show:!1},sections:[{id:"subscribe-thanks",template:"professional-site:subscribe-thanks",dataQuery:{},content:{}}]},{id:"subscribe-error",path:"/subscribe/error",title:"Subscription failed",description:"Newsletter subscription error",layout:"default",navigation:{show:!1},sections:[{id:"subscribe-error",template:"professional-site:subscribe-error",dataQuery:{},content:{}}]}];import{jsxDEV as f8A}from"preact/jsx-dev-runtime";function vU1({sections:A,siteInfo:Q,slots:B,wordmark:w}){return f8A("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[f8A(qPA,{title:Q.title,navigation:Q.navigation.primary,showThemeToggle:!0,...Q.logo!==void 0?{logo:Q.logo}:{},...w!==void 0?{wordmark:w}:{}},void 0,!1,void 0,this),f8A("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),f8A(zPA,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,title:Q.title,tagline:Q.description,children:B?.getSlot("footer-top").map(($)=>$.render())},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var vf2={layouts:{default:vU1},routes:_U1,plugin:kU1,entityDisplay:{post:{label:"Post"},deck:{label:"Deck"},project:{label:"Project"},series:{label:"Series",navigation:{slot:"secondary"}},topic:{label:"Topic",navigation:{slot:"secondary"}},link:{label:"Link",navigation:{slot:"secondary"}},base:{label:"Note",navigation:{show:!1}},"social-post":{label:"Social Post",pluralName:"social-posts",navigation:{slot:"secondary"}},newsletter:{label:"Newsletter",navigation:{slot:"secondary"}}}},Np=vf2;var xU1=`/*
|
|
6892
|
+
`).map((Q)=>Q.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/)).filter((Q)=>Q!==null).map((Q)=>({name:Q[1]??"",description:Q[2]??"",tags:Q[3]?Q[3].split(",").map((B)=>B.trim()).filter(Boolean):[]}))}var Mf2=new vB(Lf2,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:Ef2,parser:Vf2},{key:"notes",label:"Notes",type:"string"}]});class CU1 extends zQ{constructor(){super({entityType:"agent",schema:Nf2,frontmatterSchema:zf2})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=Mf2.format({about:A.about,skills:A.skills,notes:A.notes});return this.buildMarkdown(Q,{name:A.name,kind:A.kind,...A.organization?{organization:A.organization}:{},brainName:A.brainName,url:A.url,...A.did?{did:A.did}:{},status:A.status,discoveredAt:A.discoveredAt})}}class OU1 extends zQ{constructor(){super({entityType:"skill",schema:qf2,frontmatterSchema:uI})}fromMarkdown(A){let Q=this.parseFrontMatter(A,uI);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var Fpw=new CU1,Zpw=new OU1,zpw=f.object({skills:f.array(uI),agents:f.array(f.object({id:f.string().optional(),name:f.string(),kind:f.enum(["professional","team","collective"]),organization:f.string().optional(),brainName:f.string(),url:f.string().url(),did:f.string().optional(),status:lxA,discoveredAt:f.string().datetime().optional(),about:f.string(),skills:f.array(MU1),notes:f.string().default("")}))});var Cf2=f.object({}).strict();function U8A(A={}){return Cf2.parse(A),[pxA()]}eA();fA();nw();y6();fA();eA();var J8A=Hr.extend({expertise:f.array(f.string()).optional().describe("Skills, domains, areas of focus"),currentFocus:f.string().optional().describe("What you're currently working on"),availability:f.string().optional().describe("What you're open to (consulting, speaking, etc.)")}),qN=uX.extend(J8A.shape);eA();kG();fA();var Of2=new aH;class G8A{postsListUrl;decksListUrl;id="professional:homepage-list";name="Homepage List DataSource";description="Fetches profile, blog posts, and presentation decks for homepage";constructor(A,Q){this.postsListUrl=A;this.decksListUrl=Q}async fetch(A,Q,B){let w=B.entityService,[$,I,D,Y]=await Promise.all([cC(w),w.listEntities({entityType:"post",options:{limit:20}}),w.listEntities({entityType:"deck",options:{limit:20}}),Pc(w)]),X=Of2.parseProfileBody($,qN),W=I.sort(Vv).slice(0,3).map(vc),U=D.sort(Vv).slice(0,3).map(gc);if(!Y.cta)throw Error("CTA not configured in site-info");let K={profile:X,posts:W,decks:U,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:Y.cta,sections:Y.sections??{}};return Q.parse(K)}}eA();kG();var Rf2=new aH;class K8A{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,B){let w=await cC(B.entityService),I={profile:Rf2.parseProfileBody(w,qN)};return Q.parse(I)}}import{jsxDEV as pw,Fragment as jf2}from"preact/jsx-dev-runtime";var bf2="grid md:grid-cols-[14rem_1px_1fr] gap-y-2 gap-x-0 md:gap-16 items-start",Pf2="border-t md:border-t-0 md:border-l border-rule-strong md:self-stretch",ixA=({number:A,title:Q,blurb:B,children:w})=>pw("section",{className:"py-20 border-b border-rule px-6 md:px-12",children:pw("div",{className:"max-w-6xl mx-auto",children:pw("div",{className:bf2,children:[pw(kPA,{title:Q,number:A,blurb:B},void 0,!1,void 0,this),pw("div",{className:Pf2,"aria-hidden":"true"},void 0,!1,void 0,this),pw("div",{className:"mt-6 md:mt-0",children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),dxA=({profile:A,posts:Q,decks:B,postsListUrl:w,decksListUrl:$,cta:I,sections:D})=>{let Y=A.tagline||A.description,X=Q.map((Z)=>({id:Z.id,url:Z.url,title:Z.metadata.title,date:Z.metadata.publishedAt||Z.created,description:Z.frontmatter.excerpt,series:Z.frontmatter.seriesName&&Z.frontmatter.seriesIndex?{name:Z.frontmatter.seriesName,index:Z.frontmatter.seriesIndex}:void 0})),W=B.map((Z)=>({id:Z.id,url:Z.url,title:Z.frontmatter.title||Z.id,date:Z.frontmatter.publishedAt??Z.created,description:Z.frontmatter.description})),U=A.name||"Home",K=A.intro||A.description||Y||"Professional site",F=Boolean(A.description)||A.expertise!==void 0&&A.expertise.length>0;return pw(jf2,{children:[pw(Z2,{title:U,description:K,ogType:"website"},void 0,!1,void 0,this),pw("div",{className:"homepage-list bg-theme",children:[pw("header",{className:"hero-bg-pattern relative w-full px-6 md:px-12 pt-28 pb-24 md:pt-28 md:pb-24 overflow-hidden border-b border-rule",children:pw("div",{className:"relative z-10 max-w-6xl mx-auto w-full",children:[A.name&&pw("div",{className:"flex items-center gap-[0.6rem] mb-6 font-mono text-[0.7rem] font-medium uppercase tracking-[0.22em] text-accent",children:[pw("span",{className:"w-[18px] h-px bg-accent","aria-hidden":"true"},void 0,!1,void 0,this),pw("span",{children:A.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y&&pw("h1",{className:"font-heading text-[clamp(2.75rem,6.5vw,5.5rem)] font-normal text-heading leading-[1.02] tracking-[-0.025em] max-w-[18ch] [font-variation-settings:'opsz'_144,'SOFT'_30]",children:I2A(Y,"italic font-normal text-accent [font-variation-settings:'opsz'_144,'SOFT'_80]")},void 0,!1,void 0,this),A.intro&&pw("p",{className:"font-heading font-light text-[clamp(1.1rem,1.8vw,1.4rem)] leading-[1.5] text-theme-muted max-w-[42ch] mt-8 [font-variation-settings:'opsz'_24]",children:I2A(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),pw(ixA,{number:"01",title:"Essays",blurb:D.essays?.blurb,children:pw($2A,{items:X,viewAllUrl:w,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.length>0&&pw(ixA,{number:"02",title:"Presentations",blurb:D.presentations?.blurb,children:pw($2A,{items:W,viewAllUrl:$,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),F&&pw(ixA,{number:"03",title:"About",blurb:D.about?.blurb,children:pw("div",{className:"flex flex-col gap-8",children:[A.description&&pw("p",{className:"font-heading font-light text-[1.25rem] leading-[1.55] text-theme max-w-[55ch] [font-variation-settings:'opsz'_24,'SOFT'_50]",children:A.description},void 0,!1,void 0,this),A.expertise&&A.expertise.length>0&&pw(_PA,{subjects:A.expertise},void 0,!1,void 0,this),pw("a",{href:"/about",className:"mt-6 inline-flex items-center gap-2 font-mono text-[0.7rem] font-medium uppercase tracking-[0.18em] text-accent pb-1 relative before:content-[''] before:absolute before:left-0 before:right-full before:bottom-0 before:h-px before:bg-accent before:transition-[right] before:duration-300 hover:before:right-0",children:["Learn more",pw("span",{"aria-hidden":"true",children:"\u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),pw(FPA,{cta:I,variant:"editorial",socialLinks:A.socialLinks},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as ww,Fragment as kf2}from"preact/jsx-dev-runtime";var rxA=({profile:A})=>{let Q=`About ${A.name||"Me"}`,B=A.description||A.intro||"About page",w=A.expertise&&A.expertise.length>0||A.currentFocus||A.availability||A.email||A.website||A.socialLinks&&A.socialLinks.length>0;return ww(kf2,{children:[ww(Z2,{title:Q,description:B,ogType:"profile"},void 0,!1,void 0,this),ww("div",{className:"about-page bg-theme",children:[ww("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:ww("div",{className:"relative z-10 max-w-4xl mx-auto",children:[ww("h1",{className:"text-5xl md:text-6xl font-semibold mb-6 text-heading",children:["About ",A.name||"Me"]},void 0,!0,void 0,this),A.description&&ww("p",{className:"text-xl md:text-2xl text-theme-muted leading-relaxed",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),ww("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&ww("section",{className:"content-section-reveal mb-20 md:mb-28",children:ww(CD,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&ww("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),ww("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map(($,I)=>ww("li",{className:ku({variant:"accent",size:"lg"}),children:$},I,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),ww("p",{className:"text-lg text-theme leading-relaxed",children:A.currentFocus},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.availability&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),ww("p",{className:"text-lg text-theme leading-relaxed",children:A.availability},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(A.email||A.website||A.socialLinks&&A.socialLinks.length>0)&&ww("section",{children:[ww("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),ww("div",{className:"space-y-4",children:[A.email&&ww("p",{className:"text-lg",children:ww("a",{href:`mailto:${A.email}`,className:"text-brand hover:text-brand-dark transition-colors",children:A.email},void 0,!1,void 0,this)},void 0,!1,void 0,this),A.website&&ww("p",{className:"text-lg",children:ww("a",{href:A.website,target:"_blank",rel:"noopener noreferrer",className:"text-brand hover:text-brand-dark transition-colors",children:A.website},void 0,!1,void 0,this)},void 0,!1,void 0,this),A.socialLinks&&A.socialLinks.length>0&&ww("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map(($,I)=>ww(o5,{href:$.url,external:!0,variant:"secondary",size:"md",children:$.label||$.platform},I,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as X7,Fragment as RU1}from"preact/jsx-dev-runtime";var nxA=()=>{return X7(RU1,{children:[X7(Z2,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),X7("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:X7("div",{className:"text-center max-w-md",children:[X7("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),X7("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),X7("p",{className:"text-lg text-theme-muted mb-8",children:"You'll receive a confirmation email shortly. Check your inbox to confirm your subscription."},void 0,!1,void 0,this),X7(o5,{href:"/",variant:"primary",children:"Back to Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},oxA=()=>{return X7(RU1,{children:[X7(Z2,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),X7("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:X7("div",{className:"text-center max-w-md",children:[X7("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),X7("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),X7("p",{className:"text-lg text-theme-muted mb-8",children:"We couldn't process your subscription. Please try again or contact us if the problem persists."},void 0,!1,void 0,this),X7(o5,{href:"/",variant:"primary",children:"Back to Home"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};fA();var bU1=f.object({label:f.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:f.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')")}),PU1=f.object({entityDisplay:f.object({post:bU1,deck:bU1}).describe("Display metadata for post and deck entity types (required for homepage)")});var jU1={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.93",description:"Professional site composition package",type:"module",exports:{".":"./src/index.ts"},files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/blog":"workspace:*","@brains/decks":"workspace:*","@brains/identity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/site-info":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class sxA extends qB{dependencies=["blog","decks"];constructor(A){super("professional-site",jU1,A,PU1)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",J8A);let Q=this.config.entityDisplay.post,B=this.config.entityDisplay.deck,w=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,$=`/${B.pluralName??B.label.toLowerCase()+"s"}`,I=new G8A(w,$);A.entities.registerDataSource(I);let D=new K8A;A.entities.registerDataSource(D);let Y=f.object({profile:qN,posts:f.array(Nf),decks:f.array(Tc),postsListUrl:f.string(),decksListUrl:f.string(),cta:ekA,sections:f.record(f.string(),Nd)}),X=f.object({profile:qN}),W=f.object({});A.templates.register({"homepage-list":R1({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:Y,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:dxA}}),about:R1({name:"about",description:"About page with full profile information",schema:X,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:rxA}}),"subscribe-thanks":R1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:W,requiredPermission:"public",layout:{component:nxA}}),"subscribe-error":R1({name:"subscribe-error",description:"Newsletter subscription error page",schema:W,requiredPermission:"public",layout:{component:oxA}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function kU1(A){return new sxA(A??{})}var _U1=[{id:"home",path:"/",title:"Home",description:"Professional site homepage",layout:"default",navigation:{show:!0,label:"Home",slot:"secondary",priority:10},sections:[{id:"homepage",template:"professional-site:homepage-list",dataQuery:{}}]},{id:"about",path:"/about",title:"About",description:"About page",layout:"default",navigation:{show:!0,label:"About",slot:"primary",priority:90},sections:[{id:"about",template:"professional-site:about",dataQuery:{}}]},{id:"subscribe-thanks",path:"/subscribe/thanks",title:"Thanks for subscribing",description:"Newsletter subscription confirmation",layout:"default",navigation:{show:!1},sections:[{id:"subscribe-thanks",template:"professional-site:subscribe-thanks",dataQuery:{},content:{}}]},{id:"subscribe-error",path:"/subscribe/error",title:"Subscription failed",description:"Newsletter subscription error",layout:"default",navigation:{show:!1},sections:[{id:"subscribe-error",template:"professional-site:subscribe-error",dataQuery:{},content:{}}]}];import{jsxDEV as f8A}from"preact/jsx-dev-runtime";function vU1({sections:A,siteInfo:Q,slots:B,wordmark:w}){return f8A("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[f8A(qPA,{title:Q.title,navigation:Q.navigation.primary,showThemeToggle:!0,...Q.logo!==void 0?{logo:Q.logo}:{},...w!==void 0?{wordmark:w}:{}},void 0,!1,void 0,this),f8A("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),f8A(zPA,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,title:Q.title,tagline:Q.description,children:B?.getSlot("footer-top").map(($)=>$.render())},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var vf2={layouts:{default:vU1},routes:_U1,plugin:kU1,entityDisplay:{post:{label:"Post"},deck:{label:"Deck"},project:{label:"Project"},series:{label:"Series",navigation:{slot:"secondary"}},topic:{label:"Topic",navigation:{slot:"secondary"}},link:{label:"Link",navigation:{slot:"secondary"}},base:{label:"Note",navigation:{show:!1}},"social-post":{label:"Social Post",pluralName:"social-posts",navigation:{slot:"secondary"}},newsletter:{label:"Newsletter",navigation:{slot:"secondary"}}}},Np=vf2;var xU1=`/*
|
|
6881
6893
|
* Default theme \u2014 simplified editorial base inspired by the Rizom family.
|
|
6882
6894
|
*
|
|
6883
6895
|
* This theme is intentionally less branded than @brains/theme-rizom. It
|
|
@@ -7265,7 +7277,7 @@ ${JSON.stringify(B,null,2)}`}function Y8A(A){return A.map((Q)=>Q.detail===null?{
|
|
|
7265
7277
|
|
|
7266
7278
|
.btn-primary:disabled { opacity: 0.5; }
|
|
7267
7279
|
}
|
|
7268
|
-
`;var jk=xU1;import{join as Tf2}from"path";var yU1={name:"@brains/rover",version:"0.2.0-alpha.92",type:"module",private:!0,main:"./src/index.ts",files:["src","brain.eval.yaml","env.schema.template"],scripts:{"build:web-chat":"turbo run build --filter=@brains/web-chat","start:core":"bun run build:web-chat && cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"bun run build:web-chat && cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"bun run build:web-chat && cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",eval:"brain-eval",lint:"eslint .","lint:fix":"eslint . --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/cms":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email-resend":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/portfolio":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/theme-default":"workspace:*","@brains/topics":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var TU1=["prompt","note","link","wishlist","topics","directory-sync","agents","assessment","auth-service","notifications","email-resend","cms","dashboard-root","mcp","webserver","web-chat","discord","a2a"],SU1=[...TU1.filter((A)=>A!=="dashboard-root"),"image","dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],Sf2=[...SU1,"portfolio","topics","content-pipeline","document","social-media","newsletter","stock-photo"],gf2=["Rover is a personal professional knowledge and publishing brain for an independent professional. Prioritize personal knowledge management, professional website content, essays, projects, decks, newsletters, and social distribution workflows.",'Rover entity mappings: "blog post", "post", "essay", "article" \u2192 entityType: post; "case study", "portfolio piece", "project" \u2192 entityType: project; "presentation", "deck", "slides" \u2192 entityType: deck; "newsletter" \u2192 entityType: newsletter; "LinkedIn post", "social post" \u2192 entityType: social-post.',"When a user asks for a publishing/content overview, use the available publishing entity types directly instead of treating the request as generic team memory."],gU1=NZ({name:"rover",version:yU1.version,model:"gpt-5.4-mini",site:Np,theme:jk,presets:{core:TU1,default:SU1,full:Sf2},evalDisable:["discord","webserver","web-chat","mcp","analytics","dashboard","dashboard-root","email-resend"],agentInstructions:gf2,capabilities:[["prompt",RV,void 0],["image",dT,void 0],["cms",OV,{}],["auth-service",yg,void 0],["notifications",St,void 0],["email-resend",HQA,void 0],["dashboard",zN,void 0],["dashboard-root",zN,{routePath:"/"}],["blog",X_A,{}],["series",G_A,void 0],["decks",mc,void 0],["document",S_A,void 0],["note",NV,{}],["link",LV,{}],["portfolio",IvA,{}],["topics",qwA,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",SvA,{generationSchedules:{newsletter:"0 9 * * 1","social-post":"0 10 * * *"},generationConditions:{newsletter:{skipIfDraftExists:!0,minSourceEntities:1,sourceEntityType:"post"},"social-post":{skipIfDraftExists:!0,maxUnpublishedDrafts:5}}}],["social-media",tc,{autoGenerateOnBlogPublish:!0}],["newsletter",$H1,{doubleOptIn:!0}],["obsidian-vault",wxA,{autoSync:!0}],["wishlist",gwA,{}],["stock-photo",UxA,{}],["agents",Q8A,void 0],["assessment",U8A,void 0],["directory-sync",jE,{seedContent:!0,seedContentPath:Tf2(import.meta.dir,"..","seed-content"),initialSync:!0}],["analytics",_wA,{}],["rizom-ecosystem",bV,void 0],["site-info",fV,void 0],["site-builder",KV,{cms:{}}]],interfaces:[["mcp",eZ,()=>({})],["discord",xz,()=>({})],["webserver",yz,()=>({})],["web-chat",I1A,()=>({})],["a2a",nP,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"public"},{pattern:"discord:*",level:"public"},{pattern:"web-chat:*",level:"anchor"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});EZ();eA();fA();fA();eA();var F8A=f.object({routeId:f.string(),sectionId:f.string()}),qp=a1.extend({entityType:f.literal("site-content"),template:f.string().optional(),content:f.string(),metadata:F8A});eA();class hU1 extends zQ{constructor(){super({entityType:"site-content",schema:qp,frontmatterSchema:F8A})}toMarkdown(A){let Q=this.extractBody(A.content);return this.buildMarkdown(Q,A.metadata)}fromMarkdown(A){return{content:A,entityType:"site-content",metadata:this.parseFrontmatter(A)}}}var axA=new hU1;fA();var Z8A=f.object({routeId:f.string().optional().describe("Optional: specific route filter"),sectionId:f.string().optional().describe("Optional: specific section filter"),dryRun:f.boolean().optional().default(!1).describe("Optional: preview changes without executing"),force:f.boolean().optional().default(!1).describe("Force regeneration even if content exists")}),xiw=f.object({jobs:f.array(f.object({jobId:f.string(),routeId:f.string(),sectionId:f.string()})),totalSections:f.number(),queuedSections:f.number(),skippedSections:f.number().optional(),batchId:f.string().optional()});class txA{context;constructor(A){this.context=A}createJobOptions(A,Q){if(!A)return;return{source:A.operationType??Q,rootJobId:A.rootJobId??`${Q}-${Date.now()}`,metadata:{operationType:A.operationType??"content_operations",progressToken:A.progressToken,pluginId:A.pluginId??"site-content"}}}async fetchRoutes(){let A=await this.context.messaging.send({type:"site-builder:routes:list",payload:{}});if("noop"in A)throw Error("No handler for site-builder:routes:list \u2014 is site-builder plugin loaded?");if(!A.success||!A.data)throw Error("Failed to fetch routes from site-builder");return A.data}async generate(A,Q,B){let w=this.context.logger.child("SiteContentOperations"),$=await this.fetchRoutes(),I=$;if(A.routeId){if(I=$.filter((U)=>U.id===A.routeId),I.length===0)throw Error(`Route not found: ${A.routeId}`)}let D=[];for(let U of I)for(let K of U.sections){if(A.sectionId&&K.id!==A.sectionId)continue;if(K.content){w.debug("Section has static content, skipping",{routeId:U.id,sectionId:K.id});continue}if(K.template){let F=this.context.templates.getCapabilities(K.template);if(!F){w.warn("Template not found, skipping section",{routeId:U.id,sectionId:K.id,templateName:K.template});continue}if(!F.canGenerate){w.debug("Template doesn't support generation, skipping",{routeId:U.id,sectionId:K.id,templateName:K.template,capabilities:F});continue}}else{w.debug("Section has no template, skipping",{routeId:U.id,sectionId:K.id});continue}if(!A.force&&!A.dryRun){let F=`${U.id}:${K.id}`;if(await this.context.entityService.getEntity({entityType:"site-content",id:F})){w.debug("Content already exists, skipping",{routeId:U.id,sectionId:K.id});continue}}D.push({route:U,section:K})}let Y=D.length;if(A.dryRun)return{jobs:[],totalSections:Y,queuedSections:Y,batchId:`dry-run-${Date.now()}`};let X=[],W=[];for(let{route:U,section:K}of D){let F=`${U.id}:${K.id}`,Z=K.template,q={routeId:U.id,sectionId:K.id,entityId:F,entityType:"site-content",templateName:Z,context:{prompt:typeof K.content==="string"?K.content:void 0,data:{routeId:U.id,sectionId:K.id,routeTitle:U.title||Q?.title||"",routeDescription:U.description||Q?.description||"",sectionContent:K.content},conversationId:"system"},siteConfig:Q};W.push({type:"shell:content-generation",data:q})}if(W.length>0){let U=this.createJobOptions(B,"site:content-generation"),K=await this.context.jobs.enqueueBatch(W,U);for(let F=0;F<D.length;F++){let Z=D[F];if(Z)X.push({jobId:`${K}-${F}`,routeId:Z.route.id,sectionId:Z.section.id})}return{jobs:X,totalSections:Y,queuedSections:X.length,batchId:K}}return{jobs:[],totalSections:Y,queuedSections:0,batchId:`empty-${Date.now()}`}}}class exA{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new txA(A)}async generateContent(A,Q){let B=Z8A.parse(A);return this.operations.generate(B,this.siteConfig,Q)}}Z$();fA();function Lp(A,Q){return Q?A.optional():A}function QyA(A){switch(A.type){case"string":return Lp(f.string(),A.optional);case"number":return Lp(f.number(),A.optional);case"enum":{let Q=[...A.options];return Lp(f.enum(Q),A.optional)}case"object":{let Q={};for(let[B,w]of Object.entries(A.fields))Q[B]=QyA(w);return Lp(f.object(Q),A.optional)}case"array":{let Q=f.array(hf2(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return Lp(Q,A.optional)}}}function hf2(A){let{items:Q}=A;switch(Q.type){case"string":return f.string();case"number":return f.number();case"enum":{let B=[...Q.options];return f.enum(B)}case"object":{let B={};for(let[w,$]of Object.entries(Q.fields))B[w]=QyA($);return f.object(B)}}}function AyA(A,Q){switch(Q.type){case"string":case"enum":return{key:A,label:Q.label,type:"string"};case"number":return{key:A,label:Q.label,type:"number"};case"object":return{key:A,label:Q.label,type:"object",children:Object.entries(Q.fields).map(([B,w])=>AyA(B,w))};case"array":{let B={key:A,label:Q.label,type:"array"};switch(Q.items.type){case"string":case"enum":return B.itemType="string",B;case"number":return B.itemType="number",B;case"object":return B.itemType="object",B.itemMappings=Object.entries(Q.items.fields).map(([w,$])=>AyA(w,$)),B}}}}function mf2(A,Q){let B={};for(let[I,D]of Object.entries(Q.fields))B[I]=QyA(D);let w=f.object(B),$=new vB(w,{title:Q.title,mappings:Object.entries(Q.fields).map(([I,D])=>AyA(I,D))});return{name:A,description:Q.description,schema:w,formatter:$,requiredPermission:Q.requiredPermission??"public",layout:{component:Q.layout,...Q.fullscreen!==void 0?{fullscreen:Q.fullscreen}:{}},...Q.runtimeScripts?{runtimeScripts:Q.runtimeScripts}:{}}}function ByA(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,B])=>[Q,mf2(Q,B)]))}fA();var mU1=f.object({namespace:f.string(),sections:f.record(f.any())}),uU1=f.object({definitions:f.union([mU1,f.array(mU1)]).optional()});eA();function cU1(A,Q){return[j2(Q,"generate","Generate content for all routes, a specific route, or a specific section",Z8A,async(B,w)=>{let $=A();if(!$)return{success:!1,error:"Site content service not initialized"};if(B.sectionId&&!B.routeId)return{success:!1,error:"sectionId requires routeId to be specified"};let I={rootJobId:`generate-${Date.now()}`,progressToken:w.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:w.interfaceType,channelId:w.channelId},D=await $.generateContent(B,I);return{success:!0,message:`Generated ${D.queuedSections} of ${D.totalSections} sections. ${D.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:D.batchId,jobsQueued:D.queuedSections,totalSections:D.totalSections,jobs:D.jobs}}})]}var pU1={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.92",description:"Site content entity and generation orchestration",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class wyA extends qB{siteContentService;constructor(A={}){super("site-content",pU1,A,uU1)}async onRegister(A){A.entities.register("site-content",qp,axA);for(let Q of mH(this.config.definitions))A.templates.register(ByA(Q),Q.namespace);this.siteContentService=new exA(A)}async getTools(){return cU1(()=>this.siteContentService,this.id)}}function Ep(A={}){return new wyA(A)}eA();fA();nw();fA();eA();var lU1=f.enum(["available","early access","coming soon","planned"]),iU1=f.object({title:f.string(),description:f.string()}),Of=f.object({name:f.string(),availability:lU1,order:f.number()}),z8A=f.object({tagline:f.string(),promise:f.string(),role:f.string(),purpose:f.string(),audience:f.string(),values:f.array(f.string()).min(1),features:f.array(iU1).min(1).max(6),story:f.string()}),cf2=Of.pick({name:!0,availability:!0,order:!0}).extend({slug:f.string()}),kk=a1.extend({entityType:f.literal("product"),metadata:cf2}),N8A=kk.extend({frontmatter:Of,body:z8A,labels:f.record(f.string(),f.string())}),q8A=N8A.extend({url:f.string().optional(),typeLabel:f.string().optional(),listUrl:f.string().optional(),listLabel:f.string().optional()});eA();fA();Z$();class _k extends vB{constructor(){super(z8A,{title:"Product",mappings:[{key:"tagline",label:"Tagline",type:"string"},{key:"promise",label:"Promise",type:"string"},{key:"role",label:"Role",type:"string"},{key:"purpose",label:"Purpose",type:"string"},{key:"audience",label:"Audience",type:"string"},{key:"values",label:"Values",type:"array",itemType:"string"},{key:"features",label:"Capabilities",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"story",label:"Story",type:"string"}]})}}class $yA extends zQ{constructor(){super({entityType:"product",schema:kk,frontmatterSchema:Of,bodyFormatter:new _k})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,Of);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,Of),B=XQ(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:B,availability:Q.availability,order:Q.order}}}}var L8A=new $yA;fA();eA();var dU1=f.object({title:f.string(),description:f.string()}),rU1=f.object({title:f.string(),description:f.string()}),pf2=f.object({title:f.string(),description:f.string()}),nU1=f.object({heading:f.string(),buttonText:f.string(),link:f.string()}),Rf=f.object({headline:f.string(),tagline:f.string()}),lf2=f.object({title:f.string(),description:f.string()}),E8A=f.object({vision:f.string(),pillars:f.array(dU1).min(1).max(6),approach:f.array(lf2).min(1).max(6),productsIntro:f.string(),technologies:f.array(pf2).min(1).max(6),benefits:f.array(rU1).min(1).max(6),cta:nU1}),oU1=Rf.pick({headline:!0}).extend({slug:f.string()}),vk=a1.extend({entityType:f.literal("products-overview"),metadata:oU1}),Vp=vk.extend({frontmatter:Rf,body:E8A,labels:f.record(f.string(),f.string())});eA();fA();Z$();class xk extends vB{constructor(){super(E8A,{title:"Products Overview",mappings:[{key:"vision",label:"Vision",type:"string"},{key:"pillars",label:"Core Principles",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"approach",label:"How It Works",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"productsIntro",label:"Products",type:"string"},{key:"technologies",label:"Built With",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"benefits",label:"Why Brains",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"cta",label:"Ready to Build",type:"object",children:[{key:"heading",label:"Heading",type:"string"},{key:"buttonText",label:"Button Text",type:"string"},{key:"link",label:"Link",type:"string"}]}]})}}class IyA extends zQ{constructor(){super({entityType:"products-overview",schema:vk,frontmatterSchema:Rf,bodyFormatter:new xk})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,Rf);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,Rf),B=XQ(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:B}}}}var DyA=new IyA;eA();fA();var if2=f.object({entityType:f.string(),query:f.object({id:f.string().optional()}).optional()});function sU1(A,Q){let B=$2(A.content,Of),w=Q.parse(B.content),$=Q.getLabels();return N8A.parse({...A,frontmatter:B.metadata,body:w,labels:$})}function aU1(A,Q){let B=$2(A.content,Rf),w=Q.parse(B.content),$=Q.getLabels();return Vp.parse({...A,frontmatter:B.metadata,body:w,labels:$})}class V8A{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new xk;productFormatter=new _k;constructor(A){this.logger=A;this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,B){let w=if2.parse(A),$=B.entityService;if(w.entityType==="products-overview"){let W=(await $.listEntities({entityType:"products-overview",options:{limit:1}}))[0];if(!W)throw Error("Products overview entity not found");let U=aU1(W,this.overviewFormatter);return Q.parse(U)}if(w.query?.id){let W=(await $.listEntities({entityType:"product",options:{filter:{metadata:{slug:w.query.id}},limit:1}}))[0];if(!W)throw Error(`Product not found: ${w.query.id}`);return Q.parse({product:sU1(W,this.productFormatter)})}let[I,D]=await Promise.all([$.listEntities({entityType:"products-overview",options:{limit:1}}),$.listEntities({entityType:"product",options:{sortFields:[{field:"order",direction:"asc"}]}})]),Y=I[0];if(!Y)throw Error("Products overview entity not found");return Q.parse({overview:aU1(Y,this.overviewFormatter),products:D.map((X)=>sU1(X,this.productFormatter))})}}import{jsxDEV as A1,Fragment as nf2}from"preact/jsx-dev-runtime";var tU1=({overview:A,products:Q})=>{let{frontmatter:B,body:w,labels:$}=A;return A1(nf2,{children:[A1(Z2,{title:B.headline,description:B.tagline},void 0,!1,void 0,this),A1("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[A1("style",{children:`
|
|
7280
|
+
`;var jk=xU1;import{join as Tf2}from"path";var yU1={name:"@brains/rover",version:"0.2.0-alpha.93",type:"module",private:!0,main:"./src/index.ts",files:["src","brain.eval.yaml","env.schema.template"],scripts:{"build:web-chat":"turbo run build --filter=@brains/web-chat","start:core":"bun run build:web-chat && cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"bun run build:web-chat && cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"bun run build:web-chat && cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",eval:"brain-eval",lint:"eslint .","lint:fix":"eslint . --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/cms":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email-resend":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/portfolio":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/theme-default":"workspace:*","@brains/topics":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var TU1=["prompt","note","link","wishlist","topics","directory-sync","agents","assessment","auth-service","notifications","email-resend","cms","dashboard-root","mcp","webserver","web-chat","discord","a2a"],SU1=[...TU1.filter((A)=>A!=="dashboard-root"),"image","dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],Sf2=[...SU1,"portfolio","topics","content-pipeline","document","social-media","newsletter","stock-photo"],gf2=["Rover is a personal professional knowledge and publishing brain for an independent professional. Prioritize personal knowledge management, professional website content, essays, projects, decks, newsletters, and social distribution workflows.",'Rover entity mappings: "blog post", "post", "essay", "article" \u2192 entityType: post; "case study", "portfolio piece", "project" \u2192 entityType: project; "presentation", "deck", "slides" \u2192 entityType: deck; "newsletter" \u2192 entityType: newsletter; "LinkedIn post", "social post" \u2192 entityType: social-post.',"When a user asks for a publishing/content overview, use the available publishing entity types directly instead of treating the request as generic team memory."],gU1=NZ({name:"rover",version:yU1.version,model:"gpt-5.4-mini",site:Np,theme:jk,presets:{core:TU1,default:SU1,full:Sf2},evalDisable:["discord","webserver","web-chat","mcp","analytics","dashboard","dashboard-root","email-resend"],agentInstructions:gf2,capabilities:[["prompt",RV,void 0],["image",dT,void 0],["cms",OV,{}],["auth-service",yg,void 0],["notifications",St,void 0],["email-resend",HQA,void 0],["dashboard",zN,void 0],["dashboard-root",zN,{routePath:"/"}],["blog",X_A,{}],["series",G_A,void 0],["decks",mc,void 0],["document",S_A,void 0],["note",NV,{}],["link",LV,{}],["portfolio",IvA,{}],["topics",qwA,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",SvA,{generationSchedules:{newsletter:"0 9 * * 1","social-post":"0 10 * * *"},generationConditions:{newsletter:{skipIfDraftExists:!0,minSourceEntities:1,sourceEntityType:"post"},"social-post":{skipIfDraftExists:!0,maxUnpublishedDrafts:5}}}],["social-media",tc,{autoGenerateOnBlogPublish:!0}],["newsletter",$H1,{doubleOptIn:!0}],["obsidian-vault",wxA,{autoSync:!0}],["wishlist",gwA,{}],["stock-photo",UxA,{}],["agents",Q8A,void 0],["assessment",U8A,void 0],["directory-sync",jE,{seedContent:!0,seedContentPath:Tf2(import.meta.dir,"..","seed-content"),initialSync:!0}],["analytics",_wA,{}],["rizom-ecosystem",bV,void 0],["site-info",fV,void 0],["site-builder",KV,{cms:{}}]],interfaces:[["mcp",eZ,()=>({})],["discord",xz,()=>({})],["webserver",yz,()=>({})],["web-chat",I1A,()=>({})],["a2a",nP,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"public"},{pattern:"discord:*",level:"public"},{pattern:"web-chat:*",level:"anchor"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});EZ();eA();fA();fA();eA();var F8A=f.object({routeId:f.string(),sectionId:f.string()}),qp=a1.extend({entityType:f.literal("site-content"),template:f.string().optional(),content:f.string(),metadata:F8A});eA();class hU1 extends zQ{constructor(){super({entityType:"site-content",schema:qp,frontmatterSchema:F8A})}toMarkdown(A){let Q=this.extractBody(A.content);return this.buildMarkdown(Q,A.metadata)}fromMarkdown(A){return{content:A,entityType:"site-content",metadata:this.parseFrontmatter(A)}}}var axA=new hU1;fA();var Z8A=f.object({routeId:f.string().optional().describe("Optional: specific route filter"),sectionId:f.string().optional().describe("Optional: specific section filter"),dryRun:f.boolean().optional().default(!1).describe("Optional: preview changes without executing"),force:f.boolean().optional().default(!1).describe("Force regeneration even if content exists")}),xiw=f.object({jobs:f.array(f.object({jobId:f.string(),routeId:f.string(),sectionId:f.string()})),totalSections:f.number(),queuedSections:f.number(),skippedSections:f.number().optional(),batchId:f.string().optional()});class txA{context;constructor(A){this.context=A}createJobOptions(A,Q){if(!A)return;return{source:A.operationType??Q,rootJobId:A.rootJobId??`${Q}-${Date.now()}`,metadata:{operationType:A.operationType??"content_operations",progressToken:A.progressToken,pluginId:A.pluginId??"site-content"}}}async fetchRoutes(){let A=await this.context.messaging.send({type:"site-builder:routes:list",payload:{}});if("noop"in A)throw Error("No handler for site-builder:routes:list \u2014 is site-builder plugin loaded?");if(!A.success||!A.data)throw Error("Failed to fetch routes from site-builder");return A.data}async generate(A,Q,B){let w=this.context.logger.child("SiteContentOperations"),$=await this.fetchRoutes(),I=$;if(A.routeId){if(I=$.filter((U)=>U.id===A.routeId),I.length===0)throw Error(`Route not found: ${A.routeId}`)}let D=[];for(let U of I)for(let K of U.sections){if(A.sectionId&&K.id!==A.sectionId)continue;if(K.content){w.debug("Section has static content, skipping",{routeId:U.id,sectionId:K.id});continue}if(K.template){let F=this.context.templates.getCapabilities(K.template);if(!F){w.warn("Template not found, skipping section",{routeId:U.id,sectionId:K.id,templateName:K.template});continue}if(!F.canGenerate){w.debug("Template doesn't support generation, skipping",{routeId:U.id,sectionId:K.id,templateName:K.template,capabilities:F});continue}}else{w.debug("Section has no template, skipping",{routeId:U.id,sectionId:K.id});continue}if(!A.force&&!A.dryRun){let F=`${U.id}:${K.id}`;if(await this.context.entityService.getEntity({entityType:"site-content",id:F})){w.debug("Content already exists, skipping",{routeId:U.id,sectionId:K.id});continue}}D.push({route:U,section:K})}let Y=D.length;if(A.dryRun)return{jobs:[],totalSections:Y,queuedSections:Y,batchId:`dry-run-${Date.now()}`};let X=[],W=[];for(let{route:U,section:K}of D){let F=`${U.id}:${K.id}`,Z=K.template,q={routeId:U.id,sectionId:K.id,entityId:F,entityType:"site-content",templateName:Z,context:{prompt:typeof K.content==="string"?K.content:void 0,data:{routeId:U.id,sectionId:K.id,routeTitle:U.title||Q?.title||"",routeDescription:U.description||Q?.description||"",sectionContent:K.content},conversationId:"system"},siteConfig:Q};W.push({type:"shell:content-generation",data:q})}if(W.length>0){let U=this.createJobOptions(B,"site:content-generation"),K=await this.context.jobs.enqueueBatch(W,U);for(let F=0;F<D.length;F++){let Z=D[F];if(Z)X.push({jobId:`${K}-${F}`,routeId:Z.route.id,sectionId:Z.section.id})}return{jobs:X,totalSections:Y,queuedSections:X.length,batchId:K}}return{jobs:[],totalSections:Y,queuedSections:0,batchId:`empty-${Date.now()}`}}}class exA{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new txA(A)}async generateContent(A,Q){let B=Z8A.parse(A);return this.operations.generate(B,this.siteConfig,Q)}}Z$();fA();function Lp(A,Q){return Q?A.optional():A}function QyA(A){switch(A.type){case"string":return Lp(f.string(),A.optional);case"number":return Lp(f.number(),A.optional);case"enum":{let Q=[...A.options];return Lp(f.enum(Q),A.optional)}case"object":{let Q={};for(let[B,w]of Object.entries(A.fields))Q[B]=QyA(w);return Lp(f.object(Q),A.optional)}case"array":{let Q=f.array(hf2(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return Lp(Q,A.optional)}}}function hf2(A){let{items:Q}=A;switch(Q.type){case"string":return f.string();case"number":return f.number();case"enum":{let B=[...Q.options];return f.enum(B)}case"object":{let B={};for(let[w,$]of Object.entries(Q.fields))B[w]=QyA($);return f.object(B)}}}function AyA(A,Q){switch(Q.type){case"string":case"enum":return{key:A,label:Q.label,type:"string"};case"number":return{key:A,label:Q.label,type:"number"};case"object":return{key:A,label:Q.label,type:"object",children:Object.entries(Q.fields).map(([B,w])=>AyA(B,w))};case"array":{let B={key:A,label:Q.label,type:"array"};switch(Q.items.type){case"string":case"enum":return B.itemType="string",B;case"number":return B.itemType="number",B;case"object":return B.itemType="object",B.itemMappings=Object.entries(Q.items.fields).map(([w,$])=>AyA(w,$)),B}}}}function mf2(A,Q){let B={};for(let[I,D]of Object.entries(Q.fields))B[I]=QyA(D);let w=f.object(B),$=new vB(w,{title:Q.title,mappings:Object.entries(Q.fields).map(([I,D])=>AyA(I,D))});return{name:A,description:Q.description,schema:w,formatter:$,requiredPermission:Q.requiredPermission??"public",layout:{component:Q.layout,...Q.fullscreen!==void 0?{fullscreen:Q.fullscreen}:{}},...Q.runtimeScripts?{runtimeScripts:Q.runtimeScripts}:{}}}function ByA(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,B])=>[Q,mf2(Q,B)]))}fA();var mU1=f.object({namespace:f.string(),sections:f.record(f.any())}),uU1=f.object({definitions:f.union([mU1,f.array(mU1)]).optional()});eA();function cU1(A,Q){return[j2(Q,"generate","Generate content for all routes, a specific route, or a specific section",Z8A,async(B,w)=>{let $=A();if(!$)return{success:!1,error:"Site content service not initialized"};if(B.sectionId&&!B.routeId)return{success:!1,error:"sectionId requires routeId to be specified"};let I={rootJobId:`generate-${Date.now()}`,progressToken:w.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:w.interfaceType,channelId:w.channelId},D=await $.generateContent(B,I);return{success:!0,message:`Generated ${D.queuedSections} of ${D.totalSections} sections. ${D.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:D.batchId,jobsQueued:D.queuedSections,totalSections:D.totalSections,jobs:D.jobs}}})]}var pU1={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.93",description:"Site content entity and generation orchestration",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class wyA extends qB{siteContentService;constructor(A={}){super("site-content",pU1,A,uU1)}async onRegister(A){A.entities.register("site-content",qp,axA);for(let Q of mH(this.config.definitions))A.templates.register(ByA(Q),Q.namespace);this.siteContentService=new exA(A)}async getTools(){return cU1(()=>this.siteContentService,this.id)}}function Ep(A={}){return new wyA(A)}eA();fA();nw();fA();eA();var lU1=f.enum(["available","early access","coming soon","planned"]),iU1=f.object({title:f.string(),description:f.string()}),Of=f.object({name:f.string(),availability:lU1,order:f.number()}),z8A=f.object({tagline:f.string(),promise:f.string(),role:f.string(),purpose:f.string(),audience:f.string(),values:f.array(f.string()).min(1),features:f.array(iU1).min(1).max(6),story:f.string()}),cf2=Of.pick({name:!0,availability:!0,order:!0}).extend({slug:f.string()}),kk=a1.extend({entityType:f.literal("product"),metadata:cf2}),N8A=kk.extend({frontmatter:Of,body:z8A,labels:f.record(f.string(),f.string())}),q8A=N8A.extend({url:f.string().optional(),typeLabel:f.string().optional(),listUrl:f.string().optional(),listLabel:f.string().optional()});eA();fA();Z$();class _k extends vB{constructor(){super(z8A,{title:"Product",mappings:[{key:"tagline",label:"Tagline",type:"string"},{key:"promise",label:"Promise",type:"string"},{key:"role",label:"Role",type:"string"},{key:"purpose",label:"Purpose",type:"string"},{key:"audience",label:"Audience",type:"string"},{key:"values",label:"Values",type:"array",itemType:"string"},{key:"features",label:"Capabilities",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"story",label:"Story",type:"string"}]})}}class $yA extends zQ{constructor(){super({entityType:"product",schema:kk,frontmatterSchema:Of,bodyFormatter:new _k})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,Of);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,Of),B=XQ(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:B,availability:Q.availability,order:Q.order}}}}var L8A=new $yA;fA();eA();var dU1=f.object({title:f.string(),description:f.string()}),rU1=f.object({title:f.string(),description:f.string()}),pf2=f.object({title:f.string(),description:f.string()}),nU1=f.object({heading:f.string(),buttonText:f.string(),link:f.string()}),Rf=f.object({headline:f.string(),tagline:f.string()}),lf2=f.object({title:f.string(),description:f.string()}),E8A=f.object({vision:f.string(),pillars:f.array(dU1).min(1).max(6),approach:f.array(lf2).min(1).max(6),productsIntro:f.string(),technologies:f.array(pf2).min(1).max(6),benefits:f.array(rU1).min(1).max(6),cta:nU1}),oU1=Rf.pick({headline:!0}).extend({slug:f.string()}),vk=a1.extend({entityType:f.literal("products-overview"),metadata:oU1}),Vp=vk.extend({frontmatter:Rf,body:E8A,labels:f.record(f.string(),f.string())});eA();fA();Z$();class xk extends vB{constructor(){super(E8A,{title:"Products Overview",mappings:[{key:"vision",label:"Vision",type:"string"},{key:"pillars",label:"Core Principles",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"approach",label:"How It Works",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"productsIntro",label:"Products",type:"string"},{key:"technologies",label:"Built With",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"benefits",label:"Why Brains",type:"array",itemType:"object",itemMappings:[{key:"title",label:"Title",type:"string"},{key:"description",label:"Description",type:"string"}]},{key:"cta",label:"Ready to Build",type:"object",children:[{key:"heading",label:"Heading",type:"string"},{key:"buttonText",label:"Button Text",type:"string"},{key:"link",label:"Link",type:"string"}]}]})}}class IyA extends zQ{constructor(){super({entityType:"products-overview",schema:vk,frontmatterSchema:Rf,bodyFormatter:new xk})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,Rf);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,Rf),B=XQ(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:B}}}}var DyA=new IyA;eA();fA();var if2=f.object({entityType:f.string(),query:f.object({id:f.string().optional()}).optional()});function sU1(A,Q){let B=$2(A.content,Of),w=Q.parse(B.content),$=Q.getLabels();return N8A.parse({...A,frontmatter:B.metadata,body:w,labels:$})}function aU1(A,Q){let B=$2(A.content,Rf),w=Q.parse(B.content),$=Q.getLabels();return Vp.parse({...A,frontmatter:B.metadata,body:w,labels:$})}class V8A{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new xk;productFormatter=new _k;constructor(A){this.logger=A;this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,B){let w=if2.parse(A),$=B.entityService;if(w.entityType==="products-overview"){let W=(await $.listEntities({entityType:"products-overview",options:{limit:1}}))[0];if(!W)throw Error("Products overview entity not found");let U=aU1(W,this.overviewFormatter);return Q.parse(U)}if(w.query?.id){let W=(await $.listEntities({entityType:"product",options:{filter:{metadata:{slug:w.query.id}},limit:1}}))[0];if(!W)throw Error(`Product not found: ${w.query.id}`);return Q.parse({product:sU1(W,this.productFormatter)})}let[I,D]=await Promise.all([$.listEntities({entityType:"products-overview",options:{limit:1}}),$.listEntities({entityType:"product",options:{sortFields:[{field:"order",direction:"asc"}]}})]),Y=I[0];if(!Y)throw Error("Products overview entity not found");return Q.parse({overview:aU1(Y,this.overviewFormatter),products:D.map((X)=>sU1(X,this.productFormatter))})}}import{jsxDEV as A1,Fragment as nf2}from"preact/jsx-dev-runtime";var tU1=({overview:A,products:Q})=>{let{frontmatter:B,body:w,labels:$}=A;return A1(nf2,{children:[A1(Z2,{title:B.headline,description:B.tagline},void 0,!1,void 0,this),A1("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[A1("style",{children:`
|
|
7269
7281
|
@keyframes wave-drift {
|
|
7270
7282
|
from { transform: translateX(0); }
|
|
7271
7283
|
to { transform: translateX(-50%); }
|
|
@@ -7293,7 +7305,7 @@ ${JSON.stringify(B,null,2)}`}function Y8A(A){return A.map((Q)=>Q.detail===null?{
|
|
|
7293
7305
|
@media (prefers-reduced-motion: reduce) {
|
|
7294
7306
|
.detail-wave { animation: none; }
|
|
7295
7307
|
}
|
|
7296
|
-
`},void 0,!1,void 0,this),s1("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:s1("svg",{preserveAspectRatio:"none",width:"200%",height:"100%",viewBox:"0 0 1600 400",className:"block absolute inset-0 detail-wave",children:[s1("path",{d:"M0,200 C67,140 133,140 200,200 C267,260 333,260 400,200 C467,140 533,140 600,200 C667,260 733,260 800,200 C867,140 933,140 1000,200 C1067,260 1133,260 1200,200 C1267,140 1333,140 1400,200 C1467,260 1533,260 1600,200",className:"stroke-accent",strokeWidth:"2",strokeMiterlimit:"10",fill:"none",opacity:"0.15"},void 0,!1,void 0,this),s1("path",{d:"M0,230 C67,170 133,170 200,230 C267,290 333,290 400,230 C467,170 533,170 600,230 C667,290 733,290 800,230 C867,170 933,170 1000,230 C1067,290 1133,290 1200,230 C1267,170 1333,170 1400,230 C1467,290 1533,290 1600,230",className:"stroke-accent",strokeWidth:"1.5",strokeMiterlimit:"10",fill:"none",opacity:"0.06"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("div",{className:"absolute inset-0 cta-bg-pattern pointer-events-none"},void 0,!1,void 0,this),s1("div",{className:"relative z-10 max-w-5xl mx-auto w-full px-6 md:px-12 pt-12 md:pt-20 pb-16 md:pb-24",children:[s1("nav",{"aria-label":"Breadcrumb",className:"text-sm text-white/50 mb-8 hero-stagger-1",children:s1("ol",{className:"flex flex-wrap items-center gap-1",children:[s1("li",{className:"flex items-center gap-1",children:s1("a",{href:"/",className:"hover:text-white transition-colors",children:"Home"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s1("li",{className:"flex items-center gap-1",children:[s1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),s1("a",{href:$,className:"hover:text-white transition-colors",children:I},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("li",{className:"flex items-center gap-1",children:[s1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),s1("span",{className:"text-white font-medium",children:Q.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("div",{className:"mb-6 hero-stagger-1",children:s1(BI,{status:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this),s1("h1",{className:"text-5xl md:text-6xl lg:text-[7rem] font-bold text-white tracking-tighter leading-[0.95] mb-6 md:mb-8 hero-stagger-1",children:Q.name},void 0,!1,void 0,this),s1("div",{className:"w-20 h-1.5 bg-accent mb-6 md:mb-8 hero-stagger-2"},void 0,!1,void 0,this),s1("p",{className:"text-lg md:text-xl text-white/70 leading-relaxed max-w-xl hero-stagger-3",children:B.tagline},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),s1("section",{className:"bg-theme-subtle py-20 md:py-28 px-6 md:px-12",children:s1("div",{className:"max-w-4xl mx-auto space-y-16",children:[s1("div",{children:[s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:w.promise},void 0,!1,void 0,this),s1("p",{className:"text-2xl md:text-3xl lg:text-4xl leading-relaxed text-heading font-light",children:B.promise},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12 md:gap-16",children:[s1("div",{children:[s1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.role},void 0,!1,void 0,this),s1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.role},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("div",{children:[s1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.purpose},void 0,!1,void 0,this),s1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.purpose},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("div",{children:[s1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.audience},void 0,!1,void 0,this),s1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.audience},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),s1("div",{className:"flex flex-col md:flex-row md:items-center gap-6 md:gap-12",children:[s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted whitespace-nowrap",children:w.values},void 0,!1,void 0,this),s1(jj,{tags:B.values,variant:"accent",size:"md"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("section",{className:"cta-bg-pattern bg-brand py-20 md:py-32 px-6 md:px-12",children:s1("div",{className:"container mx-auto max-w-5xl",children:[s1("h2",{className:"text-sm tracking-widest uppercase text-white/50 mb-16",children:w.features},void 0,!1,void 0,this),s1("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 md:gap-16",children:B.features.map((Y,X)=>s1("div",{children:s1("div",{className:"flex items-start gap-6",children:[s1("span",{className:"text-5xl md:text-6xl font-black text-white/10 leading-none shrink-0",children:String(X+1).padStart(2,"0")},void 0,!1,void 0,this),s1("div",{className:"pt-2",children:[s1("div",{className:"w-8 h-1 bg-accent mb-4"},void 0,!1,void 0,this),s1("h3",{className:"text-xl font-bold text-white mb-3",children:Y.title},void 0,!1,void 0,this),s1("p",{className:"text-white/70 leading-relaxed",children:Y.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Y.title,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("section",{className:"py-20 md:py-32 px-6 md:px-12",children:s1("div",{className:"max-w-3xl mx-auto",children:[s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-12",children:w.story},void 0,!1,void 0,this),s1("div",{className:"space-y-6",children:D.map((Y,X)=>s1("p",{className:X===0?"text-2xl md:text-3xl leading-relaxed text-heading font-light":"text-lg leading-relaxed text-theme-muted",children:Y},X,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("section",{className:"cta-bg-pattern bg-brand-dark pt-24 md:pt-32 pb-40 md:pb-48 -mb-[60px] px-6 md:px-12",children:s1("div",{className:"max-w-4xl mx-auto",children:[s1("p",{className:"text-sm tracking-widest uppercase text-white/60 mb-4",children:Q.name},void 0,!1,void 0,this),s1("h2",{className:"text-3xl md:text-5xl font-bold text-white max-w-2xl mb-4",children:B.tagline},void 0,!1,void 0,this),s1("p",{className:"text-lg text-white/60 mb-10 max-w-xl",children:B.promise},void 0,!1,void 0,this),s1(o5,{href:$,variant:"outline-light",size:"lg",children:I},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};fA();var YyA=f.object({route:f.string().default("/products")});var AJ1={name:"@brains/products",private:!0,version:"0.2.0-alpha.92",description:"Product entity management and overview page for marketing showcase",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var af2=f.object({overview:Vp,products:f.array(q8A)}),tf2=f.object({product:q8A});class XyA extends V2{entityType=L8A.entityType;schema=kk;adapter=L8A;constructor(A={}){super("products",AJ1,A,YyA)}getTemplates(){return{"product-list":R1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:af2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:tU1}}),"product-detail":R1({name:"product-detail",description:"Individual product detail page",schema:tf2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:eU1}})}}getDataSources(){return[new V8A(this.logger.child("ProductsDataSource"))]}async onRegister(A){A.entities.register("products-overview",vk,DyA)}}function WyA(A={}){return new XyA(A)}import{join as VF2}from"path";import{jsxDEV as M8A,Fragment as ef2}from"preact/jsx-dev-runtime";var yk=({children:A})=>M8A(ef2,{children:[M8A("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:M8A("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),M8A("div",{className:"max-w-[1440px] mx-auto relative overflow-x-clip",children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this);import{jsxDEV as qrw}from"preact/jsx-dev-runtime";import{jsxDEV as QF2}from"preact/jsx-dev-runtime";var C8A="px-6 md:px-10 xl:px-20",AF2=`${C8A} relative z-[1]`,LN=({id:A,className:Q,children:B})=>QF2("section",{id:A,className:e1(AF2,Q),children:B},void 0,!1,void 0,this);import{jsxDEV as brw}from"preact/jsx-dev-runtime";import{jsxDEV as krw}from"preact/jsx-dev-runtime";import{jsxDEV as DF2}from"preact/jsx-dev-runtime";var BF2="inline-flex items-center justify-center cursor-pointer border border-solid transition-all [gap:var(--rizom-btn-gap)] [border-radius:var(--rizom-btn-radius)] [font-family:var(--rizom-btn-font-family)] [font-style:var(--rizom-btn-font-style)] [letter-spacing:var(--rizom-btn-letter-spacing)] [text-transform:var(--rizom-btn-text-transform)]",wF2={primary:"[font-weight:var(--rizom-btn-primary-font-weight)] [color:var(--rizom-btn-primary-color)] [background:var(--rizom-btn-primary-bg)] [border-color:var(--rizom-btn-primary-border-color)] [border-width:var(--rizom-btn-primary-border-width)] [box-shadow:var(--rizom-btn-primary-shadow)] hover:[color:var(--rizom-btn-primary-hover-color)] hover:[background:var(--rizom-btn-primary-hover-bg)] hover:[border-color:var(--rizom-btn-primary-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-hover-shadow)] hover:[transform:var(--rizom-btn-primary-hover-transform)]","primary-strong":"duration-400 ease-[cubic-bezier(0.2,0.8,0.2,1)] [font-weight:var(--rizom-btn-primary-strong-font-weight)] [color:var(--rizom-btn-primary-strong-color)] [background:var(--rizom-btn-primary-strong-bg)] [border-color:var(--rizom-btn-primary-strong-border-color)] [border-width:var(--rizom-btn-primary-strong-border-width)] [box-shadow:var(--rizom-btn-primary-strong-shadow)] hover:[color:var(--rizom-btn-primary-strong-hover-color)] hover:[background:var(--rizom-btn-primary-strong-hover-bg)] hover:[border-color:var(--rizom-btn-primary-strong-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-strong-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-strong-hover-shadow)] hover:[transform:var(--rizom-btn-primary-strong-hover-transform)]",secondary:"[font-weight:var(--rizom-btn-secondary-font-weight)] [color:var(--rizom-btn-secondary-color)] [background:var(--rizom-btn-secondary-bg)] [border-color:var(--rizom-btn-secondary-border-color)] [border-width:var(--rizom-btn-secondary-border-width)] [box-shadow:var(--rizom-btn-secondary-shadow)] hover:[color:var(--rizom-btn-secondary-hover-color)] hover:[background:var(--rizom-btn-secondary-hover-bg)] hover:[border-color:var(--rizom-btn-secondary-hover-border-color)] hover:[border-width:var(--rizom-btn-secondary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-secondary-hover-shadow)] hover:[transform:var(--rizom-btn-secondary-hover-transform)]"},$F2={md:"text-base [padding:var(--rizom-btn-md-padding)]",lg:"text-body-md md:text-body-lg [padding:var(--rizom-btn-lg-padding-mobile)] md:[padding:var(--rizom-btn-lg-padding-desktop)]"},IF2="w-full md:w-auto",jV=({href:A,variant:Q="primary",size:B="md",block:w=!1,className:$,children:I})=>DF2("a",{href:A,className:e1("rizom-btn",`rizom-btn-${Q}`,`rizom-btn-${B}`,w&&"rizom-btn-block",BF2,wF2[Q],$F2[B],w&&IF2,$),children:I},void 0,!1,void 0,this);import{jsxDEV as grw}from"preact/jsx-dev-runtime";import{jsxDEV as crw}from"preact/jsx-dev-runtime";import{Fragment as irw}from"preact";import{jsxDEV as rrw}from"preact/jsx-dev-runtime";import{jsxDEV as QJ1}from"preact/jsx-dev-runtime";var O8A=({sections:A})=>QJ1(yk,{children:QJ1("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);eA();fA();var BJ1=`/*
|
|
7308
|
+
`},void 0,!1,void 0,this),s1("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:s1("svg",{preserveAspectRatio:"none",width:"200%",height:"100%",viewBox:"0 0 1600 400",className:"block absolute inset-0 detail-wave",children:[s1("path",{d:"M0,200 C67,140 133,140 200,200 C267,260 333,260 400,200 C467,140 533,140 600,200 C667,260 733,260 800,200 C867,140 933,140 1000,200 C1067,260 1133,260 1200,200 C1267,140 1333,140 1400,200 C1467,260 1533,260 1600,200",className:"stroke-accent",strokeWidth:"2",strokeMiterlimit:"10",fill:"none",opacity:"0.15"},void 0,!1,void 0,this),s1("path",{d:"M0,230 C67,170 133,170 200,230 C267,290 333,290 400,230 C467,170 533,170 600,230 C667,290 733,290 800,230 C867,170 933,170 1000,230 C1067,290 1133,290 1200,230 C1267,170 1333,170 1400,230 C1467,290 1533,290 1600,230",className:"stroke-accent",strokeWidth:"1.5",strokeMiterlimit:"10",fill:"none",opacity:"0.06"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("div",{className:"absolute inset-0 cta-bg-pattern pointer-events-none"},void 0,!1,void 0,this),s1("div",{className:"relative z-10 max-w-5xl mx-auto w-full px-6 md:px-12 pt-12 md:pt-20 pb-16 md:pb-24",children:[s1("nav",{"aria-label":"Breadcrumb",className:"text-sm text-white/50 mb-8 hero-stagger-1",children:s1("ol",{className:"flex flex-wrap items-center gap-1",children:[s1("li",{className:"flex items-center gap-1",children:s1("a",{href:"/",className:"hover:text-white transition-colors",children:"Home"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s1("li",{className:"flex items-center gap-1",children:[s1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),s1("a",{href:$,className:"hover:text-white transition-colors",children:I},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("li",{className:"flex items-center gap-1",children:[s1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),s1("span",{className:"text-white font-medium",children:Q.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("div",{className:"mb-6 hero-stagger-1",children:s1(BI,{status:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this),s1("h1",{className:"text-5xl md:text-6xl lg:text-[7rem] font-bold text-white tracking-tighter leading-[0.95] mb-6 md:mb-8 hero-stagger-1",children:Q.name},void 0,!1,void 0,this),s1("div",{className:"w-20 h-1.5 bg-accent mb-6 md:mb-8 hero-stagger-2"},void 0,!1,void 0,this),s1("p",{className:"text-lg md:text-xl text-white/70 leading-relaxed max-w-xl hero-stagger-3",children:B.tagline},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),s1("section",{className:"bg-theme-subtle py-20 md:py-28 px-6 md:px-12",children:s1("div",{className:"max-w-4xl mx-auto space-y-16",children:[s1("div",{children:[s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:w.promise},void 0,!1,void 0,this),s1("p",{className:"text-2xl md:text-3xl lg:text-4xl leading-relaxed text-heading font-light",children:B.promise},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12 md:gap-16",children:[s1("div",{children:[s1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.role},void 0,!1,void 0,this),s1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.role},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("div",{children:[s1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.purpose},void 0,!1,void 0,this),s1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.purpose},void 0,!1,void 0,this)]},void 0,!0,void 0,this),s1("div",{children:[s1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.audience},void 0,!1,void 0,this),s1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.audience},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),s1("div",{className:"flex flex-col md:flex-row md:items-center gap-6 md:gap-12",children:[s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted whitespace-nowrap",children:w.values},void 0,!1,void 0,this),s1(jj,{tags:B.values,variant:"accent",size:"md"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("section",{className:"cta-bg-pattern bg-brand py-20 md:py-32 px-6 md:px-12",children:s1("div",{className:"container mx-auto max-w-5xl",children:[s1("h2",{className:"text-sm tracking-widest uppercase text-white/50 mb-16",children:w.features},void 0,!1,void 0,this),s1("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 md:gap-16",children:B.features.map((Y,X)=>s1("div",{children:s1("div",{className:"flex items-start gap-6",children:[s1("span",{className:"text-5xl md:text-6xl font-black text-white/10 leading-none shrink-0",children:String(X+1).padStart(2,"0")},void 0,!1,void 0,this),s1("div",{className:"pt-2",children:[s1("div",{className:"w-8 h-1 bg-accent mb-4"},void 0,!1,void 0,this),s1("h3",{className:"text-xl font-bold text-white mb-3",children:Y.title},void 0,!1,void 0,this),s1("p",{className:"text-white/70 leading-relaxed",children:Y.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Y.title,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("section",{className:"py-20 md:py-32 px-6 md:px-12",children:s1("div",{className:"max-w-3xl mx-auto",children:[s1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-12",children:w.story},void 0,!1,void 0,this),s1("div",{className:"space-y-6",children:D.map((Y,X)=>s1("p",{className:X===0?"text-2xl md:text-3xl leading-relaxed text-heading font-light":"text-lg leading-relaxed text-theme-muted",children:Y},X,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),s1("section",{className:"cta-bg-pattern bg-brand-dark pt-24 md:pt-32 pb-40 md:pb-48 -mb-[60px] px-6 md:px-12",children:s1("div",{className:"max-w-4xl mx-auto",children:[s1("p",{className:"text-sm tracking-widest uppercase text-white/60 mb-4",children:Q.name},void 0,!1,void 0,this),s1("h2",{className:"text-3xl md:text-5xl font-bold text-white max-w-2xl mb-4",children:B.tagline},void 0,!1,void 0,this),s1("p",{className:"text-lg text-white/60 mb-10 max-w-xl",children:B.promise},void 0,!1,void 0,this),s1(o5,{href:$,variant:"outline-light",size:"lg",children:I},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};fA();var YyA=f.object({route:f.string().default("/products")});var AJ1={name:"@brains/products",private:!0,version:"0.2.0-alpha.93",description:"Product entity management and overview page for marketing showcase",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var af2=f.object({overview:Vp,products:f.array(q8A)}),tf2=f.object({product:q8A});class XyA extends V2{entityType=L8A.entityType;schema=kk;adapter=L8A;constructor(A={}){super("products",AJ1,A,YyA)}getTemplates(){return{"product-list":R1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:af2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:tU1}}),"product-detail":R1({name:"product-detail",description:"Individual product detail page",schema:tf2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:eU1}})}}getDataSources(){return[new V8A(this.logger.child("ProductsDataSource"))]}async onRegister(A){A.entities.register("products-overview",vk,DyA)}}function WyA(A={}){return new XyA(A)}import{join as VF2}from"path";import{jsxDEV as M8A,Fragment as ef2}from"preact/jsx-dev-runtime";var yk=({children:A})=>M8A(ef2,{children:[M8A("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:M8A("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),M8A("div",{className:"max-w-[1440px] mx-auto relative overflow-x-clip",children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this);import{jsxDEV as qrw}from"preact/jsx-dev-runtime";import{jsxDEV as QF2}from"preact/jsx-dev-runtime";var C8A="px-6 md:px-10 xl:px-20",AF2=`${C8A} relative z-[1]`,LN=({id:A,className:Q,children:B})=>QF2("section",{id:A,className:e1(AF2,Q),children:B},void 0,!1,void 0,this);import{jsxDEV as brw}from"preact/jsx-dev-runtime";import{jsxDEV as krw}from"preact/jsx-dev-runtime";import{jsxDEV as DF2}from"preact/jsx-dev-runtime";var BF2="inline-flex items-center justify-center cursor-pointer border border-solid transition-all [gap:var(--rizom-btn-gap)] [border-radius:var(--rizom-btn-radius)] [font-family:var(--rizom-btn-font-family)] [font-style:var(--rizom-btn-font-style)] [letter-spacing:var(--rizom-btn-letter-spacing)] [text-transform:var(--rizom-btn-text-transform)]",wF2={primary:"[font-weight:var(--rizom-btn-primary-font-weight)] [color:var(--rizom-btn-primary-color)] [background:var(--rizom-btn-primary-bg)] [border-color:var(--rizom-btn-primary-border-color)] [border-width:var(--rizom-btn-primary-border-width)] [box-shadow:var(--rizom-btn-primary-shadow)] hover:[color:var(--rizom-btn-primary-hover-color)] hover:[background:var(--rizom-btn-primary-hover-bg)] hover:[border-color:var(--rizom-btn-primary-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-hover-shadow)] hover:[transform:var(--rizom-btn-primary-hover-transform)]","primary-strong":"duration-400 ease-[cubic-bezier(0.2,0.8,0.2,1)] [font-weight:var(--rizom-btn-primary-strong-font-weight)] [color:var(--rizom-btn-primary-strong-color)] [background:var(--rizom-btn-primary-strong-bg)] [border-color:var(--rizom-btn-primary-strong-border-color)] [border-width:var(--rizom-btn-primary-strong-border-width)] [box-shadow:var(--rizom-btn-primary-strong-shadow)] hover:[color:var(--rizom-btn-primary-strong-hover-color)] hover:[background:var(--rizom-btn-primary-strong-hover-bg)] hover:[border-color:var(--rizom-btn-primary-strong-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-strong-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-strong-hover-shadow)] hover:[transform:var(--rizom-btn-primary-strong-hover-transform)]",secondary:"[font-weight:var(--rizom-btn-secondary-font-weight)] [color:var(--rizom-btn-secondary-color)] [background:var(--rizom-btn-secondary-bg)] [border-color:var(--rizom-btn-secondary-border-color)] [border-width:var(--rizom-btn-secondary-border-width)] [box-shadow:var(--rizom-btn-secondary-shadow)] hover:[color:var(--rizom-btn-secondary-hover-color)] hover:[background:var(--rizom-btn-secondary-hover-bg)] hover:[border-color:var(--rizom-btn-secondary-hover-border-color)] hover:[border-width:var(--rizom-btn-secondary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-secondary-hover-shadow)] hover:[transform:var(--rizom-btn-secondary-hover-transform)]"},$F2={md:"text-base [padding:var(--rizom-btn-md-padding)]",lg:"text-body-md md:text-body-lg [padding:var(--rizom-btn-lg-padding-mobile)] md:[padding:var(--rizom-btn-lg-padding-desktop)]"},IF2="w-full md:w-auto",jV=({href:A,variant:Q="primary",size:B="md",block:w=!1,className:$,children:I})=>DF2("a",{href:A,className:e1("rizom-btn",`rizom-btn-${Q}`,`rizom-btn-${B}`,w&&"rizom-btn-block",BF2,wF2[Q],$F2[B],w&&IF2,$),children:I},void 0,!1,void 0,this);import{jsxDEV as grw}from"preact/jsx-dev-runtime";import{jsxDEV as crw}from"preact/jsx-dev-runtime";import{Fragment as irw}from"preact";import{jsxDEV as rrw}from"preact/jsx-dev-runtime";import{jsxDEV as QJ1}from"preact/jsx-dev-runtime";var O8A=({sections:A})=>QJ1(yk,{children:QJ1("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);eA();fA();var BJ1=`/*
|
|
7297
7309
|
* Shared globals + helpers used by tree / constellation / roots canvas
|
|
7298
7310
|
* scripts. Loaded as a shared static asset by the Rizom runtime package
|
|
7299
7311
|
* so the variant canvases
|
|
@@ -9779,7 +9791,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});fA();var T
|
|
|
9779
9791
|
`).map((Q)=>Q.trim()).find((Q)=>Q.length>0&&!Q.startsWith("#"))??""}var BZ2=5,wZ2=4,gJ1=[R6,jD,aY];class h8A{context;constructor(A){this.context=A}async retrieve(A){let Q=A.query?.trim()??"",B=Math.max(1,A.limit??BZ2),w=await this.resolveSpaceId(A),D=(await this.loadCandidates(Q,B)).filter((Y)=>{if(!w||A.includeOtherSpaces)return!0;return this.getEntitySpaceId(Y.entity)===w}).filter((Y)=>this.matchesIdentity(Y.entity,A)).sort((Y,X)=>{let W=w?this.getEntitySpaceId(Y.entity)===w:!1,U=w?this.getEntitySpaceId(X.entity)===w:!1;if(W!==U)return W?-1:1;if(X.score!==Y.score)return X.score-Y.score;return Date.parse(X.entity.updated)-Date.parse(Y.entity.updated)}).slice(0,B).map((Y)=>this.toMemory(Y));return{query:Q,...w?{spaceId:w}:{},results:D}}async resolveSpaceId(A){if(A.interfaceType&&A.channelId)return IH({interfaceType:A.interfaceType,channelId:A.channelId});if(!A.conversationId)return;let Q=await this.context.conversations.get(A.conversationId);return Q?IH(Q):void 0}async loadCandidates(A,Q){let B=Q*wZ2;if(A.length>0)return(await this.context.entityService.search({query:A,options:{types:gJ1,limit:B}})).map((I)=>({entity:I.entity,score:I.score,excerpt:I.excerpt}));return(await Promise.all(gJ1.map(($)=>this.context.entityService.listEntities({entityType:$,options:{limit:B,sortFields:[{field:"updated",direction:"desc"}]}})))).flat().map(($)=>({entity:$,score:0,excerpt:jp($)}))}toMemory(A){let{entity:Q}=A,B=Q.metadata;return{id:Q.id,entityType:Q.entityType,conversationId:B.conversationId,spaceId:this.getEntitySpaceId(Q),channelId:B.channelId,...B.channelName?{channelName:B.channelName}:{},interfaceType:B.interfaceType,updated:Q.updated,score:A.score,excerpt:A.excerpt||jp(Q),...Q.entityType===R6?{messageCount:Q.metadata.messageCount,entryCount:Q.metadata.entryCount}:{status:Q.metadata.status}}}matchesIdentity(A,Q){if(!Q.actorId&&!Q.canonicalId)return!0;return this.getIdentityReferences(A).some((B)=>{if(Q.canonicalId&&B.canonicalId===Q.canonicalId)return!0;if(!Q.actorId)return!1;return B.actorId===Q.actorId||B.sourceActorIds?.includes(Q.actorId)===!0})}getIdentityReferences(A){if(this.isSummaryEntity(A))return A.metadata.participants??[];if(this.isDecisionEntity(A))return[...A.metadata.decidedBy??[],...A.metadata.mentionedBy??[]];return[...A.metadata.assignedTo??[],...A.metadata.requestedBy??[]]}isSummaryEntity(A){return A.entityType===R6}isDecisionEntity(A){return A.entityType===jD}getEntitySpaceId(A){let Q=A.metadata;if("spaceId"in Q&&typeof Q.spaceId==="string")return Q.spaceId;return IH(Q)}}var qyA=f.object({role:f.enum(["user","assistant","system"]),content:f.string(),timestamp:f.string().datetime().optional(),actor:SC.optional(),source:gC.optional()}),$Z2=f.object({conversationId:f.string().default("eval-conversation"),messages:f.array(qyA)}),IZ2=f.object({conversationId:f.string()}),DZ2=f.object({conversationId:f.string().default("eval-conversation"),interfaceType:f.string().default("eval"),channelId:f.string().default("eval-channel"),channelName:f.string().optional(),projectionDecision:f.enum(["update","append"]).default("update"),existingSummary:f.string().optional(),existingMessageCount:f.number().int().min(0).default(0),messages:f.array(qyA)}),m8A=f.object({actorId:f.string(),canonicalId:f.string().optional(),displayName:f.string().optional()}),YZ2=m8A.extend({roles:f.array(f.enum(["user","assistant","system"])).default(["user"]),sourceActorIds:f.array(f.string()).optional()}),XZ2=f.object({actorId:f.string().optional(),canonicalId:f.string().optional(),displayName:f.string()}),WZ2=f.object({id:f.string(),entityType:f.enum(["summary","decision","action-item"]),content:f.string(),excerpt:f.string().optional(),score:f.number().optional(),conversationId:f.string(),interfaceType:f.string(),channelId:f.string(),channelName:f.string().optional(),updated:f.string().datetime().optional(),visibility:y9,status:f.string().optional(),participants:f.array(YZ2).optional(),decidedBy:f.array(m8A).optional(),mentionedBy:f.array(m8A).optional(),assignedTo:f.array(XZ2).optional(),requestedBy:f.array(m8A).optional()}),HZ2=f.object({query:f.string().optional(),conversationId:f.string().optional(),interfaceType:f.string().optional(),channelId:f.string().optional(),limit:f.number().int().min(1).optional(),includeOtherSpaces:f.boolean().optional(),actorId:f.string().optional(),canonicalId:f.string().optional(),memory:f.array(WZ2).optional()}),UZ2=f.object({conversationId:f.string().default("eval-conversation"),existingSummary:f.string().optional(),existingMessageCount:f.number().int().min(0).default(0),messages:f.array(qyA)});function mJ1(A){let{context:Q,logger:B,config:w}=A;Q.eval.registerHandler("summarizeMessages",async($)=>{let I=$Z2.parse($),D=NyA(I.messages,I.conversationId),X=await new uk(Q,B,w).extract(D);return X.entries.map((W)=>{let U=X.decisions.filter((F)=>F.timeRange.start>=W.timeRange.start).filter((F)=>F.timeRange.end<=W.timeRange.end).map((F)=>F.text),K=X.actionItems.filter((F)=>F.timeRange.start>=W.timeRange.start).filter((F)=>F.timeRange.end<=W.timeRange.end).map((F)=>F.text);return{...W,decisions:U,actionItems:K,keyPointsText:W.keyPoints.join(`
|
|
9780
9792
|
`),decisionsText:U.join(`
|
|
9781
9793
|
`),actionItemsText:K.join(`
|
|
9782
|
-
`)}})}),Q.eval.registerHandler("decideProjection",async($)=>{let I=UZ2.parse($),D=NyA(I.messages,I.conversationId),Y=I.existingSummary?hJ1({conversationId:I.conversationId,content:I.existingSummary,messageCount:I.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null;return new VN(Q,B,w).decideProjection(D,Y)}),Q.eval.registerHandler("retrieveMemory",async($)=>{let I=HZ2.parse($),D=I.memory?KZ2(Q,I.memory):Q;return new h8A(D).retrieve(I)}),Q.eval.registerHandler("projectMessages",async($)=>{let I=DZ2.parse($),D=NyA(I.messages,I.conversationId),Y=JZ2({conversationId:I.conversationId,interfaceType:I.interfaceType,channelId:I.channelId,channelName:I.channelName,messages:D}),X=I.existingSummary?hJ1({conversationId:I.conversationId,content:I.existingSummary,messageCount:I.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null,W=[],U=[],K=GZ2({context:Q,conversation:Y,messages:D,existing:X,upserted:W,deleted:U,projectionDecision:I.projectionDecision});return{result:await new VN(K,B,w).projectConversation(I.conversationId),summaries:W.filter((q)=>q.entityType==="summary"),decisions:W.filter((q)=>q.entityType==="decision"),actionItems:W.filter((q)=>q.entityType==="action-item"),deleted:U}}),Q.eval.registerHandler("projectConversation",async($)=>{let I=IZ2.parse($);return new VN(Q,B,w).projectConversation(I.conversationId)})}function hJ1(A){return{id:A.conversationId,entityType:"summary",content:A.content,contentHash:"eval-existing-summary",visibility:A.visibility,created:"2026-01-01T00:00:00.000Z",updated:"2026-01-01T00:00:00.000Z",metadata:{conversationId:A.conversationId,channelId:"eval-channel",interfaceType:"eval",messageCount:A.messageCount,entryCount:1,sourceHash:"eval-source-hash",projectionVersion:A.projectionVersion}}}function NyA(A,Q){return A.map((B,w)=>{let $=B.timestamp??new Date(Date.UTC(2026,0,1,0,w)).toISOString();return{id:`eval-message-${w+1}`,conversationId:Q,role:B.role,content:B.content,timestamp:$,metadata:{...B.actor?{actor:B.actor}:{},...B.source?{source:B.source}:{}}}})}function JZ2(A){let Q=A.messages[0],B=A.messages[A.messages.length-1],w=Q?.timestamp??"2026-01-01T00:00:00.000Z",$=B?.timestamp??w;return{id:A.conversationId,sessionId:A.conversationId,interfaceType:A.interfaceType,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},startedAt:w,lastActiveAt:$,createdAt:w,updatedAt:$,metadata:{}}}function GZ2(A){let Q=IH(A.conversation);return{...A.context,spaces:[Q],conversations:{...A.context.conversations,get:async()=>A.conversation,getMessages:async()=>A.messages},ai:{...A.context.ai,generateObject:async()=>({object:{decision:A.projectionDecision,rationale:"Forced by eval input"}})},entityService:{...A.context.entityService,getEntity:async({entityType:B})=>B==="summary"?A.existing:null,listEntities:async()=>[],deleteEntity:async(B)=>{return A.deleted.push(B),!0},upsertEntity:async({entity:B})=>{return A.upserted.push(B),{entityId:B.id,jobId:"eval-upsert",created:!0,skipped:!1}}}}}function KZ2(A,Q){let B=Q.map(fZ2),w=B.map(($,I)=>({entity:$,score:Q[I]?.score??1,excerpt:Q[I]?.excerpt??jp($)}));return{...A,entityService:{...A.entityService,search:async()=>w,listEntities:async({entityType:$})=>B.filter((I)=>I.entityType===$)}}}function fZ2(A){if(A.entityType==="summary")return FZ2(A);if(A.entityType==="decision")return ZZ2(A);return zZ2(A)}function LyA(A){let Q=A.updated??"2026-01-01T00:00:00.000Z";return{id:A.id,content:A.content,contentHash:RB(A.content),visibility:A.visibility,created:Q,updated:Q}}function FZ2(A){return{...LyA(A),entityType:"summary",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,messageCount:3,entryCount:1,sourceHash:`source-${A.id}`,projectionVersion:1,...A.participants?{participants:A.participants}:{}}}}function ZZ2(A){return{...LyA(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:IH(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:A.status==="superseded"?"superseded":"active",...A.decidedBy?{decidedBy:A.decidedBy}:{},...A.mentionedBy?{mentionedBy:A.mentionedBy}:{}}}}function zZ2(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...LyA(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:IH(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:Q,...A.assignedTo?{assignedTo:A.assignedTo}:{},...A.requestedBy?{requestedBy:A.requestedBy}:{}}}}var uJ1={name:"@brains/conversation-memory",private:!0,version:"0.2.0-alpha.92",description:"Plugin for deriving durable conversation memory",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts,.tsx",eval:"cd evals && bun run brain-eval","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/conversation-service":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};var qZ2=new VJ,LZ2=new gk,EZ2=new hk,VZ2=f.object({conversationId:f.string()});class EyA extends V2{entityType=R6;schema=Cp;adapter=qZ2;constructor(A={}){super(b8A,uJ1,A,GyA)}getConfig(){return this.config}getTemplates(){return{"summary-list":ZJ1,"summary-detail":zJ1,"ai-response":NJ1}}getDataSources(){return[new zyA(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:R6,job:{type:HJ1,handler:new x8A(A,this.logger,this.config)},initialSync:{shouldEnqueue:async()=>A.spaces.length>0&&!await r3(A,R6,{outputVisibility:this.config.memoryVisibility}),jobData:{mode:"rebuild-all",reason:"initial-sync"},jobOptions:{source:JyA,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:b8A}}},sourceChange:{sourceKind:Xr,sourceTypes:[Xr],shouldEnqueue:(Q)=>this.shouldEnqueueConversationProjection(A,Q),events:[fx],jobData:(Q)=>{let{conversationId:B}=this.parseConversationMessagePayload(Q);return{mode:"conversation",conversationId:B,reason:"message-added"}},jobOptions:(Q)=>{let{conversationId:B}=this.parseConversationMessagePayload(Q);return{priority:5,delayMs:this.config.projectionDelayMs,source:JyA,deduplication:"skip",deduplicationKey:`conversation-memory:${B}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${B}`,pluginId:b8A}}}}}]}parseConversationMessagePayload(A){return VZ2.parse(A)}async shouldEnqueueConversationProjection(A,Q){let{conversationId:B}=this.parseConversationMessagePayload(Q),w=await A.conversations.get(B);if(!w)return!1;return vV({conversation:w,spaces:A.spaces}).eligible}async onRegister(A){A.entities.register(jD,Op,LZ2),A.entities.register(aY,Rp,EZ2),EJ1({context:A,pluginId:this.id}),MJ1({context:A,pluginId:this.id}),xJ1({context:A,pluginId:this.id}),SJ1({context:A,pluginId:this.id,config:this.config}),mJ1({context:A,logger:this.logger,config:this.config})}}function VyA(A){return new EyA(A)}eA();fA();eA();var bf=f.object({title:f.string(),section:f.string(),order:f.number().int(),sourcePath:f.string(),description:f.string().optional(),slug:f.string().optional()}),cJ1=bf.pick({title:!0,section:!0,order:!0,description:!0}).extend({slug:f.string()}),lk=a1.extend({entityType:f.literal("doc"),metadata:cJ1}),Pf=lk.extend({frontmatter:bf,body:f.string()});eA();fA();class MyA extends zQ{constructor(){super({entityType:"doc",schema:lk,frontmatterSchema:bf})}toMarkdown(A){let Q=this.extractBody(A.content),B=this.parseFrontMatter(A.content,bf);return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,bf),B=Q.slug??XQ(Q.title);return{content:A,entityType:"doc",metadata:{title:Q.title,section:Q.section,order:Q.order,slug:B,...Q.description?{description:Q.description}:{}}}}}var u8A=new MyA;eA();function pJ1(A){return[...A].sort((Q,B)=>{let w=Q.metadata.order-B.metadata.order;if(w!==0)return w;return Q.metadata.title.localeCompare(B.metadata.title)})}function lJ1(A){let Q=$2(A.content,bf);return Pf.parse({...A,frontmatter:Q.metadata,body:Q.content})}class c8A extends f5{id="docs:entities";name="Docs Entity DataSource";description="Fetches and transforms doc entities for rendering";config={entityType:"doc",defaultSort:[{field:"order",direction:"asc"},{field:"section",direction:"asc"},{field:"title",direction:"asc"}],defaultLimit:100,enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return lJ1(A)}async fetch(A,Q,B){let w=this.parseQuery(A);if(!w.query.id){let U=await this.fetchList({...w.query,limit:1000,page:void 0,pageSize:void 0},B.entityService);return Q.parse(this.buildListResult(U.items,null,w.query))}let[$,I]=await Promise.all([this.fetchDetail(w.query.id,B.entityService),this.fetchList({limit:1000},B.entityService)]),D=pJ1(I.items),Y=D.findIndex((U)=>U.id===$.item.id),X=Y>0?D[Y-1]:null,W=Y>=0&&Y<D.length-1?D[Y+1]:null;return Q.parse({doc:$.item,docs:D,prevDoc:X,nextDoc:W})}buildDetailResult(A,Q){return{doc:A,docs:[A],prevDoc:Q?.prev??null,nextDoc:Q?.next??null}}buildListResult(A,Q,B){return{docs:pJ1(A),pagination:Q,baseUrl:B.baseUrl}}}eA();nw();fA();import{jsxDEV as k5}from"preact/jsx-dev-runtime";var MZ2=["I","II","III","IV","V","VI","VII","VIII","IX","X"];function kp(A){return[...A].sort((Q,B)=>{let w=Q.metadata.order-B.metadata.order;if(w!==0)return w;return Q.metadata.title.localeCompare(B.metadata.title)})}function p8A(A){let Q=new Map;for(let B of kp(A)){let w=B.metadata.section;Q.set(w,[...Q.get(w)??[],B])}return[...Q.entries()].map(([B,w])=>({section:B,docs:w}))}function ik(A){return`/docs/${A.metadata.slug}`}function l8A(A){return`section-${A+1}`}function dk(A){return MZ2[A]??String(A+1)}var rJ1="text-[var(--docs-text)] font-bold",nJ1="text-[var(--docs-accent)] font-bold",oJ1="text-[var(--docs-text-muted)]",CZ2="docs-font-label text-xs uppercase tracking-[0.18em] text-[var(--docs-accent)]",OZ2="docs-font-display text-[var(--docs-heading)]",iJ1="inline-flex items-center justify-center rounded-lg border px-[18px] py-2.5 text-sm font-semibold transition-colors duration-150",dJ1="relative hidden py-1 text-[15px] text-[var(--docs-text-muted)] transition-colors duration-150 after:absolute after:bottom-0 after:left-0 after:h-px after:w-0 after:bg-[var(--docs-accent)] after:transition-[width] after:duration-300 hover:text-[var(--docs-text)] hover:after:w-full min-[861px]:inline-block",CyA="docs-font-label text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:text-[var(--docs-text)]",MJ={wrap:"mx-auto max-w-6xl px-6 pt-20 md:px-12 md:pt-24",label:CZ2,display:OZ2,button:`${iJ1} border-[var(--docs-text)] text-[var(--docs-text)] hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)]`,primaryButton:`${iJ1} border-[var(--docs-accent)] bg-[var(--docs-accent)] text-white hover:bg-transparent hover:text-[var(--docs-accent)]`},sJ1=()=>k5("nav",{className:"docs-header fixed inset-x-0 top-0 z-[100] flex items-center justify-between px-6 py-4 md:px-10 md:py-5 xl:px-20",children:[k5("a",{href:"/docs",className:"docs-font-body text-xl font-bold","aria-label":"Brains docs",children:[k5("span",{className:rJ1,children:"brains"},void 0,!1,void 0,this),k5("span",{className:nJ1,children:"."},void 0,!1,void 0,this),k5("span",{className:oJ1,children:"docs"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k5("div",{className:"docs-header__nav flex items-center gap-4 md:gap-8",children:[k5("a",{className:dJ1,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),k5("a",{className:dJ1,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),k5("a",{href:"https://rizom.ai",className:"inline-flex items-center justify-center rounded-lg border border-[var(--docs-text)] px-4 py-2 text-[13px] font-semibold text-[var(--docs-text)] transition-colors duration-150 hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)] md:px-6 md:py-2.5 md:text-[15px]",children:"Get Brains"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),aJ1=()=>k5("footer",{className:"flex flex-col items-center justify-between gap-4 border-t border-[var(--docs-border-light)] py-8 text-center md:flex-row md:gap-6 md:py-6 md:text-left",children:[k5("a",{href:"https://rizom.ai",className:"docs-font-body text-[15px] font-bold",children:[k5("span",{className:rJ1,children:"rizom"},void 0,!1,void 0,this),k5("span",{className:nJ1,children:"."},void 0,!1,void 0,this),k5("span",{className:oJ1,children:"ai"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k5("div",{className:"flex flex-wrap items-center justify-center gap-6 md:justify-end",children:[k5("a",{className:CyA,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),k5("a",{className:CyA,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),k5("a",{className:CyA,href:"https://rizom.ai",children:"Rizom"},void 0,!1,void 0,this),k5("button",{id:"themeToggle",className:"docs-font-label cursor-pointer rounded-md border border-[var(--docs-text-light)] bg-transparent px-2.5 py-1.5 text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:border-[var(--docs-text)] hover:text-[var(--docs-text)]",type:"button",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),RZ2=`
|
|
9794
|
+
`)}})}),Q.eval.registerHandler("decideProjection",async($)=>{let I=UZ2.parse($),D=NyA(I.messages,I.conversationId),Y=I.existingSummary?hJ1({conversationId:I.conversationId,content:I.existingSummary,messageCount:I.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null;return new VN(Q,B,w).decideProjection(D,Y)}),Q.eval.registerHandler("retrieveMemory",async($)=>{let I=HZ2.parse($),D=I.memory?KZ2(Q,I.memory):Q;return new h8A(D).retrieve(I)}),Q.eval.registerHandler("projectMessages",async($)=>{let I=DZ2.parse($),D=NyA(I.messages,I.conversationId),Y=JZ2({conversationId:I.conversationId,interfaceType:I.interfaceType,channelId:I.channelId,channelName:I.channelName,messages:D}),X=I.existingSummary?hJ1({conversationId:I.conversationId,content:I.existingSummary,messageCount:I.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null,W=[],U=[],K=GZ2({context:Q,conversation:Y,messages:D,existing:X,upserted:W,deleted:U,projectionDecision:I.projectionDecision});return{result:await new VN(K,B,w).projectConversation(I.conversationId),summaries:W.filter((q)=>q.entityType==="summary"),decisions:W.filter((q)=>q.entityType==="decision"),actionItems:W.filter((q)=>q.entityType==="action-item"),deleted:U}}),Q.eval.registerHandler("projectConversation",async($)=>{let I=IZ2.parse($);return new VN(Q,B,w).projectConversation(I.conversationId)})}function hJ1(A){return{id:A.conversationId,entityType:"summary",content:A.content,contentHash:"eval-existing-summary",visibility:A.visibility,created:"2026-01-01T00:00:00.000Z",updated:"2026-01-01T00:00:00.000Z",metadata:{conversationId:A.conversationId,channelId:"eval-channel",interfaceType:"eval",messageCount:A.messageCount,entryCount:1,sourceHash:"eval-source-hash",projectionVersion:A.projectionVersion}}}function NyA(A,Q){return A.map((B,w)=>{let $=B.timestamp??new Date(Date.UTC(2026,0,1,0,w)).toISOString();return{id:`eval-message-${w+1}`,conversationId:Q,role:B.role,content:B.content,timestamp:$,metadata:{...B.actor?{actor:B.actor}:{},...B.source?{source:B.source}:{}}}})}function JZ2(A){let Q=A.messages[0],B=A.messages[A.messages.length-1],w=Q?.timestamp??"2026-01-01T00:00:00.000Z",$=B?.timestamp??w;return{id:A.conversationId,sessionId:A.conversationId,interfaceType:A.interfaceType,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},startedAt:w,lastActiveAt:$,createdAt:w,updatedAt:$,metadata:{}}}function GZ2(A){let Q=IH(A.conversation);return{...A.context,spaces:[Q],conversations:{...A.context.conversations,get:async()=>A.conversation,getMessages:async()=>A.messages},ai:{...A.context.ai,generateObject:async()=>({object:{decision:A.projectionDecision,rationale:"Forced by eval input"}})},entityService:{...A.context.entityService,getEntity:async({entityType:B})=>B==="summary"?A.existing:null,listEntities:async()=>[],deleteEntity:async(B)=>{return A.deleted.push(B),!0},upsertEntity:async({entity:B})=>{return A.upserted.push(B),{entityId:B.id,jobId:"eval-upsert",created:!0,skipped:!1}}}}}function KZ2(A,Q){let B=Q.map(fZ2),w=B.map(($,I)=>({entity:$,score:Q[I]?.score??1,excerpt:Q[I]?.excerpt??jp($)}));return{...A,entityService:{...A.entityService,search:async()=>w,listEntities:async({entityType:$})=>B.filter((I)=>I.entityType===$)}}}function fZ2(A){if(A.entityType==="summary")return FZ2(A);if(A.entityType==="decision")return ZZ2(A);return zZ2(A)}function LyA(A){let Q=A.updated??"2026-01-01T00:00:00.000Z";return{id:A.id,content:A.content,contentHash:RB(A.content),visibility:A.visibility,created:Q,updated:Q}}function FZ2(A){return{...LyA(A),entityType:"summary",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,messageCount:3,entryCount:1,sourceHash:`source-${A.id}`,projectionVersion:1,...A.participants?{participants:A.participants}:{}}}}function ZZ2(A){return{...LyA(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:IH(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:A.status==="superseded"?"superseded":"active",...A.decidedBy?{decidedBy:A.decidedBy}:{},...A.mentionedBy?{mentionedBy:A.mentionedBy}:{}}}}function zZ2(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...LyA(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:IH(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:Q,...A.assignedTo?{assignedTo:A.assignedTo}:{},...A.requestedBy?{requestedBy:A.requestedBy}:{}}}}var uJ1={name:"@brains/conversation-memory",private:!0,version:"0.2.0-alpha.93",description:"Plugin for deriving durable conversation memory",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts,.tsx",eval:"cd evals && bun run brain-eval","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/conversation-service":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};var qZ2=new VJ,LZ2=new gk,EZ2=new hk,VZ2=f.object({conversationId:f.string()});class EyA extends V2{entityType=R6;schema=Cp;adapter=qZ2;constructor(A={}){super(b8A,uJ1,A,GyA)}getConfig(){return this.config}getTemplates(){return{"summary-list":ZJ1,"summary-detail":zJ1,"ai-response":NJ1}}getDataSources(){return[new zyA(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:R6,job:{type:HJ1,handler:new x8A(A,this.logger,this.config)},initialSync:{shouldEnqueue:async()=>A.spaces.length>0&&!await r3(A,R6,{outputVisibility:this.config.memoryVisibility}),jobData:{mode:"rebuild-all",reason:"initial-sync"},jobOptions:{source:JyA,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:b8A}}},sourceChange:{sourceKind:Xr,sourceTypes:[Xr],shouldEnqueue:(Q)=>this.shouldEnqueueConversationProjection(A,Q),events:[fx],jobData:(Q)=>{let{conversationId:B}=this.parseConversationMessagePayload(Q);return{mode:"conversation",conversationId:B,reason:"message-added"}},jobOptions:(Q)=>{let{conversationId:B}=this.parseConversationMessagePayload(Q);return{priority:5,delayMs:this.config.projectionDelayMs,source:JyA,deduplication:"skip",deduplicationKey:`conversation-memory:${B}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${B}`,pluginId:b8A}}}}}]}parseConversationMessagePayload(A){return VZ2.parse(A)}async shouldEnqueueConversationProjection(A,Q){let{conversationId:B}=this.parseConversationMessagePayload(Q),w=await A.conversations.get(B);if(!w)return!1;return vV({conversation:w,spaces:A.spaces}).eligible}async onRegister(A){A.entities.register(jD,Op,LZ2),A.entities.register(aY,Rp,EZ2),EJ1({context:A,pluginId:this.id}),MJ1({context:A,pluginId:this.id}),xJ1({context:A,pluginId:this.id}),SJ1({context:A,pluginId:this.id,config:this.config}),mJ1({context:A,logger:this.logger,config:this.config})}}function VyA(A){return new EyA(A)}eA();fA();eA();var bf=f.object({title:f.string(),section:f.string(),order:f.number().int(),sourcePath:f.string(),description:f.string().optional(),slug:f.string().optional()}),cJ1=bf.pick({title:!0,section:!0,order:!0,description:!0}).extend({slug:f.string()}),lk=a1.extend({entityType:f.literal("doc"),metadata:cJ1}),Pf=lk.extend({frontmatter:bf,body:f.string()});eA();fA();class MyA extends zQ{constructor(){super({entityType:"doc",schema:lk,frontmatterSchema:bf})}toMarkdown(A){let Q=this.extractBody(A.content),B=this.parseFrontMatter(A.content,bf);return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,bf),B=Q.slug??XQ(Q.title);return{content:A,entityType:"doc",metadata:{title:Q.title,section:Q.section,order:Q.order,slug:B,...Q.description?{description:Q.description}:{}}}}}var u8A=new MyA;eA();function pJ1(A){return[...A].sort((Q,B)=>{let w=Q.metadata.order-B.metadata.order;if(w!==0)return w;return Q.metadata.title.localeCompare(B.metadata.title)})}function lJ1(A){let Q=$2(A.content,bf);return Pf.parse({...A,frontmatter:Q.metadata,body:Q.content})}class c8A extends f5{id="docs:entities";name="Docs Entity DataSource";description="Fetches and transforms doc entities for rendering";config={entityType:"doc",defaultSort:[{field:"order",direction:"asc"},{field:"section",direction:"asc"},{field:"title",direction:"asc"}],defaultLimit:100,enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return lJ1(A)}async fetch(A,Q,B){let w=this.parseQuery(A);if(!w.query.id){let U=await this.fetchList({...w.query,limit:1000,page:void 0,pageSize:void 0},B.entityService);return Q.parse(this.buildListResult(U.items,null,w.query))}let[$,I]=await Promise.all([this.fetchDetail(w.query.id,B.entityService),this.fetchList({limit:1000},B.entityService)]),D=pJ1(I.items),Y=D.findIndex((U)=>U.id===$.item.id),X=Y>0?D[Y-1]:null,W=Y>=0&&Y<D.length-1?D[Y+1]:null;return Q.parse({doc:$.item,docs:D,prevDoc:X,nextDoc:W})}buildDetailResult(A,Q){return{doc:A,docs:[A],prevDoc:Q?.prev??null,nextDoc:Q?.next??null}}buildListResult(A,Q,B){return{docs:pJ1(A),pagination:Q,baseUrl:B.baseUrl}}}eA();nw();fA();import{jsxDEV as k5}from"preact/jsx-dev-runtime";var MZ2=["I","II","III","IV","V","VI","VII","VIII","IX","X"];function kp(A){return[...A].sort((Q,B)=>{let w=Q.metadata.order-B.metadata.order;if(w!==0)return w;return Q.metadata.title.localeCompare(B.metadata.title)})}function p8A(A){let Q=new Map;for(let B of kp(A)){let w=B.metadata.section;Q.set(w,[...Q.get(w)??[],B])}return[...Q.entries()].map(([B,w])=>({section:B,docs:w}))}function ik(A){return`/docs/${A.metadata.slug}`}function l8A(A){return`section-${A+1}`}function dk(A){return MZ2[A]??String(A+1)}var rJ1="text-[var(--docs-text)] font-bold",nJ1="text-[var(--docs-accent)] font-bold",oJ1="text-[var(--docs-text-muted)]",CZ2="docs-font-label text-xs uppercase tracking-[0.18em] text-[var(--docs-accent)]",OZ2="docs-font-display text-[var(--docs-heading)]",iJ1="inline-flex items-center justify-center rounded-lg border px-[18px] py-2.5 text-sm font-semibold transition-colors duration-150",dJ1="relative hidden py-1 text-[15px] text-[var(--docs-text-muted)] transition-colors duration-150 after:absolute after:bottom-0 after:left-0 after:h-px after:w-0 after:bg-[var(--docs-accent)] after:transition-[width] after:duration-300 hover:text-[var(--docs-text)] hover:after:w-full min-[861px]:inline-block",CyA="docs-font-label text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:text-[var(--docs-text)]",MJ={wrap:"mx-auto max-w-6xl px-6 pt-20 md:px-12 md:pt-24",label:CZ2,display:OZ2,button:`${iJ1} border-[var(--docs-text)] text-[var(--docs-text)] hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)]`,primaryButton:`${iJ1} border-[var(--docs-accent)] bg-[var(--docs-accent)] text-white hover:bg-transparent hover:text-[var(--docs-accent)]`},sJ1=()=>k5("nav",{className:"docs-header fixed inset-x-0 top-0 z-[100] flex items-center justify-between px-6 py-4 md:px-10 md:py-5 xl:px-20",children:[k5("a",{href:"/docs",className:"docs-font-body text-xl font-bold","aria-label":"Brains docs",children:[k5("span",{className:rJ1,children:"brains"},void 0,!1,void 0,this),k5("span",{className:nJ1,children:"."},void 0,!1,void 0,this),k5("span",{className:oJ1,children:"docs"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k5("div",{className:"docs-header__nav flex items-center gap-4 md:gap-8",children:[k5("a",{className:dJ1,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),k5("a",{className:dJ1,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),k5("a",{href:"https://rizom.ai",className:"inline-flex items-center justify-center rounded-lg border border-[var(--docs-text)] px-4 py-2 text-[13px] font-semibold text-[var(--docs-text)] transition-colors duration-150 hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)] md:px-6 md:py-2.5 md:text-[15px]",children:"Get Brains"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),aJ1=()=>k5("footer",{className:"flex flex-col items-center justify-between gap-4 border-t border-[var(--docs-border-light)] py-8 text-center md:flex-row md:gap-6 md:py-6 md:text-left",children:[k5("a",{href:"https://rizom.ai",className:"docs-font-body text-[15px] font-bold",children:[k5("span",{className:rJ1,children:"rizom"},void 0,!1,void 0,this),k5("span",{className:nJ1,children:"."},void 0,!1,void 0,this),k5("span",{className:oJ1,children:"ai"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k5("div",{className:"flex flex-wrap items-center justify-center gap-6 md:justify-end",children:[k5("a",{className:CyA,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),k5("a",{className:CyA,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),k5("a",{className:CyA,href:"https://rizom.ai",children:"Rizom"},void 0,!1,void 0,this),k5("button",{id:"themeToggle",className:"docs-font-label cursor-pointer rounded-md border border-[var(--docs-text-light)] bg-transparent px-2.5 py-1.5 text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:border-[var(--docs-text)] hover:text-[var(--docs-text)]",type:"button",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),RZ2=`
|
|
9783
9795
|
.docs-handbook {
|
|
9784
9796
|
--docs-bg: var(--color-bg, #0d0a1a);
|
|
9785
9797
|
--docs-bg-card: var(--color-bg-card, #1a0a3e);
|
|
@@ -9931,7 +9943,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});fA();var T
|
|
|
9931
9943
|
background: transparent;
|
|
9932
9944
|
}
|
|
9933
9945
|
|
|
9934
|
-
`,tJ1=()=>k5("style",{children:RZ2},void 0,!1,void 0,this);import{jsxDEV as GQ,Fragment as bZ2}from"preact/jsx-dev-runtime";var i8A=({title:A,description:Q,children:B,detail:w=!1,footer:$=!1,contentClassName:I=""})=>GQ(bZ2,{children:[GQ(Z2,{title:A,description:Q},void 0,!1,void 0,this),GQ(tJ1,{},void 0,!1,void 0,this),GQ("div",{className:`docs-handbook${w?" docs-handbook--detail":""}`,children:[GQ(sJ1,{},void 0,!1,void 0,this),GQ("div",{className:`${MJ.wrap} ${I}`.trim(),children:[B,$&&GQ(aJ1,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),eJ1=({docsCount:A,sectionsCount:Q,startDoc:B})=>GQ("section",{className:"border-b border-[var(--docs-text)] py-14 md:py-24 md:pb-[72px]",children:[GQ("p",{className:`${MJ.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),GQ("h1",{className:`${MJ.display} m-0 max-w-[16ch] text-5xl leading-[1.05] tracking-[-0.02em] md:text-7xl`,children:["Build, run, and publish"," ",GQ("em",{className:"text-[var(--docs-accent)]",children:"brains."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),GQ("p",{className:"mt-8 max-w-[52ch] text-lg leading-[1.65] text-[var(--docs-text-muted)]",children:"Documentation for composing brain models, managing markdown entities, wiring interfaces, and shipping generated sites."},void 0,!1,void 0,this),GQ("dl",{className:"mt-10 flex flex-wrap gap-7 docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] md:mt-14 md:gap-12",children:[GQ("div",{children:[GQ("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:A},void 0,!1,void 0,this),"Documents"]},void 0,!0,void 0,this),GQ("div",{children:[GQ("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:Q},void 0,!1,void 0,this),"Sections"]},void 0,!0,void 0,this),GQ("div",{children:[GQ("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:"April 2026"},void 0,!1,void 0,this),"Updated"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),GQ("div",{className:"mt-9 flex flex-wrap gap-3.5",children:[B&&GQ("a",{className:MJ.primaryButton,href:ik(B),children:"Start reading"},void 0,!1,void 0,this),GQ("a",{className:MJ.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),AG1=({groups:A})=>GQ("aside",{className:"docs-rail sticky top-8 hidden docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] min-[861px]:block","aria-label":"Documentation sections",children:[GQ("p",{className:"m-0 mb-3.5 font-medium text-[var(--docs-text)]",children:"Sections"},void 0,!1,void 0,this),GQ("ol",{className:"m-0 list-none p-0",children:A.map((Q,B)=>GQ("li",{className:"grid grid-cols-[32px_1fr] gap-2 py-1.5",children:[GQ("span",{className:"docs-font-display text-[var(--docs-text-light)] italic",children:[dk(B),"."]},void 0,!0,void 0,this),GQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:`#${l8A(B)}`,children:Q.section},void 0,!1,void 0,this)]},Q.section,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),QG1=({group:A,index:Q})=>GQ("article",{className:"mb-16 last:mb-0",id:l8A(Q),children:[GQ("header",{className:"mb-2 grid grid-cols-[36px_auto_1fr] items-baseline gap-x-3 border-b border-[var(--docs-border)] pb-3.5 md:grid-cols-[48px_auto_1fr] md:gap-x-5",children:[GQ("span",{className:"text-right docs-font-display text-3xl leading-[1.1] text-[var(--docs-accent)] italic md:text-4xl",children:[dk(Q),"."]},void 0,!0,void 0,this),GQ("h2",{className:`${MJ.display} m-0 text-3xl leading-[1.1] tracking-[-0.015em] md:text-4xl`,children:A.section},void 0,!1,void 0,this),GQ("span",{className:"docs-chapter__leader"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),GQ("ol",{className:"m-0 list-none p-0",children:A.docs.map((B)=>GQ("li",{className:"border-b border-[var(--docs-border-light)] last:border-b-0",children:GQ("a",{className:"group block py-[18px] pl-12 md:pl-[68px]",href:ik(B),children:[GQ("p",{className:"m-0 text-[22px] leading-[1.2] tracking-[-0.005em] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:B.metadata.title},void 0,!1,void 0,this),B.metadata.description&&GQ("p",{className:"mt-1.5 mb-0 max-w-[70ch] text-sm leading-[1.55] text-[var(--docs-text-muted)]",children:B.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},B.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),BG1=({title:A})=>GQ("nav",{className:"mb-8 flex flex-wrap items-baseline gap-2.5 docs-font-label text-[11px] uppercase tracking-[0.06em] text-[var(--docs-text-light)]","aria-label":"Breadcrumb",children:[GQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/",children:"Home"},void 0,!1,void 0,this),GQ("span",{children:"/"},void 0,!1,void 0,this),GQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/docs",children:"Docs"},void 0,!1,void 0,this),GQ("span",{children:"/"},void 0,!1,void 0,this),GQ("span",{children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this),wG1=({groups:A,activeGroupIndex:Q,activeSlug:B})=>GQ("aside",{className:"docs-detail-rail sticky top-24 hidden max-h-[calc(100vh-120px)] overflow-auto pr-2 min-[861px]:block","aria-label":"Documentation navigation",children:GQ("nav",{className:"docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)]",children:[GQ("p",{className:"m-0 mb-4 border-b border-[var(--docs-text)] pb-3 text-[11px] uppercase tracking-[0.08em] text-[var(--docs-text-light)]",children:"Documentation"},void 0,!1,void 0,this),GQ("ol",{className:"m-0 list-none p-0",children:A.map((w,$)=>{let I=$===Q;return GQ("li",{className:I?"mb-[22px]":"mb-3.5",children:[GQ("a",{className:`mb-2 flex items-baseline gap-2.5 docs-font-label text-[11px] uppercase leading-[1.4] tracking-[0.06em] transition-colors duration-150 hover:text-[var(--docs-text)] ${I?"text-[var(--docs-text)]":"text-[var(--docs-text-muted)]"}`,href:`/docs#${l8A($)}`,children:[GQ("span",{className:"docs-font-display text-sm text-[var(--docs-accent)] italic",children:[dk($),"."]},void 0,!0,void 0,this)," ",w.section]},void 0,!0,void 0,this),I&&GQ("ol",{className:"mt-0.5 list-none p-0",children:w.docs.map((D)=>{let Y=D.metadata.slug===B;return GQ("li",{children:GQ("a",{className:`docs-rail__doc relative block py-1.5 docs-font-body text-sm leading-[1.4] tracking-normal transition-[color,padding-left] duration-150 hover:text-[var(--docs-text)] ${Y?"pl-3.5 font-medium text-[var(--docs-accent)]":"text-[var(--docs-text-muted)]"}`,href:ik(D),"aria-current":Y?"page":void 0,children:D.metadata.title},void 0,!1,void 0,this)},D.id,!1,void 0,this)})},void 0,!1,void 0,this)]},w.section,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),$G1=({prevDoc:A,nextDoc:Q})=>{if(!A&&!Q)return null;return GQ("nav",{className:"mt-12 grid grid-cols-1 gap-5 border-t border-[var(--docs-border)] pt-7 md:grid-cols-2","aria-label":"Previous and next docs",children:[A?GQ("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] transition-colors duration-150 hover:border-[var(--docs-accent)]",href:ik(A),children:[GQ("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Previous"},void 0,!1,void 0,this),GQ("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:["\u2190 ",A.metadata.title]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):GQ("span",{},void 0,!1,void 0,this),Q&&GQ("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] text-left transition-colors duration-150 hover:border-[var(--docs-accent)] md:text-right",href:ik(Q),children:[GQ("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Next"},void 0,!1,void 0,this),GQ("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:[Q.metadata.title," \u2192"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as rk}from"preact/jsx-dev-runtime";var OyA=({docs:A})=>{let Q=kp(A),B=p8A(Q),$=Q.filter((I)=>I.metadata.slug!=="index")[0]??Q[0];return rk(i8A,{title:"Documentation",description:"Brains documentation",children:[rk(eJ1,{docsCount:A.length,sectionsCount:B.length,startDoc:$},void 0,!1,void 0,this),rk("section",{className:"grid items-start gap-10 py-12 md:grid-cols-[200px_minmax(0,1fr)] md:gap-20 md:py-20 md:pb-[120px]",id:"sections",children:[rk(AG1,{groups:B},void 0,!1,void 0,this),rk("div",{children:B.map((I,D)=>rk(QG1,{group:I,index:D},I.section,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as kD}from"preact/jsx-dev-runtime";var RyA=({doc:A,docs:Q,prevDoc:B,nextDoc:w})=>{let $=p8A(Q.length>0?Q:[A]),I=kp(Q.length>0?Q:[A]),D=I.findIndex((X)=>X.metadata.slug===A.metadata.slug),Y=Math.max($.findIndex((X)=>X.docs.some((W)=>W.metadata.slug===A.metadata.slug)),0);return kD(i8A,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[kD(BG1,{title:A.metadata.title},void 0,!1,void 0,this),kD("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[kD(wG1,{groups:$,activeGroupIndex:Y,activeSlug:A.metadata.slug},void 0,!1,void 0,this),kD("article",{className:"min-w-0",children:[kD("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[kD("p",{className:`${MJ.label} m-0 mb-6 flex items-baseline gap-3`,children:[kD("span",{className:"docs-font-display text-lg leading-none tracking-normal normal-case text-[var(--docs-accent)] italic",children:[dk(Y),"."]},void 0,!0,void 0,this)," ",A.metadata.section,D>=0?` \xB7 ${D+1}/${I.length}`:""]},void 0,!0,void 0,this),kD("h1",{className:`${MJ.display} m-0 max-w-[18ch] text-4xl leading-[1.05] tracking-[-0.02em] md:text-6xl`,children:A.metadata.title},void 0,!1,void 0,this),A.metadata.description&&kD("p",{className:"mt-6 max-w-[56ch] docs-font-display text-[22px] font-[350] leading-[1.5] text-[var(--docs-text-muted)]",children:A.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),kD("div",{className:"docs-article__body",children:kD(CD,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),kD($G1,{prevDoc:B,nextDoc:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};var PZ2=f.object({docs:f.array(Pf),pagination:T9.nullable(),baseUrl:f.string().optional()}),jZ2=f.object({doc:Pf,docs:f.array(Pf),prevDoc:Pf.nullable(),nextDoc:Pf.nullable()});function IG1(){return{"doc-list":R1({name:"doc-list",description:"Documentation index template",schema:PZ2,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:OyA}}),"doc-detail":R1({name:"doc-detail",description:"Documentation page template",schema:jZ2,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:RyA}})}}var DG1={name:"@brains/doc",private:!0,version:"0.2.0-alpha.92",description:"Documentation entity type \u2014 markdown docs as first-class brain content",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};class byA extends V2{entityType=u8A.entityType;schema=lk;adapter=u8A;constructor(){super("docs",DG1,{},void 0)}getTemplates(){return IG1()}getDataSources(){return[new c8A(this.logger.child("DocDataSource"))]}}function PyA(){return new byA}eA();fA();fA();Z$();var YG1=f.object({label:f.string(),href:f.string()}),XG1=f.object({label:f.string(),title:f.string(),detail:f.string()}),_Z2=f.object({eyebrow:f.string(),name:f.string(),sub:f.string()}),vZ2=f.object({tone:f.enum(["capture","synthesis","share"]),title:f.string(),text:f.string()}),jyA=f.object({captures:f.number(),links:f.number(),topics:f.number(),summaries:f.number(),peers:f.number()}),nk=f.object({eyebrow:f.string(),headline:f.string(),intro:f.string(),primaryCta:YG1,secondaryCta:YG1,inputs:f.array(XG1).min(1),outputs:f.array(XG1).min(1),core:_Z2,legend:f.array(vZ2).min(1)}),kyA=nk.extend({counts:jyA}),WG1={eyebrow:"A team brain, diagrammed",headline:"Relay sits between the work and the world, and keeps both honest.",intro:"Capture sources flow into a shared brain; the brain organizes, summarizes, and \u2014 selectively \u2014 exposes a public surface. Everything else stays private and operational.",primaryCta:{label:"See it on a real team",href:"#diagram"},secondaryCta:{label:"Read the model",href:"/about"},inputs:[{label:"Source \xB7 chat",title:"Discord",detail:"Shared decisions and field notes captured in flow."},{label:"Source \xB7 agent",title:"MCP / CLI",detail:"Structured captures from tools and assistants."},{label:"Source \xB7 web",title:"Links & docs",detail:"External material indexed with sourceable metadata."}],outputs:[{label:"Surface \xB7 public",title:"Default site",detail:"A small, durable face onto what the team currently knows."},{label:"Surface \xB7 agents",title:"A2A exchange",detail:"Peer brains coordinate over an approved, signed protocol."},{label:"Surface \xB7 query",title:"Team Q&A",detail:"Ask the brain in chat; answers cite the captures behind them."}],core:{eyebrow:"The relay",name:"brain",sub:"capture \u2192 topics \u2192 summaries"},legend:[{tone:"capture",title:"Capture",text:"Anything the team already does that produces a trace \u2014 chat messages, links, deploys, decisions."},{tone:"synthesis",title:"Synthesis",text:"The work the brain does on its own time \u2014 clustering captures into topics, summaries, and durable memory."},{tone:"share",title:"Share",text:"A small, opinionated public surface and an approved agent-to-agent protocol. Most memory stays private."}]},HG1=new vB(nk,{title:"Home diagram",mappings:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"headline",label:"Headline",type:"string"},{key:"intro",label:"Intro",type:"string"},{key:"primaryCta",label:"Primary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"secondaryCta",label:"Secondary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"inputs",label:"Inputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"outputs",label:"Outputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"core",label:"Core",type:"object",children:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"name",label:"Name",type:"string"},{key:"sub",label:"Sub",type:"string"}]},{key:"legend",label:"Legend",type:"array",itemType:"object",itemMappings:[{key:"tone",label:"Tone",type:"string"},{key:"title",label:"Title",type:"string"},{key:"text",label:"Text",type:"string"}]}]});function d8A(A){return HG1.parse(A)}function UG1(A){return HG1.format(A)}fA();var xZ2=f.object({query:f.object({routeId:f.string().default("home"),sectionId:f.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}).passthrough(),yZ2={captures:"base",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class _yA{id="relay-site:home-counts";name="Relay homepage counts";description="Fetches Relay homepage content and live entity counts for the system diagram";async fetch(A,Q,B){let w=xZ2.parse(A??{}),$=await this.fetchContent(B,w.query.routeId,w.query.sectionId),I=await this.fetchCounts(B);return Q.parse({...$,counts:I})}async fetchContent(A,Q,B){let w=await A.entityService.getEntity({entityType:"site-content",id:`${Q}:${B}`});if(!w?.content)return WG1;return nk.parse(d8A(w.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(yZ2).map(async([B,w])=>[B,await this.countOrZero(A,w)]));return jyA.parse(Object.fromEntries(Q))}async countOrZero(A,Q){if(!A.entityService.hasEntityType(Q))return 0;try{return await A.entityService.countEntities({entityType:Q})}catch{return 0}}}import{jsxDEV as Q1}from"preact/jsx-dev-runtime";var JG1=f.object({label:f.string(),href:f.string()}),TZ2=f.object({eyebrow:f.string(),headline:f.string(),intro:f.string(),primaryCta:JG1,secondaryCta:JG1,signals:f.array(f.object({label:f.string(),value:f.string(),note:f.string()}))}),SZ2=f.object({eyebrow:f.string(),title:f.string(),intro:f.string(),steps:f.array(f.object({phase:f.string(),title:f.string(),text:f.string()}))}),gZ2=f.object({title:f.string(),intro:f.string(),cards:f.array(f.object({label:f.string(),title:f.string(),text:f.string()}))}),hZ2=f.object({title:f.string(),intro:f.string(),points:f.array(f.string())}),mZ2={title:"Relay is a collaborative team-memory brain.",intro:"It exists for teams that need to remember together: capturing what happened, summarizing why it matters, and coordinating with trusted peer brains when work crosses boundaries.",points:["Not a personal blog engine or portfolio shell.","Not a marketing automation stack.","A small public face for a larger private knowledge workflow."]},uZ2="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function GG1({href:A,label:Q}){return Q1("a",{href:A,className:uZ2,children:Q},void 0,!1,void 0,this)}function cZ2({siteInfo:A,children:Q}){let B=[...A.navigation.primary,...A.navigation.secondary],w=A.cta??{buttonText:"Start here",buttonLink:"/about"};return Q1(yk,{children:[Q1("nav",{className:"fixed left-0 right-0 top-0 z-[100] flex items-center justify-between border-b border-theme-light bg-nav-fade px-6 py-4 backdrop-blur-[12px] md:px-10 xl:px-20",children:[Q1("a",{href:"/",className:"font-nav text-[20px]","aria-label":"Relay home",children:[Q1("span",{className:"font-bold text-theme",children:"relay"},void 0,!1,void 0,this),Q1("span",{className:"font-bold text-accent",children:"."},void 0,!1,void 0,this),Q1("span",{className:"text-theme-muted",children:"brain"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"flex items-center gap-5 md:gap-8",children:[Q1("div",{className:"hidden items-center gap-6 md:flex",children:B.map(($)=>Q1(GG1,{...$},`${$.href}-${$.label}`,!1,void 0,this))},void 0,!1,void 0,this),Q1("a",{href:w.buttonLink,className:"rounded-[999px] border border-theme px-4 py-2 font-body text-[13px] font-semibold text-theme transition-colors hover:border-accent hover:text-accent md:px-5",children:w.buttonText},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("main",{children:Q},void 0,!1,void 0,this),Q1("footer",{className:"relative z-[1] border-t border-theme-light px-6 py-8 md:px-10 xl:px-20",children:Q1("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[Q1("div",{children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.22em] text-theme-light",children:A.copyright},void 0,!1,void 0,this),Q1("p",{className:"mt-2 max-w-[560px] font-body text-body-xs text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"flex flex-wrap items-center gap-5",children:[B.map(($)=>Q1(GG1,{...$},`footer-${$.href}-${$.label}`,!1,void 0,this)),Q1("button",{id:"themeToggle","aria-label":"Toggle light mode",className:"rounded-md border border-theme-light bg-transparent px-2.5 py-1.5 font-body text-label-md text-theme-light transition-colors hover:border-theme hover:text-theme",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var pZ2=({sections:A,siteInfo:Q})=>Q1(cZ2,{siteInfo:Q,children:A},void 0,!1,void 0,this);function lZ2({eyebrow:A,headline:Q,intro:B,primaryCta:w,secondaryCta:$,signals:I}){return Q1(LN,{className:"min-h-[92vh] pt-[152px] pb-20 md:pt-[190px]",children:Q1("div",{className:"grid gap-10 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-end",children:[Q1("div",{children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),Q1("h1",{className:"mt-7 max-w-[980px] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),Q1("p",{className:"mt-7 max-w-[720px] font-body text-body-lg text-theme-muted",children:B},void 0,!1,void 0,this),Q1("div",{className:"mt-10 flex flex-col gap-3 sm:flex-row",children:[Q1(jV,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),Q1(jV,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"rounded-[32px] border border-card-relay-border bg-card-relay-bg p-5 shadow-[0_24px_90px_var(--color-glow-relay)] backdrop-blur-sm",children:[Q1("p",{className:"font-label text-label-xs uppercase tracking-[0.24em] text-theme-light",children:"Live relay signals"},void 0,!1,void 0,this),Q1("div",{className:"mt-5 grid gap-3",children:I.map((D)=>Q1("div",{className:"rounded-[22px] border border-card-divider bg-bg-muted p-5",children:[Q1("div",{className:"flex items-center justify-between gap-4",children:[Q1("p",{className:"font-label text-label-xs uppercase tracking-[0.18em] text-secondary",children:D.label},void 0,!1,void 0,this),Q1("span",{className:"h-2 w-2 rounded-full bg-accent shadow-[0_0_22px_var(--color-accent)]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("p",{className:"mt-4 font-display text-display-sm text-theme",children:D.value},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-body text-body-xs text-theme-muted",children:D.note},void 0,!1,void 0,this)]},D.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function iZ2({eyebrow:A,title:Q,intro:B,steps:w}){return Q1(LN,{id:"operating-loop",className:"py-section",children:[Q1("div",{className:"max-w-[840px]",children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-secondary",children:A},void 0,!1,void 0,this),Q1("h2",{className:"mt-5 font-display text-display-md text-theme",children:Q},void 0,!1,void 0,this),Q1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:w.map(($)=>Q1("article",{className:"min-h-[300px] rounded-[28px] border border-card-panel-border bg-card-panel-bg p-6",children:[Q1("p",{className:"font-label text-label-sm text-accent",children:$.phase},void 0,!1,void 0,this),Q1("h3",{className:"mt-16 font-display text-display-sm text-theme",children:$.title},void 0,!1,void 0,this),Q1("p",{className:"mt-4 font-body text-body-sm text-theme-muted",children:$.text},void 0,!1,void 0,this)]},$.phase,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function dZ2({title:A,intro:Q,cards:B}){return Q1(LN,{className:"py-section",children:Q1("div",{className:"rounded-[36px] border border-theme-light bg-bg-muted p-6 md:p-10",children:Q1("div",{className:"grid gap-8 lg:grid-cols-[360px_1fr]",children:[Q1("div",{children:[Q1("h2",{className:"font-display text-display-md text-theme",children:A},void 0,!1,void 0,this),Q1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"grid gap-4",children:B.map((w)=>Q1("article",{className:"rounded-[24px] border border-card-divider bg-bg-subtle/70 p-5",children:[Q1("p",{className:"font-label text-label-xs uppercase tracking-[0.22em] text-accent",children:w.label},void 0,!1,void 0,this),Q1("h3",{className:"mt-3 font-nav text-heading-lg text-theme",children:w.title},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-body text-body-sm text-theme-muted",children:w.text},void 0,!1,void 0,this)]},w.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function rZ2({title:A,intro:Q,points:B}){return Q1(LN,{className:"min-h-[78vh] pt-[150px] pb-section md:pt-[190px]",children:[Q1("div",{className:"max-w-[920px]",children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:"Relay model"},void 0,!1,void 0,this),Q1("h1",{className:"mt-6 font-display text-display-lg text-theme",children:A},void 0,!1,void 0,this),Q1("p",{className:"mt-7 font-body text-body-lg text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:B.map((w)=>Q1("div",{className:"rounded-[24px] border border-card-panel-current-border bg-card-panel-current-bg p-6 font-body text-body-md text-theme",children:w},w,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var nZ2=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},oZ2=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),_p=(A,Q,B=`${Q}s`)=>`${oZ2(A)} ${A===1?Q:B}`;function sZ2({eyebrow:A,headline:Q,intro:B,primaryCta:w,secondaryCta:$,inputs:I,outputs:D,core:Y,legend:X,counts:W}){let U=[{key:"captures",className:"top-[-10px] left-1/2 -translate-x-1/2",label:_p(W.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:_p(W.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:_p(W.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:_p(W.summaries,"summary","summaries")}];return Q1(LN,{className:"pt-[150px] pb-section md:pt-[190px]",id:"diagram",children:[Q1("div",{className:"mx-auto max-w-[1040px] text-center",children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),Q1("h1",{className:"mx-auto mt-7 max-w-[22ch] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),Q1("p",{className:"mx-auto mt-7 max-w-[64ch] font-body text-body-lg text-theme-muted",children:B},void 0,!1,void 0,this),Q1("div",{className:"mt-10 flex flex-col justify-center gap-3 sm:flex-row",children:[Q1(jV,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),Q1(jV,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mx-auto mt-20 max-w-[1020px] rounded-[32px] border border-theme-light bg-[radial-gradient(circle_at_1px_1px,rgb(255_255_255_/_0.05)_1px,transparent_0),linear-gradient(180deg,rgb(255_255_255_/_0.02),transparent)] bg-[length:24px_24px,100%_100%] px-6 py-14",children:[Q1("div",{className:"grid items-center gap-8 lg:grid-cols-[1fr_1.4fr_1fr]",children:[Q1("div",{className:"flex flex-col gap-3.5",children:I.map((K)=>Q1("div",{className:"rounded-2xl border border-card-panel-border border-l-2 border-l-accent bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[Q1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:K.label},void 0,!1,void 0,this),Q1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:K.title},void 0,!1,void 0,this),Q1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:K.detail},void 0,!1,void 0,this)]},`${K.label}-${K.title}`,!0,void 0,this))},void 0,!1,void 0,this),Q1("div",{className:"relative mx-auto grid aspect-square w-full max-w-[320px] place-items-center rounded-full bg-[radial-gradient(circle_at_center,rgb(232_119_34_/_0.25),transparent_65%)]",children:[Q1("div",{className:"absolute inset-0 rounded-full border border-dashed border-accent/30"},void 0,!1,void 0,this),Q1("div",{className:"absolute inset-6 animate-spin rounded-full border border-dashed border-secondary/40 [animation-duration:28s]"},void 0,!1,void 0,this),U.map((K)=>Q1("span",{className:`absolute whitespace-nowrap rounded-full border border-theme bg-bg px-2.5 py-1 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light ${K.className}`,children:K.label},K.key,!1,void 0,this)),Q1("div",{className:"relative z-[1] px-6 text-center",children:[Q1("p",{className:"font-label text-[10px] uppercase tracking-[0.28em] text-accent",children:Y.eyebrow},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-display text-[36px] leading-none text-theme",children:Y.name},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-body text-[13px] text-theme-muted",children:Y.sub},void 0,!1,void 0,this),Q1("p",{className:"mt-4 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light",children:[_p(W.links,"link")," indexed"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"flex flex-col gap-3.5",children:D.map((K)=>Q1("div",{className:"rounded-2xl border border-card-panel-border border-r-2 border-r-secondary bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[Q1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:K.label},void 0,!1,void 0,this),Q1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:K.title},void 0,!1,void 0,this),Q1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:K.detail},void 0,!1,void 0,this)]},`${K.label}-${K.title}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mt-14 grid gap-4 border-t border-theme-light pt-8 md:grid-cols-3",children:X.map((K)=>Q1("div",{className:"text-left",children:[Q1("h2",{className:"font-display text-[16px] font-medium text-theme",children:[Q1("span",{className:`mr-2.5 inline-block h-3 w-3 rounded-[3px] align-middle ${nZ2(K.tone)}`},void 0,!1,void 0,this),K.title]},void 0,!0,void 0,this),Q1("p",{className:"mt-1.5 font-body text-[13px] leading-[1.6] text-theme-muted",children:K.text},void 0,!1,void 0,this)]},K.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var aZ2=R1({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:kyA,formatter:{parse:(A)=>kyA.parse({...d8A(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>UG1(nk.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:sZ2}}),tZ2=(A)=>lZ2(TZ2.parse(A)),eZ2=(A)=>iZ2(SZ2.parse(A)),Az2=(A)=>dZ2(gZ2.parse(A)),Qz2=(A)=>rZ2(hZ2.parse(A)),KG1={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},fG1={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:tZ2,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...KG1,label:"Primary CTA"},secondaryCta:{...KG1,label:"Secondary CTA"},signals:{type:"array",label:"Signals",minItems:1,items:{type:"object",label:"Signal",fields:{label:{type:"string",label:"Label"},value:{type:"string",label:"Value"},note:{type:"string",label:"Note"}}}}}},"home-loop":{title:"Home operating loop",description:"Relay capture, synthesis, and sharing loop",layout:eZ2,fields:{eyebrow:{type:"string",label:"Eyebrow"},title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},steps:{type:"array",label:"Steps",minItems:1,items:{type:"object",label:"Step",fields:{phase:{type:"string",label:"Phase"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},"home-surface":{title:"Home surface",description:"Relay default template explanation cards",layout:Az2,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},cards:{type:"array",label:"Cards",minItems:1,items:{type:"object",label:"Card",fields:{label:{type:"string",label:"Label"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},about:{title:"About Relay",description:"Default Relay about page",layout:Qz2,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},Bz2=[{id:"home",path:"/",title:"Relay",description:"Collaborative team memory and synthesis brain",layout:"default",navigation:{show:!0,label:"Home",slot:"secondary",priority:10},sections:[{id:"diagram",template:"relay-site:home-diagram"}]},{id:"about",path:"/about",title:"About Relay",description:"What Relay is designed to do",layout:"default",navigation:{show:!0,label:"About",slot:"primary",priority:20},sections:[{id:"about",template:"relay-site:about",content:mZ2}]}],FG1=UyA({packageName:"@brains/relay/site",contentNamespace:"relay-site",themeProfile:"studio",layout:pZ2,routes:Bz2,templates:{"home-diagram":aZ2},dataSources:[new _yA]});var ZG1={name:"@brains/relay",private:!0,version:"0.2.0-alpha.92",description:"Relay brain model \u2014 collaborative knowledge management",type:"module",files:["src","brain.eval.yaml","env.schema.template"],exports:{".":"./src/index.ts"},scripts:{"start:core":"cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:docs":"cd test-apps/docs && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",test:"bun test",eval:"brain-eval",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/auth-service":"workspace:*","@brains/cms":"workspace:*","@brains/content-formatters":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/doc":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/note":"workspace:*","@brains/plugins":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-info":"workspace:*","@brains/site-rizom":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/utils":"workspace:*","@brains/webserver":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/test-utils":"workspace:*",typescript:"^5.3.3"}};var zG1=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","discord","a2a"],NG1=[...zG1,"image","site-info","site-content","site-builder"],Iz2=[...NG1,"docs","decks"],Dz2=["Relay is a collaborative team-memory and synthesis brain. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence, and coordinating with peer brains.","Relay is not Rover-for-teams: do not default to personal branding, blog publishing, newsletters, social media, portfolio, or marketing workflows unless the installed plugins and user request explicitly support them.",'Relay entity mappings: "memo", "note", "team note", "capture" \u2192 entityType: base; "summary", "sync", "team digest" \u2192 entityType: summary; "decision" \u2192 entityType: decision; "action item", "todo" \u2192 entityType: action-item; "handbook", "doc", "documentation" \u2192 entityType: doc; "deck", "walkthrough", "presentation" \u2192 entityType: deck; "agent", "peer brain", "contact" \u2192 entityType: agent.'],qG1=NZ({name:"relay",version:ZG1.version,model:"gpt-5.4-mini",site:FG1,theme:Tk,presets:{core:zG1,default:NG1,full:Iz2},evalDisable:["webserver","mcp","discord"],agentInstructions:Dz2,capabilities:[["prompt",RV,void 0],["note",NV,{}],["link",LV,{}],["image",dT,void 0],["topics",qwA,{includeEntityTypes:["base","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",VyA,{}],["docs",PyA,void 0],["decks",mc,void 0],["agents",Q8A,void 0],["assessment",U8A,void 0],["auth-service",yg,void 0],["notifications",St,void 0],["email-resend",HQA,void 0],["cms",OV,{}],["dashboard",zN,void 0],["directory-sync",jE,{seedContent:!0,seedContentPath:$z2(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",Ep,{definitions:fG1}],["rizom-ecosystem",bV,void 0],["site-info",fV,void 0],["site-builder",KV,{}]],interfaces:[["mcp",eZ,()=>({})],["discord",xz,()=>({captureUrls:!0})],["a2a",nP,()=>({})],["webserver",yz,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"anchor"},{pattern:"discord:*",level:"public"}]},deployment:{cdn:{enabled:!0,provider:"bunny"}}});import{readFileSync as hq2}from"fs";import{join as mq2}from"path";import{execSync as uq2}from"child_process";import{parseArgs as Wz2}from"util";var Hz2={model:{type:"string"},domain:{type:"string"},"content-repo":{type:"string"},backend:{type:"string"},"push-to":{type:"string"},"ai-api-key":{type:"string"},"no-interactive":{type:"boolean"},preview:{type:"boolean"},deploy:{type:"boolean"},regen:{type:"boolean"},all:{type:"boolean"},only:{type:"string"},"dry-run":{type:"boolean"},"startup-check":{type:"boolean"},"storage-dir":{type:"string"},yes:{type:"boolean"},remote:{type:"string"},token:{type:"string"},outputDir:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};function DH(A,Q){let B=A[Q];return typeof B==="string"?B:void 0}function MN(A,Q){let B=A[Q];return typeof B==="boolean"?B:void 0}function LG1(A){let{values:Q,positionals:B}=Wz2({args:A,options:Hz2,allowPositionals:!0,strict:!1});if(Q.help)return{command:"help",args:[],flags:{help:!0}};if(Q.version)return{command:"version",args:[],flags:{version:!0}};return{command:B[0]??"help",args:B.slice(1),flags:{model:DH(Q,"model"),domain:DH(Q,"domain"),"content-repo":DH(Q,"content-repo"),backend:DH(Q,"backend"),"push-to":DH(Q,"push-to"),"ai-api-key":DH(Q,"ai-api-key"),"no-interactive":MN(Q,"no-interactive"),preview:MN(Q,"preview"),deploy:MN(Q,"deploy"),regen:MN(Q,"regen"),all:MN(Q,"all"),only:DH(Q,"only"),"dry-run":MN(Q,"dry-run"),"startup-check":MN(Q,"startup-check"),"storage-dir":DH(Q,"storage-dir"),yes:MN(Q,"yes"),remote:DH(Q,"remote"),token:DH(Q,"token"),outputDir:DH(Q,"outputDir")}}}vp();import{mkdirSync as Pq2}from"fs";import{join as jq2}from"path";import{execSync as kq2}from"child_process";var n8A={name:"@rizom/brain",version:"0.2.0-alpha.92",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun scripts/build.ts","dev:start":"bun dist/brain.js start",typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@clack/prompts":"^0.11.0","@modelcontextprotocol/sdk":"^1.24.0","@tailwindcss/postcss":"^4.1.13","@tailwindcss/typography":"^0.5.19",postcss:"^8.5.6",preact:"^10.27.2","preact-render-to-string":"^6.3.1",tailwindcss:"^4.1.11"},optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","playwright-core":"^1.56.0","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"workspace:*","@brains/content-formatters":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"latest",rollup:"^4.60.2","rollup-plugin-dts":"^6.4.1",typescript:"^5.3.3"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",bugs:"https://github.com/rizom-ai/brains/issues",engines:{bun:">=1.3.3"},keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"]};import{mkdirSync as TG1,writeFileSync as yp,chmodSync as Tp,existsSync as cyA,readFileSync as pyA}from"fs";import{basename as lyA,dirname as iyA,join as u8,resolve as lz2}from"path";import{fileURLToPath as iz2}from"url";var EG1=`ARG BUN_VERSION=1.3.10
|
|
9946
|
+
`,tJ1=()=>k5("style",{children:RZ2},void 0,!1,void 0,this);import{jsxDEV as GQ,Fragment as bZ2}from"preact/jsx-dev-runtime";var i8A=({title:A,description:Q,children:B,detail:w=!1,footer:$=!1,contentClassName:I=""})=>GQ(bZ2,{children:[GQ(Z2,{title:A,description:Q},void 0,!1,void 0,this),GQ(tJ1,{},void 0,!1,void 0,this),GQ("div",{className:`docs-handbook${w?" docs-handbook--detail":""}`,children:[GQ(sJ1,{},void 0,!1,void 0,this),GQ("div",{className:`${MJ.wrap} ${I}`.trim(),children:[B,$&&GQ(aJ1,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),eJ1=({docsCount:A,sectionsCount:Q,startDoc:B})=>GQ("section",{className:"border-b border-[var(--docs-text)] py-14 md:py-24 md:pb-[72px]",children:[GQ("p",{className:`${MJ.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),GQ("h1",{className:`${MJ.display} m-0 max-w-[16ch] text-5xl leading-[1.05] tracking-[-0.02em] md:text-7xl`,children:["Build, run, and publish"," ",GQ("em",{className:"text-[var(--docs-accent)]",children:"brains."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),GQ("p",{className:"mt-8 max-w-[52ch] text-lg leading-[1.65] text-[var(--docs-text-muted)]",children:"Documentation for composing brain models, managing markdown entities, wiring interfaces, and shipping generated sites."},void 0,!1,void 0,this),GQ("dl",{className:"mt-10 flex flex-wrap gap-7 docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] md:mt-14 md:gap-12",children:[GQ("div",{children:[GQ("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:A},void 0,!1,void 0,this),"Documents"]},void 0,!0,void 0,this),GQ("div",{children:[GQ("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:Q},void 0,!1,void 0,this),"Sections"]},void 0,!0,void 0,this),GQ("div",{children:[GQ("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:"April 2026"},void 0,!1,void 0,this),"Updated"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),GQ("div",{className:"mt-9 flex flex-wrap gap-3.5",children:[B&&GQ("a",{className:MJ.primaryButton,href:ik(B),children:"Start reading"},void 0,!1,void 0,this),GQ("a",{className:MJ.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),AG1=({groups:A})=>GQ("aside",{className:"docs-rail sticky top-8 hidden docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] min-[861px]:block","aria-label":"Documentation sections",children:[GQ("p",{className:"m-0 mb-3.5 font-medium text-[var(--docs-text)]",children:"Sections"},void 0,!1,void 0,this),GQ("ol",{className:"m-0 list-none p-0",children:A.map((Q,B)=>GQ("li",{className:"grid grid-cols-[32px_1fr] gap-2 py-1.5",children:[GQ("span",{className:"docs-font-display text-[var(--docs-text-light)] italic",children:[dk(B),"."]},void 0,!0,void 0,this),GQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:`#${l8A(B)}`,children:Q.section},void 0,!1,void 0,this)]},Q.section,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),QG1=({group:A,index:Q})=>GQ("article",{className:"mb-16 last:mb-0",id:l8A(Q),children:[GQ("header",{className:"mb-2 grid grid-cols-[36px_auto_1fr] items-baseline gap-x-3 border-b border-[var(--docs-border)] pb-3.5 md:grid-cols-[48px_auto_1fr] md:gap-x-5",children:[GQ("span",{className:"text-right docs-font-display text-3xl leading-[1.1] text-[var(--docs-accent)] italic md:text-4xl",children:[dk(Q),"."]},void 0,!0,void 0,this),GQ("h2",{className:`${MJ.display} m-0 text-3xl leading-[1.1] tracking-[-0.015em] md:text-4xl`,children:A.section},void 0,!1,void 0,this),GQ("span",{className:"docs-chapter__leader"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),GQ("ol",{className:"m-0 list-none p-0",children:A.docs.map((B)=>GQ("li",{className:"border-b border-[var(--docs-border-light)] last:border-b-0",children:GQ("a",{className:"group block py-[18px] pl-12 md:pl-[68px]",href:ik(B),children:[GQ("p",{className:"m-0 text-[22px] leading-[1.2] tracking-[-0.005em] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:B.metadata.title},void 0,!1,void 0,this),B.metadata.description&&GQ("p",{className:"mt-1.5 mb-0 max-w-[70ch] text-sm leading-[1.55] text-[var(--docs-text-muted)]",children:B.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},B.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),BG1=({title:A})=>GQ("nav",{className:"mb-8 flex flex-wrap items-baseline gap-2.5 docs-font-label text-[11px] uppercase tracking-[0.06em] text-[var(--docs-text-light)]","aria-label":"Breadcrumb",children:[GQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/",children:"Home"},void 0,!1,void 0,this),GQ("span",{children:"/"},void 0,!1,void 0,this),GQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/docs",children:"Docs"},void 0,!1,void 0,this),GQ("span",{children:"/"},void 0,!1,void 0,this),GQ("span",{children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this),wG1=({groups:A,activeGroupIndex:Q,activeSlug:B})=>GQ("aside",{className:"docs-detail-rail sticky top-24 hidden max-h-[calc(100vh-120px)] overflow-auto pr-2 min-[861px]:block","aria-label":"Documentation navigation",children:GQ("nav",{className:"docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)]",children:[GQ("p",{className:"m-0 mb-4 border-b border-[var(--docs-text)] pb-3 text-[11px] uppercase tracking-[0.08em] text-[var(--docs-text-light)]",children:"Documentation"},void 0,!1,void 0,this),GQ("ol",{className:"m-0 list-none p-0",children:A.map((w,$)=>{let I=$===Q;return GQ("li",{className:I?"mb-[22px]":"mb-3.5",children:[GQ("a",{className:`mb-2 flex items-baseline gap-2.5 docs-font-label text-[11px] uppercase leading-[1.4] tracking-[0.06em] transition-colors duration-150 hover:text-[var(--docs-text)] ${I?"text-[var(--docs-text)]":"text-[var(--docs-text-muted)]"}`,href:`/docs#${l8A($)}`,children:[GQ("span",{className:"docs-font-display text-sm text-[var(--docs-accent)] italic",children:[dk($),"."]},void 0,!0,void 0,this)," ",w.section]},void 0,!0,void 0,this),I&&GQ("ol",{className:"mt-0.5 list-none p-0",children:w.docs.map((D)=>{let Y=D.metadata.slug===B;return GQ("li",{children:GQ("a",{className:`docs-rail__doc relative block py-1.5 docs-font-body text-sm leading-[1.4] tracking-normal transition-[color,padding-left] duration-150 hover:text-[var(--docs-text)] ${Y?"pl-3.5 font-medium text-[var(--docs-accent)]":"text-[var(--docs-text-muted)]"}`,href:ik(D),"aria-current":Y?"page":void 0,children:D.metadata.title},void 0,!1,void 0,this)},D.id,!1,void 0,this)})},void 0,!1,void 0,this)]},w.section,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),$G1=({prevDoc:A,nextDoc:Q})=>{if(!A&&!Q)return null;return GQ("nav",{className:"mt-12 grid grid-cols-1 gap-5 border-t border-[var(--docs-border)] pt-7 md:grid-cols-2","aria-label":"Previous and next docs",children:[A?GQ("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] transition-colors duration-150 hover:border-[var(--docs-accent)]",href:ik(A),children:[GQ("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Previous"},void 0,!1,void 0,this),GQ("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:["\u2190 ",A.metadata.title]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):GQ("span",{},void 0,!1,void 0,this),Q&&GQ("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] text-left transition-colors duration-150 hover:border-[var(--docs-accent)] md:text-right",href:ik(Q),children:[GQ("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Next"},void 0,!1,void 0,this),GQ("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:[Q.metadata.title," \u2192"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as rk}from"preact/jsx-dev-runtime";var OyA=({docs:A})=>{let Q=kp(A),B=p8A(Q),$=Q.filter((I)=>I.metadata.slug!=="index")[0]??Q[0];return rk(i8A,{title:"Documentation",description:"Brains documentation",children:[rk(eJ1,{docsCount:A.length,sectionsCount:B.length,startDoc:$},void 0,!1,void 0,this),rk("section",{className:"grid items-start gap-10 py-12 md:grid-cols-[200px_minmax(0,1fr)] md:gap-20 md:py-20 md:pb-[120px]",id:"sections",children:[rk(AG1,{groups:B},void 0,!1,void 0,this),rk("div",{children:B.map((I,D)=>rk(QG1,{group:I,index:D},I.section,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as kD}from"preact/jsx-dev-runtime";var RyA=({doc:A,docs:Q,prevDoc:B,nextDoc:w})=>{let $=p8A(Q.length>0?Q:[A]),I=kp(Q.length>0?Q:[A]),D=I.findIndex((X)=>X.metadata.slug===A.metadata.slug),Y=Math.max($.findIndex((X)=>X.docs.some((W)=>W.metadata.slug===A.metadata.slug)),0);return kD(i8A,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[kD(BG1,{title:A.metadata.title},void 0,!1,void 0,this),kD("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[kD(wG1,{groups:$,activeGroupIndex:Y,activeSlug:A.metadata.slug},void 0,!1,void 0,this),kD("article",{className:"min-w-0",children:[kD("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[kD("p",{className:`${MJ.label} m-0 mb-6 flex items-baseline gap-3`,children:[kD("span",{className:"docs-font-display text-lg leading-none tracking-normal normal-case text-[var(--docs-accent)] italic",children:[dk(Y),"."]},void 0,!0,void 0,this)," ",A.metadata.section,D>=0?` \xB7 ${D+1}/${I.length}`:""]},void 0,!0,void 0,this),kD("h1",{className:`${MJ.display} m-0 max-w-[18ch] text-4xl leading-[1.05] tracking-[-0.02em] md:text-6xl`,children:A.metadata.title},void 0,!1,void 0,this),A.metadata.description&&kD("p",{className:"mt-6 max-w-[56ch] docs-font-display text-[22px] font-[350] leading-[1.5] text-[var(--docs-text-muted)]",children:A.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),kD("div",{className:"docs-article__body",children:kD(CD,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),kD($G1,{prevDoc:B,nextDoc:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};var PZ2=f.object({docs:f.array(Pf),pagination:T9.nullable(),baseUrl:f.string().optional()}),jZ2=f.object({doc:Pf,docs:f.array(Pf),prevDoc:Pf.nullable(),nextDoc:Pf.nullable()});function IG1(){return{"doc-list":R1({name:"doc-list",description:"Documentation index template",schema:PZ2,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:OyA}}),"doc-detail":R1({name:"doc-detail",description:"Documentation page template",schema:jZ2,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:RyA}})}}var DG1={name:"@brains/doc",private:!0,version:"0.2.0-alpha.93",description:"Documentation entity type \u2014 markdown docs as first-class brain content",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};class byA extends V2{entityType=u8A.entityType;schema=lk;adapter=u8A;constructor(){super("docs",DG1,{},void 0)}getTemplates(){return IG1()}getDataSources(){return[new c8A(this.logger.child("DocDataSource"))]}}function PyA(){return new byA}eA();fA();fA();Z$();var YG1=f.object({label:f.string(),href:f.string()}),XG1=f.object({label:f.string(),title:f.string(),detail:f.string()}),_Z2=f.object({eyebrow:f.string(),name:f.string(),sub:f.string()}),vZ2=f.object({tone:f.enum(["capture","synthesis","share"]),title:f.string(),text:f.string()}),jyA=f.object({captures:f.number(),links:f.number(),topics:f.number(),summaries:f.number(),peers:f.number()}),nk=f.object({eyebrow:f.string(),headline:f.string(),intro:f.string(),primaryCta:YG1,secondaryCta:YG1,inputs:f.array(XG1).min(1),outputs:f.array(XG1).min(1),core:_Z2,legend:f.array(vZ2).min(1)}),kyA=nk.extend({counts:jyA}),WG1={eyebrow:"A team brain, diagrammed",headline:"Relay sits between the work and the world, and keeps both honest.",intro:"Capture sources flow into a shared brain; the brain organizes, summarizes, and \u2014 selectively \u2014 exposes a public surface. Everything else stays private and operational.",primaryCta:{label:"See it on a real team",href:"#diagram"},secondaryCta:{label:"Read the model",href:"/about"},inputs:[{label:"Source \xB7 chat",title:"Discord",detail:"Shared decisions and field notes captured in flow."},{label:"Source \xB7 agent",title:"MCP / CLI",detail:"Structured captures from tools and assistants."},{label:"Source \xB7 web",title:"Links & docs",detail:"External material indexed with sourceable metadata."}],outputs:[{label:"Surface \xB7 public",title:"Default site",detail:"A small, durable face onto what the team currently knows."},{label:"Surface \xB7 agents",title:"A2A exchange",detail:"Peer brains coordinate over an approved, signed protocol."},{label:"Surface \xB7 query",title:"Team Q&A",detail:"Ask the brain in chat; answers cite the captures behind them."}],core:{eyebrow:"The relay",name:"brain",sub:"capture \u2192 topics \u2192 summaries"},legend:[{tone:"capture",title:"Capture",text:"Anything the team already does that produces a trace \u2014 chat messages, links, deploys, decisions."},{tone:"synthesis",title:"Synthesis",text:"The work the brain does on its own time \u2014 clustering captures into topics, summaries, and durable memory."},{tone:"share",title:"Share",text:"A small, opinionated public surface and an approved agent-to-agent protocol. Most memory stays private."}]},HG1=new vB(nk,{title:"Home diagram",mappings:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"headline",label:"Headline",type:"string"},{key:"intro",label:"Intro",type:"string"},{key:"primaryCta",label:"Primary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"secondaryCta",label:"Secondary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"inputs",label:"Inputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"outputs",label:"Outputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"core",label:"Core",type:"object",children:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"name",label:"Name",type:"string"},{key:"sub",label:"Sub",type:"string"}]},{key:"legend",label:"Legend",type:"array",itemType:"object",itemMappings:[{key:"tone",label:"Tone",type:"string"},{key:"title",label:"Title",type:"string"},{key:"text",label:"Text",type:"string"}]}]});function d8A(A){return HG1.parse(A)}function UG1(A){return HG1.format(A)}fA();var xZ2=f.object({query:f.object({routeId:f.string().default("home"),sectionId:f.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}).passthrough(),yZ2={captures:"base",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class _yA{id="relay-site:home-counts";name="Relay homepage counts";description="Fetches Relay homepage content and live entity counts for the system diagram";async fetch(A,Q,B){let w=xZ2.parse(A??{}),$=await this.fetchContent(B,w.query.routeId,w.query.sectionId),I=await this.fetchCounts(B);return Q.parse({...$,counts:I})}async fetchContent(A,Q,B){let w=await A.entityService.getEntity({entityType:"site-content",id:`${Q}:${B}`});if(!w?.content)return WG1;return nk.parse(d8A(w.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(yZ2).map(async([B,w])=>[B,await this.countOrZero(A,w)]));return jyA.parse(Object.fromEntries(Q))}async countOrZero(A,Q){if(!A.entityService.hasEntityType(Q))return 0;try{return await A.entityService.countEntities({entityType:Q})}catch{return 0}}}import{jsxDEV as Q1}from"preact/jsx-dev-runtime";var JG1=f.object({label:f.string(),href:f.string()}),TZ2=f.object({eyebrow:f.string(),headline:f.string(),intro:f.string(),primaryCta:JG1,secondaryCta:JG1,signals:f.array(f.object({label:f.string(),value:f.string(),note:f.string()}))}),SZ2=f.object({eyebrow:f.string(),title:f.string(),intro:f.string(),steps:f.array(f.object({phase:f.string(),title:f.string(),text:f.string()}))}),gZ2=f.object({title:f.string(),intro:f.string(),cards:f.array(f.object({label:f.string(),title:f.string(),text:f.string()}))}),hZ2=f.object({title:f.string(),intro:f.string(),points:f.array(f.string())}),mZ2={title:"Relay is a collaborative team-memory brain.",intro:"It exists for teams that need to remember together: capturing what happened, summarizing why it matters, and coordinating with trusted peer brains when work crosses boundaries.",points:["Not a personal blog engine or portfolio shell.","Not a marketing automation stack.","A small public face for a larger private knowledge workflow."]},uZ2="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function GG1({href:A,label:Q}){return Q1("a",{href:A,className:uZ2,children:Q},void 0,!1,void 0,this)}function cZ2({siteInfo:A,children:Q}){let B=[...A.navigation.primary,...A.navigation.secondary],w=A.cta??{buttonText:"Start here",buttonLink:"/about"};return Q1(yk,{children:[Q1("nav",{className:"fixed left-0 right-0 top-0 z-[100] flex items-center justify-between border-b border-theme-light bg-nav-fade px-6 py-4 backdrop-blur-[12px] md:px-10 xl:px-20",children:[Q1("a",{href:"/",className:"font-nav text-[20px]","aria-label":"Relay home",children:[Q1("span",{className:"font-bold text-theme",children:"relay"},void 0,!1,void 0,this),Q1("span",{className:"font-bold text-accent",children:"."},void 0,!1,void 0,this),Q1("span",{className:"text-theme-muted",children:"brain"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"flex items-center gap-5 md:gap-8",children:[Q1("div",{className:"hidden items-center gap-6 md:flex",children:B.map(($)=>Q1(GG1,{...$},`${$.href}-${$.label}`,!1,void 0,this))},void 0,!1,void 0,this),Q1("a",{href:w.buttonLink,className:"rounded-[999px] border border-theme px-4 py-2 font-body text-[13px] font-semibold text-theme transition-colors hover:border-accent hover:text-accent md:px-5",children:w.buttonText},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("main",{children:Q},void 0,!1,void 0,this),Q1("footer",{className:"relative z-[1] border-t border-theme-light px-6 py-8 md:px-10 xl:px-20",children:Q1("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[Q1("div",{children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.22em] text-theme-light",children:A.copyright},void 0,!1,void 0,this),Q1("p",{className:"mt-2 max-w-[560px] font-body text-body-xs text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"flex flex-wrap items-center gap-5",children:[B.map(($)=>Q1(GG1,{...$},`footer-${$.href}-${$.label}`,!1,void 0,this)),Q1("button",{id:"themeToggle","aria-label":"Toggle light mode",className:"rounded-md border border-theme-light bg-transparent px-2.5 py-1.5 font-body text-label-md text-theme-light transition-colors hover:border-theme hover:text-theme",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var pZ2=({sections:A,siteInfo:Q})=>Q1(cZ2,{siteInfo:Q,children:A},void 0,!1,void 0,this);function lZ2({eyebrow:A,headline:Q,intro:B,primaryCta:w,secondaryCta:$,signals:I}){return Q1(LN,{className:"min-h-[92vh] pt-[152px] pb-20 md:pt-[190px]",children:Q1("div",{className:"grid gap-10 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-end",children:[Q1("div",{children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),Q1("h1",{className:"mt-7 max-w-[980px] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),Q1("p",{className:"mt-7 max-w-[720px] font-body text-body-lg text-theme-muted",children:B},void 0,!1,void 0,this),Q1("div",{className:"mt-10 flex flex-col gap-3 sm:flex-row",children:[Q1(jV,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),Q1(jV,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"rounded-[32px] border border-card-relay-border bg-card-relay-bg p-5 shadow-[0_24px_90px_var(--color-glow-relay)] backdrop-blur-sm",children:[Q1("p",{className:"font-label text-label-xs uppercase tracking-[0.24em] text-theme-light",children:"Live relay signals"},void 0,!1,void 0,this),Q1("div",{className:"mt-5 grid gap-3",children:I.map((D)=>Q1("div",{className:"rounded-[22px] border border-card-divider bg-bg-muted p-5",children:[Q1("div",{className:"flex items-center justify-between gap-4",children:[Q1("p",{className:"font-label text-label-xs uppercase tracking-[0.18em] text-secondary",children:D.label},void 0,!1,void 0,this),Q1("span",{className:"h-2 w-2 rounded-full bg-accent shadow-[0_0_22px_var(--color-accent)]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("p",{className:"mt-4 font-display text-display-sm text-theme",children:D.value},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-body text-body-xs text-theme-muted",children:D.note},void 0,!1,void 0,this)]},D.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function iZ2({eyebrow:A,title:Q,intro:B,steps:w}){return Q1(LN,{id:"operating-loop",className:"py-section",children:[Q1("div",{className:"max-w-[840px]",children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-secondary",children:A},void 0,!1,void 0,this),Q1("h2",{className:"mt-5 font-display text-display-md text-theme",children:Q},void 0,!1,void 0,this),Q1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:w.map(($)=>Q1("article",{className:"min-h-[300px] rounded-[28px] border border-card-panel-border bg-card-panel-bg p-6",children:[Q1("p",{className:"font-label text-label-sm text-accent",children:$.phase},void 0,!1,void 0,this),Q1("h3",{className:"mt-16 font-display text-display-sm text-theme",children:$.title},void 0,!1,void 0,this),Q1("p",{className:"mt-4 font-body text-body-sm text-theme-muted",children:$.text},void 0,!1,void 0,this)]},$.phase,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function dZ2({title:A,intro:Q,cards:B}){return Q1(LN,{className:"py-section",children:Q1("div",{className:"rounded-[36px] border border-theme-light bg-bg-muted p-6 md:p-10",children:Q1("div",{className:"grid gap-8 lg:grid-cols-[360px_1fr]",children:[Q1("div",{children:[Q1("h2",{className:"font-display text-display-md text-theme",children:A},void 0,!1,void 0,this),Q1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"grid gap-4",children:B.map((w)=>Q1("article",{className:"rounded-[24px] border border-card-divider bg-bg-subtle/70 p-5",children:[Q1("p",{className:"font-label text-label-xs uppercase tracking-[0.22em] text-accent",children:w.label},void 0,!1,void 0,this),Q1("h3",{className:"mt-3 font-nav text-heading-lg text-theme",children:w.title},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-body text-body-sm text-theme-muted",children:w.text},void 0,!1,void 0,this)]},w.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function rZ2({title:A,intro:Q,points:B}){return Q1(LN,{className:"min-h-[78vh] pt-[150px] pb-section md:pt-[190px]",children:[Q1("div",{className:"max-w-[920px]",children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:"Relay model"},void 0,!1,void 0,this),Q1("h1",{className:"mt-6 font-display text-display-lg text-theme",children:A},void 0,!1,void 0,this),Q1("p",{className:"mt-7 font-body text-body-lg text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:B.map((w)=>Q1("div",{className:"rounded-[24px] border border-card-panel-current-border bg-card-panel-current-bg p-6 font-body text-body-md text-theme",children:w},w,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var nZ2=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},oZ2=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),_p=(A,Q,B=`${Q}s`)=>`${oZ2(A)} ${A===1?Q:B}`;function sZ2({eyebrow:A,headline:Q,intro:B,primaryCta:w,secondaryCta:$,inputs:I,outputs:D,core:Y,legend:X,counts:W}){let U=[{key:"captures",className:"top-[-10px] left-1/2 -translate-x-1/2",label:_p(W.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:_p(W.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:_p(W.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:_p(W.summaries,"summary","summaries")}];return Q1(LN,{className:"pt-[150px] pb-section md:pt-[190px]",id:"diagram",children:[Q1("div",{className:"mx-auto max-w-[1040px] text-center",children:[Q1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),Q1("h1",{className:"mx-auto mt-7 max-w-[22ch] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),Q1("p",{className:"mx-auto mt-7 max-w-[64ch] font-body text-body-lg text-theme-muted",children:B},void 0,!1,void 0,this),Q1("div",{className:"mt-10 flex flex-col justify-center gap-3 sm:flex-row",children:[Q1(jV,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),Q1(jV,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mx-auto mt-20 max-w-[1020px] rounded-[32px] border border-theme-light bg-[radial-gradient(circle_at_1px_1px,rgb(255_255_255_/_0.05)_1px,transparent_0),linear-gradient(180deg,rgb(255_255_255_/_0.02),transparent)] bg-[length:24px_24px,100%_100%] px-6 py-14",children:[Q1("div",{className:"grid items-center gap-8 lg:grid-cols-[1fr_1.4fr_1fr]",children:[Q1("div",{className:"flex flex-col gap-3.5",children:I.map((K)=>Q1("div",{className:"rounded-2xl border border-card-panel-border border-l-2 border-l-accent bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[Q1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:K.label},void 0,!1,void 0,this),Q1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:K.title},void 0,!1,void 0,this),Q1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:K.detail},void 0,!1,void 0,this)]},`${K.label}-${K.title}`,!0,void 0,this))},void 0,!1,void 0,this),Q1("div",{className:"relative mx-auto grid aspect-square w-full max-w-[320px] place-items-center rounded-full bg-[radial-gradient(circle_at_center,rgb(232_119_34_/_0.25),transparent_65%)]",children:[Q1("div",{className:"absolute inset-0 rounded-full border border-dashed border-accent/30"},void 0,!1,void 0,this),Q1("div",{className:"absolute inset-6 animate-spin rounded-full border border-dashed border-secondary/40 [animation-duration:28s]"},void 0,!1,void 0,this),U.map((K)=>Q1("span",{className:`absolute whitespace-nowrap rounded-full border border-theme bg-bg px-2.5 py-1 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light ${K.className}`,children:K.label},K.key,!1,void 0,this)),Q1("div",{className:"relative z-[1] px-6 text-center",children:[Q1("p",{className:"font-label text-[10px] uppercase tracking-[0.28em] text-accent",children:Y.eyebrow},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-display text-[36px] leading-none text-theme",children:Y.name},void 0,!1,void 0,this),Q1("p",{className:"mt-2 font-body text-[13px] text-theme-muted",children:Y.sub},void 0,!1,void 0,this),Q1("p",{className:"mt-4 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light",children:[_p(W.links,"link")," indexed"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"flex flex-col gap-3.5",children:D.map((K)=>Q1("div",{className:"rounded-2xl border border-card-panel-border border-r-2 border-r-secondary bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[Q1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:K.label},void 0,!1,void 0,this),Q1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:K.title},void 0,!1,void 0,this),Q1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:K.detail},void 0,!1,void 0,this)]},`${K.label}-${K.title}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q1("div",{className:"mt-14 grid gap-4 border-t border-theme-light pt-8 md:grid-cols-3",children:X.map((K)=>Q1("div",{className:"text-left",children:[Q1("h2",{className:"font-display text-[16px] font-medium text-theme",children:[Q1("span",{className:`mr-2.5 inline-block h-3 w-3 rounded-[3px] align-middle ${nZ2(K.tone)}`},void 0,!1,void 0,this),K.title]},void 0,!0,void 0,this),Q1("p",{className:"mt-1.5 font-body text-[13px] leading-[1.6] text-theme-muted",children:K.text},void 0,!1,void 0,this)]},K.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var aZ2=R1({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:kyA,formatter:{parse:(A)=>kyA.parse({...d8A(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>UG1(nk.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:sZ2}}),tZ2=(A)=>lZ2(TZ2.parse(A)),eZ2=(A)=>iZ2(SZ2.parse(A)),Az2=(A)=>dZ2(gZ2.parse(A)),Qz2=(A)=>rZ2(hZ2.parse(A)),KG1={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},fG1={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:tZ2,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...KG1,label:"Primary CTA"},secondaryCta:{...KG1,label:"Secondary CTA"},signals:{type:"array",label:"Signals",minItems:1,items:{type:"object",label:"Signal",fields:{label:{type:"string",label:"Label"},value:{type:"string",label:"Value"},note:{type:"string",label:"Note"}}}}}},"home-loop":{title:"Home operating loop",description:"Relay capture, synthesis, and sharing loop",layout:eZ2,fields:{eyebrow:{type:"string",label:"Eyebrow"},title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},steps:{type:"array",label:"Steps",minItems:1,items:{type:"object",label:"Step",fields:{phase:{type:"string",label:"Phase"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},"home-surface":{title:"Home surface",description:"Relay default template explanation cards",layout:Az2,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},cards:{type:"array",label:"Cards",minItems:1,items:{type:"object",label:"Card",fields:{label:{type:"string",label:"Label"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},about:{title:"About Relay",description:"Default Relay about page",layout:Qz2,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},Bz2=[{id:"home",path:"/",title:"Relay",description:"Collaborative team memory and synthesis brain",layout:"default",navigation:{show:!0,label:"Home",slot:"secondary",priority:10},sections:[{id:"diagram",template:"relay-site:home-diagram"}]},{id:"about",path:"/about",title:"About Relay",description:"What Relay is designed to do",layout:"default",navigation:{show:!0,label:"About",slot:"primary",priority:20},sections:[{id:"about",template:"relay-site:about",content:mZ2}]}],FG1=UyA({packageName:"@brains/relay/site",contentNamespace:"relay-site",themeProfile:"studio",layout:pZ2,routes:Bz2,templates:{"home-diagram":aZ2},dataSources:[new _yA]});var ZG1={name:"@brains/relay",private:!0,version:"0.2.0-alpha.93",description:"Relay brain model \u2014 collaborative knowledge management",type:"module",files:["src","brain.eval.yaml","env.schema.template"],exports:{".":"./src/index.ts"},scripts:{"start:core":"cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:docs":"cd test-apps/docs && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",test:"bun test",eval:"brain-eval",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/auth-service":"workspace:*","@brains/cms":"workspace:*","@brains/content-formatters":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/doc":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/note":"workspace:*","@brains/plugins":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-info":"workspace:*","@brains/site-rizom":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/utils":"workspace:*","@brains/webserver":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/test-utils":"workspace:*",typescript:"^5.3.3"}};var zG1=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","discord","a2a"],NG1=[...zG1,"image","site-info","site-content","site-builder"],Iz2=[...NG1,"docs","decks"],Dz2=["Relay is a collaborative team-memory and synthesis brain. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence, and coordinating with peer brains.","Relay is not Rover-for-teams: do not default to personal branding, blog publishing, newsletters, social media, portfolio, or marketing workflows unless the installed plugins and user request explicitly support them.",'Relay entity mappings: "memo", "note", "team note", "capture" \u2192 entityType: base; "summary", "sync", "team digest" \u2192 entityType: summary; "decision" \u2192 entityType: decision; "action item", "todo" \u2192 entityType: action-item; "handbook", "doc", "documentation" \u2192 entityType: doc; "deck", "walkthrough", "presentation" \u2192 entityType: deck; "agent", "peer brain", "contact" \u2192 entityType: agent.'],qG1=NZ({name:"relay",version:ZG1.version,model:"gpt-5.4-mini",site:FG1,theme:Tk,presets:{core:zG1,default:NG1,full:Iz2},evalDisable:["webserver","mcp","discord"],agentInstructions:Dz2,capabilities:[["prompt",RV,void 0],["note",NV,{}],["link",LV,{}],["image",dT,void 0],["topics",qwA,{includeEntityTypes:["base","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",VyA,{}],["docs",PyA,void 0],["decks",mc,void 0],["agents",Q8A,void 0],["assessment",U8A,void 0],["auth-service",yg,void 0],["notifications",St,void 0],["email-resend",HQA,void 0],["cms",OV,{}],["dashboard",zN,void 0],["directory-sync",jE,{seedContent:!0,seedContentPath:$z2(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",Ep,{definitions:fG1}],["rizom-ecosystem",bV,void 0],["site-info",fV,void 0],["site-builder",KV,{}]],interfaces:[["mcp",eZ,()=>({})],["discord",xz,()=>({captureUrls:!0})],["a2a",nP,()=>({})],["webserver",yz,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"anchor"},{pattern:"discord:*",level:"public"}]},deployment:{cdn:{enabled:!0,provider:"bunny"}}});import{readFileSync as hq2}from"fs";import{join as mq2}from"path";import{execSync as uq2}from"child_process";import{parseArgs as Wz2}from"util";var Hz2={model:{type:"string"},domain:{type:"string"},"content-repo":{type:"string"},backend:{type:"string"},"push-to":{type:"string"},"ai-api-key":{type:"string"},"no-interactive":{type:"boolean"},preview:{type:"boolean"},deploy:{type:"boolean"},regen:{type:"boolean"},all:{type:"boolean"},only:{type:"string"},"dry-run":{type:"boolean"},"startup-check":{type:"boolean"},"storage-dir":{type:"string"},yes:{type:"boolean"},remote:{type:"string"},token:{type:"string"},outputDir:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};function DH(A,Q){let B=A[Q];return typeof B==="string"?B:void 0}function MN(A,Q){let B=A[Q];return typeof B==="boolean"?B:void 0}function LG1(A){let{values:Q,positionals:B}=Wz2({args:A,options:Hz2,allowPositionals:!0,strict:!1});if(Q.help)return{command:"help",args:[],flags:{help:!0}};if(Q.version)return{command:"version",args:[],flags:{version:!0}};return{command:B[0]??"help",args:B.slice(1),flags:{model:DH(Q,"model"),domain:DH(Q,"domain"),"content-repo":DH(Q,"content-repo"),backend:DH(Q,"backend"),"push-to":DH(Q,"push-to"),"ai-api-key":DH(Q,"ai-api-key"),"no-interactive":MN(Q,"no-interactive"),preview:MN(Q,"preview"),deploy:MN(Q,"deploy"),regen:MN(Q,"regen"),all:MN(Q,"all"),only:DH(Q,"only"),"dry-run":MN(Q,"dry-run"),"startup-check":MN(Q,"startup-check"),"storage-dir":DH(Q,"storage-dir"),yes:MN(Q,"yes"),remote:DH(Q,"remote"),token:DH(Q,"token"),outputDir:DH(Q,"outputDir")}}}vp();import{mkdirSync as Pq2}from"fs";import{join as jq2}from"path";import{execSync as kq2}from"child_process";var n8A={name:"@rizom/brain",version:"0.2.0-alpha.93",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun scripts/build.ts","dev:start":"bun dist/brain.js start",typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@clack/prompts":"^0.11.0","@modelcontextprotocol/sdk":"^1.24.0","@tailwindcss/postcss":"^4.1.13","@tailwindcss/typography":"^0.5.19",postcss:"^8.5.6",preact:"^10.27.2","preact-render-to-string":"^6.3.1",tailwindcss:"^4.1.11"},optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","playwright-core":"^1.56.0","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"workspace:*","@brains/content-formatters":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"latest",rollup:"^4.60.2","rollup-plugin-dts":"^6.4.1",typescript:"^5.3.3"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",bugs:"https://github.com/rizom-ai/brains/issues",engines:{bun:">=1.3.3"},keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"]};import{mkdirSync as TG1,writeFileSync as yp,chmodSync as Tp,existsSync as cyA,readFileSync as pyA}from"fs";import{basename as lyA,dirname as iyA,join as u8,resolve as lz2}from"path";import{fileURLToPath as iz2}from"url";var EG1=`ARG BUN_VERSION=1.3.10
|
|
9935
9947
|
FROM oven/bun:\${BUN_VERSION}-slim AS runtime
|
|
9936
9948
|
|
|
9937
9949
|
WORKDIR /app
|