@rizom/brain 0.2.0-alpha.41 → 0.2.0-alpha.42

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 CHANGED
@@ -551,7 +551,7 @@ This will delete existing topics and regenerate them from scratch.`,args:{...Y,c
551
551
  hash text NOT NULL,
552
552
  created_at numeric
553
553
  )
554
- `;await A.session.run($);let Y=(await A.values(_A`SELECT id, hash, created_at FROM ${_A.identifier(w)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,I=[];for(let X of B)if(!Y||Number(Y[2])<X.folderMillis){for(let H of X.sql)I.push(A.run(_A.raw(H)));I.push(A.run(_A`INSERT INTO ${_A.identifier(w)} ("hash", "created_at") VALUES(${X.hash}, ${X.folderMillis})`))}await A.session.migrate(I)}var Xg=l(()=>{ecA();R5()});async function AlA(A,Q){let B=Q?.child("entity-migrate")??T2.getInstance().child("entity-migrate"),{db:w,client:$,url:D}=mv(A);B.debug("Running entity database migrations...");try{await uv($,D);let I=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await DV(w,{migrationsFolder:I}),await cv($),B.debug("Entity database migrations completed successfully")}catch(Y){throw B.error("Entity database migration failed:",Y),Y}finally{$.close()}}var QlA=l(()=>{Xg();tt();GA()});async function BlA(A,Q){let B=Q?.child("job-queue-migrate")??T2.getInstance().child("job-queue-migrate"),{db:w,client:$,url:D}=gv(A);B.debug("Running job queue migrations...");try{await yv($,D);let I=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await DV(w,{migrationsFolder:I}),B.debug("Job queue migrations completed successfully")}catch(Y){throw B.error("Job queue migration failed:",Y),Y}finally{$.close()}}var wlA=l(()=>{Xg();ot();GA()});async function $lA(A,Q){let B=Q?.child("conversation-migrate")??T2.getInstance().child("conversation-migrate"),{db:w,client:$,url:D}=av(A);B.debug("Running conversation database migrations...");try{if(D.startsWith("file:"))await $.execute("PRAGMA journal_mode = WAL");let I=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await DV(w,{migrationsFolder:I}),B.debug("Conversation database migrations completed successfully")}catch(Y){throw B.error("Conversation database migration failed:",Y),Y}finally{$.close()}}var DlA=l(()=>{Xg();Oe();GA()});class JR{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:pO,migrateEntities:AlA,migrateJobQueue:BlA,migrateConversations:$lA}}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 H6A=l(()=>{Yg();QlA();wlA();DlA()});var Hg;var K6A=l(()=>{GA();Hg=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 IlA;var YlA=l(()=>{IlA={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.41",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.1.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/react":"^19.0.3",typescript:"^5.3.3"}}});var FQ=x(($U1,Kg)=>{(function(){function A(QA,ZA){Object.defineProperty(w.prototype,QA,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",ZA[0],ZA[1])}})}function Q(QA){if(QA===null||typeof QA!=="object")return null;return QA=sA&&QA[sA]||QA["@@iterator"],typeof QA==="function"?QA:null}function B(QA,ZA){QA=(QA=QA.constructor)&&(QA.displayName||QA.name)||"ReactClass";var nA=QA+"."+ZA;JA[nA]||(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.",ZA,QA),JA[nA]=!0)}function w(QA,ZA,nA){this.props=QA,this.context=ZA,this.refs=vA,this.updater=nA||MA}function $(){}function D(QA,ZA,nA){this.props=QA,this.context=ZA,this.refs=vA,this.updater=nA||MA}function Y(){}function I(QA){return""+QA}function X(QA){try{I(QA);var ZA=!1}catch(m0){ZA=!0}if(ZA){ZA=console;var nA=ZA.error,y0=typeof Symbol==="function"&&Symbol.toStringTag&&QA[Symbol.toStringTag]||QA.constructor.name||"Object";return nA.call(ZA,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",y0),I(QA)}}function H(QA){if(QA==null)return null;if(typeof QA==="function")return QA.$$typeof===eA?null:QA.displayName||QA.name||null;if(typeof QA==="string")return QA;switch(QA){case e:return"Fragment";case KA:return"Profiler";case i:return"StrictMode";case h0:return"Suspense";case NA:return"SuspenseList";case VA:return"Activity"}if(typeof QA==="object")switch(typeof QA.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),QA.$$typeof){case d:return"Portal";case HA:return QA.displayName||"Context";case hA:return(QA._context.displayName||"Context")+".Consumer";case I0:var ZA=QA.render;return QA=QA.displayName,QA||(QA=ZA.displayName||ZA.name||"",QA=QA!==""?"ForwardRef("+QA+")":"ForwardRef"),QA;case _0:return ZA=QA.displayName||null,ZA!==null?ZA:H(QA.type)||"Memo";case X0:ZA=QA._payload,QA=QA._init;try{return H(QA(ZA))}catch(nA){}}return null}function W(QA){if(QA===e)return"<>";if(typeof QA==="object"&&QA!==null&&QA.$$typeof===X0)return"<...>";try{var ZA=H(QA);return ZA?"<"+ZA+">":"<...>"}catch(nA){return"<...>"}}function J(){var QA=rA.A;return QA===null?null:QA.getOwner()}function Z(){return Error("react-stack-top-frame")}function q(QA){if(CA.call(QA,"key")){var ZA=Object.getOwnPropertyDescriptor(QA,"key").get;if(ZA&&ZA.isReactWarning)return!1}return QA.key!==void 0}function V(QA,ZA){function nA(){AA||(AA=!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)",ZA))}nA.isReactWarning=!0,Object.defineProperty(QA,"key",{get:nA,configurable:!0})}function E(){var QA=H(this.type);return c0[QA]||(c0[QA]=!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.")),QA=this.props.ref,QA!==void 0?QA:null}function L(QA,ZA,nA,y0,m0,W1){var E0=nA.ref;return QA={$$typeof:s,type:QA,key:ZA,props:nA,_owner:y0},(E0!==void 0?E0:null)!==null?Object.defineProperty(QA,"ref",{enumerable:!1,get:E}):Object.defineProperty(QA,"ref",{enumerable:!1,value:null}),QA._store={},Object.defineProperty(QA._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(QA,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(QA,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:m0}),Object.defineProperty(QA,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:W1}),Object.freeze&&(Object.freeze(QA.props),Object.freeze(QA)),QA}function j(QA,ZA){return ZA=L(QA.type,ZA,QA.props,QA._owner,QA._debugStack,QA._debugTask),QA._store&&(ZA._store.validated=QA._store.validated),ZA}function _(QA){k(QA)?QA._store&&(QA._store.validated=1):typeof QA==="object"&&QA!==null&&QA.$$typeof===X0&&(QA._payload.status==="fulfilled"?k(QA._payload.value)&&QA._payload.value._store&&(QA._payload.value._store.validated=1):QA._store&&(QA._store.validated=1))}function k(QA){return typeof QA==="object"&&QA!==null&&QA.$$typeof===s}function r(QA){var ZA={"=":"=0",":":"=2"};return"$"+QA.replace(/[=:]/g,function(nA){return ZA[nA]})}function n(QA,ZA){return typeof QA==="object"&&QA!==null&&QA.key!=null?(X(QA.key),r(""+QA.key)):ZA.toString(36)}function h(QA){switch(QA.status){case"fulfilled":return QA.value;case"rejected":throw QA.reason;default:switch(typeof QA.status==="string"?QA.then(Y,Y):(QA.status="pending",QA.then(function(ZA){QA.status==="pending"&&(QA.status="fulfilled",QA.value=ZA)},function(ZA){QA.status==="pending"&&(QA.status="rejected",QA.reason=ZA)})),QA.status){case"fulfilled":return QA.value;case"rejected":throw QA.reason}}throw QA}function T(QA,ZA,nA,y0,m0){var W1=typeof QA;if(W1==="undefined"||W1==="boolean")QA=null;var E0=!1;if(QA===null)E0=!0;else switch(W1){case"bigint":case"string":case"number":E0=!0;break;case"object":switch(QA.$$typeof){case s:case d:E0=!0;break;case X0:return E0=QA._init,T(E0(QA._payload),ZA,nA,y0,m0)}}if(E0){E0=QA,m0=m0(E0);var E1=y0===""?"."+n(E0,0):y0;return D0(m0)?(nA="",E1!=null&&(nA=E1.replace(PA,"$&/")+"/"),T(m0,ZA,nA,"",function(f2){return f2})):m0!=null&&(k(m0)&&(m0.key!=null&&(E0&&E0.key===m0.key||X(m0.key)),nA=j(m0,nA+(m0.key==null||E0&&E0.key===m0.key?"":(""+m0.key).replace(PA,"$&/")+"/")+E1),y0!==""&&E0!=null&&k(E0)&&E0.key==null&&E0._store&&!E0._store.validated&&(nA._store.validated=2),m0=nA),ZA.push(m0)),1}if(E0=0,E1=y0===""?".":y0+":",D0(QA))for(var V1=0;V1<QA.length;V1++)y0=QA[V1],W1=E1+n(y0,V1),E0+=T(y0,ZA,nA,W1,m0);else if(V1=Q(QA),typeof V1==="function")for(V1===QA.entries&&(TA||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),TA=!0),QA=V1.call(QA),V1=0;!(y0=QA.next()).done;)y0=y0.value,W1=E1+n(y0,V1++),E0+=T(y0,ZA,nA,W1,m0);else if(W1==="object"){if(typeof QA.then==="function")return T(h(QA),ZA,nA,y0,m0);throw ZA=String(QA),Error("Objects are not valid as a React child (found: "+(ZA==="[object Object]"?"object with keys {"+Object.keys(QA).join(", ")+"}":ZA)+"). If you meant to render a collection of children, use an array instead.")}return E0}function S(QA,ZA,nA){if(QA==null)return QA;var y0=[],m0=0;return T(QA,y0,"","",function(W1){return ZA.call(nA,W1,m0++)}),y0}function y(QA){if(QA._status===-1){var ZA=QA._ioInfo;ZA!=null&&(ZA.start=ZA.end=performance.now()),ZA=QA._result;var nA=ZA();if(nA.then(function(m0){if(QA._status===0||QA._status===-1){QA._status=1,QA._result=m0;var W1=QA._ioInfo;W1!=null&&(W1.end=performance.now()),nA.status===void 0&&(nA.status="fulfilled",nA.value=m0)}},function(m0){if(QA._status===0||QA._status===-1){QA._status=2,QA._result=m0;var W1=QA._ioInfo;W1!=null&&(W1.end=performance.now()),nA.status===void 0&&(nA.status="rejected",nA.reason=m0)}}),ZA=QA._ioInfo,ZA!=null){ZA.value=nA;var y0=nA.displayName;typeof y0==="string"&&(ZA.name=y0)}QA._status===-1&&(QA._status=0,QA._result=nA)}if(QA._status===1)return ZA=QA._result,ZA===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
554
+ `;await A.session.run($);let Y=(await A.values(_A`SELECT id, hash, created_at FROM ${_A.identifier(w)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,I=[];for(let X of B)if(!Y||Number(Y[2])<X.folderMillis){for(let H of X.sql)I.push(A.run(_A.raw(H)));I.push(A.run(_A`INSERT INTO ${_A.identifier(w)} ("hash", "created_at") VALUES(${X.hash}, ${X.folderMillis})`))}await A.session.migrate(I)}var Xg=l(()=>{ecA();R5()});async function AlA(A,Q){let B=Q?.child("entity-migrate")??T2.getInstance().child("entity-migrate"),{db:w,client:$,url:D}=mv(A);B.debug("Running entity database migrations...");try{await uv($,D);let I=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await DV(w,{migrationsFolder:I}),await cv($),B.debug("Entity database migrations completed successfully")}catch(Y){throw B.error("Entity database migration failed:",Y),Y}finally{$.close()}}var QlA=l(()=>{Xg();tt();GA()});async function BlA(A,Q){let B=Q?.child("job-queue-migrate")??T2.getInstance().child("job-queue-migrate"),{db:w,client:$,url:D}=gv(A);B.debug("Running job queue migrations...");try{await yv($,D);let I=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await DV(w,{migrationsFolder:I}),B.debug("Job queue migrations completed successfully")}catch(Y){throw B.error("Job queue migration failed:",Y),Y}finally{$.close()}}var wlA=l(()=>{Xg();ot();GA()});async function $lA(A,Q){let B=Q?.child("conversation-migrate")??T2.getInstance().child("conversation-migrate"),{db:w,client:$,url:D}=av(A);B.debug("Running conversation database migrations...");try{if(D.startsWith("file:"))await $.execute("PRAGMA journal_mode = WAL");let I=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await DV(w,{migrationsFolder:I}),B.debug("Conversation database migrations completed successfully")}catch(Y){throw B.error("Conversation database migration failed:",Y),Y}finally{$.close()}}var DlA=l(()=>{Xg();Oe();GA()});class JR{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:pO,migrateEntities:AlA,migrateJobQueue:BlA,migrateConversations:$lA}}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 H6A=l(()=>{Yg();QlA();wlA();DlA()});var Hg;var K6A=l(()=>{GA();Hg=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 IlA;var YlA=l(()=>{IlA={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.42",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.1.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/react":"^19.0.3",typescript:"^5.3.3"}}});var FQ=x(($U1,Kg)=>{(function(){function A(QA,ZA){Object.defineProperty(w.prototype,QA,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",ZA[0],ZA[1])}})}function Q(QA){if(QA===null||typeof QA!=="object")return null;return QA=sA&&QA[sA]||QA["@@iterator"],typeof QA==="function"?QA:null}function B(QA,ZA){QA=(QA=QA.constructor)&&(QA.displayName||QA.name)||"ReactClass";var nA=QA+"."+ZA;JA[nA]||(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.",ZA,QA),JA[nA]=!0)}function w(QA,ZA,nA){this.props=QA,this.context=ZA,this.refs=vA,this.updater=nA||MA}function $(){}function D(QA,ZA,nA){this.props=QA,this.context=ZA,this.refs=vA,this.updater=nA||MA}function Y(){}function I(QA){return""+QA}function X(QA){try{I(QA);var ZA=!1}catch(m0){ZA=!0}if(ZA){ZA=console;var nA=ZA.error,y0=typeof Symbol==="function"&&Symbol.toStringTag&&QA[Symbol.toStringTag]||QA.constructor.name||"Object";return nA.call(ZA,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",y0),I(QA)}}function H(QA){if(QA==null)return null;if(typeof QA==="function")return QA.$$typeof===eA?null:QA.displayName||QA.name||null;if(typeof QA==="string")return QA;switch(QA){case e:return"Fragment";case KA:return"Profiler";case i:return"StrictMode";case h0:return"Suspense";case NA:return"SuspenseList";case VA:return"Activity"}if(typeof QA==="object")switch(typeof QA.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),QA.$$typeof){case d:return"Portal";case HA:return QA.displayName||"Context";case hA:return(QA._context.displayName||"Context")+".Consumer";case I0:var ZA=QA.render;return QA=QA.displayName,QA||(QA=ZA.displayName||ZA.name||"",QA=QA!==""?"ForwardRef("+QA+")":"ForwardRef"),QA;case _0:return ZA=QA.displayName||null,ZA!==null?ZA:H(QA.type)||"Memo";case X0:ZA=QA._payload,QA=QA._init;try{return H(QA(ZA))}catch(nA){}}return null}function W(QA){if(QA===e)return"<>";if(typeof QA==="object"&&QA!==null&&QA.$$typeof===X0)return"<...>";try{var ZA=H(QA);return ZA?"<"+ZA+">":"<...>"}catch(nA){return"<...>"}}function J(){var QA=rA.A;return QA===null?null:QA.getOwner()}function Z(){return Error("react-stack-top-frame")}function q(QA){if(CA.call(QA,"key")){var ZA=Object.getOwnPropertyDescriptor(QA,"key").get;if(ZA&&ZA.isReactWarning)return!1}return QA.key!==void 0}function V(QA,ZA){function nA(){AA||(AA=!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)",ZA))}nA.isReactWarning=!0,Object.defineProperty(QA,"key",{get:nA,configurable:!0})}function E(){var QA=H(this.type);return c0[QA]||(c0[QA]=!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.")),QA=this.props.ref,QA!==void 0?QA:null}function L(QA,ZA,nA,y0,m0,W1){var E0=nA.ref;return QA={$$typeof:s,type:QA,key:ZA,props:nA,_owner:y0},(E0!==void 0?E0:null)!==null?Object.defineProperty(QA,"ref",{enumerable:!1,get:E}):Object.defineProperty(QA,"ref",{enumerable:!1,value:null}),QA._store={},Object.defineProperty(QA._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(QA,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(QA,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:m0}),Object.defineProperty(QA,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:W1}),Object.freeze&&(Object.freeze(QA.props),Object.freeze(QA)),QA}function j(QA,ZA){return ZA=L(QA.type,ZA,QA.props,QA._owner,QA._debugStack,QA._debugTask),QA._store&&(ZA._store.validated=QA._store.validated),ZA}function _(QA){k(QA)?QA._store&&(QA._store.validated=1):typeof QA==="object"&&QA!==null&&QA.$$typeof===X0&&(QA._payload.status==="fulfilled"?k(QA._payload.value)&&QA._payload.value._store&&(QA._payload.value._store.validated=1):QA._store&&(QA._store.validated=1))}function k(QA){return typeof QA==="object"&&QA!==null&&QA.$$typeof===s}function r(QA){var ZA={"=":"=0",":":"=2"};return"$"+QA.replace(/[=:]/g,function(nA){return ZA[nA]})}function n(QA,ZA){return typeof QA==="object"&&QA!==null&&QA.key!=null?(X(QA.key),r(""+QA.key)):ZA.toString(36)}function h(QA){switch(QA.status){case"fulfilled":return QA.value;case"rejected":throw QA.reason;default:switch(typeof QA.status==="string"?QA.then(Y,Y):(QA.status="pending",QA.then(function(ZA){QA.status==="pending"&&(QA.status="fulfilled",QA.value=ZA)},function(ZA){QA.status==="pending"&&(QA.status="rejected",QA.reason=ZA)})),QA.status){case"fulfilled":return QA.value;case"rejected":throw QA.reason}}throw QA}function T(QA,ZA,nA,y0,m0){var W1=typeof QA;if(W1==="undefined"||W1==="boolean")QA=null;var E0=!1;if(QA===null)E0=!0;else switch(W1){case"bigint":case"string":case"number":E0=!0;break;case"object":switch(QA.$$typeof){case s:case d:E0=!0;break;case X0:return E0=QA._init,T(E0(QA._payload),ZA,nA,y0,m0)}}if(E0){E0=QA,m0=m0(E0);var E1=y0===""?"."+n(E0,0):y0;return D0(m0)?(nA="",E1!=null&&(nA=E1.replace(PA,"$&/")+"/"),T(m0,ZA,nA,"",function(f2){return f2})):m0!=null&&(k(m0)&&(m0.key!=null&&(E0&&E0.key===m0.key||X(m0.key)),nA=j(m0,nA+(m0.key==null||E0&&E0.key===m0.key?"":(""+m0.key).replace(PA,"$&/")+"/")+E1),y0!==""&&E0!=null&&k(E0)&&E0.key==null&&E0._store&&!E0._store.validated&&(nA._store.validated=2),m0=nA),ZA.push(m0)),1}if(E0=0,E1=y0===""?".":y0+":",D0(QA))for(var V1=0;V1<QA.length;V1++)y0=QA[V1],W1=E1+n(y0,V1),E0+=T(y0,ZA,nA,W1,m0);else if(V1=Q(QA),typeof V1==="function")for(V1===QA.entries&&(TA||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),TA=!0),QA=V1.call(QA),V1=0;!(y0=QA.next()).done;)y0=y0.value,W1=E1+n(y0,V1++),E0+=T(y0,ZA,nA,W1,m0);else if(W1==="object"){if(typeof QA.then==="function")return T(h(QA),ZA,nA,y0,m0);throw ZA=String(QA),Error("Objects are not valid as a React child (found: "+(ZA==="[object Object]"?"object with keys {"+Object.keys(QA).join(", ")+"}":ZA)+"). If you meant to render a collection of children, use an array instead.")}return E0}function S(QA,ZA,nA){if(QA==null)return QA;var y0=[],m0=0;return T(QA,y0,"","",function(W1){return ZA.call(nA,W1,m0++)}),y0}function y(QA){if(QA._status===-1){var ZA=QA._ioInfo;ZA!=null&&(ZA.start=ZA.end=performance.now()),ZA=QA._result;var nA=ZA();if(nA.then(function(m0){if(QA._status===0||QA._status===-1){QA._status=1,QA._result=m0;var W1=QA._ioInfo;W1!=null&&(W1.end=performance.now()),nA.status===void 0&&(nA.status="fulfilled",nA.value=m0)}},function(m0){if(QA._status===0||QA._status===-1){QA._status=2,QA._result=m0;var W1=QA._ioInfo;W1!=null&&(W1.end=performance.now()),nA.status===void 0&&(nA.status="rejected",nA.reason=m0)}}),ZA=QA._ioInfo,ZA!=null){ZA.value=nA;var y0=nA.displayName;typeof y0==="string"&&(ZA.name=y0)}QA._status===-1&&(QA._status=0,QA._result=nA)}if(QA._status===1)return ZA=QA._result,ZA===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
555
555
 
556
556
  Your code should look like:
557
557
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -1605,7 +1605,7 @@ Example bad output: "A dreamlike crystal formation glowing with ethereal light i
1605
1605
  Title: "${A.entityTitle??I}"
1606
1606
 
1607
1607
  Content:
1608
- ${A.entityContent}`,_Z1);X=w+j.imagePrompt}catch(j){this.logger.warn("AI prompt distillation failed, using fallback",{error:L0(j)})}}await this.reportProgress(B,{progress:F2.PROCESS,message:"Generating image"});let H=this.context.identity.get(),W=this.context.identity.getProfile(),Z=InA(H,W)+X,q;try{q=await this.context.ai.generateImage(Z,{...$&&{aspectRatio:$}})}catch(j){return this.logger.error("Image generation failed",{jobId:Q,error:L0(j)}),K6.failure(j)}await this.reportProgress(B,{progress:F2.GENERATE,message:"Creating image entity"});let V=e1(I),E=rW.createImageEntity({dataUrl:q.dataUrl,title:I});if(await this.context.entityService.getEntity("image",V))this.logger.debug("Deleting existing image for regeneration",{imageId:V}),await this.context.entityService.deleteEntity("image",V);if(await this.context.entityService.createEntity({...E,id:V}),this.logger.debug("Created image entity",{imageId:V}),D&&Y){await this.reportProgress(B,{progress:F2.SAVE,message:`Updating ${D} with cover image`});let j=await nv(this.context.entityService,D,Y,this.logger);if(!j)return K6.failure(Error(`Target entity not found: ${D}/${Y}`));let _=Sz(j,V);await this.context.entities.update(_),this.logger.debug("Updated target entity with cover image",{targetEntityType:D,targetEntityId:Y,imageId:V})}return await this.reportProgress(B,{progress:F2.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:V,targetEntityType:D,targetEntityId:Y}),{success:!0,imageId:V}}catch(X){return this.logger.error("Image generation job failed",{jobId:Q,error:L0(X)}),K6.failure(X)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}var XnA={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.41",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/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 TZ1=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 qwA extends HQ{entityType=rW.entityType;schema=Qj;adapter=rW;constructor(A={}){super("image",XnA,A,TZ1)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,B){if(!A.targetEntityType||!A.targetEntityId)return{kind:"continue",input:A};let w=await lH(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 Cy(A,this.logger)}async onRegister(A){let Q=new Cy(A,this.logger);A.jobs.registerHandler("image-generate",Q)}}function $j(A){return new qwA(A)}B0();import{StdioServerTransport as vZ1}from"@modelcontextprotocol/sdk/server/stdio.js";function HnA(){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 zwA(){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 Oy(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 zwA()}class JY{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return JY.instance??=new JY(A),JY.instance}static resetInstance(){if(JY.instance)JY.instance.stop(),JY.instance=null}static createFresh(A){return new JY(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?Oy(this.config.logger):HnA()}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 vZ1,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 KnA}from"crypto";import{WebStandardStreamableHTTPServerTransport as SZ1}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as hZ1}from"@modelcontextprotocol/sdk/types.js";var gZ1={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Session-Id","X-Content-Type-Options":"nosniff"};class HK{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?Oy(this.config.logger):zwA(),this.authConfig=A.auth??{},!this.authConfig.disabled&&!this.authConfig.token)throw Error("MCP HTTP transport requires an auth token. Set MCP_AUTH_TOKEN in your environment, or pass auth: { disabled: true } for local dev.")}static getInstance(A){return HK.instance??=new HK(A),HK.instance}static resetInstance(){HK.instance=null}static createFresh(A){return new HK(A)}withCors(A){let Q=new Headers(A.headers);for(let[B,w]of Object.entries(gZ1))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"}}))}getUnauthorizedResponse(A){return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},401)}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||!this.authConfig.token)return null;let B=A.headers.get("authorization");if(!B?.startsWith("Bearer "))return this.logger.warn("Authentication failed: Missing Bearer token"),this.getUnauthorizedResponse("Unauthorized: Bearer token required");if(B.substring(7)!==this.authConfig.token)return this.logger.warn("Authentication failed: Invalid token"),this.getUnauthorizedResponse("Unauthorized: Invalid token");return this.logger.debug("Authentication successful"),null}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&&hZ1(B))w=new SZ1({sessionIdGenerator:()=>KnA(),onsessioninitialized:(D)=>{this.logger.info(`Session initialized: ${D}`),this.transports[D]=w},onsessionclosed:(D)=>{this.logger.info(`Session closed: ${D}`),delete this.transports[D]}}),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??KnA();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=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}}GA();var NwA=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 UnA(A,Q){return[]}B0();function VwA(A,Q){A.messaging.subscribe("job-progress",async(B)=>{let w=$N.safeParse(B.payload);if(!w.success)return Q.warn("Received invalid job-progress message",{error:w.error.message}),{success:!1};let $=w.data,D=$.type,Y=$.status,I=$.id;if(Q.debug(`${D} ${I} - ${Y}:`,{id:$.id,message:$.message,progress:$.progress,metadata:$.metadata}),$.batchDetails)Q.debug(`Batch details for ${I}:`,{totalOperations:$.batchDetails.totalOperations,completedOperations:$.batchDetails.completedOperations,failedOperations:$.batchDetails.failedOperations,currentOperation:$.batchDetails.currentOperation,errors:$.batchDetails.errors});if($.jobDetails)Q.debug(`Job details for ${I}:`,{jobType:$.jobDetails.jobType,priority:$.jobDetails.priority,retryCount:$.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var WnA={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.41",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/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 nW extends gI{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",WnA,Q,NwA)}async getTools(){return UnA(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});VwA(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;return this.httpServer=HK.createFresh({port:this.config.httpPort,logger:this.logger,auth:this.config.authToken?{token:this.config.authToken}:{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)B="anchor",this.logger.debug("HTTP auth token 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=JY.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.agentService),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(){JY.resetInstance(),HK.resetInstance()}}B0();GA();var a4=o0(_Z0(),1);GA();B0();var BIA=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),...AS.shape,captureUrlEmoji:F.string().default("\uD83D\uDD16")});var bZ0={name:"@brains/discord",private:!0,version:"0.2.0-alpha.41",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 wIA=2000,At1=8000,Qt1=100;function _c(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class kG extends tD{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",bZ0,A,BIA);this.fetchText=Q.fetchText??Yv}async onRegister(A){await super.onRegister(A),this.client=new a4.Client({intents:[a4.GatewayIntentBits.Guilds,a4.GatewayIntentBits.GuildMessages,a4.GatewayIntentBits.MessageContent,a4.GatewayIntentBits.DirectMessages],partials:[a4.Partials.Channel]}),this.client.on(a4.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.once(a4.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(A,Q){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!_c(B))return;let w=$O(Q,wIA);for(let $ of w)B.send($).catch((D)=>this.logger.error("Failed to send message",{error:D}))}async sendMessageWithId(A,Q){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!_c(B))return;let w=$O(Q,wIA),$;for(let D of w)$=(await B.send(D)).id;return $}async editMessage(A,Q,B){if(!A||!this.client)return!1;let w=this.client.channels.cache.get(A);if(!_c(w))return!1;try{return await(await w.messages.fetch(Q)).edit(B.slice(0,wIA)),!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;if(this.config.allowedChannels.length>0&&!Q&&!this.config.allowedChannels.includes(A.channel.id))return;if(!Q&&!$&&this.config.requireMention&&!w){if(this.config.captureUrls){let I=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(I.length>0){await A.react(this.config.captureUrlEmoji).catch((X)=>this.logger.debug("React failed",{error:X}));for(let X of I)await this.captureUrlViaAgent(X,A.channel.id,A.author.id,"discord").catch((H)=>this.logger.error("URL capture failed",{error:H,url:X}))}}return}let D=this.stripMention(A.content);if(A.attachments.size>0){let I=this.context.permissions.getUserLevel("discord",A.author.id);if(I==="anchor"||I==="trusted")for(let H of A.attachments.values()){let W=H.name,J=H.contentType??void 0,Z=H.size;if(!this.isUploadableTextFile(W,J))continue;if(!this.isFileSizeAllowed(Z))continue;try{let q=await this.fetchText(H.url);D+=`
1608
+ ${A.entityContent}`,_Z1);X=w+j.imagePrompt}catch(j){this.logger.warn("AI prompt distillation failed, using fallback",{error:L0(j)})}}await this.reportProgress(B,{progress:F2.PROCESS,message:"Generating image"});let H=this.context.identity.get(),W=this.context.identity.getProfile(),Z=InA(H,W)+X,q;try{q=await this.context.ai.generateImage(Z,{...$&&{aspectRatio:$}})}catch(j){return this.logger.error("Image generation failed",{jobId:Q,error:L0(j)}),K6.failure(j)}await this.reportProgress(B,{progress:F2.GENERATE,message:"Creating image entity"});let V=e1(I),E=rW.createImageEntity({dataUrl:q.dataUrl,title:I});if(await this.context.entityService.getEntity("image",V))this.logger.debug("Deleting existing image for regeneration",{imageId:V}),await this.context.entityService.deleteEntity("image",V);if(await this.context.entityService.createEntity({...E,id:V}),this.logger.debug("Created image entity",{imageId:V}),D&&Y){await this.reportProgress(B,{progress:F2.SAVE,message:`Updating ${D} with cover image`});let j=await nv(this.context.entityService,D,Y,this.logger);if(!j)return K6.failure(Error(`Target entity not found: ${D}/${Y}`));let _=Sz(j,V);await this.context.entities.update(_),this.logger.debug("Updated target entity with cover image",{targetEntityType:D,targetEntityId:Y,imageId:V})}return await this.reportProgress(B,{progress:F2.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:V,targetEntityType:D,targetEntityId:Y}),{success:!0,imageId:V}}catch(X){return this.logger.error("Image generation job failed",{jobId:Q,error:L0(X)}),K6.failure(X)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}var XnA={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.42",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/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 TZ1=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 qwA extends HQ{entityType=rW.entityType;schema=Qj;adapter=rW;constructor(A={}){super("image",XnA,A,TZ1)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,B){if(!A.targetEntityType||!A.targetEntityId)return{kind:"continue",input:A};let w=await lH(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 Cy(A,this.logger)}async onRegister(A){let Q=new Cy(A,this.logger);A.jobs.registerHandler("image-generate",Q)}}function $j(A){return new qwA(A)}B0();import{StdioServerTransport as vZ1}from"@modelcontextprotocol/sdk/server/stdio.js";function HnA(){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 zwA(){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 Oy(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 zwA()}class JY{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return JY.instance??=new JY(A),JY.instance}static resetInstance(){if(JY.instance)JY.instance.stop(),JY.instance=null}static createFresh(A){return new JY(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?Oy(this.config.logger):HnA()}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 vZ1,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 KnA}from"crypto";import{WebStandardStreamableHTTPServerTransport as SZ1}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as hZ1}from"@modelcontextprotocol/sdk/types.js";var gZ1={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Session-Id","X-Content-Type-Options":"nosniff"};class HK{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?Oy(this.config.logger):zwA(),this.authConfig=A.auth??{},!this.authConfig.disabled&&!this.authConfig.token)throw Error("MCP HTTP transport requires an auth token. Set MCP_AUTH_TOKEN in your environment, or pass auth: { disabled: true } for local dev.")}static getInstance(A){return HK.instance??=new HK(A),HK.instance}static resetInstance(){HK.instance=null}static createFresh(A){return new HK(A)}withCors(A){let Q=new Headers(A.headers);for(let[B,w]of Object.entries(gZ1))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"}}))}getUnauthorizedResponse(A){return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},401)}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||!this.authConfig.token)return null;let B=A.headers.get("authorization");if(!B?.startsWith("Bearer "))return this.logger.warn("Authentication failed: Missing Bearer token"),this.getUnauthorizedResponse("Unauthorized: Bearer token required");if(B.substring(7)!==this.authConfig.token)return this.logger.warn("Authentication failed: Invalid token"),this.getUnauthorizedResponse("Unauthorized: Invalid token");return this.logger.debug("Authentication successful"),null}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&&hZ1(B))w=new SZ1({sessionIdGenerator:()=>KnA(),onsessioninitialized:(D)=>{this.logger.info(`Session initialized: ${D}`),this.transports[D]=w},onsessionclosed:(D)=>{this.logger.info(`Session closed: ${D}`),delete this.transports[D]}}),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??KnA();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=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}}GA();var NwA=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 UnA(A,Q){return[]}B0();function VwA(A,Q){A.messaging.subscribe("job-progress",async(B)=>{let w=$N.safeParse(B.payload);if(!w.success)return Q.warn("Received invalid job-progress message",{error:w.error.message}),{success:!1};let $=w.data,D=$.type,Y=$.status,I=$.id;if(Q.debug(`${D} ${I} - ${Y}:`,{id:$.id,message:$.message,progress:$.progress,metadata:$.metadata}),$.batchDetails)Q.debug(`Batch details for ${I}:`,{totalOperations:$.batchDetails.totalOperations,completedOperations:$.batchDetails.completedOperations,failedOperations:$.batchDetails.failedOperations,currentOperation:$.batchDetails.currentOperation,errors:$.batchDetails.errors});if($.jobDetails)Q.debug(`Job details for ${I}:`,{jobType:$.jobDetails.jobType,priority:$.jobDetails.priority,retryCount:$.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var WnA={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.42",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/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 nW extends gI{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",WnA,Q,NwA)}async getTools(){return UnA(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});VwA(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;return this.httpServer=HK.createFresh({port:this.config.httpPort,logger:this.logger,auth:this.config.authToken?{token:this.config.authToken}:{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)B="anchor",this.logger.debug("HTTP auth token 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=JY.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.agentService),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(){JY.resetInstance(),HK.resetInstance()}}B0();GA();var a4=o0(_Z0(),1);GA();B0();var BIA=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),...AS.shape,captureUrlEmoji:F.string().default("\uD83D\uDD16")});var bZ0={name:"@brains/discord",private:!0,version:"0.2.0-alpha.42",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 wIA=2000,At1=8000,Qt1=100;function _c(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class kG extends tD{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",bZ0,A,BIA);this.fetchText=Q.fetchText??Yv}async onRegister(A){await super.onRegister(A),this.client=new a4.Client({intents:[a4.GatewayIntentBits.Guilds,a4.GatewayIntentBits.GuildMessages,a4.GatewayIntentBits.MessageContent,a4.GatewayIntentBits.DirectMessages],partials:[a4.Partials.Channel]}),this.client.on(a4.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.once(a4.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(A,Q){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!_c(B))return;let w=$O(Q,wIA);for(let $ of w)B.send($).catch((D)=>this.logger.error("Failed to send message",{error:D}))}async sendMessageWithId(A,Q){if(!A||!this.client)return;let B=this.client.channels.cache.get(A);if(!_c(B))return;let w=$O(Q,wIA),$;for(let D of w)$=(await B.send(D)).id;return $}async editMessage(A,Q,B){if(!A||!this.client)return!1;let w=this.client.channels.cache.get(A);if(!_c(w))return!1;try{return await(await w.messages.fetch(Q)).edit(B.slice(0,wIA)),!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;if(this.config.allowedChannels.length>0&&!Q&&!this.config.allowedChannels.includes(A.channel.id))return;if(!Q&&!$&&this.config.requireMention&&!w){if(this.config.captureUrls){let I=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(I.length>0){await A.react(this.config.captureUrlEmoji).catch((X)=>this.logger.debug("React failed",{error:X}));for(let X of I)await this.captureUrlViaAgent(X,A.channel.id,A.author.id,"discord").catch((H)=>this.logger.error("URL capture failed",{error:H,url:X}))}}return}let D=this.stripMention(A.content);if(A.attachments.size>0){let I=this.context.permissions.getUserLevel("discord",A.author.id);if(I==="anchor"||I==="trusted")for(let H of A.attachments.values()){let W=H.name,J=H.contentType??void 0,Z=H.size;if(!this.isUploadableTextFile(W,J))continue;if(!this.isFileSizeAllowed(Z))continue;try{let q=await this.fetchText(H.url);D+=`
1609
1609
 
1610
1610
  `+this.formatFileUploadMessage(W,q)}catch(q){this.logger.error("Failed to download attachment",{error:q,filename:W})}}}if(D=D.trim(),!D)return;let Y=A.channel.id;await this.routeToAgent(D,Y,A)}async routeToAgent(A,Q,B){if(!this.context)return;let w=this.context.agentService,$=Q;if(this.config.useThreads&&B.guild&&!B.channel.isThread())try{$=(await B.startThread({name:JW(A,Qt1),autoArchiveDuration:this.config.threadAutoArchive})).id}catch(X){this.logger.error("Failed to create thread",{error:X})}let D=`discord-${$}`,Y=this.context.permissions.getUserLevel("discord",B.author.id),I=B.guild?.name??"DM";this.startProcessingInput($);try{let X=this.client?.channels.cache.get($);if(_c(X))this.startTypingIndicator(X);if(this.pendingConfirmations.has(D)){await this.handleConfirmationResponse(A,D,$);return}let H=await w.chat(A,D,{userPermissionLevel:Y,interfaceType:"discord",channelId:$,channelName:I});if(H.pendingConfirmation)this.pendingConfirmations.set(D,!0);let W=await this.sendMessageWithId($,H.text);if(W&&H.toolResults){for(let J of H.toolResults)if(J.jobId)this.trackAgentResponseForJob(J.jobId,W,$)}}catch(X){this.logger.error("Error handling message",{error:X,channelId:$}),this.sendMessageToChannel($,`**Error:** ${X instanceof Error?X.message:"Unknown error"}`)}finally{this.endProcessingInput(),this.stopTypingIndicator($)}}async handleConfirmationResponse(A,Q,B){let w=XN(A);if(!w){this.sendMessageToChannel(B,"_Please reply with **yes** to confirm or **no/cancel** to abort._");return}this.pendingConfirmations.delete(Q);let $=await this.context?.agentService.confirmPendingAction(Q,w.confirmed);if($)await this.sendMessageWithId(B,$.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}))},At1);this.typingIntervals.set(A.id,Q)}stopTypingIndicator(A){let Q=this.typingIntervals.get(A);if(Q)clearInterval(Q),this.typingIntervals.delete(A)}stripMention(A){if(!this.client?.user)return A;return A.replace(new RegExp(`<@!?${this.client.user.id}>`,"g"),"").trim()}}B0();import{resolve as dL,join as ut1}from"path";var $IA=(A,Q,B)=>{return(w,$)=>{let D=-1;return Y(0);async function Y(I){if(I<=D)throw Error("next() called multiple times");D=I;let X,H=!1,W;if(A[I])W=A[I][0][0],w.req.routeIndex=I;else W=I===A.length&&$||void 0;if(W)try{X=await W(w,()=>Y(I+1))}catch(J){if(J instanceof Error&&Q)w.error=J,X=await Q(J,w),H=!0;else throw J}else if(w.finalized===!1&&B)X=await B(w);if(X&&(w.finalized===!1||H))w.res=X;return w}}};var xZ0=Symbol();var TZ0=async(A,Q=Object.create(null))=>{let{all:B=!1,dot:w=!1}=Q,D=(A instanceof bc?A.raw.headers:A.headers).get("Content-Type");if(D?.startsWith("multipart/form-data")||D?.startsWith("application/x-www-form-urlencoded"))return Bt1(A,{all:B,dot:w});return{}};async function Bt1(A,Q){let B=await A.formData();if(B)return wt1(B,Q);return{}}function wt1(A,Q){let B=Object.create(null);if(A.forEach((w,$)=>{if(!(Q.all||$.endsWith("[]")))B[$]=w;else $t1(B,$,w)}),Q.dot)Object.entries(B).forEach(([w,$])=>{if(w.includes("."))Dt1(B,w,$),delete B[w]});return B}var $t1=(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]},Dt1=(A,Q,B)=>{let w=A,$=Q.split(".");$.forEach((D,Y)=>{if(Y===$.length-1)w[D]=B;else{if(!w[D]||typeof w[D]!=="object"||Array.isArray(w[D])||w[D]instanceof File)w[D]=Object.create(null);w=w[D]}})};var YIA=(A)=>{let Q=A.split("/");if(Q[0]==="")Q.shift();return Q},vZ0=(A)=>{let{groups:Q,path:B}=Yt1(A),w=YIA(B);return It1(w,Q)},Yt1=(A)=>{let Q=[];return A=A.replace(/\{[^}]+\}/g,(B,w)=>{let $=`@${w}`;return Q.push([$,B]),$}),{groups:Q,path:A}},It1=(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},xc={},SZ0=(A,Q)=>{if(A==="*")return"*";let B=A.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(B){let w=`${A}#${Q}`;if(!xc[w])if(B[2])xc[w]=Q&&Q[0]!==":"&&Q[0]!=="*"?[w,B[1],new RegExp(`^${B[2]}(?=/${Q})`)]:[A,B[1],new RegExp(`^${B[2]}$`)];else xc[w]=[A,B[1],!0];return xc[w]}return null},Tc=(A,Q)=>{try{return Q(A)}catch{return A.replace(/(?:%[0-9A-Fa-f]{2})+/g,(B)=>{try{return Q(B)}catch{return B}})}},IIA=(A)=>Tc(A,decodeURI),XIA=(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 D=Q.indexOf("?",w),Y=Q.indexOf("#",w),I=D===-1?Y===-1?void 0:Y:Y===-1?D:Math.min(D,Y),X=Q.slice(B,I);return IIA(X.includes("%25")?X.replace(/%25/g,"%2525"):X)}else if($===63||$===35)break}return Q.slice(B,w)};var hZ0=(A)=>{let Q=XIA(A);return Q.length>1&&Q.at(-1)==="/"?Q.slice(0,-1):Q},KF=(A,Q,...B)=>{if(B.length)Q=KF(Q,...B);return`${A?.[0]==="/"?"":"/"}${A}${Q==="/"?"":`${A?.at(-1)==="/"?"":"/"}${Q?.[0]==="/"?Q.slice(1):Q}`}`},vc=(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 D=$.replace("?","");w+="/"+D,B.push(w)}else w+="/"+$}),B.filter(($,D,Y)=>Y.indexOf($)===D)},DIA=(A)=>{if(!/[%+]/.test(A))return A;if(A.indexOf("+")!==-1)A=A.replace(/\+/g," ");return A.indexOf("%")!==-1?Tc(A,HIA):A},gZ0=(A,Q,B)=>{let w;if(!B&&Q&&!/[%+]/.test(Q)){let Y=A.indexOf("?",8);if(Y===-1)return;if(!A.startsWith(Q,Y+1))Y=A.indexOf(`&${Q}`,Y+1);while(Y!==-1){let I=A.charCodeAt(Y+Q.length+1);if(I===61){let X=Y+Q.length+2,H=A.indexOf("&",X);return DIA(A.slice(X,H===-1?void 0:H))}else if(I==38||isNaN(I))return"";Y=A.indexOf(`&${Q}`,Y+1)}if(w=/[%+]/.test(A),!w)return}let $={};w??=/[%+]/.test(A);let D=A.indexOf("?",8);while(D!==-1){let Y=A.indexOf("&",D+1),I=A.indexOf("=",D);if(I>Y&&Y!==-1)I=-1;let X=A.slice(D+1,I===-1?Y===-1?void 0:Y:I);if(w)X=DIA(X);if(D=Y,X==="")continue;let H;if(I===-1)H="";else if(H=A.slice(I+1,Y===-1?void 0:Y),w)H=DIA(H);if(B){if(!($[X]&&Array.isArray($[X])))$[X]=[];$[X].push(H)}else $[X]??=H}return Q?$[Q]:$},yZ0=gZ0,mZ0=(A,Q)=>{return gZ0(A,Q,!0)},HIA=decodeURIComponent;var uZ0=(A)=>Tc(A,HIA),bc=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.#D()}#B(A){let Q=this.#Q[0][this.routeIndex][1][A],B=this.#$(Q);return B&&/\%/.test(B)?uZ0(B):B}#D(){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)?uZ0(w):w}return A}#$(A){return this.#Q[1]?this.#Q[1][A]:A}query(A){return yZ0(this.url,A)}queries(A){return mZ0(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 TZ0(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((D)=>{if($==="json")D=JSON.stringify(D);return new Response(D)[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[xZ0](){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 cZ0={Stringify:1,BeforeStream:2,Stream:3},lZ0=(A,Q)=>{let B=new String(A);return B.isEscaped=!0,B.callbacks=Q,B};var KIA=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 D=A.callbacks;if(!D?.length)return Promise.resolve(A);if($)$[0]+=A;else $=[A];let Y=Promise.all(D.map((I)=>I({phase:Q,buffer:$,context:w}))).then((I)=>Promise.all(I.filter(Boolean).map((X)=>KIA(X,Q,!1,w,$))).then(()=>$[0]));if(B)return lZ0(await Y,D);else return Y};var Xt1="text/plain; charset=UTF-8",UIA=(A,Q)=>{return{"Content-Type":A,...Q}},ck=(A,Q)=>new Response(A,Q),pZ0=class{#A;#Q;env={};#B;finalized=!1;error;#D;#$;#w;#K;#X;#H;#I;#U;#W;constructor(A,Q){if(this.#A=A,Q)this.#$=Q.executionCtx,this.env=Q.env,this.#H=Q.notFoundHandler,this.#W=Q.path,this.#U=Q.matchResult}get req(){return this.#Q??=new bc(this.#A,this.#W,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||=ck(null,{headers:this.#I??=new Headers})}set res(A){if(this.#w&&A){A=ck(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.#K=A;getLayout=()=>this.#K;setRenderer=(A)=>{this.#X=A};header=(A,Q,B)=>{if(this.finalized)this.#w=ck(this.#w.body,this.#w);let w=this.#w?this.#w.headers:this.#I??=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.#D=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)}#Y(A,Q,B){let w=this.#w?new Headers(this.#w.headers):this.#I??new Headers;if(typeof Q==="object"&&"headers"in Q){let D=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);for(let[Y,I]of D)if(Y.toLowerCase()==="set-cookie")w.append(Y,I);else w.set(Y,I)}if(B)for(let[D,Y]of Object.entries(B))if(typeof Y==="string")w.set(D,Y);else{w.delete(D);for(let I of Y)w.append(D,I)}let $=typeof Q==="number"?Q:Q?.status??this.#D;return ck(A,{status:$,headers:w})}newResponse=(...A)=>this.#Y(...A);body=(A,Q,B)=>this.#Y(A,Q,B);text=(A,Q,B)=>{return!this.#I&&!this.#D&&!Q&&!B&&!this.finalized?new Response(A):this.#Y(A,Q,UIA(Xt1,B))};json=(A,Q,B)=>{return this.#Y(JSON.stringify(A),Q,UIA("application/json",B))};html=(A,Q,B)=>{let w=($)=>this.#Y($,Q,UIA("text/html; charset=UTF-8",B));return typeof A==="object"?KIA(A,cZ0.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.#H??=()=>ck(),this.#H(this)}};var mB="ALL",dZ0="all",iZ0=["get","post","put","delete","options","patch"],Sc="Can not add a route since the matcher is already built.",hc=class extends Error{};var WIA="__COMPOSED_HANDLER";var Ht1=(A)=>{return A.text("404 Not Found",404)},rZ0=(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)},nZ0=class A{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#A="/";routes=[];constructor(Q={}){[...iZ0,dZ0].forEach((D)=>{this[D]=(Y,...I)=>{if(typeof Y==="string")this.#A=Y;else this.#D(D,this.#A,Y);return I.forEach((X)=>{this.#D(D,this.#A,X)}),this}}),this.on=(D,Y,...I)=>{for(let X of[Y].flat()){this.#A=X;for(let H of[D].flat())I.map((W)=>{this.#D(H.toUpperCase(),this.#A,W)})}return this},this.use=(D,...Y)=>{if(typeof D==="string")this.#A=D;else this.#A="*",Y.unshift(D);return Y.forEach((I)=>{this.#D(mB,this.#A,I)}),this};let{strict:w,...$}=Q;Object.assign(this,$),this.getPath=w??!0?Q.getPath??XIA:hZ0}#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=Ht1;errorHandler=rZ0;route(Q,B){let w=this.basePath(Q);return B.routes.map(($)=>{let D;if(B.errorHandler===rZ0)D=$.handler;else D=async(Y,I)=>(await $IA([],B.errorHandler)(Y,()=>$.handler(Y,I))).res,D[WIA]=$.handler;w.#D($.method,$.path,D)}),this}basePath(Q){let B=this.#Q();return B._basePath=KF(this._basePath,Q),B}onError=(Q)=>{return this.errorHandler=Q,this};notFound=(Q)=>{return this.#B=Q,this};mount(Q,B,w){let $,D;if(w)if(typeof w==="function")D=w;else if(D=w.optionHandler,w.replaceRequest===!1)$=(X)=>X;else $=w.replaceRequest;let Y=D?(X)=>{let H=D(X);return Array.isArray(H)?H:[H]}:(X)=>{let H=void 0;try{H=X.executionCtx}catch{}return[X.env,H]};$||=(()=>{let X=KF(this._basePath,Q),H=X==="/"?0:X.length;return(W)=>{let J=new URL(W.url);return J.pathname=J.pathname.slice(H)||"/",new Request(J,W)}})();let I=async(X,H)=>{let W=await B($(X.req.raw),...Y(X));if(W)return W;await H()};return this.#D(mB,KF(Q,"*"),I),this}#D(Q,B,w){Q=Q.toUpperCase(),B=KF(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 D=this.getPath(Q,{env:w}),Y=this.router.match($,D),I=new pZ0(Q,{path:D,matchResult:Y,env:w,executionCtx:B,notFoundHandler:this.#B});if(Y[0].length===1){let H;try{H=Y[0][0][0][0](I,async()=>{I.res=await this.#B(I)})}catch(W){return this.#$(W,I)}return H instanceof Promise?H.then((W)=>W||(I.finalized?I.res:this.#B(I))).catch((W)=>this.#$(W,I)):H??this.#B(I)}let X=$IA(Y[0],this.errorHandler,this.#B);return(async()=>{try{let H=await X(I);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#$(H,I)}})()}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${KF("/",Q)}`,B),w,$)};fire=()=>{addEventListener("fetch",(Q)=>{Q.respondWith(this.#w(Q.request,Q,void 0,Q.request.method))})}};var lk=[];function gc(A,Q){let B=this.buildAllMatchers(),w=($,D)=>{let Y=B[$]||B[mB],I=Y[2][D];if(I)return I;let X=D.match(Y[0]);if(!X)return[[],lk];let H=X.indexOf("",1);return[Y[1][H],X]};return this.match=w,w(A,Q)}var yc="[^/]+",pk=".*",dk="(?:|/.*)",UF=Symbol(),Kt1=new Set(".\\+*[^]$()");function Ut1(A,Q){if(A.length===1)return Q.length===1?A<Q?-1:1:-1;if(Q.length===1)return 1;if(A===pk||A===dk)return 1;else if(Q===pk||Q===dk)return-1;if(A===yc)return 1;else if(Q===yc)return-1;return A.length===Q.length?A<Q?-1:1:Q.length-A.length}var oZ0=class A{#A;#Q;#B=Object.create(null);insert(Q,B,w,$,D){if(Q.length===0){if(this.#A!==void 0)throw UF;if(D)return;this.#A=B;return}let[Y,...I]=Q,X=Y==="*"?I.length===0?["","",pk]:["","",yc]:Y==="/*"?["","",dk]:Y.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(X){let W=X[1],J=X[2]||yc;if(W&&X[2]){if(J===".*")throw UF;if(J=J.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(J))throw UF}if(H=this.#B[J],!H){if(Object.keys(this.#B).some((Z)=>Z!==pk&&Z!==dk))throw UF;if(D)return;if(H=this.#B[J]=new A,W!=="")H.#Q=$.varIndex++}if(!D&&W!=="")w.push([W,H.#Q])}else if(H=this.#B[Y],!H){if(Object.keys(this.#B).some((W)=>W.length>1&&W!==pk&&W!==dk))throw UF;if(D)return;H=this.#B[Y]=new A}H.insert(I,B,w,$,D)}buildRegExpStr(){let B=Object.keys(this.#B).sort(Ut1).map((w)=>{let $=this.#B[w];return(typeof $.#Q==="number"?`(${w})@${$.#Q}`:Kt1.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 sZ0=class{#A={varIndex:0};#Q=new oZ0;insert(A,Q,B){let w=[],$=[];for(let Y=0;;){let I=!1;if(A=A.replace(/\{[^}]+\}/g,(X)=>{let H=`@\\${Y}`;return $[Y]=[H,X],Y++,I=!0,H}),!I)break}let D=A.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Y=$.length-1;Y>=0;Y--){let[I]=$[Y];for(let X=D.length-1;X>=0;X--)if(D[X].indexOf(I)!==-1){D[X]=D[X].replace(I,$[Y][1]);break}}return this.#Q.insert(D,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,($,D,Y)=>{if(D!==void 0)return B[++Q]=Number(D),"$()";if(Y!==void 0)return w[Number(Y)]=++Q,"";return""}),[new RegExp(`^${A}`),B,w]}};var Wt1=[/^$/,[],Object.create(null)],aZ0=Object.create(null);function tZ0(A){return aZ0[A]??=new RegExp(A==="*"?"":`^${A.replace(/\/\*$|([.\\+*[^\]$()])/g,(Q,B)=>B?`\\${B}`:"(?:|/.*)")}$`)}function Gt1(){aZ0=Object.create(null)}function Jt1(A){let Q=new sZ0,B=[];if(A.length===0)return Wt1;let w=A.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,W],[J,Z])=>H?1:J?-1:W.length-Z.length),$=Object.create(null);for(let H=0,W=-1,J=w.length;H<J;H++){let[Z,q,V]=w[H];if(Z)$[q]=[V.map(([L])=>[L,Object.create(null)]),lk];else W++;let E;try{E=Q.insert(q,W,Z)}catch(L){throw L===UF?new hc(q):L}if(Z)continue;B[W]=V.map(([L,j])=>{let _=Object.create(null);j-=1;for(;j>=0;j--){let[k,r]=E[j];_[k]=r}return[L,_]})}let[D,Y,I]=Q.buildRegExp();for(let H=0,W=B.length;H<W;H++)for(let J=0,Z=B[H].length;J<Z;J++){let q=B[H][J]?.[1];if(!q)continue;let V=Object.keys(q);for(let E=0,L=V.length;E<L;E++)q[V[E]]=I[q[V[E]]]}let X=[];for(let H in Y)X[H]=B[Y[H]];return[D,X,$]}function cL(A,Q){if(!A)return;for(let B of Object.keys(A).sort((w,$)=>$.length-w.length))if(tZ0(B).test(Q))return[...A[B]];return}var mc=class{name="RegExpRouter";#A;#Q;constructor(){this.#A={[mB]:Object.create(null)},this.#Q={[mB]:Object.create(null)}}add(A,Q,B){let w=this.#A,$=this.#Q;if(!w||!$)throw Error(Sc);if(!w[A])[w,$].forEach((I)=>{I[A]=Object.create(null),Object.keys(I[mB]).forEach((X)=>{I[A][X]=[...I[mB][X]]})});if(Q==="/*")Q="*";let D=(Q.match(/\/:/g)||[]).length;if(/\*$/.test(Q)){let I=tZ0(Q);if(A===mB)Object.keys(w).forEach((X)=>{w[X][Q]||=cL(w[X],Q)||cL(w[mB],Q)||[]});else w[A][Q]||=cL(w[A],Q)||cL(w[mB],Q)||[];Object.keys(w).forEach((X)=>{if(A===mB||A===X)Object.keys(w[X]).forEach((H)=>{I.test(H)&&w[X][H].push([B,D])})}),Object.keys($).forEach((X)=>{if(A===mB||A===X)Object.keys($[X]).forEach((H)=>I.test(H)&&$[X][H].push([B,D]))});return}let Y=vc(Q)||[Q];for(let I=0,X=Y.length;I<X;I++){let H=Y[I];Object.keys($).forEach((W)=>{if(A===mB||A===W)$[W][H]||=[...cL(w[W],H)||cL(w[mB],H)||[]],$[W][H].push([B,D-X+I+1])})}}match=gc;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,Gt1(),A}#B(A){let Q=[],B=A===mB;if([this.#A,this.#Q].forEach((w)=>{let $=w[A]?Object.keys(w[A]).map((D)=>[D,w[A][D]]):[];if($.length!==0)B||=!0,Q.push(...$);else if(A!==mB)Q.push(...Object.keys(w[mB]).map((D)=>[D,w[mB][D]]))}),!B)return null;else return Jt1(Q)}};var Zt1=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))}#D(A,Q,B,w,$){let D=this.#A[A];if(!$)D[2][Q][0].push([B,{}]);else w.forEach((Y)=>{if(typeof Y==="number")D[1][Y].push([B,$]);else D[2][Y||Q][0].push([B,$])})}add(A,Q,B){if(!this.#A[A]){let $=this.#A[mB],D={};for(let Y in $[2])D[Y]=[$[2][Y][0].slice(),lk];this.#A[A]=[$[0],$[1].map((Y)=>Array.isArray(Y)?Y.slice():0),D]}if(Q==="/*"||Q==="*"){let $=[B,{}];if(A===mB)for(let D in this.#A)this.#B(D,$);else this.#B(A,$);return}let w=this.#Q[Q];if(!w)throw Error(`Path ${Q} is not registered`);for(let[$,D]of w)if(A===mB)for(let Y in this.#A)this.#D(Y,Q,B,$,D);else this.#D(A,Q,B,$,D)}buildAllMatchers(){return this.#A}match=gc};var GIA=class{name="SmartRouter";#A=[];#Q=[];constructor(A){this.#A=A.routers}add(A,Q,B){if(!this.#Q)throw Error(Sc);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,D=0,Y;for(;D<$;D++){let I=B[D];try{for(let X=0,H=w.length;X<H;X++)I.add(...w[X]);Y=I.match(A,Q)}catch(X){if(X instanceof hc)continue;throw X}this.match=I.match.bind(I),this.#A=[I],this.#Q=void 0;break}if(D===$)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Y}get activeRouter(){if(this.#Q||this.#A.length!==1)throw Error("No active router has been determined yet.");return this.#A[0]}};var ik=Object.create(null),Ft1=(A)=>{for(let Q in A)return!0;return!1},eZ0=class A{#A;#Q;#B;#D=0;#$=ik;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.#D=++this.#D;let $=this,D=vZ0(B),Y=[];for(let I=0,X=D.length;I<X;I++){let H=D[I],W=D[I+1],J=SZ0(H,W),Z=Array.isArray(J)?J[0]:H;if(Z in $.#Q){if($=$.#Q[Z],J)Y.push(J[1]);continue}if($.#Q[Z]=new A,J)$.#B.push(J),Y.push(J[1]);$=$.#Q[Z]}return $.#A.push({[Q]:{handler:w,possibleKeys:Y.filter((I,X,H)=>H.indexOf(I)===X),score:this.#D}}),$}#w(Q,B,w,$,D){for(let Y=0,I=B.#A.length;Y<I;Y++){let X=B.#A[Y],H=X[w]||X[mB],W={};if(H!==void 0){if(H.params=Object.create(null),Q.push(H),$!==ik||D&&D!==ik)for(let J=0,Z=H.possibleKeys.length;J<Z;J++){let q=H.possibleKeys[J],V=W[H.score];H.params[q]=D?.[q]&&!V?D[q]:$[q]??D?.[q],W[H.score]=!0}}}}search(Q,B){let w=[];this.#$=ik;let D=[this],Y=YIA(B),I=[],X=Y.length,H=null;for(let W=0;W<X;W++){let J=Y[W],Z=W===X-1,q=[];for(let E=0,L=D.length;E<L;E++){let j=D[E],_=j.#Q[J];if(_)if(_.#$=j.#$,Z){if(_.#Q["*"])this.#w(w,_.#Q["*"],Q,j.#$);this.#w(w,_,Q,j.#$)}else q.push(_);for(let k=0,r=j.#B.length;k<r;k++){let n=j.#B[k],h=j.#$===ik?{}:{...j.#$};if(n==="*"){let c=j.#Q["*"];if(c)this.#w(w,c,Q,j.#$),c.#$=h,q.push(c);continue}let[T,S,y]=n;if(!J&&!(y instanceof RegExp))continue;let t=j.#Q[T];if(y instanceof RegExp){if(H===null){H=Array(X);let IA=B[0]==="/"?1:0;for(let P=0;P<X;P++)H[P]=IA,IA+=Y[P].length+1}let c=B.substring(H[W]),UA=y.exec(c);if(UA){if(h[S]=UA[0],this.#w(w,t,Q,j.#$,h),Ft1(t.#Q)){t.#$=h;let IA=UA[0].match(/\//)?.length??0;(I[IA]||=[]).push(t)}continue}}if(y===!0||y.test(J))if(h[S]=J,Z){if(this.#w(w,t,Q,h,j.#$),t.#Q["*"])this.#w(w,t.#Q["*"],Q,h,j.#$)}else t.#$=h,q.push(t)}}let V=I.shift();D=V?q.concat(V):q}if(w.length>1)w.sort((W,J)=>{return W.score-J.score});return[w.map(({handler:W,params:J})=>[W,J])]}};var JIA=class{name="TrieRouter";#A;constructor(){this.#A=new eZ0}add(A,Q,B){let w=vc(Q);if(w){for(let $=0,D=w.length;$<D;$++)this.#A.insert(A,w[$],B);return}this.#A.insert(A,Q,B)}match(A,Q){return this.#A.search(A,Q)}};var lL=class extends nZ0{constructor(A={}){super(A);this.router=A.router??new GIA({routers:[new mc,new JIA]})}};import{stat as Lt1}from"fs/promises";import{join as Mt1}from"path";var pL=/^\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 ZIA=(A,Q=zt1)=>{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 qt1={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"},zt1=qt1;var AF0=(...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 QF0={br:".br",zstd:".zst",gzip:".gz"},Nt1=Object.keys(QF0),Vt1="index.html",BF0=(A)=>{let Q=A.root??"./",B=A.path,w=A.join??AF0;return async($,D)=>{if($.finalized)return D();let Y;if(A.path)Y=A.path;else try{if(Y=IIA($.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(Y))throw Error()}catch{return await A.onNotFound?.($.req.path,$),D()}let I=w(Q,!B&&A.rewriteRequestPath?A.rewriteRequestPath(Y):Y);if(A.isDir&&await A.isDir(I))I=w(I,Vt1);let X=A.getContent,H=await X(I,$);if(H instanceof Response)return $.newResponse(H.body,H);if(H){let W=A.mimes&&ZIA(I,A.mimes)||ZIA(I);if($.header("Content-Type",W||"application/octet-stream"),A.precompressed&&(!W||pL.test(W))){let J=new Set($.req.header("Accept-Encoding")?.split(",").map((Z)=>Z.trim()));for(let Z of Nt1){if(!J.has(Z))continue;let q=await X(I+QF0[Z],$);if(q){H=q,$.header("Content-Encoding",Z),$.header("Vary","Accept-Encoding",{append:!0});break}}}return await A.onFound?.(I,$),$.body(H)}await A.onNotFound?.(I,$),await D();return}};var FIA=(A)=>{return async function(B,w){return BF0({...A,getContent:async(Y)=>{let I=Bun.file(Y);return await I.exists()?I:null},join:Mt1,isDir:async(Y)=>{let I;try{I=(await Lt1(Y)).isDirectory()}catch{}return I}})(B,w)}};var qIA="x-hono-disable-ssg",exQ=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[qIA]:"true"}})}catch{return null}})();var{write:TTQ}=Bun;var Ot1=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 wF0=(A)=>{return(...Q)=>{if(typeof Q[0]==="function"){let[B,w]=Q;return async function(D,Y){let I=await B(D),X=await A(D,I,w);if(X)return X;await Y()}}else{let[B,w,$]=Q;return(async()=>{let D=await A(B,w,$);if(!D)throw Error("Failed to upgrade WebSocket");return D})()}}};var uc=(A)=>("server"in A.env)?A.env.server:A.env;var ft1=wF0((A,Q)=>{let B=uc(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 Rt1=["gzip","deflate"],jt1=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,$F0=(A)=>{let Q=A?.threshold??1024;return async function(w,$){await $();let D=w.res.headers.get("Content-Length");if(w.res.headers.has("Content-Encoding")||w.res.headers.has("Transfer-Encoding")||w.req.method==="HEAD"||D&&Number(D)<Q||!kt1(w.res)||!Pt1(w.res))return;let Y=w.req.header("Accept-Encoding"),I=A?.encoding??Rt1.find((H)=>Y?.includes(H));if(!I||!w.res.body)return;let X=new CompressionStream(I);w.res=new Response(w.res.body.pipeThrough(X),w.res),w.res.headers.delete("Content-Length"),w.res.headers.set("Content-Encoding",I)}},kt1=(A)=>{let Q=A.headers.get("Content-Type");return Q&&pL.test(Q)},Pt1=(A)=>{let Q=A.headers.get("Cache-Control");return!Q||!jt1.test(Q)};import{Readable as DF0}from"stream";import{createDeflate as _t1,createGzip as bt1}from"zlib";var xt1=["gzip","deflate"],Tt1=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,YF0=(A)=>{if(typeof CompressionStream<"u")return $F0(A);let Q=A?.threshold??1024;return async function(w,$){await $();let D=w.res.headers.get("Content-Length");if(w.res.headers.has("Content-Encoding")||w.res.headers.has("Transfer-Encoding")||w.req.method==="HEAD"||D&&Number(D)<Q||!vt1(w.res)||!St1(w.res))return;let Y=w.req.header("Accept-Encoding"),I=A?.encoding??xt1.find((X)=>Y?.includes(X));if(!I||!w.res.body)return;try{let X=I==="gzip"?bt1():_t1(),H=w.res.body,J=DF0.fromWeb(H).pipe(X),Z=DF0.toWeb(J);w.res=new Response(Z,w.res),w.res.headers.delete("Content-Length"),w.res.headers.set("Content-Encoding",I)}catch(X){console.error("Compression error:",X)}}},vt1=(A)=>{let Q=A.headers.get("Content-Type");return Q&&pL.test(Q)},St1=(A)=>{let Q=A.headers.get("Cache-Control");return!Q||!Tt1.test(Q)};var ht1=(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},IF0=async(A,Q)=>{if(!A)return null;let B=void 0,w=A.getReader();for(;;){let{value:$,done:D}=await w.read();if(D)break;B=await Q(ht1(B,$))}if(!B)return null;return Array.prototype.map.call(new Uint8Array(B),($)=>$.toString(16).padStart(2,"0")).join("")};var gt1=["cache-control","content-location","date","etag","expires","vary"],XF0=(A)=>A.replace(/^W\//,"");function yt1(A,Q){return Q!=null&&Q.split(/,\s*/).some((B)=>XF0(B)===XF0(A))}function mt1(A){if(!A){if(crypto&&crypto.subtle)A=(Q)=>crypto.subtle.digest({name:"SHA-1"},Q)}return A}var HF0=(A)=>{let Q=A?.retainedHeaders??gt1,B=A?.weak??!1,w=mt1(A?.generateDigest);return async function(D,Y){let I=D.req.header("If-None-Match")??null;await Y();let X=D.res,H=X.headers.get("ETag");if(!H){if(!w)return;let W=await IF0(X.clone().body,w);if(W===null)return;H=B?`W/"${W}"`:`"${W}"`}if(yt1(H,I))D.res=new Response(null,{status:304,statusText:"Not Modified",headers:{ETag:H}}),D.res.headers.forEach((W,J)=>{if(Q.indexOf(J.toLowerCase())===-1)D.res.headers.delete(J)});else D.res.headers.set("ETag",H)}};B0();function cc(A,Q){return async(B)=>{let w=B.req.raw,$=w.headers.get("content-type")??"",D=w.headers.get("accept")?.includes("application/json"),Y={};if($.includes("application/json"))Y=await w.json();else if($.includes("form")){let q=await w.formData();for(let[V,E]of q.entries())Y[V]=E}let I=`${A.pluginId}_${A.definition.tool}`,X=await Q.send(`plugin:${A.pluginId}:tool:execute`,{toolName:I,args:Y,interfaceType:"webserver",userId:"anonymous"},"webserver"),H=typeof X==="object"&&"data"in X?X.data:X,W=WO.safeParse(H),J=W.success?W.data:H,Z=W.success&&W.data.success===!0;if(D)return B.json(J,Z?200:400);if(Z&&A.definition.successRedirect)return B.redirect(A.definition.successRedirect);if(!Z&&A.definition.errorRedirect)return B.redirect(A.definition.errorRedirect);return B.json(J,Z?200:400)}}var KF0="public, max-age=31536000, immutable";class lc{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:dL(process.cwd(),A.productionDistDir),sharedImagesDir:dL(process.cwd(),A.sharedImagesDir),...A.previewDistDir&&{previewDistDir:dL(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 lL;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("/*",YF0());return Q.use("/*",HF0()),Q.use("/*",async(B,w)=>{if(await w(),A.immutableExtensions.test(B.req.path))B.header("Cache-Control",KF0);else B.header("Cache-Control",A.defaultCache)}),Q.use("/*",this.createCleanUrlMiddleware(A.distDir)),Q.use("/*",FIA({root:A.distDir})),Q.notFound(async(B)=>{let w=Bun.file(ut1(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((Y)=>{let I=Y.definition.method??"GET";return Y.fullPath===w&&I===B});if($)return $.definition.handler(A.req.raw);let D=this.getCurrentApiRoutes().find((Y)=>{let I=Y.definition.method??"POST";return Y.fullPath===w&&I===B});if(D&&this.options.messageBus)return cc(D,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=dL(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":KF0}})}createCleanUrlMiddleware(A){return async(Q,B)=>{let w=Q.req.path;if(w.includes(".")||w==="/"){await B();return}let $=dL(A,`.${w}`,"index.html");if(!$.startsWith(A)){await B();return}let D=Bun.file($);if(await D.exists())return Q.html(await D.text());let Y=dL(A,`.${w}.html`);if(Y.startsWith(A)){let I=Bun.file(Y);if(await I.exists())return Q.html(await I.text())}await B()}}}import{existsSync as WF0}from"fs";import{join as GF0}from"path";GA();var zIA=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 NIA=`<!DOCTYPE html>
1611
1611
  <html lang="en">
@@ -1674,7 +1674,7 @@ ${A.entityContent}`,_Z1);X=w+j.imagePrompt}catch(j){this.logger.warn("AI prompt
1674
1674
  <p>Once built, this page will be replaced with your actual website.</p>
1675
1675
  </div>
1676
1676
  </body>
1677
- </html>`;var UF0={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.41",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/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class PG extends gI{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",UF0,A,zIA)}async onRegister(A){if(this.siteUrl=A.siteUrl,this.previewUrl=A.previewUrl,this.siteUrl)A.endpoints.register({label:"Site",url:this.siteUrl,priority:10});if(this.config.enablePreview&&this.previewUrl)A.endpoints.register({label:"Preview",url:this.previewUrl,priority:20});this.serverManager=new lc({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&&!WF0(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(GF0(this.config.previewDistDir,"index.html"),NIA),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!WF0(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(GF0(this.config.productionDistDir,"index.html"),NIA),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}B0();GA();var JF0=F.object({port:F.number().default(3334),organization:F.string().optional(),trustedTokens:F.record(F.string()).optional(),outboundTokens:F.record(F.string()).optional()});B0();function lt1(A,Q){return`${A.name} is ${Q.name}'s ${A.role}. Its purpose is: ${A.purpose}.`}function ZF0(A){let{character:Q,profile:B,version:w,domain:$,organization:D,tools:Y}=A,X=`${A.baseUrl??($?`https://${$}`:"http://localhost:8080")}/a2a`,H=A.skills&&A.skills.length>0?A.skills.map((Z)=>({id:Z.name.toLowerCase().replace(/\s+/g,"-"),name:Z.name,description:Z.description,tags:Z.tags,examples:Z.examples})):Y.map((Z)=>({id:Z.name,name:Z.name,description:Z.description,tags:[],examples:[]})),W={name:B.name};if(A.kind)W.kind=A.kind;if(B.description)W.description=B.description;if(D)W.organization=D;let J=[{uri:BS,description:"Anchor (operator) identity for this brain",params:W}];return{name:Q.name,description:lt1(Q,B),url:X,version:w,protocolVersion:"0.2.2",capabilities:{streaming:!0,pushNotifications:!1,extensions:J},skills:H,defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],...D&&{provider:{organization:D,url:X}},...A.authEnabled&&{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer"}},security:[{bearerAuth:[]}]}}}B0();var VIA=new Set(["completed","failed","canceled","rejected"]);class LIA{tasks=new Map;ttlMs;processingTimeoutMs;constructor(A=3600000,Q=300000){this.ttlMs=A,this.processingTimeoutMs=Q}evictExpired(){let A=Date.now();for(let[Q,B]of this.tasks)if(VIA.has(B.task.status.state)&&A-new Date(B.updatedAt).getTime()>=this.ttlMs)this.tasks.delete(Q)}createTask(A,Q){this.evictExpired();let B=crypto.randomUUID(),w=Q??crypto.randomUUID(),$=new Date().toISOString(),D={kind:"message",messageId:crypto.randomUUID(),role:"user",parts:[{kind:"text",text:A}],contextId:w,taskId:B},I={task:{id:B,contextId:w,kind:"task",status:{state:"submitted",timestamp:$},history:[D]},conversationId:`a2a:${B}`,createdAt:$,updatedAt:$};return this.tasks.set(B,I),I}getTask(A){return this.tasks.get(A)}updateState(A,Q,B){let w=this.tasks.get(A);if(!w)return;let $=new Date().toISOString();if(w.task.status={state:Q,timestamp:$},w.updatedAt=$,Q==="working")w.workingStartedAt=$;if(B){let D={kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"text",text:B}],contextId:w.task.contextId,taskId:A};w.task.status.message=D,w.task.history??=[],w.task.history.push(D)}return w}addArtifact(A,Q,B){let w=this.tasks.get(A);if(!w)return;return w.task.artifacts??=[],w.task.artifacts.push({artifactId:crypto.randomUUID(),name:Q,parts:B}),w.updatedAt=new Date().toISOString(),w}getTaskWithHistory(A,Q){let B=this.tasks.get(A);if(!B)return;if(B.task.status.state==="working"&&B.workingStartedAt&&Date.now()-new Date(B.workingStartedAt).getTime()>=this.processingTimeoutMs)this.updateState(A,"failed","Processing timed out");if(Q===void 0||!B.task.history)return B.task;return{...B.task,history:B.task.history.slice(-Q)}}deleteTask(A){return this.tasks.delete(A)}get size(){return this.tasks.size}}GA();var FF0=F.array(F.object({kind:F.string(),text:F.string().optional(),data:F.record(F.unknown()).optional()})),pt1=F.object({message:F.object({kind:F.literal("message").optional(),messageId:F.string().optional(),role:F.enum(["user","agent"]).optional(),parts:FF0,contextId:F.string().optional(),taskId:F.string().optional()}),configuration:F.object({historyLength:F.number().optional()}).optional()}),qF0=F.object({id:F.string(),historyLength:F.number().optional()});function MIA(A,Q){return{jsonrpc:"2.0",id:A,result:Q}}function qX(A,Q,B){return{jsonrpc:"2.0",id:A,error:{code:Q,message:B}}}var zF0=F.object({jsonrpc:F.string(),id:F.union([F.string(),F.number()]),method:F.string(),params:F.record(F.unknown()).optional()});async function NF0(A,Q){let{id:B,method:w,params:$}=A;switch(w){case"message/send":return dt1(B,$??{},Q);case"tasks/get":return rt1(B,$??{},Q);case"tasks/cancel":return nt1(B,$??{},Q);default:return qX(B,-32601,`Method not found: ${w}`)}}async function dt1(A,Q,B){let w=pt1.safeParse(Q);if(!w.success)return qX(A,-32602,`Invalid params: ${w.error.message}`);let $=w.data.message.parts.filter((W)=>W.kind==="text"&&typeof W.text==="string");if($.length===0)return qX(A,-32602,"Message must contain at least one text part");let D=$.map((W)=>W.text).join(`
1677
+ </html>`;var UF0={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.42",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/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class PG extends gI{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",UF0,A,zIA)}async onRegister(A){if(this.siteUrl=A.siteUrl,this.previewUrl=A.previewUrl,this.siteUrl)A.endpoints.register({label:"Site",url:this.siteUrl,priority:10});if(this.config.enablePreview&&this.previewUrl)A.endpoints.register({label:"Preview",url:this.previewUrl,priority:20});this.serverManager=new lc({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&&!WF0(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(GF0(this.config.previewDistDir,"index.html"),NIA),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!WF0(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(GF0(this.config.productionDistDir,"index.html"),NIA),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}B0();GA();var JF0=F.object({port:F.number().default(3334),organization:F.string().optional(),trustedTokens:F.record(F.string()).optional(),outboundTokens:F.record(F.string()).optional()});B0();function lt1(A,Q){return`${A.name} is ${Q.name}'s ${A.role}. Its purpose is: ${A.purpose}.`}function ZF0(A){let{character:Q,profile:B,version:w,domain:$,organization:D,tools:Y}=A,X=`${A.baseUrl??($?`https://${$}`:"http://localhost:8080")}/a2a`,H=A.skills&&A.skills.length>0?A.skills.map((Z)=>({id:Z.name.toLowerCase().replace(/\s+/g,"-"),name:Z.name,description:Z.description,tags:Z.tags,examples:Z.examples})):Y.map((Z)=>({id:Z.name,name:Z.name,description:Z.description,tags:[],examples:[]})),W={name:B.name};if(A.kind)W.kind=A.kind;if(B.description)W.description=B.description;if(D)W.organization=D;let J=[{uri:BS,description:"Anchor (operator) identity for this brain",params:W}];return{name:Q.name,description:lt1(Q,B),url:X,version:w,protocolVersion:"0.2.2",capabilities:{streaming:!0,pushNotifications:!1,extensions:J},skills:H,defaultInputModes:["text/plain"],defaultOutputModes:["text/plain"],...D&&{provider:{organization:D,url:X}},...A.authEnabled&&{securitySchemes:{bearerAuth:{type:"http",scheme:"bearer"}},security:[{bearerAuth:[]}]}}}B0();var VIA=new Set(["completed","failed","canceled","rejected"]);class LIA{tasks=new Map;ttlMs;processingTimeoutMs;constructor(A=3600000,Q=300000){this.ttlMs=A,this.processingTimeoutMs=Q}evictExpired(){let A=Date.now();for(let[Q,B]of this.tasks)if(VIA.has(B.task.status.state)&&A-new Date(B.updatedAt).getTime()>=this.ttlMs)this.tasks.delete(Q)}createTask(A,Q){this.evictExpired();let B=crypto.randomUUID(),w=Q??crypto.randomUUID(),$=new Date().toISOString(),D={kind:"message",messageId:crypto.randomUUID(),role:"user",parts:[{kind:"text",text:A}],contextId:w,taskId:B},I={task:{id:B,contextId:w,kind:"task",status:{state:"submitted",timestamp:$},history:[D]},conversationId:`a2a:${B}`,createdAt:$,updatedAt:$};return this.tasks.set(B,I),I}getTask(A){return this.tasks.get(A)}updateState(A,Q,B){let w=this.tasks.get(A);if(!w)return;let $=new Date().toISOString();if(w.task.status={state:Q,timestamp:$},w.updatedAt=$,Q==="working")w.workingStartedAt=$;if(B){let D={kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"text",text:B}],contextId:w.task.contextId,taskId:A};w.task.status.message=D,w.task.history??=[],w.task.history.push(D)}return w}addArtifact(A,Q,B){let w=this.tasks.get(A);if(!w)return;return w.task.artifacts??=[],w.task.artifacts.push({artifactId:crypto.randomUUID(),name:Q,parts:B}),w.updatedAt=new Date().toISOString(),w}getTaskWithHistory(A,Q){let B=this.tasks.get(A);if(!B)return;if(B.task.status.state==="working"&&B.workingStartedAt&&Date.now()-new Date(B.workingStartedAt).getTime()>=this.processingTimeoutMs)this.updateState(A,"failed","Processing timed out");if(Q===void 0||!B.task.history)return B.task;return{...B.task,history:B.task.history.slice(-Q)}}deleteTask(A){return this.tasks.delete(A)}get size(){return this.tasks.size}}GA();var FF0=F.array(F.object({kind:F.string(),text:F.string().optional(),data:F.record(F.unknown()).optional()})),pt1=F.object({message:F.object({kind:F.literal("message").optional(),messageId:F.string().optional(),role:F.enum(["user","agent"]).optional(),parts:FF0,contextId:F.string().optional(),taskId:F.string().optional()}),configuration:F.object({historyLength:F.number().optional()}).optional()}),qF0=F.object({id:F.string(),historyLength:F.number().optional()});function MIA(A,Q){return{jsonrpc:"2.0",id:A,result:Q}}function qX(A,Q,B){return{jsonrpc:"2.0",id:A,error:{code:Q,message:B}}}var zF0=F.object({jsonrpc:F.string(),id:F.union([F.string(),F.number()]),method:F.string(),params:F.record(F.unknown()).optional()});async function NF0(A,Q){let{id:B,method:w,params:$}=A;switch(w){case"message/send":return dt1(B,$??{},Q);case"tasks/get":return rt1(B,$??{},Q);case"tasks/cancel":return nt1(B,$??{},Q);default:return qX(B,-32601,`Method not found: ${w}`)}}async function dt1(A,Q,B){let w=pt1.safeParse(Q);if(!w.success)return qX(A,-32602,`Invalid params: ${w.error.message}`);let $=w.data.message.parts.filter((W)=>W.kind==="text"&&typeof W.text==="string");if($.length===0)return qX(A,-32602,"Message must contain at least one text part");let D=$.map((W)=>W.text).join(`
1678
1678
  `),Y=w.data.message.contextId,I=B.taskManager.createTask(D,Y),X=I.task.id;B.taskManager.updateState(X,"working"),it1(X,D,I.conversationId,B);let H=B.taskManager.getTask(X);if(!H)return qX(A,-32603,"Internal error: task disappeared");return MIA(A,H.task)}function it1(A,Q,B,w){w.agentService.chat(Q,B,{userPermissionLevel:w.callerPermissionLevel,interfaceType:"a2a"}).then(($)=>{w.taskManager.updateState(A,"completed",$.text)}).catch(($)=>{let D=$ instanceof Error?$.message:"Unknown error";w.taskManager.updateState(A,"failed",`Error: ${D}`)})}var VF0=F.object({message:F.object({kind:F.string(),parts:FF0,contextId:F.string().optional()})});function LF0(A,Q,B){let $=Q.parts.filter((H)=>H.kind==="text"&&typeof H.text==="string").map((H)=>H.text).join(`
1679
1679
  `)||"No message text",D=B.taskManager.createTask($,Q.contextId),Y=D.task.id;B.taskManager.updateState(Y,"working");let I=new TextEncoder,X=new ReadableStream({start(H){let W=!1;function J(E){if(W)return;try{H.enqueue(I.encode(`data: ${JSON.stringify(E)}
1680
1680
 
@@ -1682,7 +1682,7 @@ ${A.entityContent}`,_Z1);X=w+j.imagePrompt}catch(j){this.logger.warn("AI prompt
1682
1682
 
1683
1683
  `);w=D.pop()??"";for(let Y of D){let I=Y.split(`
1684
1684
  `).find((E)=>E.startsWith("data: "));if(!I)continue;let H=JSON.parse(I.slice(6)).result;if(!H)continue;if(H.final!==!0)continue;Q.cancel().catch(()=>{});let J=H.status,Z=J?.state??"unknown",V=(J?.message?.parts??[]).filter((E)=>E.kind==="text"&&typeof E.text==="string").map((E)=>E.text).join(`
1685
- `)||"No response text";return{success:!0,data:{state:Z,response:V}}}$=await Q.read()}return{success:!1,error:"Stream ended without a terminal event"}}function CF0(A={}){let Q=A.fetch??globalThis.fetch;return{name:"a2a_call",description:"Call a saved remote A2A agent by its local directory id. 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:MF0,visibility:"anchor",handler:async(B)=>{let w=F.object(MF0).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{agent:$,message:D}=w.data,Y=ot1($);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 I=await A.entityService.getEntity("agent",Y);if(!I)return{success:!1,error:`Agent ${Y} is not in your directory. Add it first.`};if(I.metadata.status!=="approved")return{success:!1,error:`Agent ${Y} is discovered but not approved yet. Approve it first.`};let X=`https://${Y}`,H=await st1(X,Q);if(!H)return{success:!1,error:`Could not fetch Agent Card from ${X}`};let W=H.url,J;if(A.outboundTokens)try{let Z=new URL(W).hostname;J=A.outboundTokens[Z]}catch{}return at1(W,D,Q,J)}}}var EIA={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.41",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 Ae1={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff"};class iL extends gI{agentCard;unsubscribeReady;unsubscribeSyncCompleted;taskManager=new LIA;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",EIA,A,JF0)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agentService,this.permissionContext=A.permissions,this.unsubscribeReady=A.messaging.subscribe("system:plugins:ready",()=>{return this.rebuildAgentCard(A),{noop:!0}}),this.unsubscribeSyncCompleted=A.messaging.subscribe("sync:initial:completed",()=>{return this.rebuildAgentCard(A),{success:!0}}),this.hasWebserver)this.logger.info("A2A interface registered",{domain:A.domain});else this.logger.info("A2A interface registered in tool-only mode",{domain:A.domain})}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,D;if(A.entityService.hasEntityType("skill"))try{let Y=await A.entityService.listEntities("skill");if(Y.length>0)D=Y.map((I)=>j$.safeParse(I.metadata)).filter((I)=>I.success).map((I)=>I.data)}catch{}this.agentCard=ZF0({character:Q,profile:B,version:EIA.version,domain:A.domain,organization:this.config.organization,tools:w,skills:D,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(Ae1))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 lL;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=zF0.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 Y=VF0.safeParse(w.data.params??{});if(!Y.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${Y.error.message}`},id:w.data.id}));let{stream:I}=LF0(w.data.id,Y.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(new Response(I,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let D=await NF0(w.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(Q.json(D))}),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[CF0({outboundTokens:this.config.outboundTokens,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, or contact a saved approved agent, 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, or searching general content locally.\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.unsubscribeReady?.(),this.unsubscribeSyncCompleted?.(),this.logger.info("A2A server stopped")}}}}B0();B0();class CIA{logger;syncPath;constructor(A,Q){this.logger=A,this.syncPath=Q}prepareBatchOperations(A,Q){if(A.length===0)return{operations:[],exportOperationsCount:0,importOperationsCount:0,totalFiles:0};let B=[],w=this.createImportOperations(A);B.push(...w);let $=w.length;if(Q?.includeCleanup)B.push({type:"directory-cleanup",data:{}});let D=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:$,totalFiles:D}),{operations:B,exportOperationsCount:0,importOperationsCount:$,totalFiles:D}}async queueSyncBatch(A,Q,B,w,$){let D=this.prepareBatchOperations(B,$);if(D.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch(D.operations,{source:Q,rootJobId:w?.rootJobId??j6(),metadata:{progressToken:w?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:w?.pluginId??"directory-sync",interfaceType:w?.interfaceType,channelId:w?.channelId}}),operationCount:D.operations.length,exportOperationsCount:D.exportOperationsCount,importOperationsCount:D.importOperationsCount,totalFiles:D.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}}GA();import{resolve as GQ2,isAbsolute as JQ2}from"path";import{mkdir as ZQ2}from"fs/promises";var pz0=o0(yz0(),1);aD();import{join as zX,dirname as t22,extname as Kl}from"path";import{mkdir as EXA,readFile as Hl,writeFile as mz0,readdir as e22,stat as uz0,utimes as AQ2,access as QQ2}from"fs/promises";var YP=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function cz0(A){let Q=Kl(A).toLowerCase();return YP.includes(Q)}function BQ2(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 lz0(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}async function eL(A){try{return await QQ2(A),!0}catch{return!1}}class CXA{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){let w=(A.startsWith(this.syncPath)?A:zX(this.syncPath,A)).replace(this.syncPath+"/","").split("/"),$,D;if(w.length===1)$="base",D=w;else if(w.length>1&&w[0])$=w[0],D=w.slice(1);else $="base",D=w;let Y;if(D.length>1){let I=D[D.length-1];if(I){let X=Kl(I).toLowerCase(),H=X===".md"||YP.includes(X)?I.slice(0,-X.length):I;D[D.length-1]=H}Y=D.join(":")}else{let I=D[0]??"",X=Kl(I).toLowerCase();Y=X===".md"||YP.includes(X)?I.slice(0,-X.length):I}return{entityType:$,id:Y}}async readEntity(A){let Q=A.startsWith(this.syncPath)?A:zX(this.syncPath,A),B=await uz0(Q),{entityType:w,id:$}=this.parseEntityFromPath(A),D=B.birthtime.getTime()>0?B.birthtime:B.mtime,Y=B.mtime,I;if(cz0(A)){let H=(await Hl(Q)).toString("base64"),W=Kl(A);I=`data:${BQ2(W)};base64,${H}`}else I=await Hl(Q,"utf-8");return{entityType:w,id:$,content:I,created:D,updated:Y}}async writeEntity(A){let Q=this.getEntityFilePath(A),B=A.entityType==="image",w;if(B){let D=A.content.match(/^data:image\/[a-z+]+;base64,(.+)$/i);w=D?.[1]?Buffer.from(D[1],"base64"):Buffer.from(A.content,"base64")}else w=this.entityService.serializeEntity(A);if(await eL(Q)){let D=B?await Hl(Q):await Hl(Q,"utf-8"),Y=aB(B?D.toString("base64"):D),I=aB(B?w.toString("base64"):w);if(Y===I)return}if(A.entityType!=="base")await EXA(t22(Q),{recursive:!0});if(B)await mz0(Q,w);else await mz0(Q,w,"utf-8");let $=new Date(A.updated);await AQ2(Q,$,$)}getFilePath(A,Q,B=".md"){let w=A.split(":").filter((X)=>X.length>0),$=Q==="base";if(w.length===1)return $?zX(this.syncPath,`${w[0]}${B}`):zX(this.syncPath,Q,`${w[0]}${B}`);let D=w;if(w[0]===Q)D=w.slice(1);let Y=D[D.length-1],I=D.slice(0,-1);if($)return zX(this.syncPath,...I,`${Y}${B}`);else return zX(this.syncPath,Q,...I,`${Y}${B}`)}getEntityFilePath(A){let Q=".md";if(A.entityType==="image"){let B=A.metadata.format;if(B)Q=lz0(B);else{let w=A.content.match(/^data:image\/([a-z+]+);base64,/i);if(w?.[1])Q=lz0(w[1])}}return this.getFilePath(A.id,A.entityType,Q)}async getAllMarkdownFiles(){return this.findFiles({includeImages:!1})}async getAllSyncFiles(){return this.findFiles({includeImages:!0})}async findFiles(A){let Q=[];if(!await eL(this.syncPath))return Q;let B=async(w,$="",D=!1)=>{let Y=await e22(w,{withFileTypes:!0});for(let I of Y){let X=$?zX($,I.name):I.name;if(I.isFile()&&!I.name.endsWith(".invalid")){if(I.name.endsWith(".md"))Q.push(X);else if(A.includeImages&&D&&cz0(I.name))Q.push(X)}else if(I.isDirectory()&&!I.name.startsWith(".")){if($===""&&!this.entityService.hasEntityType(I.name))continue;let H=zX(w,I.name),W=I.name==="image"&&$==="";await B(H,X,D||W)}}};return await B(this.syncPath),Q}async ensureDirectoryStructure(A){if(!await eL(this.syncPath))await EXA(this.syncPath,{recursive:!0});for(let Q of A)if(Q!=="base")await EXA(zX(this.syncPath,Q),{recursive:!0})}shouldUpdateEntity(A,Q){let B=aB(Q.content);return A.contentHash!==B}async gatherFileStatus(){let A=[],Q={totalFiles:0,byEntityType:{}};if(!await eL(this.syncPath))return{files:A,stats:Q};let B=await this.getAllMarkdownFiles();for(let w of B)try{let $=zX(this.syncPath,w),D=await uz0($),{entityType:Y}=this.parseEntityFromPath(w);A.push({path:w,entityType:Y,modified:D.mtime}),Q.totalFiles++,Q.byEntityType[Y]=(Q.byEntityType[Y]??0)+1}catch{continue}return{files:A,stats:Q}}async syncDirectoryExists(){return eL(this.syncPath)}async fileExists(A){return eL(A)}}function wQ2(A,Q){if(!A.replace(Q+"/","").startsWith("image/"))return!1;return YP.some((w)=>A.toLowerCase().endsWith(w))}function $Q2(A,Q){if(A.replace(Q+"/","").split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return wQ2(A,Q)}class OXA{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=pz0.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(!$Q2(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let B=Q.replace(this.syncPath+"/","");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=`${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}}class fXA{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:[]},D=A??await this.fileOperations.getAllMarkdownFiles(),Y=D.length;await Q.report({progress:0,message:`Starting import of ${Y} files`});for(let I=0;I<Y;I+=B){let X=D.slice(I,I+B),H=await w(X);$.imported+=H.imported,$.skipped+=H.skipped,$.failed+=H.failed,$.errors.push(...H.errors),$.jobIds.push(...H.jobIds);let W=Math.min(I+B,Y),J=Math.round(W/Y*40);await Q.report({progress:J,message:`Imported ${W}/${Y} files`})}return $}async exportEntitiesWithProgress(A,Q,B){this.logger.debug("Exporting entities with progress reporting");let w=A??this.entityService.getEntityTypes(),$={exported:0,failed:0,errors:[]},D=w.length;await Q.report({progress:50,message:`Starting export of ${D} entity types`});for(let Y=0;Y<D;Y++){let I=w[Y];if(!I)continue;let X=await this.entityService.listEntities(I,{limit:1000});for(let H=0;H<X.length;H+=B){let W=X.slice(H,H+B);for(let q of W)try{await this.fileOperations.writeEntity(q),$.exported++,this.logger.debug("Exported entity",{entityType:I,id:q.id})}catch(V){let E=V instanceof Error?V:Error(`Failed to export entity ${q.id||"unknown"}`);$.failed++,$.errors.push({entityId:q.id||"unknown",entityType:I,error:E.message}),this.logger.error("Failed to export entity",{entityType:I,id:q.id||"unknown",error:E})}let J=(Y+1)/D,Z=50+Math.round(J*50);await Q.report({progress:Z,message:`Exported ${$.exported} entities`})}}return this.logger.debug("Export completed",$),$}}class RXA{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,B,w,$=!0){if(this.logger=A,this.fileOperations=w,this.deleteOnFileRemoval=$,B)this.handleImport=async(D)=>{let Y=await B({type:"directory-import",data:{paths:[D]}});this.logger.debug("Queued import job for file change",{jobId:Y,path:D})},this.handleDelete=async(D)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:D});return}try{let{entityType:Y,id:I}=this.fileOperations.parseEntityFromPath(D),X=await B({type:"directory-delete",data:{entityId:I,entityType:Y,filePath:D}});this.logger.info("Queued delete job for removed file",{jobId:X,path:D,entityId:I,entityType:Y})}catch(Y){this.logger.warn("Could not extract entity info from deleted file",{path:D,error:Y})}};else this.handleImport=async(D)=>{await Q([D])},this.handleDelete=async(D)=>{this.logger.warn("File deleted but no job queue available",{path:D})}}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})}}}GA();async function Ul(A,Q,B,w){let{sourceUrl:$}=A,D=await Q.listEntities("image",{filter:{metadata:{sourceUrl:$}},limit:1});if(D[0])return w.debug("Reusing existing image entity",{sourceUrl:$,imageId:D[0].id}),D[0].id;let Y=await B($),{base64:I}=dW(Y),X=LZ(I),H=iW(I);if(!X||!H)throw Error("Could not detect image format or dimensions");let W=await Q.createEntity({id:A.id,entityType:"image",content:Y,metadata:{title:A.title,alt:A.alt,format:X,width:H.width,height:H.height,sourceUrl:$}});return w.debug("Created image entity from URL",{sourceUrl:$,imageId:W.entityId}),W.entityId}var dz0=F.object({title:F.string(),slug:F.string().optional(),coverImageUrl:F.string().url(),coverImageId:F.string().optional(),coverImageAlt:F.string().optional()});class jXA{entityService;fetcher;logger;constructor(A,Q,B=f7){this.entityService=A;this.fetcher=B;this.logger=Q.child("FrontmatterImageConverter")}detectCoverImageUrl(A){let Q;try{Q=uD(A)}catch{return null}let{frontmatter:B}=Q,w=dz0.safeParse(B);if(!w.success)return null;if(w.data.coverImageId)return null;let{title:$,slug:D,coverImageUrl:Y,coverImageAlt:I}=w.data;if(!SH(Y))return null;return{sourceUrl:Y,postTitle:$,postSlug:D??e1($),customAlt:I}}async convert(A){let Q;try{Q=uD(A)}catch(H){return this.logger.debug("Parse failed",{error:H}),{content:A,converted:!1}}let{frontmatter:B}=Q,w=dz0.safeParse(B);if(!w.success)return{content:A,converted:!1};if(w.data.coverImageId)return{content:A,converted:!1};let{title:$,slug:D,coverImageUrl:Y,coverImageAlt:I}=w.data;if(!SH(Y))return{content:A,converted:!1};let X={postTitle:$,postSlug:D??e1($),sourceUrl:Y,customAlt:I};try{let H=await this.createImageEntity(X),W={...B};return delete W.coverImageUrl,delete W.coverImageAlt,W.coverImageId=H,{content:M3(W,Q.content),converted:!0,imageId:H}}catch(H){return this.logger.warn("Failed to convert coverImageUrl",{url:Y,error:L0(H)}),{content:A,converted:!1}}}async createImageEntity(A){let{postTitle:Q,postSlug:B,sourceUrl:w,customAlt:$}=A,D=`Cover image for ${Q}`;return Ul({id:`${B}-cover`,title:D,alt:$??D,sourceUrl:w},this.entityService,this.fetcher,this.logger)}}GA();class IP{entityService;fetcher;logger;constructor(A,Q,B=f7){this.entityService=A;this.fetcher=B;this.logger=Q.child("MarkdownImageConverter")}detectInlineImages(A,Q){let B=[],w=cT(A);for(let $ of w){if(!SH($.url))continue;if($.url.startsWith("entity://"))continue;let D=this.reconstructMarkdown($);B.push({sourceUrl:$.url,alt:$.alt,originalMarkdown:D,postSlug:Q})}return B}reconstructMarkdown(A){if(A.title)return`![${A.alt}](${A.url} "${A.title}")`;return`![${A.alt}](${A.url})`}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,D=0;for(let Y of B)try{let I=await this.createImageEntity(Y,D++),X=`![${Y.alt}](entity://image/${I})`;w=w.replace(Y.originalMarkdown,X),$++,this.logger.debug("Converted inline image",{sourceUrl:Y.sourceUrl,imageId:I})}catch(I){this.logger.warn("Failed to convert inline image",{sourceUrl:Y.sourceUrl,error:L0(I)})}return{content:w,converted:$>0,convertedCount:$}}async createImageEntity(A,Q){let{sourceUrl:B,alt:w,postSlug:$}=A;return Ul({id:`${$}-inline-${Q}`,title:w||`Inline image ${Q+1} for ${$}`,alt:w||"",sourceUrl:B},this.entityService,this.fetcher,this.logger)}}GA();import{rename as DQ2,appendFile as YQ2,readFile as IQ2,writeFile as XQ2,access as HQ2}from"fs/promises";import{join as iz0}from"path";class kXA{logger;syncPath;constructor(A,Q){this.logger=A;this.syncPath=Q}isValidationError(A){if(A instanceof F.ZodError)return!0;let Q=L0(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),D=`${$}.invalid`;try{await DQ2($,D),B.quarantined++,B.quarantinedFiles.push(A);let Y=iz0(this.syncPath,".import-errors.log"),I=new Date().toISOString(),X=L0(Q),H=`${I} - ${A}: ${X}
1685
+ `)||"No response text";return{success:!0,data:{state:Z,response:V}}}$=await Q.read()}return{success:!1,error:"Stream ended without a terminal event"}}function CF0(A={}){let Q=A.fetch??globalThis.fetch;return{name:"a2a_call",description:"Call a saved remote A2A agent by its local directory id. 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:MF0,visibility:"anchor",handler:async(B)=>{let w=F.object(MF0).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{agent:$,message:D}=w.data,Y=ot1($);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 I=await A.entityService.getEntity("agent",Y);if(!I)return{success:!1,error:`Agent ${Y} is not in your directory. Add it first.`};if(I.metadata.status!=="approved")return{success:!1,error:`Agent ${Y} is discovered but not approved yet. Approve it first.`};let X=`https://${Y}`,H=await st1(X,Q);if(!H)return{success:!1,error:`Could not fetch Agent Card from ${X}`};let W=H.url,J;if(A.outboundTokens)try{let Z=new URL(W).hostname;J=A.outboundTokens[Z]}catch{}return at1(W,D,Q,J)}}}var EIA={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.42",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 Ae1={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff"};class iL extends gI{agentCard;unsubscribeReady;unsubscribeSyncCompleted;taskManager=new LIA;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",EIA,A,JF0)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agentService,this.permissionContext=A.permissions,this.unsubscribeReady=A.messaging.subscribe("system:plugins:ready",()=>{return this.rebuildAgentCard(A),{noop:!0}}),this.unsubscribeSyncCompleted=A.messaging.subscribe("sync:initial:completed",()=>{return this.rebuildAgentCard(A),{success:!0}}),this.hasWebserver)this.logger.info("A2A interface registered",{domain:A.domain});else this.logger.info("A2A interface registered in tool-only mode",{domain:A.domain})}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,D;if(A.entityService.hasEntityType("skill"))try{let Y=await A.entityService.listEntities("skill");if(Y.length>0)D=Y.map((I)=>j$.safeParse(I.metadata)).filter((I)=>I.success).map((I)=>I.data)}catch{}this.agentCard=ZF0({character:Q,profile:B,version:EIA.version,domain:A.domain,organization:this.config.organization,tools:w,skills:D,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(Ae1))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 lL;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=zF0.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 Y=VF0.safeParse(w.data.params??{});if(!Y.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${Y.error.message}`},id:w.data.id}));let{stream:I}=LF0(w.data.id,Y.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(new Response(I,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let D=await NF0(w.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(Q.json(D))}),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[CF0({outboundTokens:this.config.outboundTokens,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, or contact a saved approved agent, 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, or searching general content locally.\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.unsubscribeReady?.(),this.unsubscribeSyncCompleted?.(),this.logger.info("A2A server stopped")}}}}B0();B0();class CIA{logger;syncPath;constructor(A,Q){this.logger=A,this.syncPath=Q}prepareBatchOperations(A,Q){if(A.length===0)return{operations:[],exportOperationsCount:0,importOperationsCount:0,totalFiles:0};let B=[],w=this.createImportOperations(A);B.push(...w);let $=w.length;if(Q?.includeCleanup)B.push({type:"directory-cleanup",data:{}});let D=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:$,totalFiles:D}),{operations:B,exportOperationsCount:0,importOperationsCount:$,totalFiles:D}}async queueSyncBatch(A,Q,B,w,$){let D=this.prepareBatchOperations(B,$);if(D.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch(D.operations,{source:Q,rootJobId:w?.rootJobId??j6(),metadata:{progressToken:w?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:w?.pluginId??"directory-sync",interfaceType:w?.interfaceType,channelId:w?.channelId}}),operationCount:D.operations.length,exportOperationsCount:D.exportOperationsCount,importOperationsCount:D.importOperationsCount,totalFiles:D.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}}GA();import{resolve as GQ2,isAbsolute as JQ2}from"path";import{mkdir as ZQ2}from"fs/promises";var pz0=o0(yz0(),1);aD();import{join as zX,dirname as t22,extname as Kl}from"path";import{mkdir as EXA,readFile as Hl,writeFile as mz0,readdir as e22,stat as uz0,utimes as AQ2,access as QQ2}from"fs/promises";var YP=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function cz0(A){let Q=Kl(A).toLowerCase();return YP.includes(Q)}function BQ2(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 lz0(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}async function eL(A){try{return await QQ2(A),!0}catch{return!1}}class CXA{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){let w=(A.startsWith(this.syncPath)?A:zX(this.syncPath,A)).replace(this.syncPath+"/","").split("/"),$,D;if(w.length===1)$="base",D=w;else if(w.length>1&&w[0])$=w[0],D=w.slice(1);else $="base",D=w;let Y;if(D.length>1){let I=D[D.length-1];if(I){let X=Kl(I).toLowerCase(),H=X===".md"||YP.includes(X)?I.slice(0,-X.length):I;D[D.length-1]=H}Y=D.join(":")}else{let I=D[0]??"",X=Kl(I).toLowerCase();Y=X===".md"||YP.includes(X)?I.slice(0,-X.length):I}return{entityType:$,id:Y}}async readEntity(A){let Q=A.startsWith(this.syncPath)?A:zX(this.syncPath,A),B=await uz0(Q),{entityType:w,id:$}=this.parseEntityFromPath(A),D=B.birthtime.getTime()>0?B.birthtime:B.mtime,Y=B.mtime,I;if(cz0(A)){let H=(await Hl(Q)).toString("base64"),W=Kl(A);I=`data:${BQ2(W)};base64,${H}`}else I=await Hl(Q,"utf-8");return{entityType:w,id:$,content:I,created:D,updated:Y}}async writeEntity(A){let Q=this.getEntityFilePath(A),B=A.entityType==="image",w;if(B){let D=A.content.match(/^data:image\/[a-z+]+;base64,(.+)$/i);w=D?.[1]?Buffer.from(D[1],"base64"):Buffer.from(A.content,"base64")}else w=this.entityService.serializeEntity(A);if(await eL(Q)){let D=B?await Hl(Q):await Hl(Q,"utf-8"),Y=aB(B?D.toString("base64"):D),I=aB(B?w.toString("base64"):w);if(Y===I)return}if(A.entityType!=="base")await EXA(t22(Q),{recursive:!0});if(B)await mz0(Q,w);else await mz0(Q,w,"utf-8");let $=new Date(A.updated);await AQ2(Q,$,$)}getFilePath(A,Q,B=".md"){let w=A.split(":").filter((X)=>X.length>0),$=Q==="base";if(w.length===1)return $?zX(this.syncPath,`${w[0]}${B}`):zX(this.syncPath,Q,`${w[0]}${B}`);let D=w;if(w[0]===Q)D=w.slice(1);let Y=D[D.length-1],I=D.slice(0,-1);if($)return zX(this.syncPath,...I,`${Y}${B}`);else return zX(this.syncPath,Q,...I,`${Y}${B}`)}getEntityFilePath(A){let Q=".md";if(A.entityType==="image"){let B=A.metadata.format;if(B)Q=lz0(B);else{let w=A.content.match(/^data:image\/([a-z+]+);base64,/i);if(w?.[1])Q=lz0(w[1])}}return this.getFilePath(A.id,A.entityType,Q)}async getAllMarkdownFiles(){return this.findFiles({includeImages:!1})}async getAllSyncFiles(){return this.findFiles({includeImages:!0})}async findFiles(A){let Q=[];if(!await eL(this.syncPath))return Q;let B=async(w,$="",D=!1)=>{let Y=await e22(w,{withFileTypes:!0});for(let I of Y){let X=$?zX($,I.name):I.name;if(I.isFile()&&!I.name.endsWith(".invalid")){if(I.name.endsWith(".md"))Q.push(X);else if(A.includeImages&&D&&cz0(I.name))Q.push(X)}else if(I.isDirectory()&&!I.name.startsWith(".")){if($===""&&!this.entityService.hasEntityType(I.name))continue;let H=zX(w,I.name),W=I.name==="image"&&$==="";await B(H,X,D||W)}}};return await B(this.syncPath),Q}async ensureDirectoryStructure(A){if(!await eL(this.syncPath))await EXA(this.syncPath,{recursive:!0});for(let Q of A)if(Q!=="base")await EXA(zX(this.syncPath,Q),{recursive:!0})}shouldUpdateEntity(A,Q){let B=aB(Q.content);return A.contentHash!==B}async gatherFileStatus(){let A=[],Q={totalFiles:0,byEntityType:{}};if(!await eL(this.syncPath))return{files:A,stats:Q};let B=await this.getAllMarkdownFiles();for(let w of B)try{let $=zX(this.syncPath,w),D=await uz0($),{entityType:Y}=this.parseEntityFromPath(w);A.push({path:w,entityType:Y,modified:D.mtime}),Q.totalFiles++,Q.byEntityType[Y]=(Q.byEntityType[Y]??0)+1}catch{continue}return{files:A,stats:Q}}async syncDirectoryExists(){return eL(this.syncPath)}async fileExists(A){return eL(A)}}function wQ2(A,Q){if(!A.replace(Q+"/","").startsWith("image/"))return!1;return YP.some((w)=>A.toLowerCase().endsWith(w))}function $Q2(A,Q){if(A.replace(Q+"/","").split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return wQ2(A,Q)}class OXA{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=pz0.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(!$Q2(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let B=Q.replace(this.syncPath+"/","");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=`${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}}class fXA{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:[]},D=A??await this.fileOperations.getAllMarkdownFiles(),Y=D.length;await Q.report({progress:0,message:`Starting import of ${Y} files`});for(let I=0;I<Y;I+=B){let X=D.slice(I,I+B),H=await w(X);$.imported+=H.imported,$.skipped+=H.skipped,$.failed+=H.failed,$.errors.push(...H.errors),$.jobIds.push(...H.jobIds);let W=Math.min(I+B,Y),J=Math.round(W/Y*40);await Q.report({progress:J,message:`Imported ${W}/${Y} files`})}return $}async exportEntitiesWithProgress(A,Q,B){this.logger.debug("Exporting entities with progress reporting");let w=A??this.entityService.getEntityTypes(),$={exported:0,failed:0,errors:[]},D=w.length;await Q.report({progress:50,message:`Starting export of ${D} entity types`});for(let Y=0;Y<D;Y++){let I=w[Y];if(!I)continue;let X=await this.entityService.listEntities(I,{limit:1000});for(let H=0;H<X.length;H+=B){let W=X.slice(H,H+B);for(let q of W)try{await this.fileOperations.writeEntity(q),$.exported++,this.logger.debug("Exported entity",{entityType:I,id:q.id})}catch(V){let E=V instanceof Error?V:Error(`Failed to export entity ${q.id||"unknown"}`);$.failed++,$.errors.push({entityId:q.id||"unknown",entityType:I,error:E.message}),this.logger.error("Failed to export entity",{entityType:I,id:q.id||"unknown",error:E})}let J=(Y+1)/D,Z=50+Math.round(J*50);await Q.report({progress:Z,message:`Exported ${$.exported} entities`})}}return this.logger.debug("Export completed",$),$}}class RXA{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,B,w,$=!0){if(this.logger=A,this.fileOperations=w,this.deleteOnFileRemoval=$,B)this.handleImport=async(D)=>{let Y=await B({type:"directory-import",data:{paths:[D]}});this.logger.debug("Queued import job for file change",{jobId:Y,path:D})},this.handleDelete=async(D)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:D});return}try{let{entityType:Y,id:I}=this.fileOperations.parseEntityFromPath(D),X=await B({type:"directory-delete",data:{entityId:I,entityType:Y,filePath:D}});this.logger.info("Queued delete job for removed file",{jobId:X,path:D,entityId:I,entityType:Y})}catch(Y){this.logger.warn("Could not extract entity info from deleted file",{path:D,error:Y})}};else this.handleImport=async(D)=>{await Q([D])},this.handleDelete=async(D)=>{this.logger.warn("File deleted but no job queue available",{path:D})}}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})}}}GA();async function Ul(A,Q,B,w){let{sourceUrl:$}=A,D=await Q.listEntities("image",{filter:{metadata:{sourceUrl:$}},limit:1});if(D[0])return w.debug("Reusing existing image entity",{sourceUrl:$,imageId:D[0].id}),D[0].id;let Y=await B($),{base64:I}=dW(Y),X=LZ(I),H=iW(I);if(!X||!H)throw Error("Could not detect image format or dimensions");let W=await Q.createEntity({id:A.id,entityType:"image",content:Y,metadata:{title:A.title,alt:A.alt,format:X,width:H.width,height:H.height,sourceUrl:$}});return w.debug("Created image entity from URL",{sourceUrl:$,imageId:W.entityId}),W.entityId}var dz0=F.object({title:F.string(),slug:F.string().optional(),coverImageUrl:F.string().url(),coverImageId:F.string().optional(),coverImageAlt:F.string().optional()});class jXA{entityService;fetcher;logger;constructor(A,Q,B=f7){this.entityService=A;this.fetcher=B;this.logger=Q.child("FrontmatterImageConverter")}detectCoverImageUrl(A){let Q;try{Q=uD(A)}catch{return null}let{frontmatter:B}=Q,w=dz0.safeParse(B);if(!w.success)return null;if(w.data.coverImageId)return null;let{title:$,slug:D,coverImageUrl:Y,coverImageAlt:I}=w.data;if(!SH(Y))return null;return{sourceUrl:Y,postTitle:$,postSlug:D??e1($),customAlt:I}}async convert(A){let Q;try{Q=uD(A)}catch(H){return this.logger.debug("Parse failed",{error:H}),{content:A,converted:!1}}let{frontmatter:B}=Q,w=dz0.safeParse(B);if(!w.success)return{content:A,converted:!1};if(w.data.coverImageId)return{content:A,converted:!1};let{title:$,slug:D,coverImageUrl:Y,coverImageAlt:I}=w.data;if(!SH(Y))return{content:A,converted:!1};let X={postTitle:$,postSlug:D??e1($),sourceUrl:Y,customAlt:I};try{let H=await this.createImageEntity(X),W={...B};return delete W.coverImageUrl,delete W.coverImageAlt,W.coverImageId=H,{content:M3(W,Q.content),converted:!0,imageId:H}}catch(H){return this.logger.warn("Failed to convert coverImageUrl",{url:Y,error:L0(H)}),{content:A,converted:!1}}}async createImageEntity(A){let{postTitle:Q,postSlug:B,sourceUrl:w,customAlt:$}=A,D=`Cover image for ${Q}`;return Ul({id:`${B}-cover`,title:D,alt:$??D,sourceUrl:w},this.entityService,this.fetcher,this.logger)}}GA();class IP{entityService;fetcher;logger;constructor(A,Q,B=f7){this.entityService=A;this.fetcher=B;this.logger=Q.child("MarkdownImageConverter")}detectInlineImages(A,Q){let B=[],w=cT(A);for(let $ of w){if(!SH($.url))continue;if($.url.startsWith("entity://"))continue;let D=this.reconstructMarkdown($);B.push({sourceUrl:$.url,alt:$.alt,originalMarkdown:D,postSlug:Q})}return B}reconstructMarkdown(A){if(A.title)return`![${A.alt}](${A.url} "${A.title}")`;return`![${A.alt}](${A.url})`}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,D=0;for(let Y of B)try{let I=await this.createImageEntity(Y,D++),X=`![${Y.alt}](entity://image/${I})`;w=w.replace(Y.originalMarkdown,X),$++,this.logger.debug("Converted inline image",{sourceUrl:Y.sourceUrl,imageId:I})}catch(I){this.logger.warn("Failed to convert inline image",{sourceUrl:Y.sourceUrl,error:L0(I)})}return{content:w,converted:$>0,convertedCount:$}}async createImageEntity(A,Q){let{sourceUrl:B,alt:w,postSlug:$}=A;return Ul({id:`${$}-inline-${Q}`,title:w||`Inline image ${Q+1} for ${$}`,alt:w||"",sourceUrl:B},this.entityService,this.fetcher,this.logger)}}GA();import{rename as DQ2,appendFile as YQ2,readFile as IQ2,writeFile as XQ2,access as HQ2}from"fs/promises";import{join as iz0}from"path";class kXA{logger;syncPath;constructor(A,Q){this.logger=A;this.syncPath=Q}isValidationError(A){if(A instanceof F.ZodError)return!0;let Q=L0(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),D=`${$}.invalid`;try{await DQ2($,D),B.quarantined++,B.quarantinedFiles.push(A);let Y=iz0(this.syncPath,".import-errors.log"),I=new Date().toISOString(),X=L0(Q),H=`${I} - ${A}: ${X}
1686
1686
  \u2192 ${A}.invalid
1687
1687
 
1688
1688
  `;await YQ2(Y,H),this.logger.warn("Quarantined invalid entity file",{originalPath:A,quarantinePath:`${A}.invalid`,error:X})}catch(Y){this.logger.error("Failed to quarantine invalid file",{path:A,error:Y}),B.failed++,B.errors.push({path:A,error:"Failed to quarantine invalid file"})}}async markAsRecoveredIfNeeded(A){let Q=iz0(this.syncPath,".import-errors.log");try{await HQ2(Q)}catch{return}try{let B=await IQ2(Q,"utf-8");if(B.includes(A)){let $=`${new Date().toISOString()} - [RECOVERED] ${A}
@@ -1708,7 +1708,7 @@ ${A.entityContent}`,_Z1);X=w+j.imagePrompt}catch(j){this.logger.warn("AI prompt
1708
1708
  *...and ${A.files.length-10} more files*`)}if(A.exists&&A.stats.totalFiles===0)Q.push(`
1709
1709
  ## Getting Started
1710
1710
  `),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(`
1711
- `)}}B0();class vl extends EB{context;directorySync;constructor(A,Q,B){super(A,{schema:gL0,jobTypeName:"directory-export"});this.context=Q,this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let w=Date.now(),$={exported:0,failed:0,errors:[]};try{let D=A.entityTypes??this.context.entityService.getEntityTypes();this.logger.debug("Starting export",{jobId:Q,entityTypes:D}),await B.report({message:`Starting export of ${D.length} entity types`,progress:0,total:D.length});for(let[Y,I]of D.entries())await this.exportEntityType(I,A.batchSize??100,Q,$),await B.report({message:`Exported ${Y+1}/${D.length} entity types (${$.exported} entities)`,progress:Y+1,total:D.length});return this.logger.debug("Directory export job completed",{jobId:Q,exported:$.exported,failed:$.failed,duration:Date.now()-w}),$}catch(D){throw this.logger.error("Directory export job failed",{jobId:Q,error:D}),D}}async exportEntityType(A,Q,B,w){let $=0,D=!0;while(D){let Y=await this.context.entityService.listEntities(A,{limit:Q,offset:$});if(Y.length===0){D=!1;break}let I=Y.map(async(X)=>{let H=await this.directorySync.processEntityExport(X);if(H.success)w.exported++;else w.failed++,w.errors.push({entityId:X.id,entityType:A,error:H.error??"Unknown error"});return H});await Promise.all(I),this.logger.debug("Export progress",{jobId:B,entityType:A,processed:$+Y.length,exported:w.exported,failed:w.failed}),$+=Q,D=Y.length===Q}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}B0();GA();aD();class Sl extends EB{context;directorySync;constructor(A,Q,B){super(A,{schema:hL0,jobTypeName:"directory-import"});this.context=Q,this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let w=Date.now(),$={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]};try{let D=A.paths??await this.directorySync.getAllMarkdownFiles();this.logger.debug("Starting import",{jobId:Q,totalFiles:D.length}),await B.report({message:`Starting import of ${D.length} files`,progress:0,total:D.length});let Y=A.batchSize??100;for(let I=0;I<D.length;I+=Y){let X=D.slice(I,I+Y);await this.importBatch(X,Q,$,I,D.length);let H=Math.min(I+Y,D.length);await B.report({message:`Imported ${H}/${D.length} files (${$.imported} successful, ${$.failed} failed)`,progress:H,total:D.length})}return this.logger.debug("Directory import job completed",{jobId:Q,imported:$.imported,skipped:$.skipped,failed:$.failed,duration:Date.now()-w}),$}catch(D){throw this.logger.error("Directory import job failed",{jobId:Q,error:D}),D}}async importBatch(A,Q,B,w,$){let D=A.map(async(Y)=>{try{let I=await this.directorySync.fileOps.readEntity(Y);if(!this.context.entityService.getEntityTypes().includes(I.entityType))return B.skipped++,{success:!1,skipped:!0};try{let H=this.context.entityService.deserializeEntity(I.content,I.entityType),W=await this.context.entityService.getEntity(I.entityType,I.id);if(W){let J=new Date(W.updated).getTime(),Z=I.updated.getTime(),q=aB(I.content),V=W.contentHash!==q;if(J<Z||V){let E={...W,content:I.content,...H,id:I.id,entityType:I.entityType,updated:I.updated.toISOString()};await this.context.entityService.updateEntity(E),B.imported++}else B.skipped++}else{let J={id:I.id,entityType:I.entityType,content:I.content,...H,metadata:H.metadata??{},created:I.created.toISOString(),updated:I.updated.toISOString()};await this.context.entityService.createEntity(J),B.imported++}return{success:!0}}catch{return B.skipped++,{success:!1,skipped:!0}}}catch(I){return B.failed++,B.errors.push({path:Y,error:L0(I)}),{success:!1,error:I}}});await Promise.all(D),this.logger.debug("Import progress",{jobId:Q,processed:w+A.length,total:$,imported:B.imported,skipped:B.skipped,failed:B.failed})}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}B0();class hl extends EB{directorySync;context;constructor(A,Q,B){super(A,{schema:SL0,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 D={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},Y={exported:0,failed:0,errors:[]};if($!=="export")if(await B.report({progress:10,message:"Scanning directory for changes"}),D=await this.importWithProgress(A.paths,B),$==="import")await this.waitForImportJobs(D.jobIds,B),await B.report({progress:100,message:`Import complete: ${D.imported} imported`});else await B.report({progress:50,message:`Imported ${D.imported} entities`}),await this.waitForImportJobs(D.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"}),Y=await this.exportWithProgress(A.entityTypes,B),await B.report({progress:100,message:$==="export"?`Export complete: ${Y.exported} exported`:`Sync complete: ${D.imported} imported, ${Y.exported} exported`})}let I=Date.now()-w;return this.logger.info("Directory sync job completed",{jobId:Q,duration:I,imported:D.imported,exported:Y.exported}),{import:D,export:Y,duration:I}}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,D=Date.now(),Y=async()=>{let X=(await Promise.all(A.map((W)=>B.getAsyncJobStatus(W)))).filter((W)=>W&&(W.status==="completed"||W.status==="failed")).length;if(X===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-D>w){this.logger.warn(`Timeout waiting for import jobs (${X}/${A.length} completed)`);return}let H=Math.round(X/A.length*100);return await Q.report({progress:50+Math.round(H*0.05),message:`Processing ${X}/${A.length} entities`}),await new Promise((W)=>setTimeout(W,$)),Y()};return Y()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}B0();class gl extends EB{context;constructor(A,Q,B){super(A,{schema:CHA,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,B){let w=CHA.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(w.entityType,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}}}B0();GA();var d62=F.object({});class yl extends EB{directorySync;constructor(A,Q){super(A,{schema:d62,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}}B0();GA();import{readFile as i62,writeFile as r62}from"fs/promises";var n62=F.object({filePath:F.string(),sourceUrl:F.string().url(),postTitle:F.string(),postSlug:F.string(),customAlt:F.string().optional()});class ml extends EB{context;fetcher;constructor(A,Q,B=f7){super(Q,{schema:n62,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=B}async process(A,Q,B){let{filePath:w,sourceUrl:$,postTitle:D,postSlug:Y,customAlt:I}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:w,sourceUrl:$,postSlug:Y});try{await this.reportProgress(B,{progress:F2.INIT,message:`Reading file: ${w}`});let X;try{X=await i62(w,"utf-8")}catch(E){return this.logger.error("Failed to read file",{filePath:w,error:L0(E)}),K6.failure(E)}let H;try{H=uD(X)}catch(E){return this.logger.warn("Failed to parse markdown",{filePath:w,error:L0(E)}),K6.failure(E)}let W=H.frontmatter;if(W.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:w}),await this.reportProgress(B,{progress:F2.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress(B,{progress:F2.FETCH,message:"Checking for existing image"});let J=await this.context.entityService.listEntities("image",{filter:{metadata:{sourceUrl:$}},limit:1}),Z;if(J[0])Z=J[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:$,imageId:Z}),await this.reportProgress(B,{progress:F2.EXTRACT,message:`Reusing existing image: ${Z}`});else{await this.reportProgress(B,{progress:F2.PROCESS,message:`Fetching image from ${$}`});let E;try{E=await this.fetcher($)}catch(n){return this.logger.error("Failed to fetch image",{sourceUrl:$,error:L0(n)}),K6.failure(n)}await this.reportProgress(B,{progress:F2.GENERATE,message:"Creating image entity"});let{base64:L}=dW(E),j=LZ(L),_=iW(L);if(!j||!_)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:$}),K6.failure(Error("Could not detect image format or dimensions"));Z=`${Y}-cover`;let k=`Cover image for ${D}`,r=I??k;await this.context.entityService.createEntity({id:Z,entityType:"image",content:E,metadata:{title:k,alt:r,format:j,width:_.width,height:_.height,sourceUrl:$}}),this.logger.debug("Created image entity",{imageId:Z,sourceUrl:$}),await this.reportProgress(B,{progress:F2.EXTRACT,message:`Created image: ${Z}`})}await this.reportProgress(B,{progress:F2.SAVE,message:"Updating file"});let q={...W};delete q.coverImageUrl,delete q.coverImageAlt,q.coverImageId=Z;let V=M3(q,H.content);try{await r62(w,V,"utf-8")}catch(E){return this.logger.error("Failed to write file",{filePath:w,error:L0(E)}),K6.failure(E)}return await this.reportProgress(B,{progress:F2.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:w,imageId:Z,sourceUrl:$}),{success:!0,imageId:Z}}catch(X){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:w,error:L0(X)}),K6.failure(X)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}B0();GA();import{readFile as o62,writeFile as s62}from"fs/promises";class ul extends EB{converter;constructor(A,Q,B=f7){super(Q,{schema:yL0,jobTypeName:"inline-image-convert"});this.converter=new IP(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:F2.INIT,message:`Reading file: ${w}`});let D;try{D=await o62(w,"utf-8")}catch(X){let H=L0(X);return this.logger.error("Failed to read file",{filePath:w,error:H}),{success:!1,error:H}}await this.reportProgress(B,{progress:F2.FETCH,message:"Detecting inline images"});let Y=this.converter.detectInlineImages(D,$);if(Y.length===0)return this.logger.debug("No inline images to convert",{filePath:w}),await this.reportProgress(B,{progress:F2.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:w,count:Y.length}),await this.reportProgress(B,{progress:F2.PROCESS,message:`Converting ${Y.length} images`});let I=await this.converter.convert(D,$);if(!I.converted)return this.logger.debug("No images were converted",{filePath:w}),await this.reportProgress(B,{progress:F2.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress(B,{progress:F2.SAVE,message:"Writing updated file"});try{await s62(w,I.content,"utf-8")}catch(X){let H=L0(X);return this.logger.error("Failed to write file",{filePath:w,error:H}),{success:!1,error:H}}return await this.reportProgress(B,{progress:F2.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:w,convertedCount:I.convertedCount}),{success:!0,convertedCount:I.convertedCount}}catch(D){let Y=L0(D);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:w,error:Y}),{success:!1,error:Y}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function cL0(A,Q,B){let w=($)=>B.child($);A.jobs.registerHandler("directory-sync",new hl(w("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new vl(w("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new Sl(w("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new gl(w("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new yl(w("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new ml(A,w("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new ul(A,w("InlineImageConversionJobHandler"))),B.debug("Registered async job handlers")}B0();import{unlink as a62,access as t62}from"fs/promises";function lL0(A,Q,B,w){let{subscribe:$}=A.messaging,{entityService:D}=A;$("entity:created",async(Y)=>{let{entity:I}=Y.payload;try{await Q.fileOps.writeEntity(I),B.debug("Auto-exported created entity",{id:I.id,entityType:I.entityType})}catch(X){B.error("Auto-export FAILED for created entity",{id:I.id,entityType:I.entityType,error:X instanceof Error?X.message:String(X),stack:X instanceof Error?X.stack:void 0})}return{success:!0}}),$("entity:updated",async(Y)=>{let{entityType:I,entityId:X}=Y.payload;try{let H=await D.getEntity(I,X);if(!H)return B.debug("Entity not found in DB, skipping export",{entityType:I,entityId:X}),{success:!1};await Q.fileOps.writeEntity(H),B.debug("Auto-exported updated entity",{id:H.id,entityType:H.entityType})}catch(H){B.error("Auto-export FAILED for updated entity",{entityType:I,entityId:X,error:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0})}return{success:!0}}),$("entity:deleted",async(Y)=>{let{entityId:I,entityType:X}=Y.payload,H=Q.fileOps.getFilePath(I,X);if(await t62(H).then(()=>!0,()=>!1))await a62(H),B.debug("Auto-deleted entity file",{id:I,entityType:X,path:H});return{success:!0}}),B.debug("Setup auto-sync for entity events",{entityTypes:w})}function pL0(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:j6(),metadata:{operationType:"file_operations",operationTarget:B,pluginId:"directory-sync"}})})}GA();import{access as e62,readdir as dL0,mkdir as A52,copyFile as Q52}from"fs/promises";import{exec as B52}from"child_process";import{promisify as w52}from"util";import{join as fHA,resolve as OHA}from"path";var $52=w52(B52);async function cl(A){try{return await e62(A),!0}catch{return!1}}async function D52(A,Q){if(!await cl(A))return!0;if((await dL0(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await Y52(A))return Q.debug("Git repository with remote detected - skipping seed content",{path:A}),!1;return!0}async function Y52(A){let Q=fHA(A,".git");if(!await cl(Q))return!1;try{let{stdout:B}=await $52("git remote",{cwd:A});return B.trim().length>0}catch{return!1}}async function iL0(A,Q){let B=await dL0(A,{withFileTypes:!0});for(let w of B){let $=fHA(A,w.name),D=fHA(Q,w.name);if(w.isDirectory()){if(!await cl(D))await A52(D,{recursive:!0});await iL0($,D)}else await Q52($,D)}}async function rL0(A,Q,B){let w=OHA(process.cwd(),A);B=B?OHA(B):OHA(process.cwd(),"seed-content");let $=await D52(w,Q);if($&&await cl(B))Q.debug("Copying seed content to brain-data directory"),await iL0(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")}async function I52(A,Q,B,w=300000){let D=Date.now();while(Date.now()-D<w){let Y=await A.jobs.getBatchStatus(Q);if(Y&&(Y.status==="completed"||Y.status==="failed")){B.debug("Batch completed",{batchId:Q,status:Y.status,completed:Y.completedOperations,failed:Y.failedOperations});return}await new Promise((I)=>setTimeout(I,500))}B.warn(`Timeout waiting for batch ${Q} after ${w}ms`)}function nL0(A,Q,B,w,$,D){let Y=!1,I=async()=>{if(Y)return;Y=!0;let X=Q();if(B.seedContent){let H=B.syncPath??A.dataDir;await rL0(H,$,B.seedContentPath)}try{if(D){$.debug("Git enabled \u2014 pulling before import");let W=await D.pull();if(W.files.length>0)$.info("Pulled changes from remote",{filesChanged:W.files.length})}$.debug("Starting initial sync");let H=await X.queueSyncBatch(A,"initial-sync",void 0,{includeCleanup:!0});if(!H){$.debug("Initial sync: no files to import"),await A.messaging.send("sync:initial:completed",{success:!0},{broadcast:!0});return}$.debug("Initial sync: queued imports",{importOperations:H.importOperationsCount,totalFiles:H.totalFiles}),I52(A,H.batchId,$).then(()=>A.messaging.send("sync:initial:completed",{success:!0},{broadcast:!0}),(W)=>{$.error("Initial sync batch failed",W),A.messaging.send("sync:initial:completed",{success:!1,error:L0(W)},{broadcast:!0})})}catch(H){$.error("Initial sync failed",H),await A.messaging.send("sync:initial:completed",{success:!1,error:L0(H)},{broadcast:!0})}};A.messaging.subscribe("system:plugins:ready",async()=>{return $.debug("system:plugins:ready received, starting initial sync"),await I(),{success:!0}})}GA();function oL0(A,Q,B,w){let $=new R3(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(I){w.error("Git auto-commit failed",{error:I})}})},B),D=["entity:created","entity:updated","entity:deleted"],Y=[];for(let I of D){let X=A.subscribe(I,async()=>{return $.trigger(),{success:!0}});Y.push(X)}return()=>{$.dispose();for(let I of Y)I()}}function sL0(A,Q,B,w,$){if(w<=0)return()=>{};let D=w*60*1000,Y=!1,I=async()=>{if(Y)return;Y=!0;try{let{files:H}=await A.withLock(()=>A.pull());if(H.length>0)$.info("Periodic sync: pulled changes",{filesChanged:H.length});let W=await Q.queueSyncBatch(B,"periodic-sync");if(W)$.debug("Periodic sync: queued imports",{importOperations:W.importOperationsCount,totalFiles:W.totalFiles})}catch(H){$.error("Periodic git sync failed",{error:H})}finally{Y=!1}},X=setInterval(()=>{I()},D);return $.info("Started periodic git sync",{intervalMinutes:w}),()=>{clearInterval(X)}}function aL0(A,Q,B,w,$){let{subscribe:D}=A.messaging;D("entity:export:request",async(Y)=>{try{return{success:!0,data:await Q().exportEntities(Y.payload.entityTypes)}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Export failed"}}}),D("entity:import:request",async(Y)=>{try{let I=Q(),X=Y.payload.paths,H=await I.importEntities(X);if(X&&X.length>0)await I.removeOrphanedEntities();return{success:!0,data:H}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Import failed"}}}),D("sync:status:request",async()=>{try{let I=await Q().getStatus();return{success:!0,data:{syncPath:I.syncPath,isInitialized:I.exists,watchEnabled:I.watching}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Status check failed"}}}),D("sync:configure:request",async(Y)=>{try{return await B({syncPath:Y.payload.syncPath}),{success:!0,data:{syncPath:Y.payload.syncPath,configured:!0}}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Configuration failed"}}}),D("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")}B0();GA();B0();GA();function tL0(A,Q){return yQ(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 D=await Q.show(B.sha,w);return O5({sha:B.sha,entityType:B.entityType,id:B.id,content:D},`Content at ${B.sha.slice(0,7)}`)}let $=await Q.log(w,B.limit);if($.length===0)return O5({commits:[]},`No history found for ${B.entityType}/${B.id}`);return O5({commits:$,entityType:B.entityType,id:B.id},`${$.length} version${$.length===1?"":"s"} found`)}catch($){return Ew($ instanceof Error?$.message:"History lookup failed")}})}function eL0(A,Q,B,w){let $=[yQ(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(D,Y)=>{try{let I=Y.channelId?`${Y.interfaceType}:${Y.channelId}`:`plugin:${B}`,X={interfaceType:Y.interfaceType,channelId:Y.channelId},H=!1;if(w)await w.withLock(()=>w.pull()),H=!0;let W=await A.queueSyncBatch(Q,I,X);if(!W)return O5({gitPulled:H},"No files to sync");return O5({batchId:W.batchId,importOperations:W.importOperationsCount,totalFiles:W.totalFiles,gitPulled:H},`Sync started: ${W.importOperationsCount} import jobs queued for ${W.totalFiles} files${H?" (pulled from git)":""}`)}catch(I){return Ew(I instanceof Error?I.message:"Sync failed")}},{cli:{name:"sync"}}),yQ(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 D=await A.getStatus(),Y={syncPath:D.syncPath,lastSync:D.lastSync?.toISOString(),watching:D.watching};if(w){let I=await w.getStatus();Y.git={isRepo:I.isRepo,branch:I.branch,hasChanges:I.hasChanges,ahead:I.ahead,behind:I.behind,remote:I.remote}}return O5(Y)}catch(D){return Ew(D instanceof Error?D.message:"Status check failed")}},{visibility:"public"})];if(w)$.push(tL0(B,w));return $}var AM0={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.41",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/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 RHA extends tB{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",AM0,A,vL0)}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:zP,basePrompt:"",formatter:new Tl,requiredPermission:"anchor"}});let w=this.config.syncPath??A.dataDir;this.directorySync=new XP({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(Y){throw this.logger.error("Failed to initialize directory",Y),Y}await this.registerJobHandlers(A);let $=this.requireDirectorySync();if(lL0(A,$,this.logger,this.config.entityTypes),this.config.autoSync)pL0(A,$,this.config.syncPath??A.dataDir);let D=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!D)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(D&&this.config.git){let Y=this.config.syncPath??A.dataDir;if(this.gitSync=new EHA({logger:this.logger.child("GitSync"),dataDir:Y,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(oL0(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(sL0(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)nL0(A,()=>this.requireDirectorySync(),this.config,this.id,this.logger,this.gitSync);aL0(A,()=>this.requireDirectorySync(),(Y)=>this.configure(Y),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return eL0(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 XP({...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){cL0(A,this.requireDirectorySync(),this.logger)}}function zF(A={}){return new RHA(A)}B0();B0();GA();GA();var QM0=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:F.object({title:F.string(),description:F.string(),url:F.string().optional(),copyright:F.string().optional(),themeMode:F.enum(["light","dark"]).optional(),analyticsScript:F.string().optional()}),layouts:F.record(F.any()),themeCSS:F.string().optional()}),WmQ=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()});import{render as O_0}from"preact-render-to-string";import{h as pF}from"preact";class jHA{headProps=null;defaultTitle;constructor(A){this.defaultTitle=A}setHeadProps(A){this.headProps??=A}getHeadProps(){return this.headProps}reset(){this.headProps=null}generateHeadHTML(){let A=[];if(A.push('<meta charset="UTF-8">'),A.push('<meta name="viewport" content="width=device-width, initial-scale=1.0">'),A.push('<meta http-equiv="X-UA-Compatible" content="IE=edge">'),A.push('<link rel="icon" type="image/svg+xml" href="/favicon.svg">'),A.push('<link rel="icon" type="image/png" href="/favicon.png">'),A.push('<link rel="stylesheet" href="/styles/main.css">'),!this.headProps)return A.push(`<title>${this.escapeHtml(this.defaultTitle)}</title>`),A.join(`
1711
+ `)}}B0();class vl extends EB{context;directorySync;constructor(A,Q,B){super(A,{schema:gL0,jobTypeName:"directory-export"});this.context=Q,this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let w=Date.now(),$={exported:0,failed:0,errors:[]};try{let D=A.entityTypes??this.context.entityService.getEntityTypes();this.logger.debug("Starting export",{jobId:Q,entityTypes:D}),await B.report({message:`Starting export of ${D.length} entity types`,progress:0,total:D.length});for(let[Y,I]of D.entries())await this.exportEntityType(I,A.batchSize??100,Q,$),await B.report({message:`Exported ${Y+1}/${D.length} entity types (${$.exported} entities)`,progress:Y+1,total:D.length});return this.logger.debug("Directory export job completed",{jobId:Q,exported:$.exported,failed:$.failed,duration:Date.now()-w}),$}catch(D){throw this.logger.error("Directory export job failed",{jobId:Q,error:D}),D}}async exportEntityType(A,Q,B,w){let $=0,D=!0;while(D){let Y=await this.context.entityService.listEntities(A,{limit:Q,offset:$});if(Y.length===0){D=!1;break}let I=Y.map(async(X)=>{let H=await this.directorySync.processEntityExport(X);if(H.success)w.exported++;else w.failed++,w.errors.push({entityId:X.id,entityType:A,error:H.error??"Unknown error"});return H});await Promise.all(I),this.logger.debug("Export progress",{jobId:B,entityType:A,processed:$+Y.length,exported:w.exported,failed:w.failed}),$+=Q,D=Y.length===Q}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}B0();GA();aD();class Sl extends EB{context;directorySync;constructor(A,Q,B){super(A,{schema:hL0,jobTypeName:"directory-import"});this.context=Q,this.directorySync=B}async process(A,Q,B){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let w=Date.now(),$={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]};try{let D=A.paths??await this.directorySync.getAllMarkdownFiles();this.logger.debug("Starting import",{jobId:Q,totalFiles:D.length}),await B.report({message:`Starting import of ${D.length} files`,progress:0,total:D.length});let Y=A.batchSize??100;for(let I=0;I<D.length;I+=Y){let X=D.slice(I,I+Y);await this.importBatch(X,Q,$,I,D.length);let H=Math.min(I+Y,D.length);await B.report({message:`Imported ${H}/${D.length} files (${$.imported} successful, ${$.failed} failed)`,progress:H,total:D.length})}return this.logger.debug("Directory import job completed",{jobId:Q,imported:$.imported,skipped:$.skipped,failed:$.failed,duration:Date.now()-w}),$}catch(D){throw this.logger.error("Directory import job failed",{jobId:Q,error:D}),D}}async importBatch(A,Q,B,w,$){let D=A.map(async(Y)=>{try{let I=await this.directorySync.fileOps.readEntity(Y);if(!this.context.entityService.getEntityTypes().includes(I.entityType))return B.skipped++,{success:!1,skipped:!0};try{let H=this.context.entityService.deserializeEntity(I.content,I.entityType),W=await this.context.entityService.getEntity(I.entityType,I.id);if(W){let J=new Date(W.updated).getTime(),Z=I.updated.getTime(),q=aB(I.content),V=W.contentHash!==q;if(J<Z||V){let E={...W,content:I.content,...H,id:I.id,entityType:I.entityType,updated:I.updated.toISOString()};await this.context.entityService.updateEntity(E),B.imported++}else B.skipped++}else{let J={id:I.id,entityType:I.entityType,content:I.content,...H,metadata:H.metadata??{},created:I.created.toISOString(),updated:I.updated.toISOString()};await this.context.entityService.createEntity(J),B.imported++}return{success:!0}}catch{return B.skipped++,{success:!1,skipped:!0}}}catch(I){return B.failed++,B.errors.push({path:Y,error:L0(I)}),{success:!1,error:I}}});await Promise.all(D),this.logger.debug("Import progress",{jobId:Q,processed:w+A.length,total:$,imported:B.imported,skipped:B.skipped,failed:B.failed})}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}B0();class hl extends EB{directorySync;context;constructor(A,Q,B){super(A,{schema:SL0,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 D={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},Y={exported:0,failed:0,errors:[]};if($!=="export")if(await B.report({progress:10,message:"Scanning directory for changes"}),D=await this.importWithProgress(A.paths,B),$==="import")await this.waitForImportJobs(D.jobIds,B),await B.report({progress:100,message:`Import complete: ${D.imported} imported`});else await B.report({progress:50,message:`Imported ${D.imported} entities`}),await this.waitForImportJobs(D.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"}),Y=await this.exportWithProgress(A.entityTypes,B),await B.report({progress:100,message:$==="export"?`Export complete: ${Y.exported} exported`:`Sync complete: ${D.imported} imported, ${Y.exported} exported`})}let I=Date.now()-w;return this.logger.info("Directory sync job completed",{jobId:Q,duration:I,imported:D.imported,exported:Y.exported}),{import:D,export:Y,duration:I}}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,D=Date.now(),Y=async()=>{let X=(await Promise.all(A.map((W)=>B.getAsyncJobStatus(W)))).filter((W)=>W&&(W.status==="completed"||W.status==="failed")).length;if(X===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-D>w){this.logger.warn(`Timeout waiting for import jobs (${X}/${A.length} completed)`);return}let H=Math.round(X/A.length*100);return await Q.report({progress:50+Math.round(H*0.05),message:`Processing ${X}/${A.length} entities`}),await new Promise((W)=>setTimeout(W,$)),Y()};return Y()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}B0();class gl extends EB{context;constructor(A,Q,B){super(A,{schema:CHA,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,B){let w=CHA.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(w.entityType,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}}}B0();GA();var d62=F.object({});class yl extends EB{directorySync;constructor(A,Q){super(A,{schema:d62,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}}B0();GA();import{readFile as i62,writeFile as r62}from"fs/promises";var n62=F.object({filePath:F.string(),sourceUrl:F.string().url(),postTitle:F.string(),postSlug:F.string(),customAlt:F.string().optional()});class ml extends EB{context;fetcher;constructor(A,Q,B=f7){super(Q,{schema:n62,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=B}async process(A,Q,B){let{filePath:w,sourceUrl:$,postTitle:D,postSlug:Y,customAlt:I}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:w,sourceUrl:$,postSlug:Y});try{await this.reportProgress(B,{progress:F2.INIT,message:`Reading file: ${w}`});let X;try{X=await i62(w,"utf-8")}catch(E){return this.logger.error("Failed to read file",{filePath:w,error:L0(E)}),K6.failure(E)}let H;try{H=uD(X)}catch(E){return this.logger.warn("Failed to parse markdown",{filePath:w,error:L0(E)}),K6.failure(E)}let W=H.frontmatter;if(W.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:w}),await this.reportProgress(B,{progress:F2.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress(B,{progress:F2.FETCH,message:"Checking for existing image"});let J=await this.context.entityService.listEntities("image",{filter:{metadata:{sourceUrl:$}},limit:1}),Z;if(J[0])Z=J[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:$,imageId:Z}),await this.reportProgress(B,{progress:F2.EXTRACT,message:`Reusing existing image: ${Z}`});else{await this.reportProgress(B,{progress:F2.PROCESS,message:`Fetching image from ${$}`});let E;try{E=await this.fetcher($)}catch(n){return this.logger.error("Failed to fetch image",{sourceUrl:$,error:L0(n)}),K6.failure(n)}await this.reportProgress(B,{progress:F2.GENERATE,message:"Creating image entity"});let{base64:L}=dW(E),j=LZ(L),_=iW(L);if(!j||!_)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:$}),K6.failure(Error("Could not detect image format or dimensions"));Z=`${Y}-cover`;let k=`Cover image for ${D}`,r=I??k;await this.context.entityService.createEntity({id:Z,entityType:"image",content:E,metadata:{title:k,alt:r,format:j,width:_.width,height:_.height,sourceUrl:$}}),this.logger.debug("Created image entity",{imageId:Z,sourceUrl:$}),await this.reportProgress(B,{progress:F2.EXTRACT,message:`Created image: ${Z}`})}await this.reportProgress(B,{progress:F2.SAVE,message:"Updating file"});let q={...W};delete q.coverImageUrl,delete q.coverImageAlt,q.coverImageId=Z;let V=M3(q,H.content);try{await r62(w,V,"utf-8")}catch(E){return this.logger.error("Failed to write file",{filePath:w,error:L0(E)}),K6.failure(E)}return await this.reportProgress(B,{progress:F2.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:w,imageId:Z,sourceUrl:$}),{success:!0,imageId:Z}}catch(X){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:w,error:L0(X)}),K6.failure(X)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}B0();GA();import{readFile as o62,writeFile as s62}from"fs/promises";class ul extends EB{converter;constructor(A,Q,B=f7){super(Q,{schema:yL0,jobTypeName:"inline-image-convert"});this.converter=new IP(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:F2.INIT,message:`Reading file: ${w}`});let D;try{D=await o62(w,"utf-8")}catch(X){let H=L0(X);return this.logger.error("Failed to read file",{filePath:w,error:H}),{success:!1,error:H}}await this.reportProgress(B,{progress:F2.FETCH,message:"Detecting inline images"});let Y=this.converter.detectInlineImages(D,$);if(Y.length===0)return this.logger.debug("No inline images to convert",{filePath:w}),await this.reportProgress(B,{progress:F2.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:w,count:Y.length}),await this.reportProgress(B,{progress:F2.PROCESS,message:`Converting ${Y.length} images`});let I=await this.converter.convert(D,$);if(!I.converted)return this.logger.debug("No images were converted",{filePath:w}),await this.reportProgress(B,{progress:F2.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress(B,{progress:F2.SAVE,message:"Writing updated file"});try{await s62(w,I.content,"utf-8")}catch(X){let H=L0(X);return this.logger.error("Failed to write file",{filePath:w,error:H}),{success:!1,error:H}}return await this.reportProgress(B,{progress:F2.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:w,convertedCount:I.convertedCount}),{success:!0,convertedCount:I.convertedCount}}catch(D){let Y=L0(D);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:w,error:Y}),{success:!1,error:Y}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function cL0(A,Q,B){let w=($)=>B.child($);A.jobs.registerHandler("directory-sync",new hl(w("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new vl(w("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new Sl(w("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new gl(w("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new yl(w("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new ml(A,w("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new ul(A,w("InlineImageConversionJobHandler"))),B.debug("Registered async job handlers")}B0();import{unlink as a62,access as t62}from"fs/promises";function lL0(A,Q,B,w){let{subscribe:$}=A.messaging,{entityService:D}=A;$("entity:created",async(Y)=>{let{entity:I}=Y.payload;try{await Q.fileOps.writeEntity(I),B.debug("Auto-exported created entity",{id:I.id,entityType:I.entityType})}catch(X){B.error("Auto-export FAILED for created entity",{id:I.id,entityType:I.entityType,error:X instanceof Error?X.message:String(X),stack:X instanceof Error?X.stack:void 0})}return{success:!0}}),$("entity:updated",async(Y)=>{let{entityType:I,entityId:X}=Y.payload;try{let H=await D.getEntity(I,X);if(!H)return B.debug("Entity not found in DB, skipping export",{entityType:I,entityId:X}),{success:!1};await Q.fileOps.writeEntity(H),B.debug("Auto-exported updated entity",{id:H.id,entityType:H.entityType})}catch(H){B.error("Auto-export FAILED for updated entity",{entityType:I,entityId:X,error:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0})}return{success:!0}}),$("entity:deleted",async(Y)=>{let{entityId:I,entityType:X}=Y.payload,H=Q.fileOps.getFilePath(I,X);if(await t62(H).then(()=>!0,()=>!1))await a62(H),B.debug("Auto-deleted entity file",{id:I,entityType:X,path:H});return{success:!0}}),B.debug("Setup auto-sync for entity events",{entityTypes:w})}function pL0(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:j6(),metadata:{operationType:"file_operations",operationTarget:B,pluginId:"directory-sync"}})})}GA();import{access as e62,readdir as dL0,mkdir as A52,copyFile as Q52}from"fs/promises";import{exec as B52}from"child_process";import{promisify as w52}from"util";import{join as fHA,resolve as OHA}from"path";var $52=w52(B52);async function cl(A){try{return await e62(A),!0}catch{return!1}}async function D52(A,Q){if(!await cl(A))return!0;if((await dL0(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await Y52(A))return Q.debug("Git repository with remote detected - skipping seed content",{path:A}),!1;return!0}async function Y52(A){let Q=fHA(A,".git");if(!await cl(Q))return!1;try{let{stdout:B}=await $52("git remote",{cwd:A});return B.trim().length>0}catch{return!1}}async function iL0(A,Q){let B=await dL0(A,{withFileTypes:!0});for(let w of B){let $=fHA(A,w.name),D=fHA(Q,w.name);if(w.isDirectory()){if(!await cl(D))await A52(D,{recursive:!0});await iL0($,D)}else await Q52($,D)}}async function rL0(A,Q,B){let w=OHA(process.cwd(),A);B=B?OHA(B):OHA(process.cwd(),"seed-content");let $=await D52(w,Q);if($&&await cl(B))Q.debug("Copying seed content to brain-data directory"),await iL0(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")}async function I52(A,Q,B,w=300000){let D=Date.now();while(Date.now()-D<w){let Y=await A.jobs.getBatchStatus(Q);if(Y&&(Y.status==="completed"||Y.status==="failed")){B.debug("Batch completed",{batchId:Q,status:Y.status,completed:Y.completedOperations,failed:Y.failedOperations});return}await new Promise((I)=>setTimeout(I,500))}B.warn(`Timeout waiting for batch ${Q} after ${w}ms`)}function nL0(A,Q,B,w,$,D){let Y=!1,I=async()=>{if(Y)return;Y=!0;let X=Q();if(B.seedContent){let H=B.syncPath??A.dataDir;await rL0(H,$,B.seedContentPath)}try{if(D){$.debug("Git enabled \u2014 pulling before import");let W=await D.pull();if(W.files.length>0)$.info("Pulled changes from remote",{filesChanged:W.files.length})}$.debug("Starting initial sync");let H=await X.queueSyncBatch(A,"initial-sync",void 0,{includeCleanup:!0});if(!H){$.debug("Initial sync: no files to import"),await A.messaging.send("sync:initial:completed",{success:!0},{broadcast:!0});return}$.debug("Initial sync: queued imports",{importOperations:H.importOperationsCount,totalFiles:H.totalFiles}),I52(A,H.batchId,$).then(()=>A.messaging.send("sync:initial:completed",{success:!0},{broadcast:!0}),(W)=>{$.error("Initial sync batch failed",W),A.messaging.send("sync:initial:completed",{success:!1,error:L0(W)},{broadcast:!0})})}catch(H){$.error("Initial sync failed",H),await A.messaging.send("sync:initial:completed",{success:!1,error:L0(H)},{broadcast:!0})}};A.messaging.subscribe("system:plugins:ready",async()=>{return $.debug("system:plugins:ready received, starting initial sync"),await I(),{success:!0}})}GA();function oL0(A,Q,B,w){let $=new R3(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(I){w.error("Git auto-commit failed",{error:I})}})},B),D=["entity:created","entity:updated","entity:deleted"],Y=[];for(let I of D){let X=A.subscribe(I,async()=>{return $.trigger(),{success:!0}});Y.push(X)}return()=>{$.dispose();for(let I of Y)I()}}function sL0(A,Q,B,w,$){if(w<=0)return()=>{};let D=w*60*1000,Y=!1,I=async()=>{if(Y)return;Y=!0;try{let{files:H}=await A.withLock(()=>A.pull());if(H.length>0)$.info("Periodic sync: pulled changes",{filesChanged:H.length});let W=await Q.queueSyncBatch(B,"periodic-sync");if(W)$.debug("Periodic sync: queued imports",{importOperations:W.importOperationsCount,totalFiles:W.totalFiles})}catch(H){$.error("Periodic git sync failed",{error:H})}finally{Y=!1}},X=setInterval(()=>{I()},D);return $.info("Started periodic git sync",{intervalMinutes:w}),()=>{clearInterval(X)}}function aL0(A,Q,B,w,$){let{subscribe:D}=A.messaging;D("entity:export:request",async(Y)=>{try{return{success:!0,data:await Q().exportEntities(Y.payload.entityTypes)}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Export failed"}}}),D("entity:import:request",async(Y)=>{try{let I=Q(),X=Y.payload.paths,H=await I.importEntities(X);if(X&&X.length>0)await I.removeOrphanedEntities();return{success:!0,data:H}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Import failed"}}}),D("sync:status:request",async()=>{try{let I=await Q().getStatus();return{success:!0,data:{syncPath:I.syncPath,isInitialized:I.exists,watchEnabled:I.watching}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Status check failed"}}}),D("sync:configure:request",async(Y)=>{try{return await B({syncPath:Y.payload.syncPath}),{success:!0,data:{syncPath:Y.payload.syncPath,configured:!0}}}catch(I){return{success:!1,error:I instanceof Error?I.message:"Configuration failed"}}}),D("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")}B0();GA();B0();GA();function tL0(A,Q){return yQ(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 D=await Q.show(B.sha,w);return O5({sha:B.sha,entityType:B.entityType,id:B.id,content:D},`Content at ${B.sha.slice(0,7)}`)}let $=await Q.log(w,B.limit);if($.length===0)return O5({commits:[]},`No history found for ${B.entityType}/${B.id}`);return O5({commits:$,entityType:B.entityType,id:B.id},`${$.length} version${$.length===1?"":"s"} found`)}catch($){return Ew($ instanceof Error?$.message:"History lookup failed")}})}function eL0(A,Q,B,w){let $=[yQ(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(D,Y)=>{try{let I=Y.channelId?`${Y.interfaceType}:${Y.channelId}`:`plugin:${B}`,X={interfaceType:Y.interfaceType,channelId:Y.channelId},H=!1;if(w)await w.withLock(()=>w.pull()),H=!0;let W=await A.queueSyncBatch(Q,I,X);if(!W)return O5({gitPulled:H},"No files to sync");return O5({batchId:W.batchId,importOperations:W.importOperationsCount,totalFiles:W.totalFiles,gitPulled:H},`Sync started: ${W.importOperationsCount} import jobs queued for ${W.totalFiles} files${H?" (pulled from git)":""}`)}catch(I){return Ew(I instanceof Error?I.message:"Sync failed")}},{cli:{name:"sync"}}),yQ(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 D=await A.getStatus(),Y={syncPath:D.syncPath,lastSync:D.lastSync?.toISOString(),watching:D.watching};if(w){let I=await w.getStatus();Y.git={isRepo:I.isRepo,branch:I.branch,hasChanges:I.hasChanges,ahead:I.ahead,behind:I.behind,remote:I.remote}}return O5(Y)}catch(D){return Ew(D instanceof Error?D.message:"Status check failed")}},{visibility:"public"})];if(w)$.push(tL0(B,w));return $}var AM0={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.42",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/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 RHA extends tB{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",AM0,A,vL0)}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:zP,basePrompt:"",formatter:new Tl,requiredPermission:"anchor"}});let w=this.config.syncPath??A.dataDir;this.directorySync=new XP({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(Y){throw this.logger.error("Failed to initialize directory",Y),Y}await this.registerJobHandlers(A);let $=this.requireDirectorySync();if(lL0(A,$,this.logger,this.config.entityTypes),this.config.autoSync)pL0(A,$,this.config.syncPath??A.dataDir);let D=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!D)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(D&&this.config.git){let Y=this.config.syncPath??A.dataDir;if(this.gitSync=new EHA({logger:this.logger.child("GitSync"),dataDir:Y,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(oL0(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(sL0(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)nL0(A,()=>this.requireDirectorySync(),this.config,this.id,this.logger,this.gitSync);aL0(A,()=>this.requireDirectorySync(),(Y)=>this.configure(Y),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return eL0(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 XP({...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){cL0(A,this.requireDirectorySync(),this.logger)}}function zF(A={}){return new RHA(A)}B0();B0();GA();GA();var QM0=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:F.object({title:F.string(),description:F.string(),url:F.string().optional(),copyright:F.string().optional(),themeMode:F.enum(["light","dark"]).optional(),analyticsScript:F.string().optional()}),layouts:F.record(F.any()),themeCSS:F.string().optional()}),WmQ=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()});import{render as O_0}from"preact-render-to-string";import{h as pF}from"preact";class jHA{headProps=null;defaultTitle;constructor(A){this.defaultTitle=A}setHeadProps(A){this.headProps??=A}getHeadProps(){return this.headProps}reset(){this.headProps=null}generateHeadHTML(){let A=[];if(A.push('<meta charset="UTF-8">'),A.push('<meta name="viewport" content="width=device-width, initial-scale=1.0">'),A.push('<meta http-equiv="X-UA-Compatible" content="IE=edge">'),A.push('<link rel="icon" type="image/svg+xml" href="/favicon.svg">'),A.push('<link rel="icon" type="image/png" href="/favicon.png">'),A.push('<link rel="stylesheet" href="/styles/main.css">'),!this.headProps)return A.push(`<title>${this.escapeHtml(this.defaultTitle)}</title>`),A.join(`
1712
1712
  `);let{title:Q,description:B,ogImage:w,ogType:$,twitterCard:D,canonicalUrl:Y}=this.headProps;if(A.push(`<title>${this.escapeHtml(Q)}</title>`),B)A.push(`<meta name="description" content="${this.escapeHtml(B)}">`);if(A.push(`<meta property="og:title" content="${this.escapeHtml(Q)}">`),B)A.push(`<meta property="og:description" content="${this.escapeHtml(B)}">`);if(A.push(`<meta property="og:type" content="${$??"website"}">`),w)A.push(`<meta property="og:image" content="${this.escapeHtml(w)}">`);if(A.push(`<meta name="twitter:card" content="${D??"summary_large_image"}">`),A.push(`<meta name="twitter:title" content="${this.escapeHtml(Q)}">`),B)A.push(`<meta name="twitter:description" content="${this.escapeHtml(B)}">`);if(w)A.push(`<meta name="twitter:image" content="${this.escapeHtml(w)}">`);if(Y)A.push(`<link rel="canonical" href="${this.escapeHtml(Y)}">`);return A.join(`
1713
1713
  `)}escapeHtml(A){let Q={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return A.replace(/[&<>"']/g,(B)=>Q[B]??B)}}function BM0(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=BM0(A[Q]))&&(w&&(w+=" "),w+=B)}else for(B in A)A[B]&&(w&&(w+=" "),w+=B);return w}function ll(){for(var A,Q,B=0,w="",$=arguments.length;B<$;B++)(A=arguments[B])&&(Q=BM0(A))&&(w&&(w+=" "),w+=Q);return w}var H52=(A)=>{let Q=U52(A),{conflictingClassGroups:B,conflictingClassGroupModifiers:w}=A;return{getClassGroupId:(Y)=>{let I=Y.split("-");if(I[0]===""&&I.length!==1)I.shift();return IM0(I,Q)||K52(Y)},getConflictingClassGroupIds:(Y,I)=>{let X=B[Y]||[];if(I&&w[Y])return[...X,...w[Y]];return X}}},IM0=(A,Q)=>{if(A.length===0)return Q.classGroupId;let B=A[0],w=Q.nextPart.get(B),$=w?IM0(A.slice(1),w):void 0;if($)return $;if(Q.validators.length===0)return;let D=A.join("-");return Q.validators.find(({validator:Y})=>Y(D))?.classGroupId},wM0=/^\[(.+)\]$/,K52=(A)=>{if(wM0.test(A)){let Q=wM0.exec(A)[1],B=Q?.substring(0,Q.indexOf(":"));if(B)return"arbitrary.."+B}},U52=(A)=>{let{theme:Q,prefix:B}=A,w={nextPart:new Map,validators:[]};return G52(Object.entries(A.classGroups),B).forEach(([D,Y])=>{PHA(Y,w,D,Q)}),w},PHA=(A,Q,B,w)=>{A.forEach(($)=>{if(typeof $==="string"){let D=$===""?Q:$M0(Q,$);D.classGroupId=B;return}if(typeof $==="function"){if(W52($)){PHA($(w),Q,B,w);return}Q.validators.push({validator:$,classGroupId:B});return}Object.entries($).forEach(([D,Y])=>{PHA(Y,$M0(Q,D),B,w)})})},$M0=(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},W52=(A)=>A.isThemeGetter,G52=(A,Q)=>{if(!Q)return A;return A.map(([B,w])=>{let $=w.map((D)=>{if(typeof D==="string")return Q+D;if(typeof D==="object")return Object.fromEntries(Object.entries(D).map(([Y,I])=>[Q+Y,I]));return D});return[B,$]})},J52=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,B=new Map,w=new Map,$=(D,Y)=>{if(B.set(D,Y),Q++,Q>A)Q=0,w=B,B=new Map};return{get(D){let Y=B.get(D);if(Y!==void 0)return Y;if((Y=w.get(D))!==void 0)return $(D,Y),Y},set(D,Y){if(B.has(D))B.set(D,Y);else $(D,Y)}}};var Z52=(A)=>{let{separator:Q,experimentalParseClassName:B}=A,w=Q.length===1,$=Q[0],D=Q.length,Y=(I)=>{let X=[],H=0,W=0,J;for(let L=0;L<I.length;L++){let j=I[L];if(H===0){if(j===$&&(w||I.slice(L,L+D)===Q)){X.push(I.slice(W,L)),W=L+D;continue}if(j==="/"){J=L;continue}}if(j==="[")H++;else if(j==="]")H--}let Z=X.length===0?I:I.substring(W),q=Z.startsWith("!"),V=q?Z.substring(1):Z,E=J&&J>W?J-W:void 0;return{modifiers:X,hasImportantModifier:q,baseClassName:V,maybePostfixModifierPosition:E}};if(B)return(I)=>B({className:I,parseClassName:Y});return Y},F52=(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},q52=(A)=>({cache:J52(A.cacheSize),parseClassName:Z52(A),...H52(A)}),z52=/\s+/,N52=(A,Q)=>{let{parseClassName:B,getClassGroupId:w,getConflictingClassGroupIds:$}=Q,D=[],Y=A.trim().split(z52),I="";for(let X=Y.length-1;X>=0;X-=1){let H=Y[X],{modifiers:W,hasImportantModifier:J,baseClassName:Z,maybePostfixModifierPosition:q}=B(H),V=Boolean(q),E=w(V?Z.substring(0,q):Z);if(!E){if(!V){I=H+(I.length>0?" "+I:I);continue}if(E=w(Z),!E){I=H+(I.length>0?" "+I:I);continue}V=!1}let L=F52(W).join(":"),j=J?L+"!":L,_=j+E;if(D.includes(_))continue;D.push(_);let k=$(E,V);for(let r=0;r<k.length;++r){let n=k[r];D.push(j+n)}I=H+(I.length>0?" "+I:I)}return I};function V52(){let A=0,Q,B,w="";while(A<arguments.length)if(Q=arguments[A++]){if(B=XM0(Q))w&&(w+=" "),w+=B}return w}var XM0=(A)=>{if(typeof A==="string")return A;let Q,B="";for(let w=0;w<A.length;w++)if(A[w]){if(Q=XM0(A[w]))B&&(B+=" "),B+=Q}return B};function DM0(A,...Q){let B,w,$,D=Y;function Y(X){let H=Q.reduce((W,J)=>J(W),A());return B=q52(H),w=B.cache.get,$=B.cache.set,D=I,I(X)}function I(X){let H=w(X);if(H)return H;let W=N52(X,B);return $(X,W),W}return function(){return D(V52.apply(null,arguments))}}var L8=(A)=>{let Q=(B)=>B[A]||[];return Q.isThemeGetter=!0,Q},HM0=/^\[(?:([a-z-]+):)?(.+)\]$/i,L52=/^\d+\/\d+$/,M52=new Set(["px","full","screen"]),E52=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,C52=/\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$/,O52=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,f52=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,R52=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,kK=(A)=>DM(A)||M52.has(A)||L52.test(A),xG=(A)=>YM(A,"length",v52),DM=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),kHA=(A)=>YM(A,"number",DM),NP=(A)=>Boolean(A)&&Number.isInteger(Number(A)),j52=(A)=>A.endsWith("%")&&DM(A.slice(0,-1)),YQ=(A)=>HM0.test(A),TG=(A)=>E52.test(A),k52=new Set(["length","size","percentage"]),P52=(A)=>YM(A,k52,KM0),_52=(A)=>YM(A,"position",KM0),b52=new Set(["image","url"]),x52=(A)=>YM(A,b52,h52),T52=(A)=>YM(A,"",S52),VP=()=>!0,YM=(A,Q,B)=>{let w=HM0.exec(A);if(w){if(w[1])return typeof Q==="string"?w[1]===Q:Q.has(w[1]);return B(w[2])}return!1},v52=(A)=>C52.test(A)&&!O52.test(A),KM0=()=>!1,S52=(A)=>f52.test(A),h52=(A)=>R52.test(A);var YM0=()=>{let A=L8("colors"),Q=L8("spacing"),B=L8("blur"),w=L8("brightness"),$=L8("borderColor"),D=L8("borderRadius"),Y=L8("borderSpacing"),I=L8("borderWidth"),X=L8("contrast"),H=L8("grayscale"),W=L8("hueRotate"),J=L8("invert"),Z=L8("gap"),q=L8("gradientColorStops"),V=L8("gradientColorStopPositions"),E=L8("inset"),L=L8("margin"),j=L8("opacity"),_=L8("padding"),k=L8("saturate"),r=L8("scale"),n=L8("sepia"),h=L8("skew"),T=L8("space"),S=L8("translate"),y=()=>["auto","contain","none"],t=()=>["auto","hidden","clip","visible","scroll"],c=()=>["auto",YQ,Q],UA=()=>[YQ,Q],IA=()=>["",kK,xG],P=()=>["auto",DM,YQ],R=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],b=()=>["solid","dashed","dotted","double","none"],s=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],d=()=>["start","end","center","between","around","evenly","stretch"],e=()=>["","0",YQ],i=()=>["auto","avoid","all","avoid-page","page","left","right","column"],KA=()=>[DM,YQ];return{cacheSize:500,separator:":",theme:{colors:[VP],spacing:[kK,xG],blur:["none","",TG,YQ],brightness:KA(),borderColor:[A],borderRadius:["none","","full",TG,YQ],borderSpacing:UA(),borderWidth:IA(),contrast:KA(),grayscale:e(),hueRotate:KA(),invert:e(),gap:UA(),gradientColorStops:[A],gradientColorStopPositions:[j52,xG],inset:c(),margin:c(),opacity:KA(),padding:UA(),saturate:KA(),scale:KA(),sepia:e(),skew:KA(),space:UA(),translate:UA()},classGroups:{aspect:[{aspect:["auto","square","video",YQ]}],container:["container"],columns:[{columns:[TG]}],"break-after":[{"break-after":i()}],"break-before":[{"break-before":i()}],"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:[...R(),YQ]}],overflow:[{overflow:t()}],"overflow-x":[{"overflow-x":t()}],"overflow-y":[{"overflow-y":t()}],overscroll:[{overscroll:y()}],"overscroll-x":[{"overscroll-x":y()}],"overscroll-y":[{"overscroll-y":y()}],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",NP,YQ]}],basis:[{basis:c()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",YQ]}],grow:[{grow:e()}],shrink:[{shrink:e()}],order:[{order:["first","last","none",NP,YQ]}],"grid-cols":[{"grid-cols":[VP]}],"col-start-end":[{col:["auto",{span:["full",NP,YQ]},YQ]}],"col-start":[{"col-start":P()}],"col-end":[{"col-end":P()}],"grid-rows":[{"grid-rows":[VP]}],"row-start-end":[{row:["auto",{span:[NP,YQ]},YQ]}],"row-start":[{"row-start":P()}],"row-end":[{"row-end":P()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",YQ]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",YQ]}],gap:[{gap:[Z]}],"gap-x":[{"gap-x":[Z]}],"gap-y":[{"gap-y":[Z]}],"justify-content":[{justify:["normal",...d()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...d(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...d(),"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":[T]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[T]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",YQ,Q]}],"min-w":[{"min-w":[YQ,Q,"min","max","fit"]}],"max-w":[{"max-w":[YQ,Q,"none","full","min","max","fit","prose",{screen:[TG]},TG]}],h:[{h:[YQ,Q,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[YQ,Q,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[YQ,Q,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[YQ,Q,"auto","min","max","fit"]}],"font-size":[{text:["base",TG,xG]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",kHA]}],"font-family":[{font:[VP]}],"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",YQ]}],"line-clamp":[{"line-clamp":["none",DM,kHA]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",kK,YQ]}],"list-image":[{"list-image":["none",YQ]}],"list-style-type":[{list:["none","disc","decimal",YQ]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[A]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[A]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...b(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",kK,xG]}],"underline-offset":[{"underline-offset":["auto",kK,YQ]}],"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:UA()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",YQ]}],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",YQ]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...R(),_52]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",P52]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},x52]}],"bg-color":[{bg:[A]}],"gradient-from-pos":[{from:[V]}],"gradient-via-pos":[{via:[V]}],"gradient-to-pos":[{to:[V]}],"gradient-from":[{from:[q]}],"gradient-via":[{via:[q]}],"gradient-to":[{to:[q]}],rounded:[{rounded:[D]}],"rounded-s":[{"rounded-s":[D]}],"rounded-e":[{"rounded-e":[D]}],"rounded-t":[{"rounded-t":[D]}],"rounded-r":[{"rounded-r":[D]}],"rounded-b":[{"rounded-b":[D]}],"rounded-l":[{"rounded-l":[D]}],"rounded-ss":[{"rounded-ss":[D]}],"rounded-se":[{"rounded-se":[D]}],"rounded-ee":[{"rounded-ee":[D]}],"rounded-es":[{"rounded-es":[D]}],"rounded-tl":[{"rounded-tl":[D]}],"rounded-tr":[{"rounded-tr":[D]}],"rounded-br":[{"rounded-br":[D]}],"rounded-bl":[{"rounded-bl":[D]}],"border-w":[{border:[I]}],"border-w-x":[{"border-x":[I]}],"border-w-y":[{"border-y":[I]}],"border-w-s":[{"border-s":[I]}],"border-w-e":[{"border-e":[I]}],"border-w-t":[{"border-t":[I]}],"border-w-r":[{"border-r":[I]}],"border-w-b":[{"border-b":[I]}],"border-w-l":[{"border-l":[I]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...b(),"hidden"]}],"divide-x":[{"divide-x":[I]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[I]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:b()}],"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:["",...b()]}],"outline-offset":[{"outline-offset":[kK,YQ]}],"outline-w":[{outline:[kK,xG]}],"outline-color":[{outline:[A]}],"ring-w":[{ring:IA()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[A]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[kK,xG]}],"ring-offset-color":[{"ring-offset":[A]}],shadow:[{shadow:["","inner","none",TG,T52]}],"shadow-color":[{shadow:[VP]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...s(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":s()}],filter:[{filter:["","none"]}],blur:[{blur:[B]}],brightness:[{brightness:[w]}],contrast:[{contrast:[X]}],"drop-shadow":[{"drop-shadow":["","none",TG,YQ]}],grayscale:[{grayscale:[H]}],"hue-rotate":[{"hue-rotate":[W]}],invert:[{invert:[J]}],saturate:[{saturate:[k]}],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":[H]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[W]}],"backdrop-invert":[{"backdrop-invert":[J]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[k]}],"backdrop-sepia":[{"backdrop-sepia":[n]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[Y]}],"border-spacing-x":[{"border-spacing-x":[Y]}],"border-spacing-y":[{"border-spacing-y":[Y]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",YQ]}],duration:[{duration:KA()}],ease:[{ease:["linear","in","out","in-out",YQ]}],delay:[{delay:KA()}],animate:[{animate:["none","spin","ping","pulse","bounce",YQ]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[r]}],"scale-x":[{"scale-x":[r]}],"scale-y":[{"scale-y":[r]}],rotate:[{rotate:[NP,YQ]}],"translate-x":[{"translate-x":[S]}],"translate-y":[{"translate-y":[S]}],"skew-x":[{"skew-x":[h]}],"skew-y":[{"skew-y":[h]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",YQ]}],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",YQ]}],"caret-color":[{caret:[A]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":UA()}],"scroll-mx":[{"scroll-mx":UA()}],"scroll-my":[{"scroll-my":UA()}],"scroll-ms":[{"scroll-ms":UA()}],"scroll-me":[{"scroll-me":UA()}],"scroll-mt":[{"scroll-mt":UA()}],"scroll-mr":[{"scroll-mr":UA()}],"scroll-mb":[{"scroll-mb":UA()}],"scroll-ml":[{"scroll-ml":UA()}],"scroll-p":[{"scroll-p":UA()}],"scroll-px":[{"scroll-px":UA()}],"scroll-py":[{"scroll-py":UA()}],"scroll-ps":[{"scroll-ps":UA()}],"scroll-pe":[{"scroll-pe":UA()}],"scroll-pt":[{"scroll-pt":UA()}],"scroll-pr":[{"scroll-pr":UA()}],"scroll-pb":[{"scroll-pb":UA()}],"scroll-pl":[{"scroll-pl":UA()}],"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",YQ]}],fill:[{fill:[A,"none"]}],"stroke-w":[{stroke:[kK,xG,kHA]}],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"]}}},g52=(A,{cacheSize:Q,prefix:B,separator:w,experimentalParseClassName:$,extend:D={},override:Y={}})=>{LP(A,"cacheSize",Q),LP(A,"prefix",B),LP(A,"separator",w),LP(A,"experimentalParseClassName",$);for(let I in Y)y52(A[I],Y[I]);for(let I in D)m52(A[I],D[I]);return A},LP=(A,Q,B)=>{if(B!==void 0)A[Q]=B},y52=(A,Q)=>{if(Q)for(let B in Q)LP(A,B,Q[B])},m52=(A,Q)=>{if(Q)for(let B in Q){let w=Q[B];if(w!==void 0)A[B]=(A[B]||[]).concat(w)}},UM0=(A,...Q)=>typeof A==="function"?DM0(YM0,A,...Q):DM0(()=>g52(YM0(),A),...Q);var u52=UM0({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 g1(...A){return u52(ll(A))}var WM0=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,GM0=ll,uB=(A,Q)=>(B)=>{var w;if((Q===null||Q===void 0?void 0:Q.variants)==null)return GM0(A,B===null||B===void 0?void 0:B.class,B===null||B===void 0?void 0:B.className);let{variants:$,defaultVariants:D}=Q,Y=Object.keys($).map((H)=>{let W=B===null||B===void 0?void 0:B[H],J=D===null||D===void 0?void 0:D[H];if(W===null)return null;let Z=WM0(W)||WM0(J);return $[H][Z]}),I=B&&Object.entries(B).reduce((H,W)=>{let[J,Z]=W;if(Z===void 0)return H;return H[J]=Z,H},{}),X=Q===null||Q===void 0?void 0:(w=Q.compoundVariants)===null||w===void 0?void 0:w.reduce((H,W)=>{let{class:J,className:Z,...q}=W;return Object.entries(q).every((V)=>{let[E,L]=V;return Array.isArray(L)?L.includes({...D,...I}[E]):{...D,...I}[E]===L})?[...H,J,Z]:H},[]);return GM0(A,Y,X,B===null||B===void 0?void 0:B.class,B===null||B===void 0?void 0:B.className)};import{jsxDEV as _HA}from"preact/jsx-dev-runtime";var JM0=uB("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 bHA({variant:A,title:Q,children:B,className:w}){return _HA("div",{className:g1(JM0({variant:A}),w),role:"alert",children:[Q&&_HA("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),_HA("div",{className:g1(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 c52}from"preact/jsx-dev-runtime";var ZM0=uB("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 NF({variant:A,size:Q,className:B,children:w,ssrOnClick:$,type:D="button",...Y}){return c52("button",{type:D,className:g1(ZM0({variant:A,size:Q}),B),...Y,...$&&{onclick:$},children:w},void 0,!1,void 0,this)}import{jsxDEV as l52}from"preact/jsx-dev-runtime";var FM0=uB("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 J5({href:A,children:Q,variant:B,size:w,external:$=!1,className:D,"aria-label":Y}){let I=$?{target:"_blank",rel:"noopener noreferrer"}:{};return l52("a",{href:A,className:g1(FM0({variant:B,size:w}),D),"aria-label":Y,...I,children:Q},void 0,!1,void 0,this)}import{jsxDEV as pl}from"preact/jsx-dev-runtime";var qM0=uB("rounded-full transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2",{variants:{variant:{default:"bg-theme-muted/50 hover:bg-theme-muted text-theme",light:"bg-theme-subtle hover:bg-theme-muted text-theme",dark:"bg-theme-dark hover:bg-theme-muted text-theme-inverse",footer:"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"}}),p52={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function IM({variant:A,size:Q,className:B}){let w=p52[Q??"md"];return pl("button",{onclick:"toggleTheme()",type:"button",className:g1(qM0({variant:A,size:Q}),B),"aria-label":"Toggle dark mode",children:pl("svg",{className:g1(w,"transition-colors"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[pl("path",{className:"sun-icon",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,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),pl("path",{className:"moon-icon",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z",transform:"rotate(45 12 12)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as xHA}from"preact/jsx-dev-runtime";var zM0=uB("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function dl({items:A,className:Q,linkClassName:B="hover:text-accent transition-colors",orientation:w,children:$}){if(A.length===0&&!$)return null;let D=[...A].sort((Y,I)=>Y.priority-I.priority);return xHA("ul",{className:g1(zM0({orientation:w}),Q),children:[D.map((Y)=>xHA("li",{children:xHA("a",{href:Y.href,className:B,children:Y.label},void 0,!1,void 0,this)},Y.href,!1,void 0,this)),$]},void 0,!0,void 0,this)}import{jsxDEV as lmQ}from"preact/jsx-dev-runtime";import{jsxDEV as imQ}from"preact/jsx-dev-runtime";GA();GA();import{createContext as d52,h as i52}from"preact";import{useContext as r52}from"preact/hooks";var NM0=d52(null);function il({imageRenderer:A,children:Q}){return i52(NM0.Provider,{value:A??null},Q)}function VM0(){return r52(NM0)}function VF(){let A=VM0();return(Q)=>mT(Q,A?{imageRenderer:A}:void 0)}import{jsxDEV as PK}from"preact/jsx-dev-runtime";var THA=({markdown:A})=>{let Q=VF(),w=A.split(/^---$/gm).map((Y)=>Y.trim()).map((Y)=>{let{attributes:I,markdown:X}=Xv(Y),H=Hv(X),W;if(H)W=`<div class="slide-columns">${H.map((Z)=>`<div class="slide-column">${IO(Q(Z.trim()))}</div>`).join("")}</div>`;else W=IO(Q(X));return{attributes:I,htmlContent:W}}),$=w.some((Y)=>Y.htmlContent.includes('class="mermaid"')),D=w.map(({attributes:Y,htmlContent:I},X)=>PK("section",{...Y,dangerouslySetInnerHTML:{__html:I}},X,!1,void 0,this));return PK("section",{className:"presentation-section",children:[PK("link",{rel:"stylesheet",href:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.css"},void 0,!1,void 0,this),PK("div",{className:"reveal",children:PK("div",{className:"slides",children:D},void 0,!1,void 0,this)},void 0,!1,void 0,this),PK("script",{src:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.js",defer:!0},void 0,!1,void 0,this),$&&PK("script",{src:"https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js",defer:!0},void 0,!1,void 0,this),PK("script",{dangerouslySetInnerHTML:{__html:`
1714
1714
  window.addEventListener('DOMContentLoaded', () => {
@@ -2534,7 +2534,7 @@ ${Q.join(`
2534
2534
  `+$:B,Y=CX(this.outputDir,"styles","main.css");await this.cssProcessor.process(D,Y,this.workingDir,this.outputDir,this.logger);let I=await gw.readFile(Y,"utf-8"),X=w.length>0?w:Q;if(X.length>0){let H=X.join(`
2535
2535
  `)+`
2536
2536
 
2537
- `+I;await gw.writeFile(Y,H,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=CX(process.cwd(),"public");try{await gw.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await gw.readdir(A,{withFileTypes:!0});for(let B of Q){let w=CX(A,B.name),$=CX(this.outputDir,B.name);if(B.isDirectory())await this.copyDirectory(w,$);else await gw.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,D=CX(this.outputDir,$);await gw.mkdir(UG2(D),{recursive:!0}),await gw.writeFile(D,w,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await gw.mkdir(Q,{recursive:!0});let B=await gw.readdir(A,{withFileTypes:!0});for(let w of B){let $=CX(A,w.name),D=CX(Q,w.name);if(w.isDirectory())await this.copyDirectory($,D);else await gw.copyFile($,D)}}}function JWA(A){return new f_0(A)}function WG2(A,Q){let B=new Map;for(let w of A.sections){let $=Q.getViewTemplate(w.template);if(!$?.runtimeScripts)continue;for(let D of $.runtimeScripts)if(!B.has(D.src))B.set(D.src,D)}return[...B.values()].map((w)=>{let $=[`src="${w.src}"`];if(w.defer)$.push("defer");if(w.module)$.push('type="module"');return`<script ${$.join(" ")}></script>`})}import{join as yF2}from"path";GA();class ZWA{context;routeRegistry;entityDisplay;constructor(A,Q,B){this.context=A;this.routeRegistry=Q;this.entityDisplay=B}async generateEntityRoutes(){let A=this.context.logger.child("DynamicRouteGenerator"),Q=this.routeRegistry.list(),B=0;for(let $ of Q)if($.sourceEntityType)this.routeRegistry.unregister($.path),B++;if(B>0)A.debug(`Cleared ${B} dynamic routes before regeneration`);let w=this.context.entityService.getEntityTypes();A.debug(`Found ${w.length} entity types`,{entityTypes:w});for(let $ of w)await this.generateRoutesForEntityType($)}async generateRoutesForEntityType(A){let Q=this.context.logger.child("DynamicRouteGenerator"),{listTemplateName:B,detailTemplateName:w}=this.findTemplatesForEntityType(A);if(!B&&!w){Q.debug(`No matching templates found for entity type: ${A}`);return}if(Q.debug(`Generating routes for entity type: ${A}`,{listTemplate:B,detailTemplate:w}),B){let{pluralName:$,label:D,layout:Y,paginate:I,pageSize:X,navigation:H}=this.getEntityDisplayConfig(A);if(I)await this.generatePaginatedRoutes(A,B,$,D,Y,X,H,Q);else{let W={id:`${A}-index`,path:`/${$}`,title:D,description:`Browse all ${$}`,...Y&&{layout:Y},navigation:{show:H.show,label:D,slot:H.slot,priority:H.priority},sections:[{id:"list",template:B,dataQuery:{entityType:A,query:{limit:100}}}],sourceEntityType:A};try{this.routeRegistry.register(W),Q.debug(`Registered index route for ${A}`,{path:W.path})}catch(J){Q.warn(`Failed to register index route for ${A}`,{error:J})}}}if(w)try{let $=await this.context.entityService.listEntities(A,{limit:1000});Q.debug(`Found ${$.length} ${A} entities to generate routes for`);let{pluralName:D,layout:Y}=this.getEntityDisplayConfig(A);for(let X of $){let H="slug"in X.metadata?X.metadata.slug:X.id,W={id:`${A}-${X.id}`,path:`/${D}/${H}`,title:`${this.capitalize(A)}: ${H}`,description:`View ${A} details`,...Y&&{layout:Y},sections:[{id:"detail",template:w,dataQuery:{entityType:A,query:{id:H}}}],sourceEntityType:A};try{this.routeRegistry.register(W)}catch(J){Q.warn(`Failed to register detail route for ${A}/${X.id}`,{error:J})}}let I=B?$.length+1:$.length;Q.debug(`Successfully registered ${I} routes for ${A}`)}catch($){Q.error(`Failed to list entities for type: ${A}`,{error:$})}}async generatePaginatedRoutes(A,Q,B,w,$,D,Y,I){let H=(await this.context.entityService.listEntities(A,{limit:1000})).length,W=Math.max(1,Math.ceil(H/D));I.debug(`Generating ${W} paginated routes for ${A}`,{totalItems:H,pageSize:D});for(let J=1;J<=W;J++){let Z=J===1,q=Z?`/${B}`:`/${B}/page/${J}`,V={id:`${A}-index${Z?"":`-page-${J}`}`,path:q,title:Z?w:`${w} - Page ${J}`,description:`Browse all ${B}${Z?"":` - Page ${J}`}`,...$&&{layout:$},navigation:Z?{show:Y.show,label:w,slot:Y.slot,priority:Y.priority}:void 0,sections:[{id:"list",template:Q,dataQuery:{entityType:A,query:{page:J,pageSize:D,baseUrl:`/${B}`}}}],sourceEntityType:A};try{this.routeRegistry.register(V),I.debug(`Registered paginated route for ${A}`,{path:V.path,page:J})}catch(E){I.warn(`Failed to register paginated route for ${A} page ${J}`,{error:E})}}}findTemplatesForEntityType(A){let Q=this.context.views.list(),B,w,$=`${A}-list`,D=`${A}-detail`;for(let I of Q){let X=I.name;if(X.endsWith($)){let H=X.slice(0,-$.length);if(H===""||H.endsWith(":"))B=X}if(X.endsWith(D)){let H=X.slice(0,-D.length);if(H===""||H.endsWith(":"))w=X}}let Y={};if(B)Y.listTemplateName=B;if(w)Y.detailTemplateName=w;return Y}getEntityDisplayConfig(A){let Q=this.entityDisplay?.[A],B=10,w=!0,$=!0,D="primary",Y=40;if(Q){let X=Q.pluralName??E$(Q.label.toLowerCase()),H=this.capitalize(E$(Q.label.toLowerCase()));return{pluralName:X,label:H,...Q.layout&&{layout:Q.layout},paginate:Q.paginate??!0,pageSize:Q.pageSize??10,navigation:{show:Q.navigation?.show??!0,slot:Q.navigation?.slot??"primary",priority:Q.navigation?.priority??40}}}let I=E$(A);return{pluralName:I,label:this.capitalize(I),paginate:!0,pageSize:10,navigation:{show:!0,slot:"primary",priority:40}}}capitalize(A){return A.split(" ").map((Q)=>Q.charAt(0).toUpperCase()+Q.slice(1)).join(" ")}}B0();GA();B0();var R_0=F.object({}),f_=Q2.extend({id:F.literal("site-info"),entityType:F.literal("site-info"),metadata:R_0}),R_=F.object({heading:F.string().describe("Main CTA heading text"),buttonText:F.string().describe("Call-to-action button text"),buttonLink:F.string().describe("URL or anchor for the CTA button")}),OX=F.object({title:F.string().describe("The site's title"),description:F.string().describe("The site's description"),copyright:F.string().optional().describe("Copyright notice text"),logo:F.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:F.enum(["light","dark"]).optional().describe("Default theme mode"),cta:R_.optional().describe("Call-to-action configuration")});B0();class uY extends I2{constructor(){super({entityType:"site-info",schema:f_,frontmatterSchema:OX,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=OX.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 fX{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,B){return fX.instance??=new fX(A,Q,B),fX.instance}static resetInstance(){fX.instance=null}static createFresh(A,Q,B){return new fX(A,Q,B)}constructor(A,Q,B){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new uY;let w=fX.getDefaultSiteInfo();this.defaultSiteInfo={...w,...B}}async initialize(){try{if(!await this.entityService.getEntity("site-info","site-info")){this.logger.info("No site info found, creating default site info");let Q=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({id:"site-info",entityType:"site-info",content:Q,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("site-info","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 GG2=new uY;class Td{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 I=await w.getEntity("site-info","site-info");$=I?GG2.parseSiteInfoBody(I.content):{title:"Brain",description:"A knowledge management system"}}catch{$={title:"Brain",description:"A knowledge management system"}}let D;try{let I=await w.getEntity("anchor-profile","anchor-profile");if(I)D=I.metadata.socialLinks}catch{}let Y={...$,socialLinks:D,copyright:$.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:Y.title,hasSocialLinks:!!Y.socialLinks}),Q.parse(Y)}}var j_0={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.41",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/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 ZG2=new uY;class FWA extends HQ{entityType="site-info";schema=f_;adapter=ZG2;defaultSiteInfo;constructor(A){super("site-info",j_0);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new Td(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=fX.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function dF(A){return new FWA(A)}var FG2=new uY;async function iK(A){let B=(await A.listEntities("site-info",{limit:1}))[0];if(!B)throw Error("Site info not found \u2014 create a site-info entity");return FG2.parseSiteInfoBody(B.content)}GA();var qG2=OX.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")});async function k_0(A,Q,B){let w;try{w=await iK(A)}catch{w={title:"Brain",description:"A knowledge management system"}}let $=Q.getProfile(),D=B.getNavigationItems("primary"),Y=B.getNavigationItems("secondary");return{...w,socialLinks:$.socialLinks,navigation:{primary:D,secondary:Y},copyright:w.copyright??"Powered by Rizom"}}GA();GA();import{promises as ex0}from"fs";import{join as gF2}from"path";import{createHash as xF2}from"crypto";import{promises as lWA}from"fs";import{join as ox0}from"path";var sx0=null;async function TF2(){return sx0??=Promise.resolve().then(() => o0(nx0(),1)).then((A)=>A.default),sx0}var vF2=[480,960,1920],SF2=80,hF2="(max-width: 640px) 480px, (max-width: 1280px) 960px, 1920px";class pWA{imagesDir;logger;constructor(A,Q){this.imagesDir=A;this.logger=Q.child("ImageOptimizer")}async optimize(A,Q){try{let B=await TF2(),w=xF2("sha256").update(A).digest("hex").slice(0,16),$=await B(A).metadata();if(!$.width||!$.height)return this.logger.warn("Could not determine image dimensions",{originalUrl:Q}),null;let{width:D,height:Y}=$,I=[];for(let J of vF2){if(J>D)continue;let Z=`${w}-${J}w.webp`,q=ox0(this.imagesDir,Z),V=`/images/${Z}`;if(await lWA.access(q).then(()=>!0).catch(()=>!1)){this.logger.debug("Cache hit, skipping optimization",{fileName:Z}),I.push({width:J,url:V});continue}await B(A).resize(J,null,{withoutEnlargement:!0}).webp({quality:SF2}).toFile(q),I.push({width:J,url:V}),this.logger.debug("Created WebP variant",{fileName:Z,width:J})}if(I.length===0)return null;let X=I[I.length-1];if(!X)return null;let H=I.find((J)=>J.width===960)??X,W=Math.round(Y*(H.width/D));return{src:H.url,srcset:I.map((J)=>`${J.url} ${J.width}w`).join(", "),sizes:hF2,width:H.width,height:W}}catch(B){return this.logger.warn("Image optimization failed, using original",{originalUrl:Q,error:B instanceof Error?B.message:String(B)}),null}}async optimizeAll(){let A={},Q;try{Q=await lWA.readdir(this.imagesDir,{withFileTypes:!0})}catch{return this.logger.debug("Images directory does not exist, nothing to optimize"),A}let B=Q.filter((w)=>w.isFile()&&/\.(png|jpe?g)$/i.test(w.name));if(B.length===0)return this.logger.debug("No PNG/JPEG images found to optimize"),A;this.logger.debug(`Optimizing ${B.length} images`);for(let w of B){let $=ox0(this.imagesDir,w.name),D=`/images/${w.name}`;try{let Y=await lWA.readFile($),I=await this.optimize(Y,D);if(I)A[D]=I}catch(Y){this.logger.warn("Failed to optimize image",{file:w.name,error:Y instanceof Error?Y.message:String(Y)})}}return this.logger.debug(`Optimized ${Object.keys(A).length}/${B.length} images`),A}}function ax0(A,Q){if(A.format)return A.format;return Q.match(/^data:image\/([^;]+);/)?.[1]??"png"}function tx0(A){return A.match(/^data:image\/[^;]+;base64,(.+)$/)?.[1]??null}function mM(A){return A.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class dWA{entityService;logger;imageMap={};imagesDir;optimizer;constructor(A,Q,B){this.entityService=A;this.logger=Q.child("ImageBuildService"),this.imagesDir=B,this.optimizer=new pWA(this.imagesDir,this.logger)}async resolveAll(A){let Q=[...new Set(A)];if(Q.length===0)return;await ex0.mkdir(this.imagesDir,{recursive:!0});let B=E3(4);await Promise.all(Q.map((w)=>B(async()=>{try{await this.resolveImage(w)}catch($){this.logger.warn("Failed to resolve image",{imageId:w,error:$ instanceof Error?$.message:String($)})}}))),this.logger.debug(`Resolved ${Object.keys(this.imageMap).length}/${Q.length} images`)}async resolveImage(A){let Q=await this.entityService.getEntity("image",A);if(!Q?.content){this.logger.warn("Image entity not found or has no content",{imageId:A});return}let B=tx0(Q.content);if(!B){this.logger.warn("Could not extract base64 from image",{imageId:A});return}let w=Buffer.from(B,"base64"),$=ax0(Q.metadata,Q.content),D=`${A}.${$}`,Y=gF2(this.imagesDir,D);await ex0.writeFile(Y,w);let I=`/images/${D}`,X=await this.optimizer.optimize(w,I);if(X)this.imageMap[A]={src:X.src,srcset:X.srcset,sizes:X.sizes,width:X.width,height:X.height};else this.imageMap[A]={src:I,width:Q.metadata.width??0,height:Q.metadata.height??0};this.logger.debug("Resolved image",{imageId:A,optimized:Boolean(X)})}get(A){return this.imageMap[A]}getMap(){return this.imageMap}createImageRenderer(){let A=this.imageMap;return(Q,B,w)=>{let $=/^entity:\/\/image\/(.+)$/.exec(Q);if(!$?.[1])return;let D=A[$[1]];if(!D)return;let Y=[`src="${mM(D.src)}"`,`alt="${mM(w)}"`];if(D.srcset)Y.push(`srcset="${mM(D.srcset)}"`);if(D.sizes)Y.push(`sizes="${mM(D.sizes)}"`);if(D.width)Y.push(`width="${D.width}"`);if(D.height)Y.push(`height="${D.height}"`);if(B)Y.push(`title="${mM(B)}"`);return Y.push('loading="lazy"'),Y.push('decoding="async"'),`<img ${Y.join(" ")}>`}}}var mF2=Q2.extend({metadata:F.object({slug:F.string()}).passthrough()});class A4{static instance=null;static defaultStaticSiteBuilderFactory=JWA;logger;context;staticSiteBuilderFactory;routeRegistry;profileService;entityDisplay;imageBuildService=null;static setDefaultStaticSiteBuilderFactory(A){A4.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,B,w,$){return A4.instance??=new A4(A,A4.defaultStaticSiteBuilderFactory,Q,B,w,$),A4.instance}static resetInstance(){A4.instance=null}static createFresh(A,Q,B,w,$,D){return new A4(A,$??A4.defaultStaticSiteBuilderFactory,Q,B,w,D)}constructor(A,Q,B,w,$,D){this.logger=A,this.context=B,this.staticSiteBuilderFactory=Q,this.routeRegistry=w,this.profileService=$,this.entityDisplay=D,O7.getInstance().configure(D)}async getSiteInfo(){return k_0(this.context.entityService,this.profileService,this.routeRegistry)}async build(A,Q){let B=QM0.parse(A),w=Lw.from(Q),$=[],D=[];try{await w?.report({message:"Starting site build",progress:0,total:100}),await w?.report({message:"Generating dynamic routes",progress:10,total:100}),await new ZWA(this.context,this.routeRegistry,this.entityDisplay).generateEntityRoutes();let I=B.workingDir??yF2(B.outputDir,".preact-work"),X=this.staticSiteBuilderFactory({logger:this.logger.child("StaticSiteBuilder"),workingDir:I,outputDir:B.outputDir});if(B.cleanBeforeBuild)await X.clean();let H=this.routeRegistry.list();if(H.length===0)D.push("No routes registered for site build");await w?.report({message:`Building ${H.length} routes`,progress:20,total:100}),await w?.report({message:"Resolving images",progress:25,total:100}),this.imageBuildService=new dWA(this.context.entityService,this.logger,B.sharedImagesDir);let W=await this.collectAllImageIds();if(W.length>0)await this.imageBuildService.resolveAll(W);let J=B.siteConfig,Z={routes:H,pluginContext:this.context,siteConfig:{title:J.title,description:J.description,...J.url&&{url:J.url},...J.copyright&&{copyright:J.copyright},...J.themeMode&&{themeMode:J.themeMode},...J.analyticsScript&&{analyticsScript:J.analyticsScript}},headScripts:A.headScripts,...A.staticAssets&&{staticAssets:A.staticAssets},getContent:async(j,_)=>{let k=B.environment==="production";return this.getContentForSection(_,j,k)},getViewTemplate:(j)=>{return this.context.views.get(j)},layouts:B.layouts,getSiteInfo:async()=>{return this.getSiteInfo()},...B.themeCSS!==void 0&&{themeCSS:B.themeCSS},...A.slots&&{slots:A.slots},imageBuildService:this.imageBuildService},q=0,V=H.length+4;await X.build(Z,(j)=>{q++;let _=85+Math.round(q/V*10);w?.report({message:j,progress:_,total:100}).catch(()=>{})}),await w?.report({message:"Site build complete",progress:100,total:100});let E=H.length+1,L={success:$.length===0,outputDir:B.outputDir,filesGenerated:E,routesBuilt:H.length};if($.length>0)L.errors=$;if(D.length>0)L.warnings=D;return L}catch(Y){let I=Error("Site build process failed");return this.logger.error("Site build failed",{error:I,originalError:Y}),$.push(I.message),{success:!1,outputDir:B.outputDir,filesGenerated:0,routesBuilt:0,errors:$}}}async getContentForSection(A,Q,B){if(!A.template)return A.content??null;let w=A.template,$=O7.getInstance();if(A.dataQuery){let Y={dataParams:A.dataQuery,fallback:A.content,publishedOnly:B},I=await this.context.templates.resolve(w,Y);if(I)return this.enrichWithUrls(I,$);return null}let D=await this.context.templates.resolve(w,{savedContent:{entityType:"site-content",entityId:`${Q.id}:${A.id}`},fallback:A.content});if(D)return this.enrichWithUrls(D,$);return null}async enrichWithUrls(A,Q){if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((k)=>this.enrichWithUrls(k,Q)));if(typeof A!=="object")return A;let B=A,w={},$=Object.entries(B),D=await Promise.all($.map(([,k])=>this.enrichWithUrls(k,Q)));for(let k=0;k<$.length;k++){let r=$[k];if(r)w[r[0]]=D[k]}let Y=mF2.safeParse(B);if(!Y.success)return w;let I=Y.data,X=I.entityType,H=I.metadata.slug,W=this.entityDisplay?.[X],J=W?W.label:X.charAt(0).toUpperCase()+X.slice(1),Z=W?W.pluralName??W.label.toLowerCase()+"s":E$(X),q=`/${Z}`,V=Z.charAt(0).toUpperCase()+Z.slice(1),E=Bj(I),L=E?this.imageBuildService?.get(E):void 0,j={};if(L)j={coverImageUrl:L.src,coverImageWidth:L.width,coverImageHeight:L.height,...L.srcset&&{coverImageSrcset:L.srcset,coverImageSizes:L.sizes}};else{let k=await wj(I,this.context.entityService);if(k)j={coverImageUrl:k.url,coverImageWidth:k.width,coverImageHeight:k.height}}return{...w,...I,url:Q.generateUrl(X,H),typeLabel:J,listUrl:q,listLabel:V,...j}}async collectAllImageIds(){let A=new Set;try{let Q=this.context.entityService.getEntityTypes();for(let B of Q){if(B==="image")continue;let w=await this.context.entityService.listEntities(B);for(let $ of w){let D=Bj($);if(D)A.add(D)}}}catch(Q){this.logger.warn("Failed to collect image IDs for pre-resolution",{error:Q instanceof Error?Q.message:String(Q)})}return[...A]}}B0();GA();class iWA{logger;routes=new Map;constructor(A){this.logger=A}register(A){for(let Q of vH(A)){let B=KN.parse(Q);if(this.routes.has(B.path)){let w=this.routes.get(B.path);this.logger.debug(`Overriding route "${B.path}" (was registered by plugin "${w?.pluginId}")`)}this.routes.set(B.path,B)}}unregister(A){vH(A).forEach((Q)=>this.routes.delete(Q))}unregisterByPlugin(A){for(let[Q,B]of this.routes.entries())if(B.pluginId===A)this.routes.delete(Q)}get(A){return this.routes.get(A)}list(A){let Q=Array.from(this.routes.values()).filter((B)=>!B.external);if(A?.pluginId)Q=Q.filter((B)=>B.pluginId===A.pluginId);return Q}listByPlugin(A){return this.list({pluginId:A})}clear(){this.routes.clear()}size(){return this.routes.size}getNavigationItems(A){let Q=[];for(let[B,w]of this.routes.entries())if(w.navigation?.show&&w.navigation.slot===A)Q.push({label:w.navigation.label??w.title,href:B,priority:w.navigation.priority});return Q.sort((B,w)=>B.priority-w.priority)}}class td{slots=new Map;register(A,Q){let B={...Q,priority:Q.priority??50},w=this.slots.get(A)??[];w.push(B),this.slots.set(A,w)}getSlot(A){return[...this.slots.get(A)??[]].sort((B,w)=>w.priority-B.priority)}hasSlot(A){let Q=this.slots.get(A);return Q!==void 0&&Q.length>0}unregister(A,Q){let B=this.slots.get(A);if(!B)return;let w=B.filter(($)=>$.pluginId!==Q);if(w.length>0)this.slots.set(A,w);else this.slots.delete(A)}unregisterAll(A){for(let[Q,B]of this.slots){let w=B.filter(($)=>$.pluginId!==A);if(w.length>0)this.slots.set(Q,w);else this.slots.delete(Q)}}getSlotNames(){return Array.from(this.slots.keys())}clear(){this.slots.clear()}}GA();class rWA{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 R3(()=>{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("site-build",{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},null,{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})}}}B0();function uF2(A,Q){return A.map((B)=>({...B,template:B.template.includes(":")?B.template:`${Q}:${B.template}`}))}function ed(A,Q,B){for(let w of A)B.register({...w,pluginId:Q,sections:w.sections?uF2(w.sections,Q):[]})}function AT0(A,Q,B){A.messaging.subscribe("plugin:site-builder:route:register",async(w)=>{try{let $=Pe.parse(w.payload),{routes:D,pluginId:Y}=$;return ed(D,Y,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 $=_e.parse(w.payload),{paths:D,pluginId:Y}=$;if(D)for(let I of D)Q.unregister(I);else if(Y)Q.unregisterByPlugin(Y);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 $=be.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 $=xe.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 wT0}from"fs";import{join as $T0}from"path";function QT0(A,Q){if(Q==="preview")return`User-agent: *
2537
+ `+I;await gw.writeFile(Y,H,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=CX(process.cwd(),"public");try{await gw.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await gw.readdir(A,{withFileTypes:!0});for(let B of Q){let w=CX(A,B.name),$=CX(this.outputDir,B.name);if(B.isDirectory())await this.copyDirectory(w,$);else await gw.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,D=CX(this.outputDir,$);await gw.mkdir(UG2(D),{recursive:!0}),await gw.writeFile(D,w,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await gw.mkdir(Q,{recursive:!0});let B=await gw.readdir(A,{withFileTypes:!0});for(let w of B){let $=CX(A,w.name),D=CX(Q,w.name);if(w.isDirectory())await this.copyDirectory($,D);else await gw.copyFile($,D)}}}function JWA(A){return new f_0(A)}function WG2(A,Q){let B=new Map;for(let w of A.sections){let $=Q.getViewTemplate(w.template);if(!$?.runtimeScripts)continue;for(let D of $.runtimeScripts)if(!B.has(D.src))B.set(D.src,D)}return[...B.values()].map((w)=>{let $=[`src="${w.src}"`];if(w.defer)$.push("defer");if(w.module)$.push('type="module"');return`<script ${$.join(" ")}></script>`})}import{join as yF2}from"path";GA();class ZWA{context;routeRegistry;entityDisplay;constructor(A,Q,B){this.context=A;this.routeRegistry=Q;this.entityDisplay=B}async generateEntityRoutes(){let A=this.context.logger.child("DynamicRouteGenerator"),Q=this.routeRegistry.list(),B=0;for(let $ of Q)if($.sourceEntityType)this.routeRegistry.unregister($.path),B++;if(B>0)A.debug(`Cleared ${B} dynamic routes before regeneration`);let w=this.context.entityService.getEntityTypes();A.debug(`Found ${w.length} entity types`,{entityTypes:w});for(let $ of w)await this.generateRoutesForEntityType($)}async generateRoutesForEntityType(A){let Q=this.context.logger.child("DynamicRouteGenerator"),{listTemplateName:B,detailTemplateName:w}=this.findTemplatesForEntityType(A);if(!B&&!w){Q.debug(`No matching templates found for entity type: ${A}`);return}if(Q.debug(`Generating routes for entity type: ${A}`,{listTemplate:B,detailTemplate:w}),B){let{pluralName:$,label:D,layout:Y,paginate:I,pageSize:X,navigation:H}=this.getEntityDisplayConfig(A);if(I)await this.generatePaginatedRoutes(A,B,$,D,Y,X,H,Q);else{let W={id:`${A}-index`,path:`/${$}`,title:D,description:`Browse all ${$}`,...Y&&{layout:Y},navigation:{show:H.show,label:D,slot:H.slot,priority:H.priority},sections:[{id:"list",template:B,dataQuery:{entityType:A,query:{limit:100}}}],sourceEntityType:A};try{this.routeRegistry.register(W),Q.debug(`Registered index route for ${A}`,{path:W.path})}catch(J){Q.warn(`Failed to register index route for ${A}`,{error:J})}}}if(w)try{let $=await this.context.entityService.listEntities(A,{limit:1000});Q.debug(`Found ${$.length} ${A} entities to generate routes for`);let{pluralName:D,layout:Y}=this.getEntityDisplayConfig(A);for(let X of $){let H="slug"in X.metadata?X.metadata.slug:X.id,W={id:`${A}-${X.id}`,path:`/${D}/${H}`,title:`${this.capitalize(A)}: ${H}`,description:`View ${A} details`,...Y&&{layout:Y},sections:[{id:"detail",template:w,dataQuery:{entityType:A,query:{id:H}}}],sourceEntityType:A};try{this.routeRegistry.register(W)}catch(J){Q.warn(`Failed to register detail route for ${A}/${X.id}`,{error:J})}}let I=B?$.length+1:$.length;Q.debug(`Successfully registered ${I} routes for ${A}`)}catch($){Q.error(`Failed to list entities for type: ${A}`,{error:$})}}async generatePaginatedRoutes(A,Q,B,w,$,D,Y,I){let H=(await this.context.entityService.listEntities(A,{limit:1000})).length,W=Math.max(1,Math.ceil(H/D));I.debug(`Generating ${W} paginated routes for ${A}`,{totalItems:H,pageSize:D});for(let J=1;J<=W;J++){let Z=J===1,q=Z?`/${B}`:`/${B}/page/${J}`,V={id:`${A}-index${Z?"":`-page-${J}`}`,path:q,title:Z?w:`${w} - Page ${J}`,description:`Browse all ${B}${Z?"":` - Page ${J}`}`,...$&&{layout:$},navigation:Z?{show:Y.show,label:w,slot:Y.slot,priority:Y.priority}:void 0,sections:[{id:"list",template:Q,dataQuery:{entityType:A,query:{page:J,pageSize:D,baseUrl:`/${B}`}}}],sourceEntityType:A};try{this.routeRegistry.register(V),I.debug(`Registered paginated route for ${A}`,{path:V.path,page:J})}catch(E){I.warn(`Failed to register paginated route for ${A} page ${J}`,{error:E})}}}findTemplatesForEntityType(A){let Q=this.context.views.list(),B,w,$=`${A}-list`,D=`${A}-detail`;for(let I of Q){let X=I.name;if(X.endsWith($)){let H=X.slice(0,-$.length);if(H===""||H.endsWith(":"))B=X}if(X.endsWith(D)){let H=X.slice(0,-D.length);if(H===""||H.endsWith(":"))w=X}}let Y={};if(B)Y.listTemplateName=B;if(w)Y.detailTemplateName=w;return Y}getEntityDisplayConfig(A){let Q=this.entityDisplay?.[A],B=10,w=!0,$=!0,D="primary",Y=40;if(Q){let X=Q.pluralName??E$(Q.label.toLowerCase()),H=this.capitalize(E$(Q.label.toLowerCase()));return{pluralName:X,label:H,...Q.layout&&{layout:Q.layout},paginate:Q.paginate??!0,pageSize:Q.pageSize??10,navigation:{show:Q.navigation?.show??!0,slot:Q.navigation?.slot??"primary",priority:Q.navigation?.priority??40}}}let I=E$(A);return{pluralName:I,label:this.capitalize(I),paginate:!0,pageSize:10,navigation:{show:!0,slot:"primary",priority:40}}}capitalize(A){return A.split(" ").map((Q)=>Q.charAt(0).toUpperCase()+Q.slice(1)).join(" ")}}B0();GA();B0();var R_0=F.object({}),f_=Q2.extend({id:F.literal("site-info"),entityType:F.literal("site-info"),metadata:R_0}),R_=F.object({heading:F.string().describe("Main CTA heading text"),buttonText:F.string().describe("Call-to-action button text"),buttonLink:F.string().describe("URL or anchor for the CTA button")}),OX=F.object({title:F.string().describe("The site's title"),description:F.string().describe("The site's description"),copyright:F.string().optional().describe("Copyright notice text"),logo:F.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:F.enum(["light","dark"]).optional().describe("Default theme mode"),cta:R_.optional().describe("Call-to-action configuration")});B0();class uY extends I2{constructor(){super({entityType:"site-info",schema:f_,frontmatterSchema:OX,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=OX.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 fX{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,B){return fX.instance??=new fX(A,Q,B),fX.instance}static resetInstance(){fX.instance=null}static createFresh(A,Q,B){return new fX(A,Q,B)}constructor(A,Q,B){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new uY;let w=fX.getDefaultSiteInfo();this.defaultSiteInfo={...w,...B}}async initialize(){try{if(!await this.entityService.getEntity("site-info","site-info")){this.logger.info("No site info found, creating default site info");let Q=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({id:"site-info",entityType:"site-info",content:Q,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("site-info","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 GG2=new uY;class Td{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 I=await w.getEntity("site-info","site-info");$=I?GG2.parseSiteInfoBody(I.content):{title:"Brain",description:"A knowledge management system"}}catch{$={title:"Brain",description:"A knowledge management system"}}let D;try{let I=await w.getEntity("anchor-profile","anchor-profile");if(I)D=I.metadata.socialLinks}catch{}let Y={...$,socialLinks:D,copyright:$.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:Y.title,hasSocialLinks:!!Y.socialLinks}),Q.parse(Y)}}var j_0={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.42",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/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 ZG2=new uY;class FWA extends HQ{entityType="site-info";schema=f_;adapter=ZG2;defaultSiteInfo;constructor(A){super("site-info",j_0);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new Td(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=fX.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function dF(A){return new FWA(A)}var FG2=new uY;async function iK(A){let B=(await A.listEntities("site-info",{limit:1}))[0];if(!B)throw Error("Site info not found \u2014 create a site-info entity");return FG2.parseSiteInfoBody(B.content)}GA();var qG2=OX.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")});async function k_0(A,Q,B){let w;try{w=await iK(A)}catch{w={title:"Brain",description:"A knowledge management system"}}let $=Q.getProfile(),D=B.getNavigationItems("primary"),Y=B.getNavigationItems("secondary");return{...w,socialLinks:$.socialLinks,navigation:{primary:D,secondary:Y},copyright:w.copyright??"Powered by Rizom"}}GA();GA();import{promises as ex0}from"fs";import{join as gF2}from"path";import{createHash as xF2}from"crypto";import{promises as lWA}from"fs";import{join as ox0}from"path";var sx0=null;async function TF2(){return sx0??=Promise.resolve().then(() => o0(nx0(),1)).then((A)=>A.default),sx0}var vF2=[480,960,1920],SF2=80,hF2="(max-width: 640px) 480px, (max-width: 1280px) 960px, 1920px";class pWA{imagesDir;logger;constructor(A,Q){this.imagesDir=A;this.logger=Q.child("ImageOptimizer")}async optimize(A,Q){try{let B=await TF2(),w=xF2("sha256").update(A).digest("hex").slice(0,16),$=await B(A).metadata();if(!$.width||!$.height)return this.logger.warn("Could not determine image dimensions",{originalUrl:Q}),null;let{width:D,height:Y}=$,I=[];for(let J of vF2){if(J>D)continue;let Z=`${w}-${J}w.webp`,q=ox0(this.imagesDir,Z),V=`/images/${Z}`;if(await lWA.access(q).then(()=>!0).catch(()=>!1)){this.logger.debug("Cache hit, skipping optimization",{fileName:Z}),I.push({width:J,url:V});continue}await B(A).resize(J,null,{withoutEnlargement:!0}).webp({quality:SF2}).toFile(q),I.push({width:J,url:V}),this.logger.debug("Created WebP variant",{fileName:Z,width:J})}if(I.length===0)return null;let X=I[I.length-1];if(!X)return null;let H=I.find((J)=>J.width===960)??X,W=Math.round(Y*(H.width/D));return{src:H.url,srcset:I.map((J)=>`${J.url} ${J.width}w`).join(", "),sizes:hF2,width:H.width,height:W}}catch(B){return this.logger.warn("Image optimization failed, using original",{originalUrl:Q,error:B instanceof Error?B.message:String(B)}),null}}async optimizeAll(){let A={},Q;try{Q=await lWA.readdir(this.imagesDir,{withFileTypes:!0})}catch{return this.logger.debug("Images directory does not exist, nothing to optimize"),A}let B=Q.filter((w)=>w.isFile()&&/\.(png|jpe?g)$/i.test(w.name));if(B.length===0)return this.logger.debug("No PNG/JPEG images found to optimize"),A;this.logger.debug(`Optimizing ${B.length} images`);for(let w of B){let $=ox0(this.imagesDir,w.name),D=`/images/${w.name}`;try{let Y=await lWA.readFile($),I=await this.optimize(Y,D);if(I)A[D]=I}catch(Y){this.logger.warn("Failed to optimize image",{file:w.name,error:Y instanceof Error?Y.message:String(Y)})}}return this.logger.debug(`Optimized ${Object.keys(A).length}/${B.length} images`),A}}function ax0(A,Q){if(A.format)return A.format;return Q.match(/^data:image\/([^;]+);/)?.[1]??"png"}function tx0(A){return A.match(/^data:image\/[^;]+;base64,(.+)$/)?.[1]??null}function mM(A){return A.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class dWA{entityService;logger;imageMap={};imagesDir;optimizer;constructor(A,Q,B){this.entityService=A;this.logger=Q.child("ImageBuildService"),this.imagesDir=B,this.optimizer=new pWA(this.imagesDir,this.logger)}async resolveAll(A){let Q=[...new Set(A)];if(Q.length===0)return;await ex0.mkdir(this.imagesDir,{recursive:!0});let B=E3(4);await Promise.all(Q.map((w)=>B(async()=>{try{await this.resolveImage(w)}catch($){this.logger.warn("Failed to resolve image",{imageId:w,error:$ instanceof Error?$.message:String($)})}}))),this.logger.debug(`Resolved ${Object.keys(this.imageMap).length}/${Q.length} images`)}async resolveImage(A){let Q=await this.entityService.getEntity("image",A);if(!Q?.content){this.logger.warn("Image entity not found or has no content",{imageId:A});return}let B=tx0(Q.content);if(!B){this.logger.warn("Could not extract base64 from image",{imageId:A});return}let w=Buffer.from(B,"base64"),$=ax0(Q.metadata,Q.content),D=`${A}.${$}`,Y=gF2(this.imagesDir,D);await ex0.writeFile(Y,w);let I=`/images/${D}`,X=await this.optimizer.optimize(w,I);if(X)this.imageMap[A]={src:X.src,srcset:X.srcset,sizes:X.sizes,width:X.width,height:X.height};else this.imageMap[A]={src:I,width:Q.metadata.width??0,height:Q.metadata.height??0};this.logger.debug("Resolved image",{imageId:A,optimized:Boolean(X)})}get(A){return this.imageMap[A]}getMap(){return this.imageMap}createImageRenderer(){let A=this.imageMap;return(Q,B,w)=>{let $=/^entity:\/\/image\/(.+)$/.exec(Q);if(!$?.[1])return;let D=A[$[1]];if(!D)return;let Y=[`src="${mM(D.src)}"`,`alt="${mM(w)}"`];if(D.srcset)Y.push(`srcset="${mM(D.srcset)}"`);if(D.sizes)Y.push(`sizes="${mM(D.sizes)}"`);if(D.width)Y.push(`width="${D.width}"`);if(D.height)Y.push(`height="${D.height}"`);if(B)Y.push(`title="${mM(B)}"`);return Y.push('loading="lazy"'),Y.push('decoding="async"'),`<img ${Y.join(" ")}>`}}}var mF2=Q2.extend({metadata:F.object({slug:F.string()}).passthrough()});class A4{static instance=null;static defaultStaticSiteBuilderFactory=JWA;logger;context;staticSiteBuilderFactory;routeRegistry;profileService;entityDisplay;imageBuildService=null;static setDefaultStaticSiteBuilderFactory(A){A4.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,B,w,$){return A4.instance??=new A4(A,A4.defaultStaticSiteBuilderFactory,Q,B,w,$),A4.instance}static resetInstance(){A4.instance=null}static createFresh(A,Q,B,w,$,D){return new A4(A,$??A4.defaultStaticSiteBuilderFactory,Q,B,w,D)}constructor(A,Q,B,w,$,D){this.logger=A,this.context=B,this.staticSiteBuilderFactory=Q,this.routeRegistry=w,this.profileService=$,this.entityDisplay=D,O7.getInstance().configure(D)}async getSiteInfo(){return k_0(this.context.entityService,this.profileService,this.routeRegistry)}async build(A,Q){let B=QM0.parse(A),w=Lw.from(Q),$=[],D=[];try{await w?.report({message:"Starting site build",progress:0,total:100}),await w?.report({message:"Generating dynamic routes",progress:10,total:100}),await new ZWA(this.context,this.routeRegistry,this.entityDisplay).generateEntityRoutes();let I=B.workingDir??yF2(B.outputDir,".preact-work"),X=this.staticSiteBuilderFactory({logger:this.logger.child("StaticSiteBuilder"),workingDir:I,outputDir:B.outputDir});if(B.cleanBeforeBuild)await X.clean();let H=this.routeRegistry.list();if(H.length===0)D.push("No routes registered for site build");await w?.report({message:`Building ${H.length} routes`,progress:20,total:100}),await w?.report({message:"Resolving images",progress:25,total:100}),this.imageBuildService=new dWA(this.context.entityService,this.logger,B.sharedImagesDir);let W=await this.collectAllImageIds();if(W.length>0)await this.imageBuildService.resolveAll(W);let J=B.siteConfig,Z={routes:H,pluginContext:this.context,siteConfig:{title:J.title,description:J.description,...J.url&&{url:J.url},...J.copyright&&{copyright:J.copyright},...J.themeMode&&{themeMode:J.themeMode},...J.analyticsScript&&{analyticsScript:J.analyticsScript}},headScripts:A.headScripts,...A.staticAssets&&{staticAssets:A.staticAssets},getContent:async(j,_)=>{let k=B.environment==="production";return this.getContentForSection(_,j,k)},getViewTemplate:(j)=>{return this.context.views.get(j)},layouts:B.layouts,getSiteInfo:async()=>{return this.getSiteInfo()},...B.themeCSS!==void 0&&{themeCSS:B.themeCSS},...A.slots&&{slots:A.slots},imageBuildService:this.imageBuildService},q=0,V=H.length+4;await X.build(Z,(j)=>{q++;let _=85+Math.round(q/V*10);w?.report({message:j,progress:_,total:100}).catch(()=>{})}),await w?.report({message:"Site build complete",progress:100,total:100});let E=H.length+1,L={success:$.length===0,outputDir:B.outputDir,filesGenerated:E,routesBuilt:H.length};if($.length>0)L.errors=$;if(D.length>0)L.warnings=D;return L}catch(Y){let I=Error("Site build process failed");return this.logger.error("Site build failed",{error:I,originalError:Y}),$.push(I.message),{success:!1,outputDir:B.outputDir,filesGenerated:0,routesBuilt:0,errors:$}}}async getContentForSection(A,Q,B){if(!A.template)return A.content??null;let w=A.template,$=O7.getInstance();if(A.dataQuery){let Y={dataParams:A.dataQuery,fallback:A.content,publishedOnly:B},I=await this.context.templates.resolve(w,Y);if(I)return this.enrichWithUrls(I,$);return null}let D=await this.context.templates.resolve(w,{savedContent:{entityType:"site-content",entityId:`${Q.id}:${A.id}`},fallback:A.content});if(D)return this.enrichWithUrls(D,$);return null}async enrichWithUrls(A,Q){if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((k)=>this.enrichWithUrls(k,Q)));if(typeof A!=="object")return A;let B=A,w={},$=Object.entries(B),D=await Promise.all($.map(([,k])=>this.enrichWithUrls(k,Q)));for(let k=0;k<$.length;k++){let r=$[k];if(r)w[r[0]]=D[k]}let Y=mF2.safeParse(B);if(!Y.success)return w;let I=Y.data,X=I.entityType,H=I.metadata.slug,W=this.entityDisplay?.[X],J=W?W.label:X.charAt(0).toUpperCase()+X.slice(1),Z=W?W.pluralName??W.label.toLowerCase()+"s":E$(X),q=`/${Z}`,V=Z.charAt(0).toUpperCase()+Z.slice(1),E=Bj(I),L=E?this.imageBuildService?.get(E):void 0,j={};if(L)j={coverImageUrl:L.src,coverImageWidth:L.width,coverImageHeight:L.height,...L.srcset&&{coverImageSrcset:L.srcset,coverImageSizes:L.sizes}};else{let k=await wj(I,this.context.entityService);if(k)j={coverImageUrl:k.url,coverImageWidth:k.width,coverImageHeight:k.height}}return{...w,...I,url:Q.generateUrl(X,H),typeLabel:J,listUrl:q,listLabel:V,...j}}async collectAllImageIds(){let A=new Set;try{let Q=this.context.entityService.getEntityTypes();for(let B of Q){if(B==="image")continue;let w=await this.context.entityService.listEntities(B);for(let $ of w){let D=Bj($);if(D)A.add(D)}}}catch(Q){this.logger.warn("Failed to collect image IDs for pre-resolution",{error:Q instanceof Error?Q.message:String(Q)})}return[...A]}}B0();GA();class iWA{logger;routes=new Map;constructor(A){this.logger=A}register(A){for(let Q of vH(A)){let B=KN.parse(Q);if(this.routes.has(B.path)){let w=this.routes.get(B.path);this.logger.debug(`Overriding route "${B.path}" (was registered by plugin "${w?.pluginId}")`)}this.routes.set(B.path,B)}}unregister(A){vH(A).forEach((Q)=>this.routes.delete(Q))}unregisterByPlugin(A){for(let[Q,B]of this.routes.entries())if(B.pluginId===A)this.routes.delete(Q)}get(A){return this.routes.get(A)}list(A){let Q=Array.from(this.routes.values()).filter((B)=>!B.external);if(A?.pluginId)Q=Q.filter((B)=>B.pluginId===A.pluginId);return Q}listByPlugin(A){return this.list({pluginId:A})}clear(){this.routes.clear()}size(){return this.routes.size}getNavigationItems(A){let Q=[];for(let[B,w]of this.routes.entries())if(w.navigation?.show&&w.navigation.slot===A)Q.push({label:w.navigation.label??w.title,href:B,priority:w.navigation.priority});return Q.sort((B,w)=>B.priority-w.priority)}}class td{slots=new Map;register(A,Q){let B={...Q,priority:Q.priority??50},w=this.slots.get(A)??[];w.push(B),this.slots.set(A,w)}getSlot(A){return[...this.slots.get(A)??[]].sort((B,w)=>w.priority-B.priority)}hasSlot(A){let Q=this.slots.get(A);return Q!==void 0&&Q.length>0}unregister(A,Q){let B=this.slots.get(A);if(!B)return;let w=B.filter(($)=>$.pluginId!==Q);if(w.length>0)this.slots.set(A,w);else this.slots.delete(A)}unregisterAll(A){for(let[Q,B]of this.slots){let w=B.filter(($)=>$.pluginId!==A);if(w.length>0)this.slots.set(Q,w);else this.slots.delete(Q)}}getSlotNames(){return Array.from(this.slots.keys())}clear(){this.slots.clear()}}GA();class rWA{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 R3(()=>{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("site-build",{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},null,{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})}}}B0();function uF2(A,Q){return A.map((B)=>({...B,template:B.template.includes(":")?B.template:`${Q}:${B.template}`}))}function ed(A,Q,B){for(let w of A)B.register({...w,pluginId:Q,sections:w.sections?uF2(w.sections,Q):[]})}function AT0(A,Q,B){A.messaging.subscribe("plugin:site-builder:route:register",async(w)=>{try{let $=Pe.parse(w.payload),{routes:D,pluginId:Y}=$;return ed(D,Y,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 $=_e.parse(w.payload),{paths:D,pluginId:Y}=$;if(D)for(let I of D)Q.unregister(I);else if(Y)Q.unregisterByPlugin(Y);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 $=be.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 $=xe.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 wT0}from"fs";import{join as $T0}from"path";function QT0(A,Q){if(Q==="preview")return`User-agent: *
2538
2538
  Disallow: /
2539
2539
 
2540
2540
  Sitemap: ${A}/sitemap.xml
@@ -2552,7 +2552,7 @@ ${A.map((D)=>({url:`${Q}${D.path}`,lastmod:B,changefreq:D.path==="/"?"daily":"we
2552
2552
  </url>`).join(`
2553
2553
  `)}
2554
2554
  </urlset>
2555
- `}async function lF2(A,Q,B){let w=A.siteConfig.url??"https://example.com",$=Q.list(),D=QT0(w,A.environment);await wT0.writeFile($T0(A.outputDir,"robots.txt"),D,"utf-8"),B.info(`Generated robots.txt for ${A.environment} environment`);let Y=BT0($,w);await wT0.writeFile($T0(A.outputDir,"sitemap.xml"),Y,"utf-8"),B.info(`Generated sitemap.xml with ${$.length} URLs`)}function DT0(A){let{context:Q,routeRegistry:B,logger:w}=A;Q.messaging.subscribe("site:build:completed",async($)=>{try{let D=$.payload;return w.info(`Received site:build:completed event for ${D.environment} environment - generating SEO files`),await lF2(D,B,w),{success:!0}}catch(D){return w.error("Failed to generate SEO files",D),{success:!1}}})}B0();GA();var YT0=F.object({environment:F.enum(["preview","production"]).optional(),outputDir:F.string(),workingDir:F.string().optional(),enableContentGeneration:F.boolean().optional(),siteConfig:F.object({title:F.string(),description:F.string(),url:F.string().optional(),analyticsScript:F.string().optional()}).optional()});GA();class nWA extends EB{sendMessage;cfg;constructor(A,Q,B){super(A,{schema:YT0,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 D=B.createSub({scale:{start:10,end:90}}),Y=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:$,environment:w,cleanBeforeBuild:!0,siteConfig:A.siteConfig??this.cfg.defaultSiteConfig,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},D.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 I=w==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage("site:build:completed",{outputDir:A.outputDir,environment:w,routesBuilt:Y.routesBuilt,siteConfig:{...A.siteConfig??this.cfg.defaultSiteConfig,url:I},generateEntityUrl:(X,H)=>O7.getInstance().generateUrl(X,H)},{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(D){throw this.logger.error("Site build job failed",D),D}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}GA();B0();var pF2=F.object({slot:F.enum(HN).optional().default("primary"),limit:F.number().optional()});class oWA{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=pF2.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:w});let $=this.routeRegistry.getNavigationItems(w.slot),D=w.limit?$.slice(0,w.limit):$,Y=D.map((X)=>({label:X.label,href:X.href}));this.logger.debug("NavigationDataSource returning",{slot:w.slot,itemCount:D.length,items:Y});let I={navigation:Y};return Q.parse(I)}}B0();GA();var dF2=F.object({environment:F.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function IT0(A,Q){return[yQ(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'.",dF2,async(B)=>{return Q(B.environment),{success:!0,message:`Site build requested${B.environment?` for ${B.environment}`:""} (debounced)`,data:{}}},{cli:{name:"build"}})]}GA();B0();var XT0=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:OX.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(KN).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(HN).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 HT0={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.41",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/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/ui-library":"workspace:*","@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",sharp:"^0.34.5",tailwindcss:"^4.1.11"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/sharp":"^0.32.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class sWA extends tB{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",HT0,{...A,layouts:Q},XT0);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new iWA(A.logger),this._slotRegistry=new td,A.messaging.subscribe("plugin:site-builder:slot:register",async(Q)=>{let{slotName:B,pluginId:w,render:$,priority:D}=Q.payload;return this._slotRegistry?.register(B,{pluginId:w,render:$,...D!==void 0&&{priority:D}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async(Q)=>{let{pluginId:B,script:w}=Q.payload;return this.headScripts.set(B,w),{success:!0}}),A.entities.registerDataSource(new oWA(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=_7.getInstance(A.entityService,A.logger),A.messaging.subscribe("sync:initial:completed",async()=>{return await this.profileService?.initialize(),this.logger.info("AnchorProfileService initialized"),{success:!0}}),AT0(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)ed(this.config.routes,this.id,this.routeRegistry);if(this.siteBuilder=A4.getInstance(A.logger.child("SiteBuilder"),A,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new nWA(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 rWA(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe("entity:updated",async(Q)=>{if(Q.payload.entityType==="site-info"){let w=await this.getInstructions();if(w)A.registerInstructions(w)}return{success:!0}}),DT0({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 IT0(this.id,(Q)=>A.requestBuild(Q))}async getResources(){let A=this.getContext();return[{uri:"brain://site",name:"Site Info",description:"Site metadata \u2014 title, description, domain, URLs",mimeType:"application/json",handler:async()=>{let Q;try{Q=await iK(A.entityService)}catch{Q={title:"Brain",description:""}}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.";try{let B=await iK(A.entityService);return`## Your Site
2555
+ `}async function lF2(A,Q,B){let w=A.siteConfig.url??"https://example.com",$=Q.list(),D=QT0(w,A.environment);await wT0.writeFile($T0(A.outputDir,"robots.txt"),D,"utf-8"),B.info(`Generated robots.txt for ${A.environment} environment`);let Y=BT0($,w);await wT0.writeFile($T0(A.outputDir,"sitemap.xml"),Y,"utf-8"),B.info(`Generated sitemap.xml with ${$.length} URLs`)}function DT0(A){let{context:Q,routeRegistry:B,logger:w}=A;Q.messaging.subscribe("site:build:completed",async($)=>{try{let D=$.payload;return w.info(`Received site:build:completed event for ${D.environment} environment - generating SEO files`),await lF2(D,B,w),{success:!0}}catch(D){return w.error("Failed to generate SEO files",D),{success:!1}}})}B0();GA();var YT0=F.object({environment:F.enum(["preview","production"]).optional(),outputDir:F.string(),workingDir:F.string().optional(),enableContentGeneration:F.boolean().optional(),siteConfig:F.object({title:F.string(),description:F.string(),url:F.string().optional(),analyticsScript:F.string().optional()}).optional()});GA();class nWA extends EB{sendMessage;cfg;constructor(A,Q,B){super(A,{schema:YT0,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 D=B.createSub({scale:{start:10,end:90}}),Y=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:$,environment:w,cleanBeforeBuild:!0,siteConfig:A.siteConfig??this.cfg.defaultSiteConfig,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},D.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 I=w==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage("site:build:completed",{outputDir:A.outputDir,environment:w,routesBuilt:Y.routesBuilt,siteConfig:{...A.siteConfig??this.cfg.defaultSiteConfig,url:I},generateEntityUrl:(X,H)=>O7.getInstance().generateUrl(X,H)},{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(D){throw this.logger.error("Site build job failed",D),D}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}GA();B0();var pF2=F.object({slot:F.enum(HN).optional().default("primary"),limit:F.number().optional()});class oWA{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=pF2.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:w});let $=this.routeRegistry.getNavigationItems(w.slot),D=w.limit?$.slice(0,w.limit):$,Y=D.map((X)=>({label:X.label,href:X.href}));this.logger.debug("NavigationDataSource returning",{slot:w.slot,itemCount:D.length,items:Y});let I={navigation:Y};return Q.parse(I)}}B0();GA();var dF2=F.object({environment:F.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function IT0(A,Q){return[yQ(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'.",dF2,async(B)=>{return Q(B.environment),{success:!0,message:`Site build requested${B.environment?` for ${B.environment}`:""} (debounced)`,data:{}}},{cli:{name:"build"}})]}GA();B0();var XT0=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:OX.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(KN).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(HN).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 HT0={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.42",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/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/ui-library":"workspace:*","@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",sharp:"^0.34.5",tailwindcss:"^4.1.11"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/sharp":"^0.32.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class sWA extends tB{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",HT0,{...A,layouts:Q},XT0);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new iWA(A.logger),this._slotRegistry=new td,A.messaging.subscribe("plugin:site-builder:slot:register",async(Q)=>{let{slotName:B,pluginId:w,render:$,priority:D}=Q.payload;return this._slotRegistry?.register(B,{pluginId:w,render:$,...D!==void 0&&{priority:D}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async(Q)=>{let{pluginId:B,script:w}=Q.payload;return this.headScripts.set(B,w),{success:!0}}),A.entities.registerDataSource(new oWA(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=_7.getInstance(A.entityService,A.logger),A.messaging.subscribe("sync:initial:completed",async()=>{return await this.profileService?.initialize(),this.logger.info("AnchorProfileService initialized"),{success:!0}}),AT0(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)ed(this.config.routes,this.id,this.routeRegistry);if(this.siteBuilder=A4.getInstance(A.logger.child("SiteBuilder"),A,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new nWA(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 rWA(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe("entity:updated",async(Q)=>{if(Q.payload.entityType==="site-info"){let w=await this.getInstructions();if(w)A.registerInstructions(w)}return{success:!0}}),DT0({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 IT0(this.id,(Q)=>A.requestBuild(Q))}async getResources(){let A=this.getContext();return[{uri:"brain://site",name:"Site Info",description:"Site metadata \u2014 title, description, domain, URLs",mimeType:"application/json",handler:async()=>{let Q;try{Q=await iK(A.entityService)}catch{Q={title:"Brain",description:""}}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.";try{let B=await iK(A.entityService);return`## Your Site
2556
2556
  ${[`**Title:** ${B.title}`,`**Description:** ${B.description}`,A.domain&&`**Domain:** ${A.domain}`,A.siteUrl&&`**URL:** ${A.siteUrl}`].filter(Boolean).join(`
2557
2557
  `)}
2558
2558
 
@@ -2603,7 +2603,7 @@ The excerpt should be clear, concise, and compelling.`});GA();s8();TX();import{j
2603
2603
  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=Gq2.parse(Q);return A.ai.generate({prompt:`Title: ${B.title}
2604
2604
 
2605
2605
  Content:
2606
- ${B.content}`,templateName:"blog:excerpt"})})}var CT0={name:"@brains/blog",private:!0,version:"0.2.0-alpha.41",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/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 wGA extends HQ{entityType=tF.entityType;schema=uM;adapter=tF;constructor(A={}){super("blog",CT0,A,tWA)}getEntityTypeConfig(){return{weight:2}}createGenerationHandler(A){return new eWA(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return zT0()}getDataSources(){return[new QGA(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (RT0(),fT0));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),await NT0(A,this.logger),VT0(A,this.logger),MT0(A,this.logger),ET0(A),this.logger.info("Blog plugin registered (routes auto-generated at /posts/)")}}function $GA(A={}){return new wGA(A)}TX();S_();B0();GA();P6();var $D=F.object({title:F.string(),slug:F.string(),coverImageId:F.string().optional()}),jT0=$D.pick({title:!0,slug:!0}),pM=Q2.extend({metadata:jT0}),wi=pM.extend({frontmatter:$D}),$i=wi.extend({description:F.string().optional(),postCount:F.number(),coverImageUrl:F.string().optional(),coverImageWidth:F.number().optional(),coverImageHeight:F.number().optional()}),kT0=F.object({description:F.string().optional()});function eF(A){return new $B(kT0,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}P6();class DGA extends I2{constructor(){super({entityType:"series",schema:pM,frontmatterSchema:$D,supportsCoverImage:!0,bodyFormatter:eF("")})}toMarkdown(A){let Q,B={};try{Q=this.parseFrontMatter(A.content,$D).coverImageId,B=eF(A.metadata.title).parse(this.extractBody(A.content))}catch{}let w={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},D=eF(A.metadata.title).format(B);return this.buildMarkdown(D,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,$D);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,$D);return eF(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var dM=new DGA;B0();GA();aD();class YGA{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("series",{limit:1000}),B=new Map(Q.map(($)=>[$.id,$])),w=new Set;for(let $ of A){let D=e1($);w.add(D);let Y=B.get(D),I=Y?.content??this.createSeriesContent($),X=aB(I);if(Y?.contentHash===X)continue;let H={id:D,entityType:"series",content:I,contentHash:X,created:Y?.created??new Date().toISOString(),updated:new Date().toISOString(),metadata:{title:$,slug:e1($)}};await this.entityService.upsertEntity(H),this.logger.debug(`Upserted series: ${$}`)}for(let $ of Q)if(!w.has($.id))await this.entityService.deleteEntity("series",$.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=e1(A);if(await this.entityService.getEntity("series",Q))return;let w=this.createSeriesContent(A),$={id:Q,entityType:"series",content:w,contentHash:aB(w),created:new Date().toISOString(),updated:new Date().toISOString(),metadata:{title:A,slug:e1(A)}};await this.entityService.upsertEntity($),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=e1(A);if(!await this.entityService.getEntity("series",Q))return;if(!await this.hasSeriesReferences(A))await this.entityService.deleteEntity("series",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(B,{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(B,{limit:1000});for(let $ of w){let D=this.getSeriesName($);if(D)A.add(D)}}return A}createSeriesContent(A){let Q={title:A,slug:e1(A)};return o5("",Q)}}B0();GA();var Fq2=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()}),qq2=F.object({type:F.enum(["list","detail"]),seriesName:F.string().optional()});function zq2(A){let Q=qq2.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let B=Fq2.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 PT0(A){let Q=G2(A.content,$D);return wi.parse({...A,frontmatter:Q.metadata})}class IGA{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=zq2(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("series",{limit:1000}),w=await this.countEntitiesPerSeries(Q),$=B.map((D)=>{let Y=PT0(D),I=dM.parseBody(D.content);return{...Y,description:I.description,postCount:w.get(D.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("series",{filter:{metadata:{title:A}}}))[0];if(!w)throw Error(`Series not found: ${A}`);let $=PT0(w),D=dM.parseBody(w.content),Y=await this.getSeriesMembers(A,B);return this.logger.debug(`Found ${Y.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:Y,series:{...$,description:D.description,postCount:Y.length},description:D.description})}async fetchSeriesDetailBySlug(A,Q,B){let $=(await B.listEntities("series",{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(w,{limit:1000});for(let D of $){let Y=this.getSeriesName(D);if(Y)Q.set(Y,(Q.get(Y)??0)+1)}}return Q}async getSeriesMembers(A,Q){let B=[],w=Q.getEntityTypes();for(let $ of w){if($==="series")continue;let D=await Q.listEntities($,{filter:{metadata:{seriesName:A}}});B.push(...D)}return B.sort(($,D)=>{let Y=$.metadata.seriesIndex,I=D.metadata.seriesIndex;return(typeof Y==="number"?Y:999)-(typeof I==="number"?I:999)}),B}getSeriesName(A){let B=A.metadata.seriesName;return typeof B==="string"?B:void 0}}B0();GA();aD();var Nq2=F.object({prompt:F.string().optional(),title:F.string().optional(),seriesId:F.string().optional()});class Di{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("series",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}
2606
+ ${B.content}`,templateName:"blog:excerpt"})})}var CT0={name:"@brains/blog",private:!0,version:"0.2.0-alpha.42",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/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 wGA extends HQ{entityType=tF.entityType;schema=uM;adapter=tF;constructor(A={}){super("blog",CT0,A,tWA)}getEntityTypeConfig(){return{weight:2}}createGenerationHandler(A){return new eWA(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return zT0()}getDataSources(){return[new QGA(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (RT0(),fT0));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),await NT0(A,this.logger),VT0(A,this.logger),MT0(A,this.logger),ET0(A),this.logger.info("Blog plugin registered (routes auto-generated at /posts/)")}}function $GA(A={}){return new wGA(A)}TX();S_();B0();GA();P6();var $D=F.object({title:F.string(),slug:F.string(),coverImageId:F.string().optional()}),jT0=$D.pick({title:!0,slug:!0}),pM=Q2.extend({metadata:jT0}),wi=pM.extend({frontmatter:$D}),$i=wi.extend({description:F.string().optional(),postCount:F.number(),coverImageUrl:F.string().optional(),coverImageWidth:F.number().optional(),coverImageHeight:F.number().optional()}),kT0=F.object({description:F.string().optional()});function eF(A){return new $B(kT0,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}P6();class DGA extends I2{constructor(){super({entityType:"series",schema:pM,frontmatterSchema:$D,supportsCoverImage:!0,bodyFormatter:eF("")})}toMarkdown(A){let Q,B={};try{Q=this.parseFrontMatter(A.content,$D).coverImageId,B=eF(A.metadata.title).parse(this.extractBody(A.content))}catch{}let w={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},D=eF(A.metadata.title).format(B);return this.buildMarkdown(D,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,$D);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,$D);return eF(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var dM=new DGA;B0();GA();aD();class YGA{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("series",{limit:1000}),B=new Map(Q.map(($)=>[$.id,$])),w=new Set;for(let $ of A){let D=e1($);w.add(D);let Y=B.get(D),I=Y?.content??this.createSeriesContent($),X=aB(I);if(Y?.contentHash===X)continue;let H={id:D,entityType:"series",content:I,contentHash:X,created:Y?.created??new Date().toISOString(),updated:new Date().toISOString(),metadata:{title:$,slug:e1($)}};await this.entityService.upsertEntity(H),this.logger.debug(`Upserted series: ${$}`)}for(let $ of Q)if(!w.has($.id))await this.entityService.deleteEntity("series",$.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=e1(A);if(await this.entityService.getEntity("series",Q))return;let w=this.createSeriesContent(A),$={id:Q,entityType:"series",content:w,contentHash:aB(w),created:new Date().toISOString(),updated:new Date().toISOString(),metadata:{title:A,slug:e1(A)}};await this.entityService.upsertEntity($),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=e1(A);if(!await this.entityService.getEntity("series",Q))return;if(!await this.hasSeriesReferences(A))await this.entityService.deleteEntity("series",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(B,{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(B,{limit:1000});for(let $ of w){let D=this.getSeriesName($);if(D)A.add(D)}}return A}createSeriesContent(A){let Q={title:A,slug:e1(A)};return o5("",Q)}}B0();GA();var Fq2=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()}),qq2=F.object({type:F.enum(["list","detail"]),seriesName:F.string().optional()});function zq2(A){let Q=qq2.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let B=Fq2.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 PT0(A){let Q=G2(A.content,$D);return wi.parse({...A,frontmatter:Q.metadata})}class IGA{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=zq2(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("series",{limit:1000}),w=await this.countEntitiesPerSeries(Q),$=B.map((D)=>{let Y=PT0(D),I=dM.parseBody(D.content);return{...Y,description:I.description,postCount:w.get(D.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("series",{filter:{metadata:{title:A}}}))[0];if(!w)throw Error(`Series not found: ${A}`);let $=PT0(w),D=dM.parseBody(w.content),Y=await this.getSeriesMembers(A,B);return this.logger.debug(`Found ${Y.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:Y,series:{...$,description:D.description,postCount:Y.length},description:D.description})}async fetchSeriesDetailBySlug(A,Q,B){let $=(await B.listEntities("series",{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(w,{limit:1000});for(let D of $){let Y=this.getSeriesName(D);if(Y)Q.set(Y,(Q.get(Y)??0)+1)}}return Q}async getSeriesMembers(A,Q){let B=[],w=Q.getEntityTypes();for(let $ of w){if($==="series")continue;let D=await Q.listEntities($,{filter:{metadata:{seriesName:A}}});B.push(...D)}return B.sort(($,D)=>{let Y=$.metadata.seriesIndex,I=D.metadata.seriesIndex;return(typeof Y==="number"?Y:999)-(typeof I==="number"?I:999)}),B}getSeriesName(A){let B=A.metadata.seriesName;return typeof B==="string"?B:void 0}}B0();GA();aD();var Nq2=F.object({prompt:F.string().optional(),title:F.string().optional(),seriesId:F.string().optional()});class Di{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("series",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}
2607
2607
 
2608
2608
  Content in this series:
2609
2609
  ${w.join(`
@@ -2615,7 +2615,7 @@ Your task is to write a series description (2-3 sentences) that:
2615
2615
  3. Is engaging and makes readers want to explore the content
2616
2616
  4. Works well as a series overview on a website
2617
2617
 
2618
- Be concise and focus on what makes this series unique and valuable.`});var hT0={name:"@brains/series",private:!0,version:"0.2.0-alpha.41",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/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"}};class XGA extends HQ{entityType="series";schema=pM;adapter=dM;manager;constructor(){super("series",hT0)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new Di(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...vT0(),description:ST0}}getDataSources(){return[new IGA(this.logger.child("SeriesDataSource"))]}async onRegister(A){this.manager=new YGA(A.entityService,this.logger.child("SeriesManager"));let Q=this.manager;for(let B of["entity:created","entity:updated"])A.messaging.subscribe(B,async(w)=>{try{let $=w.payload;if($.entityType==="series")return{success:!0};if($.entity){if(Q.getSeriesName($.entity))await Q.handleEntityChange($.entity)}return{success:!0}}catch($){return this.logger.error("Failed to handle entity event for series",{error:$}),{success:!1,error:"Series derivation failed"}}});A.messaging.subscribe("entity:deleted",async(B)=>{try{if(B.payload.entityType==="series")return{success:!0};return await Q.handleEntityDeleted(),{success:!0}}catch(w){return this.logger.error("Failed to handle entity deletion for series",{error:w}),{success:!1,error:"Series cleanup failed"}}}),A.messaging.subscribe("sync:initial:completed",async()=>{try{return this.logger.info("Initial sync completed, syncing series"),await Q.syncAllSeries(),{success:!0}}catch(B){return this.logger.error("Failed to sync series after initial sync",{error:B}),{success:!1,error:"Series sync failed"}}})}requireManager(){if(!this.manager)throw Error("SeriesPlugin not registered");return this.manager}async derive(A,Q,B){await this.requireManager().handleEntityChange(A)}async deriveAll(A){await this.requireManager().syncAllSeries();let Q=new Di(this.logger.child("SeriesGenerationHandler"),A),B=await A.entityService.listEntities("series",{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 HGA(){return new XGA}B0();GA();B0();GA();GA();B0();var Cq2=F.enum(["draft","queued","published"]),BJ=F.object({title:F.string(),slug:F.string().optional(),description:F.string().optional(),author:F.string().optional(),status:Cq2,publishedAt:F.string().datetime().optional(),event:F.string().optional(),coverImageId:F.string().optional()}),Oq2=BJ.pick({title:!0,description:!0,status:!0,publishedAt:!0,coverImageId:!0}).extend({slug:F.string()}),Yi=Q2.extend({entityType:F.literal("deck"),metadata:Oq2}),Ii=Yi.extend({frontmatter:BJ,body:F.string()}),y_=Ii.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 KGA extends I2{constructor(){super({entityType:"deck",schema:Yi,frontmatterSchema:BJ,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);try{let B=this.parseFrontMatter(A.content,BJ),w={...B,slug:B.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontmatter(A),B=this.extractBody(A);this.validateSlideStructure(B);let w=Q.slug??e1(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 m_=new KGA;GA();s8();var fq2=F.object({markdown:F.string().describe("Markdown content with slide separators (---)")}),UGA=M1({name:"deck-detail",description:"Render a presentation deck as Reveal.js slides",schema:fq2,dataSourceId:"decks:entities",requiredPermission:"public",layout:{component:THA,fullscreen:!0}});s8();GA();var WGA=F.object({decks:F.array(Ii)}),GGA=F.object({decks:F.array(y_),pageTitle:F.string().optional()});import{jsxDEV as JGA}from"preact/jsx-dev-runtime";var ZGA=({decks:A,pageTitle:Q})=>{let B=A.map((w)=>({id:w.id,url:w.url,title:w.frontmatter.title,date:w.frontmatter.publishedAt??w.created,description:w.frontmatter.description}));return JGA("div",{className:"deck-list bg-theme",children:JGA("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:JGA(bK,{title:Q??"Presentations",items:B},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)};GA();class Xi extends $B{constructor(){super(WGA,{title:"Deck List",mappings:[{key:"decks",label:"Decks",type:"array",itemType:"object"}]})}}var FGA=M1({name:"deck-list",description:"List view of all presentation decks",schema:GGA,dataSourceId:"decks:entities",requiredPermission:"public",formatter:new Xi,layout:{component:ZGA}});GA();B0();var Rq2=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")}),gT0=M1({name:"decks:generation",description:"Template for AI to generate complete slide decks from prompts",schema:Rq2,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are creating slide decks in a distinctive voice that blends philosophy, technology, and culture.
2618
+ Be concise and focus on what makes this series unique and valuable.`});var hT0={name:"@brains/series",private:!0,version:"0.2.0-alpha.42",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/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"}};class XGA extends HQ{entityType="series";schema=pM;adapter=dM;manager;constructor(){super("series",hT0)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new Di(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...vT0(),description:ST0}}getDataSources(){return[new IGA(this.logger.child("SeriesDataSource"))]}async onRegister(A){this.manager=new YGA(A.entityService,this.logger.child("SeriesManager"));let Q=this.manager;for(let B of["entity:created","entity:updated"])A.messaging.subscribe(B,async(w)=>{try{let $=w.payload;if($.entityType==="series")return{success:!0};if($.entity){if(Q.getSeriesName($.entity))await Q.handleEntityChange($.entity)}return{success:!0}}catch($){return this.logger.error("Failed to handle entity event for series",{error:$}),{success:!1,error:"Series derivation failed"}}});A.messaging.subscribe("entity:deleted",async(B)=>{try{if(B.payload.entityType==="series")return{success:!0};return await Q.handleEntityDeleted(),{success:!0}}catch(w){return this.logger.error("Failed to handle entity deletion for series",{error:w}),{success:!1,error:"Series cleanup failed"}}}),A.messaging.subscribe("sync:initial:completed",async()=>{try{return this.logger.info("Initial sync completed, syncing series"),await Q.syncAllSeries(),{success:!0}}catch(B){return this.logger.error("Failed to sync series after initial sync",{error:B}),{success:!1,error:"Series sync failed"}}})}requireManager(){if(!this.manager)throw Error("SeriesPlugin not registered");return this.manager}async derive(A,Q,B){await this.requireManager().handleEntityChange(A)}async deriveAll(A){await this.requireManager().syncAllSeries();let Q=new Di(this.logger.child("SeriesGenerationHandler"),A),B=await A.entityService.listEntities("series",{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 HGA(){return new XGA}B0();GA();B0();GA();GA();B0();var Cq2=F.enum(["draft","queued","published"]),BJ=F.object({title:F.string(),slug:F.string().optional(),description:F.string().optional(),author:F.string().optional(),status:Cq2,publishedAt:F.string().datetime().optional(),event:F.string().optional(),coverImageId:F.string().optional()}),Oq2=BJ.pick({title:!0,description:!0,status:!0,publishedAt:!0,coverImageId:!0}).extend({slug:F.string()}),Yi=Q2.extend({entityType:F.literal("deck"),metadata:Oq2}),Ii=Yi.extend({frontmatter:BJ,body:F.string()}),y_=Ii.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 KGA extends I2{constructor(){super({entityType:"deck",schema:Yi,frontmatterSchema:BJ,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);try{let B=this.parseFrontMatter(A.content,BJ),w={...B,slug:B.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontmatter(A),B=this.extractBody(A);this.validateSlideStructure(B);let w=Q.slug??e1(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 m_=new KGA;GA();s8();var fq2=F.object({markdown:F.string().describe("Markdown content with slide separators (---)")}),UGA=M1({name:"deck-detail",description:"Render a presentation deck as Reveal.js slides",schema:fq2,dataSourceId:"decks:entities",requiredPermission:"public",layout:{component:THA,fullscreen:!0}});s8();GA();var WGA=F.object({decks:F.array(Ii)}),GGA=F.object({decks:F.array(y_),pageTitle:F.string().optional()});import{jsxDEV as JGA}from"preact/jsx-dev-runtime";var ZGA=({decks:A,pageTitle:Q})=>{let B=A.map((w)=>({id:w.id,url:w.url,title:w.frontmatter.title,date:w.frontmatter.publishedAt??w.created,description:w.frontmatter.description}));return JGA("div",{className:"deck-list bg-theme",children:JGA("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:JGA(bK,{title:Q??"Presentations",items:B},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)};GA();class Xi extends $B{constructor(){super(WGA,{title:"Deck List",mappings:[{key:"decks",label:"Decks",type:"array",itemType:"object"}]})}}var FGA=M1({name:"deck-list",description:"List view of all presentation decks",schema:GGA,dataSourceId:"decks:entities",requiredPermission:"public",formatter:new Xi,layout:{component:ZGA}});GA();B0();var Rq2=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")}),gT0=M1({name:"decks:generation",description:"Template for AI to generate complete slide decks from prompts",schema:Rq2,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are creating slide decks in a distinctive voice that blends philosophy, technology, and culture.
2619
2619
 
2620
2620
  Your task is to generate a complete slide deck based on the user's prompt.
2621
2621
 
@@ -2683,7 +2683,7 @@ Add your conclusion here`,X=X??`Presentation: ${Y}`,await this.reportProgress(Q,
2683
2683
  Note: This presentation is for "${$}".`:""}`,j=await this.context.ai.generate({prompt:L,templateName:"decks:generation"});Y=Y??j.title,I=I??j.content,X=X??j.description,await this.reportProgress(Q,{progress:50,message:`Generated deck: "${Y}"`})}else if(!X)await this.reportProgress(Q,{progress:30,message:"Generating description with AI"}),X=(await this.context.ai.generate({prompt:`Title: ${Y}
2684
2684
 
2685
2685
  Content:
2686
- ${I}`,templateName:"decks:description"})).description,await this.reportProgress(Q,{progress:50,message:"Description generated"});else await this.reportProgress(Q,{progress:50,message:"Using provided content"});if(!Y||!I)this.failEarly("Title and content are required");let W={slug:e1(Y),title:Y,status:"draft"},J=await dH({entityType:"deck",title:Y,deriveId:(V)=>V,regeneratePrompt:"Generate a different presentation deck title on the same topic.",context:this.context});if(J!==Y)W.title=J,W.slug=e1(J);let Z={title:W.title,status:W.status,slug:W.slug,description:X,author:w,event:$},q=o5(I,Z);return{id:J,content:q,metadata:W,title:J,resultExtras:{title:J,slug:W.slug},createOptions:{deduplicateId:!0}}}summarizeDataForLog(A){return{prompt:A.prompt,title:A.title}}}var mT0={name:"@brains/decks",private:!0,version:"0.2.0-alpha.41",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/image":"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 NGA extends HQ{entityType=m_.entityType;schema=m_.schema;adapter=m_;constructor(){super("decks",mT0)}createGenerationHandler(A){return new zGA(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":UGA,"deck-list":FGA,generation:gT0,description:yT0}}getDataSources(){return[new qGA(this.logger)]}getEntityTypeConfig(){return{weight:1.5}}async onRegister(A){await this.registerWithPublishPipeline(A),this.subscribeToPublishExecute(A),this.registerEvalHandlers(A),this.logger.info("Decks plugin registered")}async registerWithPublishPipeline(A){await A.messaging.send("publish:register",{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("deck",w);if(!$)return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:`Deck not found: ${w}`}),{success:!0};if($.metadata.status==="published")return{success:!0};let D=new Date().toISOString(),Y={...$,metadata:{...$.metadata,status:"published",publishedAt:D}};await A.entityService.updateEntity({...Y,content:this.adapter.toMarkdown(Y)}),await A.messaging.send("publish:report:success",{entityType:B,entityId:w,result:{id:w}})}catch($){await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:L0($)})}return{success:!0}})}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?`
2686
+ ${I}`,templateName:"decks:description"})).description,await this.reportProgress(Q,{progress:50,message:"Description generated"});else await this.reportProgress(Q,{progress:50,message:"Using provided content"});if(!Y||!I)this.failEarly("Title and content are required");let W={slug:e1(Y),title:Y,status:"draft"},J=await dH({entityType:"deck",title:Y,deriveId:(V)=>V,regeneratePrompt:"Generate a different presentation deck title on the same topic.",context:this.context});if(J!==Y)W.title=J,W.slug=e1(J);let Z={title:W.title,status:W.status,slug:W.slug,description:X,author:w,event:$},q=o5(I,Z);return{id:J,content:q,metadata:W,title:J,resultExtras:{title:J,slug:W.slug},createOptions:{deduplicateId:!0}}}summarizeDataForLog(A){return{prompt:A.prompt,title:A.title}}}var mT0={name:"@brains/decks",private:!0,version:"0.2.0-alpha.42",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/image":"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 NGA extends HQ{entityType=m_.entityType;schema=m_.schema;adapter=m_;constructor(){super("decks",mT0)}createGenerationHandler(A){return new zGA(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":UGA,"deck-list":FGA,generation:gT0,description:yT0}}getDataSources(){return[new qGA(this.logger)]}getEntityTypeConfig(){return{weight:1.5}}async onRegister(A){await this.registerWithPublishPipeline(A),this.subscribeToPublishExecute(A),this.registerEvalHandlers(A),this.logger.info("Decks plugin registered")}async registerWithPublishPipeline(A){await A.messaging.send("publish:register",{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("deck",w);if(!$)return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:`Deck not found: ${w}`}),{success:!0};if($.metadata.status==="published")return{success:!0};let D=new Date().toISOString(),Y={...$,metadata:{...$.metadata,status:"published",publishedAt:D}};await A.entityService.updateEntity({...Y,content:this.adapter.toMarkdown(Y)}),await A.messaging.send("publish:report:success",{entityType:B,entityId:w,result:{id:w}})}catch($){await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:L0($)})}return{success:!0}})}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?`
2687
2687
 
2688
2688
  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}
2689
2689
 
@@ -2698,7 +2698,7 @@ Guidelines:
2698
2698
  3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
2699
2699
  4. Style: Informative and educational. Write as if explaining to yourself for future reference.
2700
2700
  5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
2701
- 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});B0();GA();var lT0=F.object({prompt:F.string(),title:F.string().optional()}),bq2=R7.extend({title:F.string().optional()});class Hi extends Q9{constructor(A,Q){super(A,Q,{schema:lT0,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:rM.createNoteContent(w,B.body),metadata:{title:w},title:w,resultExtras:{title:w}}}summarizeDataForLog(A){return{prompt:A.prompt,title:A.title}}}var pT0={name:"@brains/note",private:!0,version:"0.2.0-alpha.41",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/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 EGA extends HQ{entityType=rM.entityType;schema=iM;adapter=rM;constructor(A={}){super("note",pT0,A,LGA)}createGenerationHandler(A){return new Hi(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:MGA}}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 Aq(A={}){return new EGA(A)}B0();GA();GA();B0();var dT0=F.object({ref:F.string(),label:F.string()}),iT0=F.enum(["pending","draft","published"]),eK=F.object({status:iT0,title:F.string(),url:F.string().url(),description:F.string().optional(),domain:F.string(),capturedAt:F.string().datetime(),source:dT0}),rT0=eK.pick({title:!0,status:!0}),l_=Q2.extend({entityType:F.literal("link"),metadata:rT0}),CGA=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)")});B0();class $J extends I2{constructor(){super({entityType:"link",schema:l_,frontmatterSchema:eK})}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,eK),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 OGA=new $J;B0();GA();var Tq2=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.")}),nT0=M1({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:Tq2,basePrompt:`You are an expert at extracting key information from webpage content.
2701
+ 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});B0();GA();var lT0=F.object({prompt:F.string(),title:F.string().optional()}),bq2=R7.extend({title:F.string().optional()});class Hi extends Q9{constructor(A,Q){super(A,Q,{schema:lT0,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:rM.createNoteContent(w,B.body),metadata:{title:w},title:w,resultExtras:{title:w}}}summarizeDataForLog(A){return{prompt:A.prompt,title:A.title}}}var pT0={name:"@brains/note",private:!0,version:"0.2.0-alpha.42",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/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 EGA extends HQ{entityType=rM.entityType;schema=iM;adapter=rM;constructor(A={}){super("note",pT0,A,LGA)}createGenerationHandler(A){return new Hi(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:MGA}}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 Aq(A={}){return new EGA(A)}B0();GA();GA();B0();var dT0=F.object({ref:F.string(),label:F.string()}),iT0=F.enum(["pending","draft","published"]),eK=F.object({status:iT0,title:F.string(),url:F.string().url(),description:F.string().optional(),domain:F.string(),capturedAt:F.string().datetime(),source:dT0}),rT0=eK.pick({title:!0,status:!0}),l_=Q2.extend({entityType:F.literal("link"),metadata:rT0}),CGA=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)")});B0();class $J extends I2{constructor(){super({entityType:"link",schema:l_,frontmatterSchema:eK})}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,eK),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 OGA=new $J;B0();GA();var Tq2=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.")}),nT0=M1({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:Tq2,basePrompt:`You are an expert at extracting key information from webpage content.
2702
2702
 
2703
2703
  You will receive webpage content in markdown format. Your job is to extract structured information from it.
2704
2704
 
@@ -2715,7 +2715,7 @@ Focus only on information present in the provided content. Do not make up or hal
2715
2715
 
2716
2716
  `))return{success:!1,error:Y.trim(),errorType:"fetch_failed"};return{success:!0,content:Y}}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 gq2}from"crypto";class Qq{static URL_PATTERN=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi;static extractUrls(A){let Q=A.match(Qq.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=gq2("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}}}B0();GA();var yq2=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()}),ZQB=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 Ui extends EB{context;linkAdapter;urlFetcher;constructor(A,Q,B){super(A,{schema:yq2,jobTypeName:"link-capture"});this.context=Q,this.linkAdapter=new $J,this.urlFetcher=new nM(B?.jinaApiKey?{jinaApiKey:B.jinaApiKey}:void 0)}async process(A,Q,B){let{url:w,metadata:$}=A;try{await B.report({progress:F2.START,total:100,message:"Starting link capture"});let D=Qq.generateEntityId(w);await B.report({progress:F2.INIT,total:100,message:"Checking for existing link"});let Y=await this.context.entityService.getEntity("link",D);if(Y){this.logger.info("Link already captured, returning existing",{url:w,entityId:D});let{frontmatter:q}=this.linkAdapter.parseLinkContent(Y.content);return{success:!0,entityId:Y.id,title:q.title,url:w,status:Y.metadata.status}}await B.report({progress:F2.FETCH,total:100,message:"Fetching webpage content"});let I=await this.urlFetcher.fetch(w);if(!I.success){if(I.errorType==="url_not_found"||I.errorType==="url_unreachable")return this.logger.warn("Link URL not accessible",{url:w,errorType:I.errorType,error:I.error}),{success:!1,error:`Could not capture link: ${I.error}`}}await B.report({progress:F2.PROCESS,total:100,message:"Extracting content with AI"});let X=await this.context.ai.generate({templateName:"link:extraction",prompt:I.success?`Extract structured information from this webpage content:
2717
2717
 
2718
- ${I.content}`:`The URL ${w} could not be fetched. Return success: false with error: "${I.error}"`,data:{url:w,hasContent:I.success},interfacePermissionGrant:"public"});this.logger.debug("AI extraction result",{result:X}),await B.report({progress:F2.EXTRACT,total:100,message:"Processing extraction results"});let H=this.resolveSource($),W=new Date().toISOString();if(X.success===!1||!X.title||!X.description||!X.summary){let q=X.title||new URL(w).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:w}),await B.report({progress:F2.SAVE,total:100,message:"Saving link as pending"});let V=this.linkAdapter.createLinkContent({status:"pending",title:q,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:W,source:H}),E=await this.context.entityService.createEntity({id:D,entityType:"link",content:V,metadata:{status:"pending",title:q}});return await B.report({progress:F2.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:E.entityId,title:q,url:w,status:"pending"}}await B.report({progress:F2.SAVE,total:100,message:`Saving link: "${X.title}"`});let J=this.linkAdapter.createLinkContent({status:"draft",title:X.title,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:W,source:H}),Z=await this.context.entityService.createEntity({id:D,entityType:"link",content:J,metadata:{status:"draft",title:X.title}});return await B.report({progress:F2.COMPLETE,total:100,message:`Link captured: "${X.title}"`}),{success:!0,entityId:Z.entityId,title:X.title,url:w,status:"draft"}}catch(D){return this.logger.error("Link capture job failed",{error:D,jobId:Q,data:A}),K6.failure(D)}}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 aT0={name:"@brains/link",private:!0,version:"0.2.0-alpha.41",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/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 _GA extends HQ{entityType=OGA.entityType;schema=l_;adapter=OGA;shell;constructor(A={}){super("link",aT0,A,CGA)}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 Ui(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 D=this.adapter.fromMarkdown(A.content).metadata,Y=typeof D?.title==="string"?D.title:void 0,I=typeof D?.status==="string"?D.status:void 0,X=this.extractFirstUrl(A.content);if(Y&&I&&X){let H=e1(X)||e1(Y)||`${A.entityType}-${Date.now()}`,W=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await B.entityService.createEntity({id:H,entityType:A.entityType,content:A.content,metadata:{title:Y,status:I},created:W,updated:W})).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("link-capture",{url:w,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},{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 Ui(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:nT0,"link-list":oT0,"link-detail":sT0}}getDataSources(){return[new PGA(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 nM(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:
2718
+ ${I.content}`:`The URL ${w} could not be fetched. Return success: false with error: "${I.error}"`,data:{url:w,hasContent:I.success},interfacePermissionGrant:"public"});this.logger.debug("AI extraction result",{result:X}),await B.report({progress:F2.EXTRACT,total:100,message:"Processing extraction results"});let H=this.resolveSource($),W=new Date().toISOString();if(X.success===!1||!X.title||!X.description||!X.summary){let q=X.title||new URL(w).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:w}),await B.report({progress:F2.SAVE,total:100,message:"Saving link as pending"});let V=this.linkAdapter.createLinkContent({status:"pending",title:q,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:W,source:H}),E=await this.context.entityService.createEntity({id:D,entityType:"link",content:V,metadata:{status:"pending",title:q}});return await B.report({progress:F2.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:E.entityId,title:q,url:w,status:"pending"}}await B.report({progress:F2.SAVE,total:100,message:`Saving link: "${X.title}"`});let J=this.linkAdapter.createLinkContent({status:"draft",title:X.title,url:w,description:X.description,summary:X.summary,domain:new URL(w).hostname,capturedAt:W,source:H}),Z=await this.context.entityService.createEntity({id:D,entityType:"link",content:J,metadata:{status:"draft",title:X.title}});return await B.report({progress:F2.COMPLETE,total:100,message:`Link captured: "${X.title}"`}),{success:!0,entityId:Z.entityId,title:X.title,url:w,status:"draft"}}catch(D){return this.logger.error("Link capture job failed",{error:D,jobId:Q,data:A}),K6.failure(D)}}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 aT0={name:"@brains/link",private:!0,version:"0.2.0-alpha.42",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/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 _GA extends HQ{entityType=OGA.entityType;schema=l_;adapter=OGA;shell;constructor(A={}){super("link",aT0,A,CGA)}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 Ui(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 D=this.adapter.fromMarkdown(A.content).metadata,Y=typeof D?.title==="string"?D.title:void 0,I=typeof D?.status==="string"?D.status:void 0,X=this.extractFirstUrl(A.content);if(Y&&I&&X){let H=e1(X)||e1(Y)||`${A.entityType}-${Date.now()}`,W=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await B.entityService.createEntity({id:H,entityType:A.entityType,content:A.content,metadata:{title:Y,status:I},created:W,updated:W})).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("link-capture",{url:w,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},{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 Ui(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:nT0,"link-list":oT0,"link-detail":sT0}}getDataSources(){return[new PGA(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 nM(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:
2719
2719
 
2720
2720
  ${$.content}`,data:{url:B,hasContent:!0},interfacePermissionGrant:"public"})})}extractFirstUrl(...A){for(let Q of A){if(!Q)continue;let[B]=Qq.extractUrls(Q);if(B)return B}return}}function tT0(A={}){return new _GA(A)}var Bq=tT0;GA();var vQB=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()});B0();GA();s8();GA();B0();var eT0=F.enum(["draft","published"]),DD=F.object({title:F.string(),slug:F.string().optional(),status:eT0,publishedAt:F.string().datetime().optional(),description:F.string(),year:F.number(),coverImageId:F.string().optional(),url:F.string().url().optional()}),Av0=DD.pick({title:!0,status:!0,publishedAt:!0,year:!0}).extend({slug:F.string()}),oM=Q2.extend({entityType:F.literal("project"),metadata:Av0}),Wi=F.object({context:F.string(),problem:F.string(),solution:F.string(),outcome:F.string()}),d_=oM.extend({frontmatter:DD,body:F.string(),structuredContent:Wi.optional(),coverImageUrl:F.string().optional()}),sM=d_.extend({url:F.string().optional(),typeLabel:F.string().optional(),coverImageUrl:F.string().optional(),coverImageWidth:F.number().optional(),coverImageHeight:F.number().optional()}),uq2=d_.extend({url:F.string(),typeLabel:F.string(),coverImageUrl:F.string().optional(),coverImageWidth:F.number().optional(),coverImageHeight:F.number().optional()});B0();GA();GA();class bGA extends $B{constructor(){super(Wi,{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 xGA=new bGA;class TGA extends I2{constructor(){super({entityType:"project",schema:oM,frontmatterSchema:DD,supportsCoverImage:!0,bodyFormatter:xGA})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,DD),w={...B,slug:B.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,DD),B=Q.slug??e1(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,DD)}parseStructuredContent(A){return xGA.parse(this.extractBody(A.content))}createProjectContent(A,Q){let B=xGA.format(Q);return this.buildMarkdown(B,A)}}var DJ=new TGA;GA();var vGA=F.object({});import{jsxDEV as B4,Fragment as lq2}from"preact/jsx-dev-runtime";var cq2=({project:A})=>{let{frontmatter:Q,url:B,coverImageUrl:w}=A;return B4(MQ,{href:B,children:[w&&B4("img",{src:w,alt:Q.title,className:"w-full h-56 object-cover rounded-md mb-4"},void 0,!1,void 0,this),B4(G9,{children:Q.title},void 0,!1,void 0,this),B4("p",{className:"text-theme leading-relaxed",children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},SGA=({projects:A,pageTitle:Q,pagination:B,baseUrl:w="/projects"})=>{let $=Q??"Projects",D=B?.totalItems??A.length,Y=`Browse all ${D} ${D===1?"project":"projects"}`;return B4(lq2,{children:[B4(n2,{title:$,description:Y},void 0,!1,void 0,this),B4("div",{className:"project-list bg-theme",children:B4("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[B4("h1",{className:"text-4xl font-bold text-heading mb-12",children:$},void 0,!1,void 0,this),B4("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:A.map((I)=>B4(cq2,{project:I},I.id,!1,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&B4("div",{className:"mt-12",children:B4(jY,{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 KB,Fragment as Qv0}from"preact/jsx-dev-runtime";var pq2=({prevProject:A,nextProject:Q})=>{if(!A&&!Q)return null;return KB("nav",{className:"pt-12 mt-12 border-t border-theme-muted",children:KB("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[A?KB(MQ,{href:A.url,variant:"compact",children:[KB("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Previous"},void 0,!1,void 0,this),KB("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):KB("div",{},void 0,!1,void 0,this),Q&&KB(MQ,{href:Q.url,variant:"compact",className:"md:text-right",children:[KB("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Next"},void 0,!1,void 0,this),KB("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)},Gi=({title:A,content:Q})=>{if(!Q)return null;return KB("section",{className:"mb-12",children:[KB("h2",{className:"text-2xl font-bold text-heading mb-4",children:A},void 0,!1,void 0,this),KB(RY,{markdown:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},hGA=({project:A,prevProject:Q,nextProject:B})=>{let{frontmatter:w,structuredContent:$,metadata:D,coverImageUrl:Y}=A;return KB(Qv0,{children:[KB(n2,{title:w.title,description:w.description,...Y&&{ogImage:Y},ogType:"article"},void 0,!1,void 0,this),KB("article",{className:"project-detail",children:KB("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:KB("div",{className:"max-w-3xl mx-auto",children:[Y&&A.coverImageWidth&&A.coverImageHeight&&KB(_K,{src:Y,alt:w.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8 shadow-lg"},void 0,!1,void 0,this),KB("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),KB("div",{className:"flex flex-wrap items-center gap-4 text-theme-muted mb-8",children:[KB("span",{className:"text-sm",children:D.year},void 0,!1,void 0,this),w.url&&KB(Qv0,{children:[KB("span",{className:"text-theme-muted",children:"|"},void 0,!1,void 0,this),KB("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),KB("p",{className:"text-lg text-theme mb-12 leading-relaxed",children:w.description},void 0,!1,void 0,this),$&&KB("div",{className:"case-study",children:[KB(Gi,{title:"Context",content:$.context},void 0,!1,void 0,this),KB(Gi,{title:"Problem",content:$.problem},void 0,!1,void 0,this),KB(Gi,{title:"Solution",content:$.solution},void 0,!1,void 0,this),KB(Gi,{title:"Outcome",content:$.outcome},void 0,!1,void 0,this)]},void 0,!0,void 0,this),KB(pq2,{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)};GA();B0();var dq2=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)")}),gGA=M1({name:"portfolio:generation",description:"Template for AI to generate portfolio project case studies",schema:dq2,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create a professional portfolio case study based on REAL project information.
2721
2721
 
@@ -2734,7 +2734,7 @@ Guidelines:
2734
2734
  CRITICAL: Only include information that can be derived from the provided content. If information is missing, keep that section brief rather than inventing details.
2735
2735
 
2736
2736
  Tone: Professional but accessible. Write for someone evaluating real work.
2737
- Structure: Use markdown formatting. Break long sections into paragraphs for readability.`});B0();GA();var iq2=F.object({prompt:F.string(),year:F.number(),title:F.string().optional()}),JBB=R7.extend({title:F.string().optional()});class Ji extends Q9{constructor(A,Q){super(A,Q,{schema:iq2,jobTypeName:"project-generation",entityType:"project"})}async generate(A,Q){let{prompt:B,year:w}=A;await this.reportProgress(Q,{progress:10,message:"Generating project content with AI"});let $=await this.context.ai.generate({prompt:B,templateName:"portfolio:generation"}),D=A.title??$.title,Y=e1(D);await this.reportProgress(Q,{progress:50,message:`Generated project: "${D}"`});let I={title:D,slug:Y,status:"draft",description:$.description,year:w},X={context:$.context,problem:$.problem,solution:$.solution,outcome:$.outcome};return{id:Y,content:DJ.createProjectContent(I,X),metadata:{title:D,slug:Y,status:"draft",year:w},title:D,resultExtras:{title:D}}}summarizeDataForLog(A){return{prompt:A.prompt.substring(0,100),year:A.year,title:A.title}}}B0();B0();function rq2(A){let Q=G2(A.content,DD),B=DJ.parseStructuredContent(A);return d_.parse({...A,frontmatter:Q.metadata,body:Q.content,structuredContent:B})}class Zi extends s5{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 rq2(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 Bv0={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.41",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/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 oq2=F.object({projects:F.array(sM),pageTitle:F.string().optional(),pagination:P7.nullable(),baseUrl:F.string().optional()});class yGA extends HQ{entityType=DJ.entityType;schema=oM;adapter=DJ;constructor(A={}){super("portfolio",Bv0,A,vGA)}createGenerationHandler(A){return new Ji(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":M1({name:"project-list",description:"Portfolio project list page template",schema:oq2,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:SGA}}),"project-detail":M1({name:"project-detail",description:"Individual project case study template",schema:F.object({project:sM,prevProject:sM.nullable(),nextProject:sM.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:hGA}}),generation:gGA}}getDataSources(){return[new Zi(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:B.prompt,templateName:"portfolio:generation"})})}async registerWithPublishPipeline(A){let Q={name:"internal",publish:async()=>({id:"internal"})};await A.messaging.send("publish:register",{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("project",w);if(!$)return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:`Project not found: ${w}`}),{success:!0};if($.metadata.status==="published")return{success:!0};let D=G2($.content,DD),Y=new Date().toISOString(),I=o5(D.content,{...D.metadata,status:"published",publishedAt:Y});await A.entityService.updateEntity({...$,content:I,metadata:{...$.metadata,status:"published",publishedAt:Y}}),await A.messaging.send("publish:report:success",{entityType:B,entityId:w,publishedAt:Y})}catch($){await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:L0($)})}return{success:!0}})}}function mGA(A={}){return new yGA(A)}B0();GA();GA();var wv0=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),enableAutoExtraction:F.boolean().default(!0)});B0();GA();B0();var sq2=F.object({aliases:F.array(F.string()).optional()}),Fi=Q2.extend({entityType:F.literal("topic"),metadata:sq2}),oBB=F.object({content:F.string()}),$v0=F.object({title:F.string().describe("Topic title")}),sBB=F.object({timeWindowHours:F.number().min(1),minRelevanceScore:F.number().min(0).max(1)}),aBB=F.object({topicIds:F.array(F.string()).min(2),similarityThreshold:F.number().min(0).max(1)});class w4 extends I2{constructor(){super({entityType:"topic",schema:Fi,frontmatterSchema:$v0})}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:"topic"}}extractMetadata(A){return{aliases:A.metadata.aliases??[]}}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))}}GA();var Dv0=40,aq2=new w4;async function qi(A,Q=Dv0){return(await A.listEntities("topic",{limit:Q})).map((w)=>aq2.parseTopicBody(w.content).title).filter((w)=>w.trim().length>0)}function zi(A){let Q=(A.existingTopicTitles??[]).slice(0,Dv0),B=Q.length>0?`
2737
+ Structure: Use markdown formatting. Break long sections into paragraphs for readability.`});B0();GA();var iq2=F.object({prompt:F.string(),year:F.number(),title:F.string().optional()}),JBB=R7.extend({title:F.string().optional()});class Ji extends Q9{constructor(A,Q){super(A,Q,{schema:iq2,jobTypeName:"project-generation",entityType:"project"})}async generate(A,Q){let{prompt:B,year:w}=A;await this.reportProgress(Q,{progress:10,message:"Generating project content with AI"});let $=await this.context.ai.generate({prompt:B,templateName:"portfolio:generation"}),D=A.title??$.title,Y=e1(D);await this.reportProgress(Q,{progress:50,message:`Generated project: "${D}"`});let I={title:D,slug:Y,status:"draft",description:$.description,year:w},X={context:$.context,problem:$.problem,solution:$.solution,outcome:$.outcome};return{id:Y,content:DJ.createProjectContent(I,X),metadata:{title:D,slug:Y,status:"draft",year:w},title:D,resultExtras:{title:D}}}summarizeDataForLog(A){return{prompt:A.prompt.substring(0,100),year:A.year,title:A.title}}}B0();B0();function rq2(A){let Q=G2(A.content,DD),B=DJ.parseStructuredContent(A);return d_.parse({...A,frontmatter:Q.metadata,body:Q.content,structuredContent:B})}class Zi extends s5{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 rq2(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 Bv0={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.42",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/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 oq2=F.object({projects:F.array(sM),pageTitle:F.string().optional(),pagination:P7.nullable(),baseUrl:F.string().optional()});class yGA extends HQ{entityType=DJ.entityType;schema=oM;adapter=DJ;constructor(A={}){super("portfolio",Bv0,A,vGA)}createGenerationHandler(A){return new Ji(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":M1({name:"project-list",description:"Portfolio project list page template",schema:oq2,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:SGA}}),"project-detail":M1({name:"project-detail",description:"Individual project case study template",schema:F.object({project:sM,prevProject:sM.nullable(),nextProject:sM.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:hGA}}),generation:gGA}}getDataSources(){return[new Zi(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:B.prompt,templateName:"portfolio:generation"})})}async registerWithPublishPipeline(A){let Q={name:"internal",publish:async()=>({id:"internal"})};await A.messaging.send("publish:register",{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("project",w);if(!$)return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:`Project not found: ${w}`}),{success:!0};if($.metadata.status==="published")return{success:!0};let D=G2($.content,DD),Y=new Date().toISOString(),I=o5(D.content,{...D.metadata,status:"published",publishedAt:Y});await A.entityService.updateEntity({...$,content:I,metadata:{...$.metadata,status:"published",publishedAt:Y}}),await A.messaging.send("publish:report:success",{entityType:B,entityId:w,publishedAt:Y})}catch($){await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:L0($)})}return{success:!0}})}}function mGA(A={}){return new yGA(A)}B0();GA();GA();var wv0=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),enableAutoExtraction:F.boolean().default(!0)});B0();GA();B0();var sq2=F.object({aliases:F.array(F.string()).optional()}),Fi=Q2.extend({entityType:F.literal("topic"),metadata:sq2}),oBB=F.object({content:F.string()}),$v0=F.object({title:F.string().describe("Topic title")}),sBB=F.object({timeWindowHours:F.number().min(1),minRelevanceScore:F.number().min(0).max(1)}),aBB=F.object({topicIds:F.array(F.string()).min(2),similarityThreshold:F.number().min(0).max(1)});class w4 extends I2{constructor(){super({entityType:"topic",schema:Fi,frontmatterSchema:$v0})}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:"topic"}}extractMetadata(A){return{aliases:A.metadata.aliases??[]}}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))}}GA();var Dv0=40,aq2=new w4;async function qi(A,Q=Dv0){return(await A.listEntities("topic",{limit:Q})).map((w)=>aq2.parseTopicBody(w.content).title).filter((w)=>w.trim().length>0)}function zi(A){let Q=(A.existingTopicTitles??[]).slice(0,Dv0),B=Q.length>0?`
2738
2738
 
2739
2739
  Existing topic titles to reuse when they clearly fit:
2740
2740
  ${Q.map((w)=>`- ${w}`).join(`
@@ -2835,13 +2835,13 @@ RULES:
2835
2835
 
2836
2836
  Return JSON with:
2837
2837
  - title
2838
- - content`,requiredPermission:"public"});s8();GA();var Gz2=F.object({id:F.string(),title:F.string(),summary:F.string(),created:F.string(),updated:F.string()}),r_=F.object({topics:F.array(Gz2),totalCount:F.number()});import{jsxDEV as vX}from"preact/jsx-dev-runtime";var lGA=({topics:A,totalCount:Q})=>{return vX("div",{className:"topic-list-container w-full max-w-4xl mx-auto p-6 bg-theme",children:[vX(fY,{title:"Topics",count:Q,singularLabel:"topic",description:"discovered from your knowledge base"},void 0,!1,void 0,this),vX("div",{className:"space-y-6",children:A.map((B)=>vX(MQ,{variant:"vertical",children:[vX(G9,{href:`/topics/${B.id}`,className:"text-xl",children:B.title},void 0,!1,void 0,this),vX("p",{className:"text-theme-muted mb-4",children:B.summary},void 0,!1,void 0,this),vX(D7,{children:vX("div",{className:"flex justify-between text-sm text-theme-muted",children:vX("time",{dateTime:B.updated,children:["Updated ",m8(B.updated)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},B.id,!0,void 0,this))},void 0,!1,void 0,this),A.length===0&&vX(a$,{message:"No topics discovered yet.",description:"Topics will appear here as they are extracted from your content."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};GA();class Li extends $B{constructor(){super(r_,{title:"Topic List",mappings:[{key:"topics",label:"Topics",type:"array",itemType:"object"},{key:"totalCount",label:"Total Count",type:"number"}]})}}var qv0=M1({name:"topics:topic-list",description:"List view of all discovered topics",schema:r_,dataSourceId:"topics:entities",requiredPermission:"public",formatter:new Li,layout:{component:lGA}});s8();GA();var n_=F.object({id:F.string(),title:F.string(),content:F.string(),created:F.string(),updated:F.string()});import{jsxDEV as o_}from"preact/jsx-dev-runtime";var pGA=({title:A,content:Q,created:B,updated:w})=>{return o_("article",{className:"topic-detail-container max-w-4xl mx-auto p-6 bg-theme",children:[o_(EF,{title:A,created:B,updated:w},void 0,!1,void 0,this),o_("div",{className:"prose prose-lg max-w-none mb-8 text-theme-muted",children:o_("div",{dangerouslySetInnerHTML:{__html:Q}},void 0,!1,void 0,this)},void 0,!1,void 0,this),o_(LF,{href:"/topics",children:"Back to Topics"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};GA();class Mi extends $B{constructor(){super(n_,{title:"Topic Detail",mappings:[{key:"id",label:"ID",type:"string"},{key:"title",label:"Title",type:"string"},{key:"content",label:"Content",type:"string"},{key:"created",label:"Created",type:"string"},{key:"updated",label:"Updated",type:"string"}]})}}var zv0=M1({name:"topics:topic-detail",description:"Detailed view of a single topic",schema:n_,dataSourceId:"topics:entities",requiredPermission:"public",formatter:new Mi,layout:{component:pGA}});B0();GA();class dGA extends s5{id="topics:entities";name="Topics Entity DataSource";description="Fetches and transforms topic entities for rendering";config={entityType:"topic",defaultSort:[{field:"updated",direction:"desc"}],defaultLimit:100,lookupField:"id"};adapter=new w4;constructor(A){super(A);this.logger.debug("TopicsDataSource initialized")}transformEntity(A){let Q=this.adapter.parseTopicBody(A.content);return{id:A.id,title:Q.title,summary:JW(Q.content,200),created:A.created,updated:A.updated}}buildListResult(A,Q,B){return{topics:A,totalCount:A.length}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A);if(w.id){let D=await B.entityService.getEntity(this.config.entityType,w.id);if(!D)throw Error(`Entity not found: ${w.id}`);let Y=this.adapter.parseTopicBody(D.content);return Q.parse({id:D.id,title:Y.title,content:Y.content,created:D.created,updated:D.updated})}return super.fetch(A,Q,B)}}aD();function Nv0(){let A=new w4;return async(Q)=>{if(!Q.hasEntityType("topic"))return{topics:[]};return{topics:(await Q.listEntities("topic")).map(($)=>{let D=A.parseTopicBody($.content);return{topic:$.id,title:D.title}})}}}var Vv0={name:"@brains/topics",private:!0,version:"0.2.0-alpha.41",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/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var Zz2=new w4;function Fz2(A){let Q=A.replace(/\s+/g," ").trim();if(!Q)return;let B=Q.match(/^(.*?[.!?])(?:\s|$)/);if(B?.[1])return B[1];return Q.length<=200?Q:`${Q.slice(0,197)}\u2026`}class Lv0 extends HQ{entityType="topic";schema=Fi;adapter=Zz2;autoExtractionEnabled=!1;initialDerivationDone=!1;constructor(A={}){super("topics",Vv0,A,wv0)}getEntityTypeConfig(){return{weight:0.5}}getTemplates(){return{extraction:Zv0,"merge-synthesis":Fv0,"topic-list":qv0,"topic-detail":zv0}}getDataSources(){return[new dGA(this.logger.child("TopicsDataSource"))]}async onRegister(A){let Q=new Vi(A,this.logger);A.jobs.registerHandler("process-single",Q);let B=new cGA(A,this.logger);if(A.jobs.registerHandler("extract",B),A.insights.register("topic-distribution",Nv0()),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("dashboard:register-widget",{id:"topics",pluginId:this.id,title:"Topics",section:"secondary",priority:20,rendererName:"ListWidget",dataProvider:async()=>{return{items:(await A.entityService.listEntities("topic",{limit:10,sortFields:[{field:"updated",direction:"desc"}]})).map(($)=>{let D=this.adapter.parseTopicBody($.content),Y=Fz2(D.content);return{id:$.id,name:D.title||$.id,...Y&&{description:Y}}})}}}),{success:!0}}),this.registerEvalHandler(A),this.config.enableAutoExtraction){A.messaging.subscribe("sync:initial:completed",async()=>{if(this.enableAutoExtraction(),!this.initialDerivationDone)this.initialDerivationDone=!0,await this.deriveAll(A);return{success:!0}});let w=async($)=>{if(!this.autoExtractionEnabled)return{success:!0};let{entityType:D,entity:Y}=$.payload;if(!this.shouldProcessEntityType(D))return{success:!0};if(!Y)return{success:!0};return await this.handleEntityChanged(A,Y),{success:!0}};A.messaging.subscribe("entity:created",w),A.messaging.subscribe("entity:updated",w)}}async derive(A,Q,B){if(!this.shouldProcessEntityType(A.entityType))return;if(!this.isEntityPublished(A))return;await this.handleEntityChanged(B,A)}async deriveAll(A){let Q=await this.getEntitiesToExtract(A);if(Q.length===0){this.logger.info("No entities to extract topics from");return}this.logger.info(`Batch topic extraction: ${Q.length} entities`);let B=await Ni(Q,A,this.logger);this.logger.info("Batch topic extraction complete",B)}async rebuildAll(A){let Q=await this.getEntitiesToExtract(A),B=await this.replaceAllTopics(Q,A);this.logger.info("Topic rebuild complete",B)}isAutoExtractionEnabled(){return this.autoExtractionEnabled}hasRunInitialDerivation(){return this.initialDerivationDone}enableAutoExtraction(){if(this.config.enableAutoExtraction)this.autoExtractionEnabled=!0,this.logger.info("Auto-extraction enabled after initial sync")}shouldProcessEntityType(A){if(A==="topic")return!1;return this.config.includeEntityTypes.includes(A)}isEntityPublished(A){let B=A.metadata.status;return B==="published"||B===void 0||B===null}async replaceAllTopics(A,Q){let B=new YD(Q.entityService,this.logger),w=await B.listTopics();for(let D of w)await B.deleteTopic(D.id);if(A.length===0)return{deleted:w.length,created:0,skipped:0,batches:0};let $=await Ni(A,Q,this.logger);return{deleted:w.length,...$}}async getEntitiesToExtract(A){let Q=this.getExtractableEntityTypes(A),B=[];for(let w of Q){let $=await A.entityService.listEntities(w);for(let D of $){if(!this.isEntityPublished(D))continue;B.push(D)}}return B}getExtractableEntityTypes(A){return A.entityService.getEntityTypes().filter((B)=>this.shouldProcessEntityType(B))}async handleEntityChanged(A,Q){if(!this.isEntityPublished(Q))return;try{await A.jobs.enqueue("extract",{entityId:Q.id,entityType:Q.entityType,contentHash:Q.contentHash,minRelevanceScore:this.config.minRelevanceScore,autoMerge:this.config.autoMerge,mergeSimilarityThreshold:this.config.mergeSimilarityThreshold},null,{priority:5,source:"topics-plugin",metadata:{operationType:"data_processing",operationTarget:`topic-extraction:${Q.entityType}:${Q.id}`,pluginId:"topics"}})}catch(B){this.logger.error("Failed to queue topic extraction job",{error:L0(B),entityId:Q.id,entityType:Q.entityType})}}registerEvalHandler(A){let Q=new i_(A,this.logger),B=F.object({entityType:F.string(),content:F.string(),metadata:F.record(F.unknown()).optional()}),w=(V,E="")=>({id:`eval${E}-${Date.now()}`,entityType:V.entityType,content:V.content,contentHash:aB(V.content),metadata:V.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}),$=async(V,E,L="")=>{let j=w(V,L);return Q.extractFromEntity(j,E)},D=B.extend({minRelevanceScore:F.number().optional()});A.eval.registerHandler("extractFromEntity",async(V)=>{let E=D.parse(V),L=E.minRelevanceScore??this.config.minRelevanceScore;return $(E,L)});let Y=F.object({contentA:B,contentB:B,minRelevanceScore:F.number().optional()});A.eval.registerHandler("checkMergeSimilarity",async(V)=>{let E=Y.parse(V),L=E.minRelevanceScore??this.config.minRelevanceScore,[j,_]=await Promise.all([$(E.contentA,L,"-a"),$(E.contentB,L,"-b")]),k=j.map((h)=>h.title.toLowerCase()),r=_.map((h)=>h.title.toLowerCase()),n=k.filter((h)=>r.includes(h));return{topicsA:j.map((h)=>({title:h.title,relevanceScore:h.relevanceScore})),topicsB:_.map((h)=>({title:h.title,relevanceScore:h.relevanceScore})),matchingTitles:n,wouldMerge:n.length>0}});let I=F.object({title:F.string(),content:F.string()}),X=F.object({existingTopics:F.array(I),incomingTopic:I,threshold:F.number().optional()});A.eval.registerHandler("detectMergeCandidate",async(V)=>{let E=X.parse(V),L=E.threshold??this.config.mergeSimilarityThreshold,j=new YD(A.entityService,this.logger);for(let k of E.existingTopics)await j.createTopic(k);let _=await j.findMergeCandidate({title:E.incomingTopic.title},L);return{found:_!==null,candidateTitle:_?.title,candidateScore:_?.score}});let H=F.object({existingAliases:F.array(F.string()).optional(),canonicalTitle:F.string(),candidateAliases:F.array(F.string())});A.eval.registerHandler("mergeAliases",async(V)=>{let E=H.parse(V);return{aliases:new YD(A.entityService,this.logger).mergeAliases(E.existingAliases,E.canonicalTitle,E.candidateAliases)}});let W=F.object({existingTopics:F.array(I.extend({aliases:F.array(F.string()).optional()})).default([]),incomingTopic:I.extend({relevanceScore:F.number().min(0).max(1).optional()}),threshold:F.number().optional()});A.eval.registerHandler("processTopicWithAutoMerge",async(V)=>{let E=W.parse(V),L=new YD(A.entityService,this.logger);for(let n of E.existingTopics)await L.createTopic({title:n.title,content:n.content,metadata:{aliases:n.aliases??[]}});let j=new Vi(A,this.logger),_=Lw.from(async()=>{});if(!_)throw Error("Failed to create progress reporter");let k=await j.process({topic:{title:E.incomingTopic.title,content:E.incomingTopic.content,relevanceScore:E.incomingTopic.relevanceScore??0.9},sourceEntityId:"eval-source",sourceEntityType:"post",autoMerge:!0,mergeSimilarityThreshold:E.threshold??this.config.mergeSimilarityThreshold},`eval-job-${Date.now()}`,_),r=await A.entityService.listEntities("topic");return{...k,topicCount:r.length,topics:r.map((n)=>{let h=this.adapter.parseTopicBody(n.content);return{id:n.id,title:h.title,content:h.content,metadata:n.metadata}})}});let J=F.object({entities:F.array(B).min(1),minRelevanceScore:F.number().optional()}),Z=F.object({existingTopics:F.array(I).optional(),entities:F.array(B)});A.eval.registerHandler("rebuildTopics",async(V)=>{let E=Z.parse(V),L=new YD(A.entityService,this.logger);for(let r of E.existingTopics??[])await L.createTopic(r);let j=E.entities.map((r,n)=>w(r,`-rebuild-${n}`)),_=await this.replaceAllTopics(j,A),k=await A.entityService.listEntities("topic");return{..._,topicCount:k.length,topics:k.map((r)=>{let n=this.adapter.parseTopicBody(r.content);return{id:r.id,title:n.title,content:n.content,metadata:r.metadata}})}}),A.eval.registerHandler("extractSequentially",async(V)=>{let E=J.parse(V),L=E.minRelevanceScore??this.config.minRelevanceScore,j=new YD(A.entityService,this.logger),_=[];for(let[r,n]of E.entities.entries()){let h=w(n,`-sequential-${r}`),T=await Q.extractFromEntity(h,L);for(let S of T)await j.createTopic({title:S.title,content:S.content});_.push({extractedTitles:T.map((S)=>S.title)})}let k=await A.entityService.listEntities("topic");return{totalTopics:k.length,perEntity:_,topics:k.map((r)=>{let n=this.adapter.parseTopicBody(r.content);return{id:r.id,title:n.title,content:n.content}})}});let q=F.object({entities:F.array(B)});A.eval.registerHandler("batchExtract",async(V)=>{let L=q.parse(V).entities.map((k,r)=>w(k,`-batch-${r}`)),j=await Ni(L,A,this.logger),_=await A.entityService.listEntities("topic");return{...j,topics:_.map((k)=>{let r=this.adapter.parseTopicBody(k.content);return{id:k.id,title:r.title,content:r.content}})}})}}function Ei(A){return new Lv0(A)}B0();GA();B0();var Mv0=F.enum(["linkedin"]),Ev0=F.enum(["draft","queued","published","failed"]),Cv0=F.enum(["post","deck"]),ID=F.object({title:F.string().describe("Short descriptive title (3-6 words) for file naming"),platform:Mv0.describe("Target platform"),status:Ev0,coverImageId:F.string().optional().describe("Image entity ID for post image"),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:Cv0.optional().describe("Source entity type (post, deck)")}),Ov0=ID.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:F.string().describe("URL-friendly identifier: {platform}-{title}")}),aM=Q2.extend({entityType:F.literal("social-post"),metadata:Ov0}),Ci=aM.extend({frontmatter:ID,body:F.string()}),Oi=Ci.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()});B0();GA();class iGA extends I2{constructor(){super({entityType:"social-post",schema:aM,frontmatterSchema:ID,supportsCoverImage:!0})}toMarkdown(A){let Q="",B={};try{B=this.parseFrontMatter(A.content,ID),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,ID),B=`${Q.platform}-${e1(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,ID)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}}var a7=new iGA;B0();B0();GA();var qz2=yI.extend({platform:F.enum(["linkedin"]).optional(),status:F.enum(["draft","queued","published","failed"]).optional(),sortByQueue:F.boolean().optional(),nextInQueue:F.boolean().optional()}),zz2=mI.extend({query:qz2.optional()});function fv0(A){let Q=G2(A.content,ID);return Ci.parse({...A,frontmatter:Q.metadata,body:Q.content})}class fi extends s5{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=zz2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return fv0(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:W}=await this.fetchDetail(w.id,$);return Q.parse(this.buildDetailResult(W,null))}let D={};if(w.platform)D.platform=w.platform;if(w.status)D.status=w.status;let Y=Object.keys(D).length>0,I=w.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:X,pagination:H}=await this.fetchList(w,$,{...Y&&{filter:{metadata:D}},sortFields:I});return Q.parse(this.buildListResult(X,H,w))}async fetchNextInQueue(A,Q){let w=(await Q.listEntities(this.config.entityType,{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}))[0],$=w?fv0(w):null;return A.parse({post:$})}}GA();var Rv0=F.object({accessToken:F.string().optional(),refreshToken:F.string().optional(),organizationId:F.string().optional()}),rGA=F.object({linkedin:Rv0.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)});B0();GA();oGA();import{jsxDEV as y6,Fragment as Lz2}from"preact/jsx-dev-runtime";function Nz2(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function Vz2(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var ji=({posts:A,pageTitle:Q,pagination:B,baseUrl:w="/social-posts"})=>{let $=Q??"Social Posts",D=B?.totalItems??A.length,Y=`Browse all ${D} social ${D===1?"post":"posts"}`;return y6(Lz2,{children:[y6(n2,{title:$,description:Y},void 0,!1,void 0,this),y6("div",{className:"social-post-list bg-theme",children:y6("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[y6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:$},void 0,!1,void 0,this),A.length===0?y6("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):y6("ul",{className:"space-y-6",children:A.map((I)=>y6("li",{children:y6(MQ,{href:I.url,variant:"horizontal",children:y6("div",{className:"flex flex-col sm:flex-row gap-4",children:[I.coverImageUrl&&y6("img",{src:I.coverImageUrl,alt:I.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),y6("div",{className:"flex-1 min-w-0",children:[y6("div",{className:"flex items-start justify-between gap-4 mb-2",children:[y6("h2",{className:"text-lg font-semibold text-heading",children:I.frontmatter.title},void 0,!1,void 0,this),y6("time",{className:"text-sm text-theme-muted shrink-0",children:Vz2(I.frontmatter.publishedAt??I.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y6("div",{className:"flex items-center gap-2 mb-3",children:[y6(r7,{status:I.frontmatter.status},void 0,!1,void 0,this),y6("span",{className:"text-xs text-theme-muted uppercase",children:I.frontmatter.platform},void 0,!1,void 0,this),y6("span",{className:"text-xs text-theme-muted font-mono",children:I.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y6("p",{className:"text-theme leading-relaxed",children:Nz2(I.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)},I.id,!1,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&y6(jY,{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 m6,Fragment as Mz2}from"preact/jsx-dev-runtime";function jv0(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var ki=({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 m6(Mz2,{children:[m6(n2,{title:Q,description:B},void 0,!1,void 0,this),m6("section",{className:"social-post-detail",children:m6("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:m6("div",{className:"max-w-3xl mx-auto",children:[m6(AD,{items:w},void 0,!1,void 0,this),m6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),m6("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[m6(r7,{status:A.frontmatter.status},void 0,!1,void 0,this),m6("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),m6("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&&m6(_K,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),m6(MQ,{className:"p-8 mb-8",children:m6("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),m6("div",{className:"space-y-4 text-sm text-theme-muted",children:[m6("div",{children:[m6("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",jv0(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&m6("div",{children:[m6("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",jv0(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&m6("div",{children:m6("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 s_(A){return`social-media:${A}`}var sGA=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")}),Ez2=R7.extend({slug:F.string().optional()});class wq extends Q9{constructor(A,Q){super(A,Q,{schema:sGA,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let B=A.platform??"linkedin",w=A.addToQueue??!1,{prompt:$,sourceEntityType:D,sourceEntityId:Y}=A,{content:I,title:X}=A;if(I&&X)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(I&&!X){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let L=await this.context.ai.generate({prompt:I,templateName:s_(B)});X=L.title,I=L.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(Y&&D){await this.reportProgress(Q,{progress:10,message:`Fetching source ${D}`});let L=await this.context.entityService.getEntity(D,Y);if(!L)this.failEarly(`Source entity not found: ${D}/${Y}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let _=F.object({slug:F.string()}).safeParse(L.metadata),k=_.success?_.data.slug:Y,r=await this.context.ai.generate({prompt:`Create an engaging ${B} post to promote this ${D}:
2838
+ - content`,requiredPermission:"public"});s8();GA();var Gz2=F.object({id:F.string(),title:F.string(),summary:F.string(),created:F.string(),updated:F.string()}),r_=F.object({topics:F.array(Gz2),totalCount:F.number()});import{jsxDEV as vX}from"preact/jsx-dev-runtime";var lGA=({topics:A,totalCount:Q})=>{return vX("div",{className:"topic-list-container w-full max-w-4xl mx-auto p-6 bg-theme",children:[vX(fY,{title:"Topics",count:Q,singularLabel:"topic",description:"discovered from your knowledge base"},void 0,!1,void 0,this),vX("div",{className:"space-y-6",children:A.map((B)=>vX(MQ,{variant:"vertical",children:[vX(G9,{href:`/topics/${B.id}`,className:"text-xl",children:B.title},void 0,!1,void 0,this),vX("p",{className:"text-theme-muted mb-4",children:B.summary},void 0,!1,void 0,this),vX(D7,{children:vX("div",{className:"flex justify-between text-sm text-theme-muted",children:vX("time",{dateTime:B.updated,children:["Updated ",m8(B.updated)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},B.id,!0,void 0,this))},void 0,!1,void 0,this),A.length===0&&vX(a$,{message:"No topics discovered yet.",description:"Topics will appear here as they are extracted from your content."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};GA();class Li extends $B{constructor(){super(r_,{title:"Topic List",mappings:[{key:"topics",label:"Topics",type:"array",itemType:"object"},{key:"totalCount",label:"Total Count",type:"number"}]})}}var qv0=M1({name:"topics:topic-list",description:"List view of all discovered topics",schema:r_,dataSourceId:"topics:entities",requiredPermission:"public",formatter:new Li,layout:{component:lGA}});s8();GA();var n_=F.object({id:F.string(),title:F.string(),content:F.string(),created:F.string(),updated:F.string()});import{jsxDEV as o_}from"preact/jsx-dev-runtime";var pGA=({title:A,content:Q,created:B,updated:w})=>{return o_("article",{className:"topic-detail-container max-w-4xl mx-auto p-6 bg-theme",children:[o_(EF,{title:A,created:B,updated:w},void 0,!1,void 0,this),o_("div",{className:"prose prose-lg max-w-none mb-8 text-theme-muted",children:o_("div",{dangerouslySetInnerHTML:{__html:Q}},void 0,!1,void 0,this)},void 0,!1,void 0,this),o_(LF,{href:"/topics",children:"Back to Topics"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};GA();class Mi extends $B{constructor(){super(n_,{title:"Topic Detail",mappings:[{key:"id",label:"ID",type:"string"},{key:"title",label:"Title",type:"string"},{key:"content",label:"Content",type:"string"},{key:"created",label:"Created",type:"string"},{key:"updated",label:"Updated",type:"string"}]})}}var zv0=M1({name:"topics:topic-detail",description:"Detailed view of a single topic",schema:n_,dataSourceId:"topics:entities",requiredPermission:"public",formatter:new Mi,layout:{component:pGA}});B0();GA();class dGA extends s5{id="topics:entities";name="Topics Entity DataSource";description="Fetches and transforms topic entities for rendering";config={entityType:"topic",defaultSort:[{field:"updated",direction:"desc"}],defaultLimit:100,lookupField:"id"};adapter=new w4;constructor(A){super(A);this.logger.debug("TopicsDataSource initialized")}transformEntity(A){let Q=this.adapter.parseTopicBody(A.content);return{id:A.id,title:Q.title,summary:JW(Q.content,200),created:A.created,updated:A.updated}}buildListResult(A,Q,B){return{topics:A,totalCount:A.length}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A);if(w.id){let D=await B.entityService.getEntity(this.config.entityType,w.id);if(!D)throw Error(`Entity not found: ${w.id}`);let Y=this.adapter.parseTopicBody(D.content);return Q.parse({id:D.id,title:Y.title,content:Y.content,created:D.created,updated:D.updated})}return super.fetch(A,Q,B)}}aD();function Nv0(){let A=new w4;return async(Q)=>{if(!Q.hasEntityType("topic"))return{topics:[]};return{topics:(await Q.listEntities("topic")).map(($)=>{let D=A.parseTopicBody($.content);return{topic:$.id,title:D.title}})}}}var Vv0={name:"@brains/topics",private:!0,version:"0.2.0-alpha.42",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/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var Zz2=new w4;function Fz2(A){let Q=A.replace(/\s+/g," ").trim();if(!Q)return;let B=Q.match(/^(.*?[.!?])(?:\s|$)/);if(B?.[1])return B[1];return Q.length<=200?Q:`${Q.slice(0,197)}\u2026`}class Lv0 extends HQ{entityType="topic";schema=Fi;adapter=Zz2;autoExtractionEnabled=!1;initialDerivationDone=!1;constructor(A={}){super("topics",Vv0,A,wv0)}getEntityTypeConfig(){return{weight:0.5}}getTemplates(){return{extraction:Zv0,"merge-synthesis":Fv0,"topic-list":qv0,"topic-detail":zv0}}getDataSources(){return[new dGA(this.logger.child("TopicsDataSource"))]}async onRegister(A){let Q=new Vi(A,this.logger);A.jobs.registerHandler("process-single",Q);let B=new cGA(A,this.logger);if(A.jobs.registerHandler("extract",B),A.insights.register("topic-distribution",Nv0()),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("dashboard:register-widget",{id:"topics",pluginId:this.id,title:"Topics",section:"secondary",priority:20,rendererName:"ListWidget",dataProvider:async()=>{return{items:(await A.entityService.listEntities("topic",{limit:10,sortFields:[{field:"updated",direction:"desc"}]})).map(($)=>{let D=this.adapter.parseTopicBody($.content),Y=Fz2(D.content);return{id:$.id,name:D.title||$.id,...Y&&{description:Y}}})}}}),{success:!0}}),this.registerEvalHandler(A),this.config.enableAutoExtraction){A.messaging.subscribe("sync:initial:completed",async()=>{if(this.enableAutoExtraction(),!this.initialDerivationDone)this.initialDerivationDone=!0,await this.deriveAll(A);return{success:!0}});let w=async($)=>{if(!this.autoExtractionEnabled)return{success:!0};let{entityType:D,entity:Y}=$.payload;if(!this.shouldProcessEntityType(D))return{success:!0};if(!Y)return{success:!0};return await this.handleEntityChanged(A,Y),{success:!0}};A.messaging.subscribe("entity:created",w),A.messaging.subscribe("entity:updated",w)}}async derive(A,Q,B){if(!this.shouldProcessEntityType(A.entityType))return;if(!this.isEntityPublished(A))return;await this.handleEntityChanged(B,A)}async deriveAll(A){let Q=await this.getEntitiesToExtract(A);if(Q.length===0){this.logger.info("No entities to extract topics from");return}this.logger.info(`Batch topic extraction: ${Q.length} entities`);let B=await Ni(Q,A,this.logger);this.logger.info("Batch topic extraction complete",B)}async rebuildAll(A){let Q=await this.getEntitiesToExtract(A),B=await this.replaceAllTopics(Q,A);this.logger.info("Topic rebuild complete",B)}isAutoExtractionEnabled(){return this.autoExtractionEnabled}hasRunInitialDerivation(){return this.initialDerivationDone}enableAutoExtraction(){if(this.config.enableAutoExtraction)this.autoExtractionEnabled=!0,this.logger.info("Auto-extraction enabled after initial sync")}shouldProcessEntityType(A){if(A==="topic")return!1;return this.config.includeEntityTypes.includes(A)}isEntityPublished(A){let B=A.metadata.status;return B==="published"||B===void 0||B===null}async replaceAllTopics(A,Q){let B=new YD(Q.entityService,this.logger),w=await B.listTopics();for(let D of w)await B.deleteTopic(D.id);if(A.length===0)return{deleted:w.length,created:0,skipped:0,batches:0};let $=await Ni(A,Q,this.logger);return{deleted:w.length,...$}}async getEntitiesToExtract(A){let Q=this.getExtractableEntityTypes(A),B=[];for(let w of Q){let $=await A.entityService.listEntities(w);for(let D of $){if(!this.isEntityPublished(D))continue;B.push(D)}}return B}getExtractableEntityTypes(A){return A.entityService.getEntityTypes().filter((B)=>this.shouldProcessEntityType(B))}async handleEntityChanged(A,Q){if(!this.isEntityPublished(Q))return;try{await A.jobs.enqueue("extract",{entityId:Q.id,entityType:Q.entityType,contentHash:Q.contentHash,minRelevanceScore:this.config.minRelevanceScore,autoMerge:this.config.autoMerge,mergeSimilarityThreshold:this.config.mergeSimilarityThreshold},null,{priority:5,source:"topics-plugin",metadata:{operationType:"data_processing",operationTarget:`topic-extraction:${Q.entityType}:${Q.id}`,pluginId:"topics"}})}catch(B){this.logger.error("Failed to queue topic extraction job",{error:L0(B),entityId:Q.id,entityType:Q.entityType})}}registerEvalHandler(A){let Q=new i_(A,this.logger),B=F.object({entityType:F.string(),content:F.string(),metadata:F.record(F.unknown()).optional()}),w=(V,E="")=>({id:`eval${E}-${Date.now()}`,entityType:V.entityType,content:V.content,contentHash:aB(V.content),metadata:V.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}),$=async(V,E,L="")=>{let j=w(V,L);return Q.extractFromEntity(j,E)},D=B.extend({minRelevanceScore:F.number().optional()});A.eval.registerHandler("extractFromEntity",async(V)=>{let E=D.parse(V),L=E.minRelevanceScore??this.config.minRelevanceScore;return $(E,L)});let Y=F.object({contentA:B,contentB:B,minRelevanceScore:F.number().optional()});A.eval.registerHandler("checkMergeSimilarity",async(V)=>{let E=Y.parse(V),L=E.minRelevanceScore??this.config.minRelevanceScore,[j,_]=await Promise.all([$(E.contentA,L,"-a"),$(E.contentB,L,"-b")]),k=j.map((h)=>h.title.toLowerCase()),r=_.map((h)=>h.title.toLowerCase()),n=k.filter((h)=>r.includes(h));return{topicsA:j.map((h)=>({title:h.title,relevanceScore:h.relevanceScore})),topicsB:_.map((h)=>({title:h.title,relevanceScore:h.relevanceScore})),matchingTitles:n,wouldMerge:n.length>0}});let I=F.object({title:F.string(),content:F.string()}),X=F.object({existingTopics:F.array(I),incomingTopic:I,threshold:F.number().optional()});A.eval.registerHandler("detectMergeCandidate",async(V)=>{let E=X.parse(V),L=E.threshold??this.config.mergeSimilarityThreshold,j=new YD(A.entityService,this.logger);for(let k of E.existingTopics)await j.createTopic(k);let _=await j.findMergeCandidate({title:E.incomingTopic.title},L);return{found:_!==null,candidateTitle:_?.title,candidateScore:_?.score}});let H=F.object({existingAliases:F.array(F.string()).optional(),canonicalTitle:F.string(),candidateAliases:F.array(F.string())});A.eval.registerHandler("mergeAliases",async(V)=>{let E=H.parse(V);return{aliases:new YD(A.entityService,this.logger).mergeAliases(E.existingAliases,E.canonicalTitle,E.candidateAliases)}});let W=F.object({existingTopics:F.array(I.extend({aliases:F.array(F.string()).optional()})).default([]),incomingTopic:I.extend({relevanceScore:F.number().min(0).max(1).optional()}),threshold:F.number().optional()});A.eval.registerHandler("processTopicWithAutoMerge",async(V)=>{let E=W.parse(V),L=new YD(A.entityService,this.logger);for(let n of E.existingTopics)await L.createTopic({title:n.title,content:n.content,metadata:{aliases:n.aliases??[]}});let j=new Vi(A,this.logger),_=Lw.from(async()=>{});if(!_)throw Error("Failed to create progress reporter");let k=await j.process({topic:{title:E.incomingTopic.title,content:E.incomingTopic.content,relevanceScore:E.incomingTopic.relevanceScore??0.9},sourceEntityId:"eval-source",sourceEntityType:"post",autoMerge:!0,mergeSimilarityThreshold:E.threshold??this.config.mergeSimilarityThreshold},`eval-job-${Date.now()}`,_),r=await A.entityService.listEntities("topic");return{...k,topicCount:r.length,topics:r.map((n)=>{let h=this.adapter.parseTopicBody(n.content);return{id:n.id,title:h.title,content:h.content,metadata:n.metadata}})}});let J=F.object({entities:F.array(B).min(1),minRelevanceScore:F.number().optional()}),Z=F.object({existingTopics:F.array(I).optional(),entities:F.array(B)});A.eval.registerHandler("rebuildTopics",async(V)=>{let E=Z.parse(V),L=new YD(A.entityService,this.logger);for(let r of E.existingTopics??[])await L.createTopic(r);let j=E.entities.map((r,n)=>w(r,`-rebuild-${n}`)),_=await this.replaceAllTopics(j,A),k=await A.entityService.listEntities("topic");return{..._,topicCount:k.length,topics:k.map((r)=>{let n=this.adapter.parseTopicBody(r.content);return{id:r.id,title:n.title,content:n.content,metadata:r.metadata}})}}),A.eval.registerHandler("extractSequentially",async(V)=>{let E=J.parse(V),L=E.minRelevanceScore??this.config.minRelevanceScore,j=new YD(A.entityService,this.logger),_=[];for(let[r,n]of E.entities.entries()){let h=w(n,`-sequential-${r}`),T=await Q.extractFromEntity(h,L);for(let S of T)await j.createTopic({title:S.title,content:S.content});_.push({extractedTitles:T.map((S)=>S.title)})}let k=await A.entityService.listEntities("topic");return{totalTopics:k.length,perEntity:_,topics:k.map((r)=>{let n=this.adapter.parseTopicBody(r.content);return{id:r.id,title:n.title,content:n.content}})}});let q=F.object({entities:F.array(B)});A.eval.registerHandler("batchExtract",async(V)=>{let L=q.parse(V).entities.map((k,r)=>w(k,`-batch-${r}`)),j=await Ni(L,A,this.logger),_=await A.entityService.listEntities("topic");return{...j,topics:_.map((k)=>{let r=this.adapter.parseTopicBody(k.content);return{id:k.id,title:r.title,content:r.content}})}})}}function Ei(A){return new Lv0(A)}B0();GA();B0();var Mv0=F.enum(["linkedin"]),Ev0=F.enum(["draft","queued","published","failed"]),Cv0=F.enum(["post","deck"]),ID=F.object({title:F.string().describe("Short descriptive title (3-6 words) for file naming"),platform:Mv0.describe("Target platform"),status:Ev0,coverImageId:F.string().optional().describe("Image entity ID for post image"),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:Cv0.optional().describe("Source entity type (post, deck)")}),Ov0=ID.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:F.string().describe("URL-friendly identifier: {platform}-{title}")}),aM=Q2.extend({entityType:F.literal("social-post"),metadata:Ov0}),Ci=aM.extend({frontmatter:ID,body:F.string()}),Oi=Ci.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()});B0();GA();class iGA extends I2{constructor(){super({entityType:"social-post",schema:aM,frontmatterSchema:ID,supportsCoverImage:!0})}toMarkdown(A){let Q="",B={};try{B=this.parseFrontMatter(A.content,ID),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,ID),B=`${Q.platform}-${e1(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,ID)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}}var a7=new iGA;B0();B0();GA();var qz2=yI.extend({platform:F.enum(["linkedin"]).optional(),status:F.enum(["draft","queued","published","failed"]).optional(),sortByQueue:F.boolean().optional(),nextInQueue:F.boolean().optional()}),zz2=mI.extend({query:qz2.optional()});function fv0(A){let Q=G2(A.content,ID);return Ci.parse({...A,frontmatter:Q.metadata,body:Q.content})}class fi extends s5{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=zz2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return fv0(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:W}=await this.fetchDetail(w.id,$);return Q.parse(this.buildDetailResult(W,null))}let D={};if(w.platform)D.platform=w.platform;if(w.status)D.status=w.status;let Y=Object.keys(D).length>0,I=w.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:X,pagination:H}=await this.fetchList(w,$,{...Y&&{filter:{metadata:D}},sortFields:I});return Q.parse(this.buildListResult(X,H,w))}async fetchNextInQueue(A,Q){let w=(await Q.listEntities(this.config.entityType,{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}))[0],$=w?fv0(w):null;return A.parse({post:$})}}GA();var Rv0=F.object({accessToken:F.string().optional(),refreshToken:F.string().optional(),organizationId:F.string().optional()}),rGA=F.object({linkedin:Rv0.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)});B0();GA();oGA();import{jsxDEV as y6,Fragment as Lz2}from"preact/jsx-dev-runtime";function Nz2(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function Vz2(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var ji=({posts:A,pageTitle:Q,pagination:B,baseUrl:w="/social-posts"})=>{let $=Q??"Social Posts",D=B?.totalItems??A.length,Y=`Browse all ${D} social ${D===1?"post":"posts"}`;return y6(Lz2,{children:[y6(n2,{title:$,description:Y},void 0,!1,void 0,this),y6("div",{className:"social-post-list bg-theme",children:y6("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[y6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:$},void 0,!1,void 0,this),A.length===0?y6("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):y6("ul",{className:"space-y-6",children:A.map((I)=>y6("li",{children:y6(MQ,{href:I.url,variant:"horizontal",children:y6("div",{className:"flex flex-col sm:flex-row gap-4",children:[I.coverImageUrl&&y6("img",{src:I.coverImageUrl,alt:I.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),y6("div",{className:"flex-1 min-w-0",children:[y6("div",{className:"flex items-start justify-between gap-4 mb-2",children:[y6("h2",{className:"text-lg font-semibold text-heading",children:I.frontmatter.title},void 0,!1,void 0,this),y6("time",{className:"text-sm text-theme-muted shrink-0",children:Vz2(I.frontmatter.publishedAt??I.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y6("div",{className:"flex items-center gap-2 mb-3",children:[y6(r7,{status:I.frontmatter.status},void 0,!1,void 0,this),y6("span",{className:"text-xs text-theme-muted uppercase",children:I.frontmatter.platform},void 0,!1,void 0,this),y6("span",{className:"text-xs text-theme-muted font-mono",children:I.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y6("p",{className:"text-theme leading-relaxed",children:Nz2(I.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)},I.id,!1,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&y6(jY,{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 m6,Fragment as Mz2}from"preact/jsx-dev-runtime";function jv0(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var ki=({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 m6(Mz2,{children:[m6(n2,{title:Q,description:B},void 0,!1,void 0,this),m6("section",{className:"social-post-detail",children:m6("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:m6("div",{className:"max-w-3xl mx-auto",children:[m6(AD,{items:w},void 0,!1,void 0,this),m6("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),m6("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[m6(r7,{status:A.frontmatter.status},void 0,!1,void 0,this),m6("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),m6("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&&m6(_K,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),m6(MQ,{className:"p-8 mb-8",children:m6("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),m6("div",{className:"space-y-4 text-sm text-theme-muted",children:[m6("div",{children:[m6("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",jv0(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&m6("div",{children:[m6("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",jv0(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&m6("div",{children:m6("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 s_(A){return`social-media:${A}`}var sGA=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")}),Ez2=R7.extend({slug:F.string().optional()});class wq extends Q9{constructor(A,Q){super(A,Q,{schema:sGA,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let B=A.platform??"linkedin",w=A.addToQueue??!1,{prompt:$,sourceEntityType:D,sourceEntityId:Y}=A,{content:I,title:X}=A;if(I&&X)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(I&&!X){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let L=await this.context.ai.generate({prompt:I,templateName:s_(B)});X=L.title,I=L.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(Y&&D){await this.reportProgress(Q,{progress:10,message:`Fetching source ${D}`});let L=await this.context.entityService.getEntity(D,Y);if(!L)this.failEarly(`Source entity not found: ${D}/${Y}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let _=F.object({slug:F.string()}).safeParse(L.metadata),k=_.success?_.data.slug:Y,r=await this.context.ai.generate({prompt:`Create an engaging ${B} post to promote this ${D}:
2839
2839
 
2840
2840
  Source: ${D}/${k}
2841
2841
 
2842
2842
  ${L.content}`,templateName:s_(B)});X=r.title,I=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:s_(B)});X=L.title,I=L.content,await this.reportProgress(Q,{progress:50,message:"Social post generated"})}else this.failEarly("No content source provided (prompt, sourceEntityId, or content)");if(!I||!X)this.failEarly("Content or title was not generated");let W={title:X,platform:B,status:w?"queued":"draft",...Y&&{sourceEntityId:Y},...D&&{sourceEntityType:D}},J=a7.createPostContent(W,I),q=a7.fromMarkdown(J).metadata;if(!q)this.failEarly("Failed to parse social post metadata");let V=await dH({entityType:"social-post",title:X,deriveId:(L)=>`${B}-${e1(L)}`,regeneratePrompt:"Generate a different social media post title on the same topic.",context:this.context}),E=J;if(V!==X){q.title=V,q.slug=`${B}-${e1(V)}`;let L={...W,title:V};E=a7.createPostContent(L,I)}return{id:q.slug,content:E,metadata:q,title:V,resultExtras:{slug:q.slug},createOptions:{deduplicateId:!0}}}async onGenerationFailure(A,Q){await this.context.messaging.send("generate:report:failure",{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("image:image-generate",{prompt:`Social media graphic for: ${$}`,title:`${$} Image`,aspectRatio:"16:9",targetEntityType:"social-post",targetEntityId:Q},{interfaceType:"job",userId:"system"})}await this.context.messaging.send("generate:report:success",{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}}}class aGA{config;logger;name="linkedin";apiBaseUrl="https://api.linkedin.com/v2";cachedUserId=null;constructor(A,Q){this.config=A;this.logger=Q}async publish(A,Q,B){if(!this.config.accessToken)throw Error("LinkedIn access token not configured");let w=await this.getAuthor(),$=null;if(B)$=await this.uploadImage(w,B);let D={shareCommentary:{text:A},shareMediaCategory:$?"IMAGE":"NONE",...$&&{media:[{status:"READY",media:$}]}},Y=await 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:w,lifecycleState:"PUBLISHED",specificContent:{"com.linkedin.ugc.ShareContent":D},visibility:{"com.linkedin.ugc.MemberNetworkVisibility":"PUBLIC"}})});if(!Y.ok){let H=await Y.text();throw this.logger.error("LinkedIn API error",{status:Y.status,error:H}),Error(`LinkedIn API error: ${Y.status} - ${H}`)}let I=Y.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn post created",{postId:I,hasImage:!!$});let X={id:I};if(I)X.url=`https://www.linkedin.com/feed/update/${I}`;return X}async uploadImage(A,Q){try{let B=await 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 I=await B.text();return this.logger.warn("LinkedIn image upload registration failed",{status:B.status,error:I}),null}let w=await B.json(),$=w.value.uploadMechanism["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"].uploadUrl,D=w.value.asset,Y=await fetch($,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!Y.ok)return this.logger.warn("LinkedIn image binary upload failed",{status:Y.status}),null;return this.logger.info("LinkedIn image uploaded",{assetUrn:D}),D}catch(B){return this.logger.warn("LinkedIn image upload error",{error:B}),null}}async validateCredentials(){if(!this.config.accessToken)return!1;try{if(this.config.organizationId)return(await 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 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 fetch("https://api.linkedin.com/v2/me",{headers:{Authorization:`Bearer ${this.config.accessToken}`}});if(!A.ok){let B=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 tGA(A,Q){return new aGA(A,Q)}B0();GA();s8();oGA();var Cz2=F.object({posts:F.array(Oi),totalCount:F.number().optional(),pagination:P7.nullable(),baseUrl:F.string().optional()}),Oz2=F.object({post:Oi});function kv0(){return{linkedin:Ri,"social-post-list":M1({name:"social-post-list",description:"Social post list page template",schema:Cz2,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:ji}}),"social-post-detail":M1({name:"social-post-detail",description:"Individual social post template",schema:Oz2,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:ki}})}}GA();var fz2=F.object({prompt:F.string().optional(),content:F.string().optional(),platform:F.enum(["linkedin"]).default("linkedin")}),Rz2=F.object({prompt:F.string().optional(),content:F.string().optional(),title:F.string().optional(),platform:F.enum(["linkedin"]).optional()});function Pv0(A){A.eval.registerHandler("generation",async(Q)=>{let B=fz2.parse(Q),w=B.content?`Create an engaging LinkedIn post to share this content:
2843
2843
 
2844
- ${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=Rz2.parse(Q),w=[],$=Lw.from(async(H)=>{let W={progress:H.progress};if(H.message!==void 0)W.message=H.message;w.push(W)});if(!$)throw Error("Failed to create progress reporter");let Y=await new wq(A.logger,A).process(B,`eval-${Date.now()}`,$),I=!1,X;if(Y.success&&Y.entityId){let H=await A.entityService.getEntity("social-post",Y.entityId);I=!!H,X=H?.content.slice(0,300)}return{...Y,entityExists:I,entityPreview:X,progressSteps:w}})}GA();B0();class a_{sendMessage;logger;entityService;providers;constructor(A){this.sendMessage=A.sendMessage,this.logger=A.logger,this.entityService=A.entityService,this.providers=A.providers}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("social-post",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,D=this.providers.get($);if(!D){await this.reportFailure(Q,B,`No provider configured for platform: ${$}`);return}let Y=G2(w.content,ID),I;if(Y.metadata.coverImageId)I=await this.fetchImageData(Y.metadata.coverImageId);try{let X=await D.publish(Y.content,w.metadata,I),H=new Date().toISOString(),W=X.id||void 0,J={...Y.metadata,status:"published",publishedAt:H,...W&&{platformPostId:W}},Z=a7.createPostContent(J,Y.content);await this.entityService.updateEntity({...w,content:Z,metadata:{...w.metadata,status:"published",publishedAt:H,platformPostId:W}}),await this.reportSuccess(Q,B,X.id),this.logger.info(`Post published successfully: ${B}`,{platform:$,platformPostId:W})}catch(X){let H=X instanceof Error?X.message:String(X),W={...Y.metadata,status:"failed"},J=a7.createPostContent(W,Y.content);await this.entityService.updateEntity({...w,content:J,metadata:{...w.metadata,status:"failed"}}),await this.reportFailure(Q,B,H),this.logger.error(`Post publish failed: ${B}`,{platform:$,error:H})}}catch(w){let $=L0(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("publish:report:success",{entityType:A,entityId:Q,result:{id:B}})}async reportFailure(A,Q,B){await this.sendMessage("publish:report:failure",{entityType:A,entityId:Q,error:B})}async fetchImageData(A){try{let Q=await this.entityService.getEntity("image",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],D=w[2];return{data:Buffer.from(D,"base64"),mimeType:$}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function _v0(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("publish:register",{entityType:"social-post",provider:w}),B.info("Registered social-post with publish-pipeline"),{success:!0}})}function bv0(A,Q,B){let w=new a_({sendMessage:A.messaging.send,logger:B.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q});A.messaging.subscribe("publish:execute",async($)=>{return await w.handle($.payload),{success:!0}}),B.debug("Subscribed to publish:execute messages")}GA();function xv0(A,Q){A.messaging.subscribe("entity:updated",async(B)=>{let{entityType:w,entityId:$,entity:D}=B.payload;if(w!=="post")return{success:!0};if(D.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities("social-post",{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("social:auto-generate",{sourceEntityType:w,sourceEntityId:$,platform:"linkedin"}),Q.info(`Auto-generate social post triggered for queued post ${$}`),{success:!0}}catch(I){let X=L0(I);return Q.error(`Failed to trigger auto-generate for ${$}:`,{error:X}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function Tv0(A,Q){A.messaging.subscribe("social:auto-generate",async(B)=>{let{sourceEntityType:w,sourceEntityId:$,platform:D}=B.payload;try{let Y=await A.jobs.enqueue(`${a7.entityType}:generation`,{sourceEntityType:w,sourceEntityId:$,platform:D,addToQueue:!1},{interfaceType:"job",userId:"system"});return Q.info(`Social post generation job enqueued for ${w}/${$}`,{jobId:Y}),{success:!0,jobId:Y}}catch(Y){let I=L0(Y);return Q.error(`Failed to enqueue social post generation for ${$}:`,{error:I}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function vv0(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("post",{filter:{metadata:{status:"published"}},limit:5});if($.length===0)return Q.info("No published posts found for social post generation"),await A.messaging.send("generate:report:failure",{entityType:"social-post",error:"No published posts available for social post generation"}),{success:!0};let D=null;for(let I of $)if((await A.entityService.listEntities("social-post",{filter:{metadata:{sourceEntityType:"post",sourceEntityId:I.id}},limit:1})).length===0){D=I;break}if(!D)return Q.info("All recent posts already have social posts"),await A.messaging.send("generate:report:failure",{entityType:"social-post",error:"All recent posts already have social posts generated"}),{success:!0};let Y=await A.jobs.enqueue(`${a7.entityType}:generation`,{sourceEntityType:"post",sourceEntityId:D.id,platform:"linkedin",addToQueue:!1},{interfaceType:"job",userId:"system"});return Q.info("Social post generation job queued",{jobId:Y,sourcePostId:D.id}),{success:!0}}catch($){let D=L0($);return Q.error("Failed to handle generate:execute:",{error:D}),await A.messaging.send("generate:report:failure",{entityType:"social-post",error:D}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}var Sv0={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.41",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/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 eGA extends HQ{entityType=a7.entityType;schema=aM;adapter=a7;providers=new Map;constructor(A){super("social-media",Sv0,A,rGA)}createGenerationHandler(A){return new wq(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return kv0()}getDataSources(){return[new fi(this.logger.child("SocialPostDataSource"))]}async onRegister(A){if(this.initializeProviders(),_v0(A,this.providers,this.logger),bv0(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)xv0(A,this.logger),Tv0(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");vv0(A,this.logger),Pv0(A),this.logger.info("Social media plugin registered successfully")}async derive(A,Q,B){if(A.metadata.status!=="published")return;await B.jobs.enqueue(`${this.entityType}:generation`,{sourceEntityId:A.id,sourceEntityType:A.entityType},null,{priority:5,source:"social-media-plugin",metadata:{operationType:"content_operations",operationTarget:`social-post:${A.entityType}:${A.id}`,pluginId:"social-media"}})}initializeProviders(){if(this.config.linkedin?.accessToken){let A=tGA(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function t_(A){return new eGA(A)}GA();var kz2=F.enum(["draft","queued","published","failed"]),FwB=F.object({status:kz2.default("draft"),queueOrder:F.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:F.string().datetime().optional()});class AJA{name="internal";async publish(A,Q){return{id:"internal"}}}var u6={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"},SX={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"};GA();var Pz2=F.object({skipIfDraftExists:F.boolean().optional(),minSourceEntities:F.number().optional(),maxUnpublishedDrafts:F.number().optional(),sourceEntityType:F.string().optional()}),hv0=F.object({entitySchedules:F.record(F.string(),F.string()).optional(),generationSchedules:F.record(F.string(),F.string()).optional(),generationConditions:F.record(F.string(),Pz2).optional(),maxRetries:F.number().optional().default(3),retryBaseDelayMs:F.number().optional().default(5000)});class hX{static instance=null;queues=new Map;static getInstance(){return hX.instance??=new hX,hX.instance}static resetInstance(){hX.instance=null}static createFresh(){return new hX}constructor(){}async add(A,Q){let B=this.getOrCreateQueue(A),w=B.find((Y)=>Y.entityId===Q);if(w)return{position:w.position};let $=B.length+1,D={entityId:Q,entityType:A,position:$,queuedAt:new Date().toISOString()};return B.push(D),{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((I)=>I.entityId===Q);if($===-1)return;let[D]=w.splice($,1);if(!D)return;let Y=Math.max(0,Math.min(B-1,w.length));w.splice(Y,0,D),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 gX{static instance=null;providers=new Map;defaultProvider=new AJA;static getInstance(){return gX.instance??=new gX,gX.instance}static resetInstance(){gX.instance=null}static createFresh(){return new gX}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())}}GA();GA();async function gv0(A,Q){let B={entityType:A.entityType,entityId:A.entityId};if(Q.messageBus)await Q.messageBus.send(u6.EXECUTE,B,"publish-service");Q.onExecute?.(B)}async function yv0(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(A.entityType,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 D=L0($);Q.retryTracker.recordFailure(A.entityId,D);let Y=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:D,retryCount:Y?.retryCount??1,willRetry:Y?.willRetry??!1})}}function mv0(A,Q,B,w){if(w.retryTracker.clearRetries(Q),w.messageBus)w.messageBus.send(u6.COMPLETED,{entityType:A,entityId:Q,result:B},"publish-service");w.onPublish?.({entityType:A,entityId:Q,result:B})}function uv0(A,Q,B,w){w.retryTracker.recordFailure(Q,B);let $=w.retryTracker.getRetryInfo(Q),D={entityType:A,entityId:Q,error:B,retryCount:$?.retryCount??1,willRetry:$?.willRetry??!1};if(w.messageBus)w.messageBus.send(u6.FAILED,D,"publish-service");w.onFailed?.(D)}async function cv0(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(SX.SKIPPED,{entityType:A,reason:$.reason??"Conditions not met"},"content-pipeline");return}}let w={entityType:A};if(Q.messageBus)await Q.messageBus.send(SX.EXECUTE,w,"content-pipeline");Q.onGenerate?.(w)}function lv0(A,Q,B){if(B)B.send(SX.COMPLETED,{entityType:A,entityId:Q},"content-pipeline")}function pv0(A,Q,B){if(B)B.send(SX.FAILED,{entityType:A,error:Q},"content-pipeline")}var _z2=1000;class lY{static instance=null;config;publishJobs=new Map;generationJobs=new Map;immediateIntervalJob=null;running=!1;static getInstance(A){return lY.instance??=new lY(A),lY.instance}static resetInstance(){if(lY.instance)lY.instance.stop();lY.instance=null}static createFresh(A){return new lY(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions()}async start(){if(this.running)return;this.running=!0;for(let[A,Q]of Object.entries(this.entitySchedules)){let B=this.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,B)}for(let[A,Q]of Object.entries(this.generationSchedules)){let B=this.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,B)}this.immediateIntervalJob=this.config.backend.scheduleInterval(_z2,()=>this.processUnscheduledTypes())}async stop(){if(this.running=!1,this.stopAndClearJobs(this.publishJobs),this.stopAndClearJobs(this.generationJobs),this.immediateIntervalJob)this.immediateIntervalJob.stop(),this.immediateIntervalJob=null}isRunning(){return this.running}async processEntityType(A){if(!this.running)return;try{let Q=await this.config.queueManager.getNext(A);if(Q)await this.processEntry(Q)}catch(Q){this.config.logger.error(`Scheduler error for ${A}:`,Q)}}async processUnscheduledTypes(){if(!this.running)return;try{let A=await this.config.queueManager.getQueuedEntityTypes();for(let Q of A)if(!this.entitySchedules[Q]){let B=await this.config.queueManager.getNext(Q);if(B){await this.processEntry(B);break}}}catch(A){this.config.logger.error("Scheduler error for unscheduled types:",A)}}async processEntry(A){if(await this.config.queueManager.remove(A.entityType,A.entityId),this.config.messageBus!==void 0)await gv0(A,this.publishDeps);else await yv0(A,this.publishDeps)}completePublish(A,Q,B){mv0(A,Q,B,this.publishDeps)}failPublish(A,Q,B){uv0(A,Q,B,this.publishDeps)}async publishDirect(A,Q,B,w){return this.config.providerRegistry.get(A).publish(B,w)}async handleTriggerGeneration(A){if(!this.running)return;try{await cv0(A,this.generationDeps)}catch(Q){this.config.logger.error(`Generation trigger error for ${A}:`,Q)}}completeGeneration(A,Q){lv0(A,Q,this.config.messageBus)}failGeneration(A,Q){pv0(A,Q,this.config.messageBus)}stopAndClearJobs(A){for(let Q of A.values())Q.stop();A.clear()}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}" - ${L0(w)}`)}}}var dv0={maxRetries:3,baseDelayMs:5000};class yX{static instance=null;retries=new Map;config;static getInstance(A){return yX.instance??=new yX(A??dv0),yX.instance}static resetInstance(){yX.instance=null}static createFresh(A){return new yX(A??dv0)}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),D=Date.now()+$;this.retries.set(A,{entityId:A,retryCount:w,lastError:Q,nextRetryAt:D})}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 N9(A,Q,B,w,$,D,Y,I){return N9.fromTZ(N9.tp(A,Q,B,w,$,D,Y),I)}N9.fromTZISO=(A,Q,B)=>N9.fromTZ(bz2(A,Q),B);N9.fromTZ=function(A,Q){let B=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),w=QJA(A.tz,B),$=new Date(B.getTime()-w),D=QJA(A.tz,$);if(D-w===0)return $;{let Y=new Date(B.getTime()-D),I=QJA(A.tz,Y);if(I-D===0)return Y;if(!Q&&I-D>0)return Y;if(Q)throw Error("Invalid date passed to fromTZ()");return $}};N9.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}};N9.tp=(A,Q,B,w,$,D,Y)=>({y:A,m:Q,d:B,h:w,i:$,s:D,tz:Y});function QJA(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 bz2(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("+")?N9.tp(B.getUTCFullYear(),B.getUTCMonth()+1,B.getUTCDate(),B.getUTCHours(),B.getUTCMinutes(),B.getUTCSeconds(),"Etc/UTC"):N9.tp(B.getFullYear(),B.getMonth()+1,B.getDate(),B.getHours(),B.getMinutes(),B.getSeconds(),Q)}N9.minitz=N9;var BJA=32,Ab=31|BJA,ov0=[1,2,4,8,16],iv0=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 XD(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,Ab),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(A,Q,B,w){let $=this[A],D=A==="day"&&this.lastDayOfMonth;if(Q===""&&!D)throw TypeError("CronPattern: configuration entry "+A+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return $.fill(w);let Y=Q.split(",");if(Y.length>1)for(let I=0;I<Y.length;I++)this.partToArray(A,Y[I],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),D=parseInt($[0],10)+B;if(isNaN(D))throw TypeError("CronPattern: "+Q+" is not a number: '"+A+"'");this.setPart(Q,D,$[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),D=$[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(D===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+A+"'");let[,Y,I,X]=D,H=parseInt(Y,10)+B,W=parseInt(I,10)+B,J=parseInt(X,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(J))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(J===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(J>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if(H>W)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let Z=H;Z<=W;Z+=J)this.setPart(Q,Z,$[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),D=$[0].split("-");if(D.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+A+"'");let Y=parseInt(D[0],10)+B,I=parseInt(D[1],10)+B;if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(I))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Y>I)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let X=Y;X<=I;X++)this.setPart(Q,X,$[1]||w)}handleStepping(A,Q,B,w){let $=this.extractNth(A,Q),D=$[0].split("/");if(D.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+A+"'");D[0]===""&&(D[0]="*");let Y=0;D[0]!=="*"&&(Y=parseInt(D[0],10)+B);let I=parseInt(D[1],10);if(isNaN(I))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(I===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(I>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let X=Y;X<this[Q].length;X+=I)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]|BJA;else if(Q===Ab)this.dayOfWeek[A]=Ab;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|ov0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},rv0=[31,28,31,30,31,30,31,31,30,31,30,31],AU=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],XD=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 D=new Date(Date.UTC(Q,B,w)).getUTCDay(),Y=0;for(let I=1;I<=w;I++)new Date(Date.UTC(Q,B,I)).getUTCDay()===D&&Y++;if($&Ab&&ov0[Y-1]&$)return!0;if($&BJA){let I=new Date(Date.UTC(Q,B+1,0)).getUTCDate();for(let X=w+1;X<=I;X++)if(new Date(Date.UTC(Q,B,X)).getUTCDay()===D)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=N9.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>rv0[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=N9.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(N9.fromTZISO(Q,this.tz))}findNext(Q,B,w,$){let D=this[B],Y;w.lastDayOfMonth&&(this.month!==1?Y=rv0[this.month]:Y=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let I=!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 H=w[B][X];if(B==="day"&&w.lastDayOfMonth&&X-$==Y&&(H=1),B==="day"&&!w.starDOW){let W=w.dayOfWeek[(I+(X-$-1))%7];if(W&&W&Ab)W=this.isNthWeekdayOfMonth(this.year,this.month,X-$,W)?1:0;else if(W)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${W}`);Q.legacyMode&&!w.starDOM?H=H||W:H=H&&W}if(H)return this[B]=X-$,D!==this[B]?2:1}return 3}recurse(Q,B,w){let $=this.findNext(B,AU[w][0],Q,AU[w][2]);if($>1){let D=w+1;for(;D<AU.length;)this[AU[D][0]]=-AU[D][2],D++;if($===3)return this[AU[w][1]]++,this[AU[w][0]]=-AU[w][2],this.apply(),this.recurse(Q,B,0);if(this.apply())return this.recurse(Q,B,w-1)}return w+=1,w>=AU.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)):N9.fromTZ(N9.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xz2(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 XD(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new XD(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 e_(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function Tz2(A){return e_(A)}function vz2(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var nv0=30000,Pi=[],wJA=class{name;options;_states;fn;constructor(A,Q,B){let w,$;if(e_(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(e_(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=xz2(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 iv0("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new XD(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new iv0(A,this.options.timezone),this.name){if(Pi.find((D)=>D.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Pi.push(this)}return $!==void 0&&Tz2($)&&(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 XD||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new XD(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=Pi.indexOf(this);A>=0&&Pi.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>nv0&&(Q=nv0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(B),Q),this._states.currentTimeout&&this.options.unref&&vz2(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new XD(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){e_(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new XD(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&&e_(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 XD(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 XD(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 XD(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 XD(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 _i{scheduleCron(A,Q){let B=new wJA(A,()=>{Q()});return{stop:()=>B.stop()}}scheduleInterval(A,Q){let B=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(B)}}validateCron(A){new wJA(A).stop()}}B0();GA();var $JA=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)")}),DJA=F.object({position:F.number(),entityType:F.string(),entityId:F.string(),queuedAt:F.string()}),Sz2=F.object({success:F.literal(!0),message:F.string().optional(),data:F.object({queue:F.array(DJA).optional(),entityType:F.string().optional(),entityId:F.string().optional(),position:F.number().optional()}).optional()}),hz2=F.object({success:F.literal(!1),error:F.string(),code:F.string().optional()}),YJA=F.union([Sz2,hz2]);function bi(A,Q,B){return{...yQ(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",$JA,async($)=>{let{action:D,entityType:Y,entityId:I,position:X}=$;switch(D){case"list":return gz2(B,Y);case"add":return yz2(B,Y,I);case"remove":return mz2(B,Y,I);case"reorder":return uz2(B,Y,I,X);default:return{success:!1,error:`Unknown action: ${D}`}}}),outputSchema:YJA}}async function gz2(A,Q){let B=[];if(Q)B=await A.list(Q);else{let $=A.getRegisteredTypes();for(let D of $){let Y=await A.list(D);B.push(...Y)}B.sort((D,Y)=>new Date(D.queuedAt).getTime()-new Date(Y.queuedAt).getTime())}if(B.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:B.map(($,D)=>({position:D+1,entityType:$.entityType,entityId:$.entityId,queuedAt:$.queuedAt}))},message:`${B.length} items in queue`}}async function yz2(A,Q,B){if(!Q)return{success:!1,error:"entityType is required for add action"};if(!B)return{success:!1,error:"entityId is required for add action"};let w=await A.add(Q,B);return{success:!0,data:{entityType:Q,entityId:B,position:w.position},message:`Added to queue at position ${w.position}`}}async function mz2(A,Q,B){if(!Q)return{success:!1,error:"entityType is required for remove action"};if(!B)return{success:!1,error:"entityId is required for remove action"};return await A.remove(Q,B),{success:!0,data:{entityType:Q,entityId:B},message:"Removed from queue"}}async function uz2(A,Q,B,w){if(!Q)return{success:!1,error:"entityType is required for reorder action"};if(!B)return{success:!1,error:"entityId is required for reorder action"};if(w===void 0)return{success:!1,error:"position is required for reorder action"};if(w<1)return{success:!1,error:"position must be a positive number"};return await A.reorder(Q,B,w),{success:!0,data:{entityType:Q,entityId:B,position:w},message:`Moved to position ${w}`}}B0();GA();var IJA=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")}),cz2=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()}),lz2=F.object({success:F.literal(!1),error:F.string(),code:F.string().optional()}),XJA=F.union([cz2,lz2]);function xi(A,Q,B){return{...yQ(Q,"publish","Publish an entity directly to its platform. Works with any registered entity type (social-post, post, deck, etc.)",IJA,async($)=>{let{entityType:D,id:Y,slug:I}=$;if(!Y&&!I)return{success:!1,error:"Either 'id' or 'slug' must be provided"};let X=null;if(Y)X=await A.entityService.getEntity(D,Y);else if(I)X=(await A.entityService.listEntities(D,{filter:{metadata:{slug:I}},limit:1}))[0]??null;if(!X)return{success:!1,error:`Entity not found: ${D}:${Y??I}`};if(X.metadata.status==="published")return{success:!1,error:"Entity is already published"};if(!B.has(D))return{success:!1,error:`No publish provider registered for ${D}. Check that the required credentials are configured.`};let H=B.get(D),W=X.content,J;try{let V=G2(X.content,F.record(F.unknown()));W=V.content;let E=V.metadata.coverImageId;J=typeof E==="string"?E:void 0}catch{}let Z;if(J){let V=await A.entityService.getEntity("image",J);if(V?.content){let E=V.content.match(/^data:([^;]+);base64,(.+)$/);if(E?.[1]&&E[2])Z={data:Buffer.from(E[2],"base64"),mimeType:E[1]}}}let q=await H.publish(W,X.metadata,Z);return await A.entityService.updateEntity({...X,metadata:{...X.metadata,status:"published",publishedAt:new Date().toISOString(),platformId:q.id}}),{success:!0,data:{entityType:D,entityId:X.id,platformId:q.id,url:q.url},message:`Published ${D}:${X.id}`}}),outputSchema:XJA}}B0();GA();function sv0(A,Q){let{logger:B}=Q;A.messaging.subscribe(u6.REGISTER,async(w)=>pz2(Q,w.payload)),A.messaging.subscribe(u6.QUEUE,async(w)=>dz2(A,Q,w.payload)),A.messaging.subscribe(u6.DIRECT,async(w)=>iz2(A,Q,w.payload)),A.messaging.subscribe(u6.REMOVE,async(w)=>rz2(Q,w.payload)),A.messaging.subscribe(u6.REORDER,async(w)=>nz2(Q,w.payload)),A.messaging.subscribe(u6.LIST,async(w)=>oz2(A,Q,w.payload)),A.messaging.subscribe(u6.REPORT_SUCCESS,async(w)=>sz2(A,Q,w.payload)),A.messaging.subscribe(u6.REPORT_FAILURE,async(w)=>az2(A,Q,w.payload)),B.debug("Subscribed to publish messages"),A.messaging.subscribe(SX.REPORT_SUCCESS,async(w)=>{let{entityType:$,entityId:D}=w.payload;return Q.scheduler.completeGeneration($,D),B.info("Generation completed",{entityType:$,entityId:D}),{success:!0}}),A.messaging.subscribe(SX.REPORT_FAILURE,async(w)=>{let{entityType:$,error:D}=w.payload;return Q.scheduler.failGeneration($,D),B.warn("Generation failed",{entityType:$,error:D}),{success:!0}}),B.debug("Subscribed to generation messages")}async function pz2(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 D=L0($);return A.logger.error(`Failed to register provider: ${D}`),{success:!1}}}async function dz2(A,Q,B){let{entityType:w,entityId:$}=B;try{let D=await Q.queueManager.add(w,$);return await A.messaging.send(u6.QUEUED,{entityType:w,entityId:$,position:D.position}),Q.logger.debug(`Entity queued: ${$}`,{entityType:w,position:D.position}),{success:!0}}catch(D){let Y=L0(D);return Q.logger.error(`Failed to queue entity: ${Y}`),{success:!1}}}async function iz2(A,Q,B){let{entityType:w,entityId:$}=B;return await A.messaging.send(u6.EXECUTE,{entityType:w,entityId:$}),Q.logger.debug(`Direct publish requested: ${$}`,{entityType:w}),{success:!0}}async function rz2(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 D=L0($);return A.logger.error(`Failed to remove entity: ${D}`),{success:!1}}}async function nz2(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(D){let Y=L0(D);return A.logger.error(`Failed to reorder entity: ${Y}`),{success:!1}}}async function oz2(A,Q,B){let{entityType:w}=B;try{let $=await Q.queueManager.list(w);return await A.messaging.send(u6.LIST_RESPONSE,{entityType:w,queue:$.map((D)=>({entityId:D.entityId,position:D.position,queuedAt:D.queuedAt}))}),{success:!0}}catch($){let D=L0($);return Q.logger.error(`Failed to list queue: ${D}`),{success:!1}}}async function sz2(A,Q,B){let{entityType:w,entityId:$,result:D}=B;return Q.retryTracker.clearRetries($),await A.messaging.send(u6.COMPLETED,{entityType:w,entityId:$,result:D}),Q.logger.info(`Publish reported success: ${$}`,{entityType:w}),{success:!0}}async function az2(A,Q,B){let{entityType:w,entityId:$,error:D}=B;Q.retryTracker.recordFailure($,D);let Y=Q.retryTracker.getRetryInfo($);return await A.messaging.send(u6.FAILED,{entityType:w,entityId:$,error:D,retryCount:Y?.retryCount??1,willRetry:Y?.willRetry??!1}),Q.logger.info(`Publish reported failure: ${$}`,{entityType:w,error:D,retryCount:Y?.retryCount,willRetry:Y?.willRetry}),{success:!0}}GA();async function av0(A,Q,B,w){try{if(w.skipIfDraftExists!==!1){if((await A.listEntities(B,{filter:{metadata:{status:"draft"}},limit:1})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(w.maxUnpublishedDrafts!==void 0){let $=await A.listEntities(B,{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(w.sourceEntityType,{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:L0($)}),{shouldGenerate:!1,reason:`Condition check failed: ${L0($)}`}}}function tv0(A){let{context:Q,config:B,queueManager:w,providerRegistry:$,retryTracker:D,logger:Y}=A,I={send:async(X,H)=>{return Q.messaging.send(X,H)},subscribe:()=>()=>{}};return lY.createFresh({queueManager:w,providerRegistry:$,retryTracker:D,logger:Y,backend:new _i,...B.entitySchedules&&{entitySchedules:B.entitySchedules},...B.generationSchedules&&{generationSchedules:B.generationSchedules},...B.generationConditions&&{generationConditions:B.generationConditions},messageBus:I,entityService:Q.entityService,onPublish:(X)=>{Q.messaging.send(u6.COMPLETED,{entityType:X.entityType,entityId:X.entityId,result:X.result})},onFailed:(X)=>{Q.messaging.send(u6.FAILED,{entityType:X.entityType,entityId:X.entityId,error:X.error,retryCount:X.retryCount,willRetry:X.willRetry})},onCheckGenerationConditions:(X,H)=>av0(Q.entityService,Y,X,H),onGenerate:(X)=>{Y.info(`Generation triggered for ${X.entityType}`),Q.messaging.send(SX.EXECUTE,{entityType:X.entityType})}})}async function ev0(A,Q,B){let w=A.getEntityTypes();for(let D of w){let Y=await A.listEntities(D,{filter:{metadata:{status:"queued"}}});for(let I of Y)await Q.add(I.entityType,I.id)}let $=0;for(let D of w){let Y=await Q.list(D);$+=Y.length}if($>0)B.info(`Rebuilt queue with ${$} queued entities`)}var AS0={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.41",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/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 HJA extends tB{pluginContext;queueManager;providerRegistry;retryTracker;scheduler;constructor(A){super("content-pipeline",AS0,A??{},hv0)}async onRegister(A){this.pluginContext=A,this.queueManager=hX.createFresh(),this.providerRegistry=gX.createFresh(),this.retryTracker=yX.createFresh({maxRetries:this.config.maxRetries,baseDelayMs:this.config.retryBaseDelayMs}),this.scheduler=tv0({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,logger:this.logger}),sv0(A,{queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,scheduler:this.scheduler,logger:this.logger}),A.messaging.subscribe("sync:initial:completed",async()=>{return await ev0(A.entityService,this.queueManager,this.logger),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("dashboard:register-widget",{id:"publication-pipeline",pluginId:this.id,title:"Publication Pipeline",section:"secondary",priority:100,rendererName:"PipelineWidget",dataProvider:async()=>{let Q=A.entityService.getEntityTypes(),B=[],w={draft:0,queued:0,published:0,failed:0};for(let $ of Q){let D=await A.entityService.listEntities($);for(let Y of D){let I=Y.metadata.status;if(I!=="draft"&&I!=="queued"&&I!=="published"&&I!=="failed")continue;w[I]++;let X=Y.metadata.title;B.push({id:Y.id,title:typeof X==="string"?X:Y.id,type:$,status:I})}}return{summary:w,items:B}}}),{success:!0}}),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[bi(this.pluginContext,this.id,this.queueManager),xi(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`.'}async cleanup(){await this.scheduler.stop(),this.logger.info("Content pipeline plugin stopped")}getQueueManager(){return this.queueManager}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getScheduler(){return this.scheduler}async onShutdown(){hX.resetInstance(),gX.resetInstance(),yX.resetInstance()}}function KJA(A){return new HJA(A)}B0();GA();var QS0=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")}),UJA=F.object({cloudflare:QS0.optional()});B0();GA();var ez2=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 AN2(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 BS0(A,Q,B){let w=[];if(!B)return w;return w.push(yQ(A,"query",`Query website analytics from Cloudflare.
2844
+ ${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=Rz2.parse(Q),w=[],$=Lw.from(async(H)=>{let W={progress:H.progress};if(H.message!==void 0)W.message=H.message;w.push(W)});if(!$)throw Error("Failed to create progress reporter");let Y=await new wq(A.logger,A).process(B,`eval-${Date.now()}`,$),I=!1,X;if(Y.success&&Y.entityId){let H=await A.entityService.getEntity("social-post",Y.entityId);I=!!H,X=H?.content.slice(0,300)}return{...Y,entityExists:I,entityPreview:X,progressSteps:w}})}GA();B0();class a_{sendMessage;logger;entityService;providers;constructor(A){this.sendMessage=A.sendMessage,this.logger=A.logger,this.entityService=A.entityService,this.providers=A.providers}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("social-post",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,D=this.providers.get($);if(!D){await this.reportFailure(Q,B,`No provider configured for platform: ${$}`);return}let Y=G2(w.content,ID),I;if(Y.metadata.coverImageId)I=await this.fetchImageData(Y.metadata.coverImageId);try{let X=await D.publish(Y.content,w.metadata,I),H=new Date().toISOString(),W=X.id||void 0,J={...Y.metadata,status:"published",publishedAt:H,...W&&{platformPostId:W}},Z=a7.createPostContent(J,Y.content);await this.entityService.updateEntity({...w,content:Z,metadata:{...w.metadata,status:"published",publishedAt:H,platformPostId:W}}),await this.reportSuccess(Q,B,X.id),this.logger.info(`Post published successfully: ${B}`,{platform:$,platformPostId:W})}catch(X){let H=X instanceof Error?X.message:String(X),W={...Y.metadata,status:"failed"},J=a7.createPostContent(W,Y.content);await this.entityService.updateEntity({...w,content:J,metadata:{...w.metadata,status:"failed"}}),await this.reportFailure(Q,B,H),this.logger.error(`Post publish failed: ${B}`,{platform:$,error:H})}}catch(w){let $=L0(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("publish:report:success",{entityType:A,entityId:Q,result:{id:B}})}async reportFailure(A,Q,B){await this.sendMessage("publish:report:failure",{entityType:A,entityId:Q,error:B})}async fetchImageData(A){try{let Q=await this.entityService.getEntity("image",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],D=w[2];return{data:Buffer.from(D,"base64"),mimeType:$}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function _v0(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("publish:register",{entityType:"social-post",provider:w}),B.info("Registered social-post with publish-pipeline"),{success:!0}})}function bv0(A,Q,B){let w=new a_({sendMessage:A.messaging.send,logger:B.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q});A.messaging.subscribe("publish:execute",async($)=>{return await w.handle($.payload),{success:!0}}),B.debug("Subscribed to publish:execute messages")}GA();function xv0(A,Q){A.messaging.subscribe("entity:updated",async(B)=>{let{entityType:w,entityId:$,entity:D}=B.payload;if(w!=="post")return{success:!0};if(D.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities("social-post",{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("social:auto-generate",{sourceEntityType:w,sourceEntityId:$,platform:"linkedin"}),Q.info(`Auto-generate social post triggered for queued post ${$}`),{success:!0}}catch(I){let X=L0(I);return Q.error(`Failed to trigger auto-generate for ${$}:`,{error:X}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function Tv0(A,Q){A.messaging.subscribe("social:auto-generate",async(B)=>{let{sourceEntityType:w,sourceEntityId:$,platform:D}=B.payload;try{let Y=await A.jobs.enqueue(`${a7.entityType}:generation`,{sourceEntityType:w,sourceEntityId:$,platform:D,addToQueue:!1},{interfaceType:"job",userId:"system"});return Q.info(`Social post generation job enqueued for ${w}/${$}`,{jobId:Y}),{success:!0,jobId:Y}}catch(Y){let I=L0(Y);return Q.error(`Failed to enqueue social post generation for ${$}:`,{error:I}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function vv0(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("post",{filter:{metadata:{status:"published"}},limit:5});if($.length===0)return Q.info("No published posts found for social post generation"),await A.messaging.send("generate:report:failure",{entityType:"social-post",error:"No published posts available for social post generation"}),{success:!0};let D=null;for(let I of $)if((await A.entityService.listEntities("social-post",{filter:{metadata:{sourceEntityType:"post",sourceEntityId:I.id}},limit:1})).length===0){D=I;break}if(!D)return Q.info("All recent posts already have social posts"),await A.messaging.send("generate:report:failure",{entityType:"social-post",error:"All recent posts already have social posts generated"}),{success:!0};let Y=await A.jobs.enqueue(`${a7.entityType}:generation`,{sourceEntityType:"post",sourceEntityId:D.id,platform:"linkedin",addToQueue:!1},{interfaceType:"job",userId:"system"});return Q.info("Social post generation job queued",{jobId:Y,sourcePostId:D.id}),{success:!0}}catch($){let D=L0($);return Q.error("Failed to handle generate:execute:",{error:D}),await A.messaging.send("generate:report:failure",{entityType:"social-post",error:D}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}var Sv0={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.42",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/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 eGA extends HQ{entityType=a7.entityType;schema=aM;adapter=a7;providers=new Map;constructor(A){super("social-media",Sv0,A,rGA)}createGenerationHandler(A){return new wq(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return kv0()}getDataSources(){return[new fi(this.logger.child("SocialPostDataSource"))]}async onRegister(A){if(this.initializeProviders(),_v0(A,this.providers,this.logger),bv0(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)xv0(A,this.logger),Tv0(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");vv0(A,this.logger),Pv0(A),this.logger.info("Social media plugin registered successfully")}async derive(A,Q,B){if(A.metadata.status!=="published")return;await B.jobs.enqueue(`${this.entityType}:generation`,{sourceEntityId:A.id,sourceEntityType:A.entityType},null,{priority:5,source:"social-media-plugin",metadata:{operationType:"content_operations",operationTarget:`social-post:${A.entityType}:${A.id}`,pluginId:"social-media"}})}initializeProviders(){if(this.config.linkedin?.accessToken){let A=tGA(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function t_(A){return new eGA(A)}GA();var kz2=F.enum(["draft","queued","published","failed"]),FwB=F.object({status:kz2.default("draft"),queueOrder:F.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:F.string().datetime().optional()});class AJA{name="internal";async publish(A,Q){return{id:"internal"}}}var u6={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"},SX={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"};GA();var Pz2=F.object({skipIfDraftExists:F.boolean().optional(),minSourceEntities:F.number().optional(),maxUnpublishedDrafts:F.number().optional(),sourceEntityType:F.string().optional()}),hv0=F.object({entitySchedules:F.record(F.string(),F.string()).optional(),generationSchedules:F.record(F.string(),F.string()).optional(),generationConditions:F.record(F.string(),Pz2).optional(),maxRetries:F.number().optional().default(3),retryBaseDelayMs:F.number().optional().default(5000)});class hX{static instance=null;queues=new Map;static getInstance(){return hX.instance??=new hX,hX.instance}static resetInstance(){hX.instance=null}static createFresh(){return new hX}constructor(){}async add(A,Q){let B=this.getOrCreateQueue(A),w=B.find((Y)=>Y.entityId===Q);if(w)return{position:w.position};let $=B.length+1,D={entityId:Q,entityType:A,position:$,queuedAt:new Date().toISOString()};return B.push(D),{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((I)=>I.entityId===Q);if($===-1)return;let[D]=w.splice($,1);if(!D)return;let Y=Math.max(0,Math.min(B-1,w.length));w.splice(Y,0,D),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 gX{static instance=null;providers=new Map;defaultProvider=new AJA;static getInstance(){return gX.instance??=new gX,gX.instance}static resetInstance(){gX.instance=null}static createFresh(){return new gX}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())}}GA();GA();async function gv0(A,Q){let B={entityType:A.entityType,entityId:A.entityId};if(Q.messageBus)await Q.messageBus.send(u6.EXECUTE,B,"publish-service");Q.onExecute?.(B)}async function yv0(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(A.entityType,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 D=L0($);Q.retryTracker.recordFailure(A.entityId,D);let Y=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:D,retryCount:Y?.retryCount??1,willRetry:Y?.willRetry??!1})}}function mv0(A,Q,B,w){if(w.retryTracker.clearRetries(Q),w.messageBus)w.messageBus.send(u6.COMPLETED,{entityType:A,entityId:Q,result:B},"publish-service");w.onPublish?.({entityType:A,entityId:Q,result:B})}function uv0(A,Q,B,w){w.retryTracker.recordFailure(Q,B);let $=w.retryTracker.getRetryInfo(Q),D={entityType:A,entityId:Q,error:B,retryCount:$?.retryCount??1,willRetry:$?.willRetry??!1};if(w.messageBus)w.messageBus.send(u6.FAILED,D,"publish-service");w.onFailed?.(D)}async function cv0(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(SX.SKIPPED,{entityType:A,reason:$.reason??"Conditions not met"},"content-pipeline");return}}let w={entityType:A};if(Q.messageBus)await Q.messageBus.send(SX.EXECUTE,w,"content-pipeline");Q.onGenerate?.(w)}function lv0(A,Q,B){if(B)B.send(SX.COMPLETED,{entityType:A,entityId:Q},"content-pipeline")}function pv0(A,Q,B){if(B)B.send(SX.FAILED,{entityType:A,error:Q},"content-pipeline")}var _z2=1000;class lY{static instance=null;config;publishJobs=new Map;generationJobs=new Map;immediateIntervalJob=null;running=!1;static getInstance(A){return lY.instance??=new lY(A),lY.instance}static resetInstance(){if(lY.instance)lY.instance.stop();lY.instance=null}static createFresh(A){return new lY(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions()}async start(){if(this.running)return;this.running=!0;for(let[A,Q]of Object.entries(this.entitySchedules)){let B=this.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,B)}for(let[A,Q]of Object.entries(this.generationSchedules)){let B=this.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,B)}this.immediateIntervalJob=this.config.backend.scheduleInterval(_z2,()=>this.processUnscheduledTypes())}async stop(){if(this.running=!1,this.stopAndClearJobs(this.publishJobs),this.stopAndClearJobs(this.generationJobs),this.immediateIntervalJob)this.immediateIntervalJob.stop(),this.immediateIntervalJob=null}isRunning(){return this.running}async processEntityType(A){if(!this.running)return;try{let Q=await this.config.queueManager.getNext(A);if(Q)await this.processEntry(Q)}catch(Q){this.config.logger.error(`Scheduler error for ${A}:`,Q)}}async processUnscheduledTypes(){if(!this.running)return;try{let A=await this.config.queueManager.getQueuedEntityTypes();for(let Q of A)if(!this.entitySchedules[Q]){let B=await this.config.queueManager.getNext(Q);if(B){await this.processEntry(B);break}}}catch(A){this.config.logger.error("Scheduler error for unscheduled types:",A)}}async processEntry(A){if(await this.config.queueManager.remove(A.entityType,A.entityId),this.config.messageBus!==void 0)await gv0(A,this.publishDeps);else await yv0(A,this.publishDeps)}completePublish(A,Q,B){mv0(A,Q,B,this.publishDeps)}failPublish(A,Q,B){uv0(A,Q,B,this.publishDeps)}async publishDirect(A,Q,B,w){return this.config.providerRegistry.get(A).publish(B,w)}async handleTriggerGeneration(A){if(!this.running)return;try{await cv0(A,this.generationDeps)}catch(Q){this.config.logger.error(`Generation trigger error for ${A}:`,Q)}}completeGeneration(A,Q){lv0(A,Q,this.config.messageBus)}failGeneration(A,Q){pv0(A,Q,this.config.messageBus)}stopAndClearJobs(A){for(let Q of A.values())Q.stop();A.clear()}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}" - ${L0(w)}`)}}}var dv0={maxRetries:3,baseDelayMs:5000};class yX{static instance=null;retries=new Map;config;static getInstance(A){return yX.instance??=new yX(A??dv0),yX.instance}static resetInstance(){yX.instance=null}static createFresh(A){return new yX(A??dv0)}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),D=Date.now()+$;this.retries.set(A,{entityId:A,retryCount:w,lastError:Q,nextRetryAt:D})}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 N9(A,Q,B,w,$,D,Y,I){return N9.fromTZ(N9.tp(A,Q,B,w,$,D,Y),I)}N9.fromTZISO=(A,Q,B)=>N9.fromTZ(bz2(A,Q),B);N9.fromTZ=function(A,Q){let B=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),w=QJA(A.tz,B),$=new Date(B.getTime()-w),D=QJA(A.tz,$);if(D-w===0)return $;{let Y=new Date(B.getTime()-D),I=QJA(A.tz,Y);if(I-D===0)return Y;if(!Q&&I-D>0)return Y;if(Q)throw Error("Invalid date passed to fromTZ()");return $}};N9.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}};N9.tp=(A,Q,B,w,$,D,Y)=>({y:A,m:Q,d:B,h:w,i:$,s:D,tz:Y});function QJA(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 bz2(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("+")?N9.tp(B.getUTCFullYear(),B.getUTCMonth()+1,B.getUTCDate(),B.getUTCHours(),B.getUTCMinutes(),B.getUTCSeconds(),"Etc/UTC"):N9.tp(B.getFullYear(),B.getMonth()+1,B.getDate(),B.getHours(),B.getMinutes(),B.getSeconds(),Q)}N9.minitz=N9;var BJA=32,Ab=31|BJA,ov0=[1,2,4,8,16],iv0=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 XD(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,Ab),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(A,Q,B,w){let $=this[A],D=A==="day"&&this.lastDayOfMonth;if(Q===""&&!D)throw TypeError("CronPattern: configuration entry "+A+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return $.fill(w);let Y=Q.split(",");if(Y.length>1)for(let I=0;I<Y.length;I++)this.partToArray(A,Y[I],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),D=parseInt($[0],10)+B;if(isNaN(D))throw TypeError("CronPattern: "+Q+" is not a number: '"+A+"'");this.setPart(Q,D,$[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),D=$[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(D===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+A+"'");let[,Y,I,X]=D,H=parseInt(Y,10)+B,W=parseInt(I,10)+B,J=parseInt(X,10);if(isNaN(H))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(J))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(J===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(J>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if(H>W)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let Z=H;Z<=W;Z+=J)this.setPart(Q,Z,$[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),D=$[0].split("-");if(D.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+A+"'");let Y=parseInt(D[0],10)+B,I=parseInt(D[1],10)+B;if(isNaN(Y))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(I))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(Y>I)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let X=Y;X<=I;X++)this.setPart(Q,X,$[1]||w)}handleStepping(A,Q,B,w){let $=this.extractNth(A,Q),D=$[0].split("/");if(D.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+A+"'");D[0]===""&&(D[0]="*");let Y=0;D[0]!=="*"&&(Y=parseInt(D[0],10)+B);let I=parseInt(D[1],10);if(isNaN(I))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(I===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(I>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let X=Y;X<this[Q].length;X+=I)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]|BJA;else if(Q===Ab)this.dayOfWeek[A]=Ab;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|ov0[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},rv0=[31,28,31,30,31,30,31,31,30,31,30,31],AU=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],XD=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 D=new Date(Date.UTC(Q,B,w)).getUTCDay(),Y=0;for(let I=1;I<=w;I++)new Date(Date.UTC(Q,B,I)).getUTCDay()===D&&Y++;if($&Ab&&ov0[Y-1]&$)return!0;if($&BJA){let I=new Date(Date.UTC(Q,B+1,0)).getUTCDate();for(let X=w+1;X<=I;X++)if(new Date(Date.UTC(Q,B,X)).getUTCDay()===D)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=N9.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>rv0[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=N9.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(N9.fromTZISO(Q,this.tz))}findNext(Q,B,w,$){let D=this[B],Y;w.lastDayOfMonth&&(this.month!==1?Y=rv0[this.month]:Y=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let I=!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 H=w[B][X];if(B==="day"&&w.lastDayOfMonth&&X-$==Y&&(H=1),B==="day"&&!w.starDOW){let W=w.dayOfWeek[(I+(X-$-1))%7];if(W&&W&Ab)W=this.isNthWeekdayOfMonth(this.year,this.month,X-$,W)?1:0;else if(W)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${W}`);Q.legacyMode&&!w.starDOM?H=H||W:H=H&&W}if(H)return this[B]=X-$,D!==this[B]?2:1}return 3}recurse(Q,B,w){let $=this.findNext(B,AU[w][0],Q,AU[w][2]);if($>1){let D=w+1;for(;D<AU.length;)this[AU[D][0]]=-AU[D][2],D++;if($===3)return this[AU[w][1]]++,this[AU[w][0]]=-AU[w][2],this.apply(),this.recurse(Q,B,0);if(this.apply())return this.recurse(Q,B,w-1)}return w+=1,w>=AU.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)):N9.fromTZ(N9.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function xz2(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 XD(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new XD(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 e_(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function Tz2(A){return e_(A)}function vz2(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var nv0=30000,Pi=[],wJA=class{name;options;_states;fn;constructor(A,Q,B){let w,$;if(e_(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(e_(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=xz2(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 iv0("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new XD(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new iv0(A,this.options.timezone),this.name){if(Pi.find((D)=>D.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");Pi.push(this)}return $!==void 0&&Tz2($)&&(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 XD||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new XD(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=Pi.indexOf(this);A>=0&&Pi.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>nv0&&(Q=nv0),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(B),Q),this._states.currentTimeout&&this.options.unref&&vz2(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new XD(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){e_(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new XD(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&&e_(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 XD(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 XD(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 XD(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 XD(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 _i{scheduleCron(A,Q){let B=new wJA(A,()=>{Q()});return{stop:()=>B.stop()}}scheduleInterval(A,Q){let B=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(B)}}validateCron(A){new wJA(A).stop()}}B0();GA();var $JA=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)")}),DJA=F.object({position:F.number(),entityType:F.string(),entityId:F.string(),queuedAt:F.string()}),Sz2=F.object({success:F.literal(!0),message:F.string().optional(),data:F.object({queue:F.array(DJA).optional(),entityType:F.string().optional(),entityId:F.string().optional(),position:F.number().optional()}).optional()}),hz2=F.object({success:F.literal(!1),error:F.string(),code:F.string().optional()}),YJA=F.union([Sz2,hz2]);function bi(A,Q,B){return{...yQ(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",$JA,async($)=>{let{action:D,entityType:Y,entityId:I,position:X}=$;switch(D){case"list":return gz2(B,Y);case"add":return yz2(B,Y,I);case"remove":return mz2(B,Y,I);case"reorder":return uz2(B,Y,I,X);default:return{success:!1,error:`Unknown action: ${D}`}}}),outputSchema:YJA}}async function gz2(A,Q){let B=[];if(Q)B=await A.list(Q);else{let $=A.getRegisteredTypes();for(let D of $){let Y=await A.list(D);B.push(...Y)}B.sort((D,Y)=>new Date(D.queuedAt).getTime()-new Date(Y.queuedAt).getTime())}if(B.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:B.map(($,D)=>({position:D+1,entityType:$.entityType,entityId:$.entityId,queuedAt:$.queuedAt}))},message:`${B.length} items in queue`}}async function yz2(A,Q,B){if(!Q)return{success:!1,error:"entityType is required for add action"};if(!B)return{success:!1,error:"entityId is required for add action"};let w=await A.add(Q,B);return{success:!0,data:{entityType:Q,entityId:B,position:w.position},message:`Added to queue at position ${w.position}`}}async function mz2(A,Q,B){if(!Q)return{success:!1,error:"entityType is required for remove action"};if(!B)return{success:!1,error:"entityId is required for remove action"};return await A.remove(Q,B),{success:!0,data:{entityType:Q,entityId:B},message:"Removed from queue"}}async function uz2(A,Q,B,w){if(!Q)return{success:!1,error:"entityType is required for reorder action"};if(!B)return{success:!1,error:"entityId is required for reorder action"};if(w===void 0)return{success:!1,error:"position is required for reorder action"};if(w<1)return{success:!1,error:"position must be a positive number"};return await A.reorder(Q,B,w),{success:!0,data:{entityType:Q,entityId:B,position:w},message:`Moved to position ${w}`}}B0();GA();var IJA=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")}),cz2=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()}),lz2=F.object({success:F.literal(!1),error:F.string(),code:F.string().optional()}),XJA=F.union([cz2,lz2]);function xi(A,Q,B){return{...yQ(Q,"publish","Publish an entity directly to its platform. Works with any registered entity type (social-post, post, deck, etc.)",IJA,async($)=>{let{entityType:D,id:Y,slug:I}=$;if(!Y&&!I)return{success:!1,error:"Either 'id' or 'slug' must be provided"};let X=null;if(Y)X=await A.entityService.getEntity(D,Y);else if(I)X=(await A.entityService.listEntities(D,{filter:{metadata:{slug:I}},limit:1}))[0]??null;if(!X)return{success:!1,error:`Entity not found: ${D}:${Y??I}`};if(X.metadata.status==="published")return{success:!1,error:"Entity is already published"};if(!B.has(D))return{success:!1,error:`No publish provider registered for ${D}. Check that the required credentials are configured.`};let H=B.get(D),W=X.content,J;try{let V=G2(X.content,F.record(F.unknown()));W=V.content;let E=V.metadata.coverImageId;J=typeof E==="string"?E:void 0}catch{}let Z;if(J){let V=await A.entityService.getEntity("image",J);if(V?.content){let E=V.content.match(/^data:([^;]+);base64,(.+)$/);if(E?.[1]&&E[2])Z={data:Buffer.from(E[2],"base64"),mimeType:E[1]}}}let q=await H.publish(W,X.metadata,Z);return await A.entityService.updateEntity({...X,metadata:{...X.metadata,status:"published",publishedAt:new Date().toISOString(),platformId:q.id}}),{success:!0,data:{entityType:D,entityId:X.id,platformId:q.id,url:q.url},message:`Published ${D}:${X.id}`}}),outputSchema:XJA}}B0();GA();function sv0(A,Q){let{logger:B}=Q;A.messaging.subscribe(u6.REGISTER,async(w)=>pz2(Q,w.payload)),A.messaging.subscribe(u6.QUEUE,async(w)=>dz2(A,Q,w.payload)),A.messaging.subscribe(u6.DIRECT,async(w)=>iz2(A,Q,w.payload)),A.messaging.subscribe(u6.REMOVE,async(w)=>rz2(Q,w.payload)),A.messaging.subscribe(u6.REORDER,async(w)=>nz2(Q,w.payload)),A.messaging.subscribe(u6.LIST,async(w)=>oz2(A,Q,w.payload)),A.messaging.subscribe(u6.REPORT_SUCCESS,async(w)=>sz2(A,Q,w.payload)),A.messaging.subscribe(u6.REPORT_FAILURE,async(w)=>az2(A,Q,w.payload)),B.debug("Subscribed to publish messages"),A.messaging.subscribe(SX.REPORT_SUCCESS,async(w)=>{let{entityType:$,entityId:D}=w.payload;return Q.scheduler.completeGeneration($,D),B.info("Generation completed",{entityType:$,entityId:D}),{success:!0}}),A.messaging.subscribe(SX.REPORT_FAILURE,async(w)=>{let{entityType:$,error:D}=w.payload;return Q.scheduler.failGeneration($,D),B.warn("Generation failed",{entityType:$,error:D}),{success:!0}}),B.debug("Subscribed to generation messages")}async function pz2(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 D=L0($);return A.logger.error(`Failed to register provider: ${D}`),{success:!1}}}async function dz2(A,Q,B){let{entityType:w,entityId:$}=B;try{let D=await Q.queueManager.add(w,$);return await A.messaging.send(u6.QUEUED,{entityType:w,entityId:$,position:D.position}),Q.logger.debug(`Entity queued: ${$}`,{entityType:w,position:D.position}),{success:!0}}catch(D){let Y=L0(D);return Q.logger.error(`Failed to queue entity: ${Y}`),{success:!1}}}async function iz2(A,Q,B){let{entityType:w,entityId:$}=B;return await A.messaging.send(u6.EXECUTE,{entityType:w,entityId:$}),Q.logger.debug(`Direct publish requested: ${$}`,{entityType:w}),{success:!0}}async function rz2(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 D=L0($);return A.logger.error(`Failed to remove entity: ${D}`),{success:!1}}}async function nz2(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(D){let Y=L0(D);return A.logger.error(`Failed to reorder entity: ${Y}`),{success:!1}}}async function oz2(A,Q,B){let{entityType:w}=B;try{let $=await Q.queueManager.list(w);return await A.messaging.send(u6.LIST_RESPONSE,{entityType:w,queue:$.map((D)=>({entityId:D.entityId,position:D.position,queuedAt:D.queuedAt}))}),{success:!0}}catch($){let D=L0($);return Q.logger.error(`Failed to list queue: ${D}`),{success:!1}}}async function sz2(A,Q,B){let{entityType:w,entityId:$,result:D}=B;return Q.retryTracker.clearRetries($),await A.messaging.send(u6.COMPLETED,{entityType:w,entityId:$,result:D}),Q.logger.info(`Publish reported success: ${$}`,{entityType:w}),{success:!0}}async function az2(A,Q,B){let{entityType:w,entityId:$,error:D}=B;Q.retryTracker.recordFailure($,D);let Y=Q.retryTracker.getRetryInfo($);return await A.messaging.send(u6.FAILED,{entityType:w,entityId:$,error:D,retryCount:Y?.retryCount??1,willRetry:Y?.willRetry??!1}),Q.logger.info(`Publish reported failure: ${$}`,{entityType:w,error:D,retryCount:Y?.retryCount,willRetry:Y?.willRetry}),{success:!0}}GA();async function av0(A,Q,B,w){try{if(w.skipIfDraftExists!==!1){if((await A.listEntities(B,{filter:{metadata:{status:"draft"}},limit:1})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(w.maxUnpublishedDrafts!==void 0){let $=await A.listEntities(B,{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(w.sourceEntityType,{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:L0($)}),{shouldGenerate:!1,reason:`Condition check failed: ${L0($)}`}}}function tv0(A){let{context:Q,config:B,queueManager:w,providerRegistry:$,retryTracker:D,logger:Y}=A,I={send:async(X,H)=>{return Q.messaging.send(X,H)},subscribe:()=>()=>{}};return lY.createFresh({queueManager:w,providerRegistry:$,retryTracker:D,logger:Y,backend:new _i,...B.entitySchedules&&{entitySchedules:B.entitySchedules},...B.generationSchedules&&{generationSchedules:B.generationSchedules},...B.generationConditions&&{generationConditions:B.generationConditions},messageBus:I,entityService:Q.entityService,onPublish:(X)=>{Q.messaging.send(u6.COMPLETED,{entityType:X.entityType,entityId:X.entityId,result:X.result})},onFailed:(X)=>{Q.messaging.send(u6.FAILED,{entityType:X.entityType,entityId:X.entityId,error:X.error,retryCount:X.retryCount,willRetry:X.willRetry})},onCheckGenerationConditions:(X,H)=>av0(Q.entityService,Y,X,H),onGenerate:(X)=>{Y.info(`Generation triggered for ${X.entityType}`),Q.messaging.send(SX.EXECUTE,{entityType:X.entityType})}})}async function ev0(A,Q,B){let w=A.getEntityTypes();for(let D of w){let Y=await A.listEntities(D,{filter:{metadata:{status:"queued"}}});for(let I of Y)await Q.add(I.entityType,I.id)}let $=0;for(let D of w){let Y=await Q.list(D);$+=Y.length}if($>0)B.info(`Rebuilt queue with ${$} queued entities`)}var AS0={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.42",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/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 HJA extends tB{pluginContext;queueManager;providerRegistry;retryTracker;scheduler;constructor(A){super("content-pipeline",AS0,A??{},hv0)}async onRegister(A){this.pluginContext=A,this.queueManager=hX.createFresh(),this.providerRegistry=gX.createFresh(),this.retryTracker=yX.createFresh({maxRetries:this.config.maxRetries,baseDelayMs:this.config.retryBaseDelayMs}),this.scheduler=tv0({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,logger:this.logger}),sv0(A,{queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,scheduler:this.scheduler,logger:this.logger}),A.messaging.subscribe("sync:initial:completed",async()=>{return await ev0(A.entityService,this.queueManager,this.logger),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("dashboard:register-widget",{id:"publication-pipeline",pluginId:this.id,title:"Publication Pipeline",section:"secondary",priority:100,rendererName:"PipelineWidget",dataProvider:async()=>{let Q=A.entityService.getEntityTypes(),B=[],w={draft:0,queued:0,published:0,failed:0};for(let $ of Q){let D=await A.entityService.listEntities($);for(let Y of D){let I=Y.metadata.status;if(I!=="draft"&&I!=="queued"&&I!=="published"&&I!=="failed")continue;w[I]++;let X=Y.metadata.title;B.push({id:Y.id,title:typeof X==="string"?X:Y.id,type:$,status:I})}}return{summary:w,items:B}}}),{success:!0}}),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[bi(this.pluginContext,this.id,this.queueManager),xi(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`.'}async cleanup(){await this.scheduler.stop(),this.logger.info("Content pipeline plugin stopped")}getQueueManager(){return this.queueManager}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getScheduler(){return this.scheduler}async onShutdown(){hX.resetInstance(),gX.resetInstance(),yX.resetInstance()}}function KJA(A){return new HJA(A)}B0();GA();var QS0=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")}),UJA=F.object({cloudflare:QS0.optional()});B0();GA();var ez2=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 AN2(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 BS0(A,Q,B){let w=[];if(!B)return w;return w.push(yQ(A,"query",`Query website analytics from Cloudflare.
2845
2845
 
2846
2846
  Date range options (use only one):
2847
2847
  - No params: yesterday only
@@ -2979,7 +2979,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,ez2,
2979
2979
  }
2980
2980
  }
2981
2981
  }
2982
- `,variables:B})});if(!w.ok){let Y=await w.text();throw Error(`Cloudflare API error: ${w.status} - ${Y}`)}let $=await w.json();if($.errors&&$.errors.length>0)throw Error(`Cloudflare GraphQL error: ${$.errors.map((Y)=>Y.message).join(", ")}`);return($.data.viewer.accounts[0]?.rumPageloadEventsAdaptiveGroups??[]).map((Y)=>({country:Y.dimensions.countryName,visits:Y.sum.visits}))}}GA();var GJA=7,QN2=10;function $S0(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=oz(),B=Dv(GJA),w=ZW(B),$=ZW(Q);try{let[D,Y]=await Promise.all([A.getWebsiteStats({startDate:w,endDate:$}),A.getTopPages({startDate:w,endDate:$,limit:QN2})]);return{days:GJA,startDate:w,endDate:$,pageviews:D.pageviews,visitors:D.visitors,topPages:Y}}catch(D){return{error:D instanceof Error?D.message:"Failed to fetch analytics",days:GJA}}}}var DS0={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.41",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 YS0 extends tB{cloudflareClient;constructor(A={}){super("analytics",DS0,A,UJA)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new WJA(this.config.cloudflare):void 0,A.insights.register("traffic-overview",$S0(this.cloudflareClient));let Q=this.config.cloudflare?.siteTag;if(Q)A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("plugin:site-builder:head-script:register",{pluginId:this.id,script:wS0(Q)}),{success:!0}})}async getTools(){return BS0(this.id,this.getContext(),this.cloudflareClient)}}function wN2(A={}){return new YS0(A)}var Ti=wN2;B0();GA();P6();var $N2=new Set(["description","excerpt","summary","tagline","story"]);function DN2(A){if(A.endsWith("s"))return A;return E$(A)}function JJA(A,Q=!1,B){let w=A._def.typeName;if(w==="ZodOptional"||w==="ZodNullable")return JJA(A._def.innerType,!0,B);if(w==="ZodDefault")return JJA(A._def.innerType,Q,A._def.defaultValue());return{inner:A,isOptional:Q,defaultValue:B}}function ZJA(A,Q){let{inner:B,isOptional:w,defaultValue:$}=JJA(Q),D=B._def.typeName,Y={name:A,label:fI(A),widget:"string",...w&&{required:!1},...$!==void 0&&{default:$}};switch(D){case"ZodString":{if((B._def.checks??[]).some((X)=>X.kind==="datetime"))return{...Y,widget:"datetime"};if($N2.has(A))return{...Y,widget:"text"};return{...Y,widget:"string"}}case"ZodNumber":return{...Y,widget:"number"};case"ZodBoolean":return{...Y,widget:"boolean"};case"ZodEnum":{let I=B._def.values;return{...Y,widget:"select",options:I}}case"ZodArray":{let I=B._def.type,X=ZJA("item",I);if(X.widget==="object"&&X.fields)return{...Y,widget:"list",fields:X.fields};return{...Y,widget:"list",field:{name:A,label:fI(A),widget:X.widget}}}case"ZodObject":{let I=B.shape,X=Object.entries(I).map(([H,W])=>ZJA(H,W));return{...Y,widget:"object",fields:X}}default:return{...Y,widget:"string"}}}function IS0(A,Q){let B=Object.entries(A.shape).map(([w,$])=>ZJA(w,$));if(Q)B.push({name:"body",label:"Body",widget:"markdown"});return B}function XS0(A){let Q=[],B=[];for(let w of A.entityTypes){let $=A.getFrontmatterSchema(w);if(!$)continue;let D=A.getAdapter(w),Y=D?.hasBody!==!1,I=A.entityDisplay?.[w],X=w===rv?"Note":fI(w),H=I?.label??X,W=I?.pluralName??DN2(H);if(D?.isSingleton){B.push({name:w,label:H,file:`${w}/${w}.md`,fields:IS0($,Y)});continue}if(w===rv){Q.push({name:w,label:W,folder:".",create:!0,extension:"md",format:"frontmatter",fields:[{name:"body",label:"Body",widget:"markdown"}]});continue}Q.push({name:w,label:W,folder:w,create:!0,extension:"md",format:"frontmatter",fields:IS0($,Y)})}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 FJA(A){return`<!doctype html>
2982
+ `,variables:B})});if(!w.ok){let Y=await w.text();throw Error(`Cloudflare API error: ${w.status} - ${Y}`)}let $=await w.json();if($.errors&&$.errors.length>0)throw Error(`Cloudflare GraphQL error: ${$.errors.map((Y)=>Y.message).join(", ")}`);return($.data.viewer.accounts[0]?.rumPageloadEventsAdaptiveGroups??[]).map((Y)=>({country:Y.dimensions.countryName,visits:Y.sum.visits}))}}GA();var GJA=7,QN2=10;function $S0(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=oz(),B=Dv(GJA),w=ZW(B),$=ZW(Q);try{let[D,Y]=await Promise.all([A.getWebsiteStats({startDate:w,endDate:$}),A.getTopPages({startDate:w,endDate:$,limit:QN2})]);return{days:GJA,startDate:w,endDate:$,pageviews:D.pageviews,visitors:D.visitors,topPages:Y}}catch(D){return{error:D instanceof Error?D.message:"Failed to fetch analytics",days:GJA}}}}var DS0={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.42",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 YS0 extends tB{cloudflareClient;constructor(A={}){super("analytics",DS0,A,UJA)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new WJA(this.config.cloudflare):void 0,A.insights.register("traffic-overview",$S0(this.cloudflareClient));let Q=this.config.cloudflare?.siteTag;if(Q)A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("plugin:site-builder:head-script:register",{pluginId:this.id,script:wS0(Q)}),{success:!0}})}async getTools(){return BS0(this.id,this.getContext(),this.cloudflareClient)}}function wN2(A={}){return new YS0(A)}var Ti=wN2;B0();GA();P6();var $N2=new Set(["description","excerpt","summary","tagline","story"]);function DN2(A){if(A.endsWith("s"))return A;return E$(A)}function JJA(A,Q=!1,B){let w=A._def.typeName;if(w==="ZodOptional"||w==="ZodNullable")return JJA(A._def.innerType,!0,B);if(w==="ZodDefault")return JJA(A._def.innerType,Q,A._def.defaultValue());return{inner:A,isOptional:Q,defaultValue:B}}function ZJA(A,Q){let{inner:B,isOptional:w,defaultValue:$}=JJA(Q),D=B._def.typeName,Y={name:A,label:fI(A),widget:"string",...w&&{required:!1},...$!==void 0&&{default:$}};switch(D){case"ZodString":{if((B._def.checks??[]).some((X)=>X.kind==="datetime"))return{...Y,widget:"datetime"};if($N2.has(A))return{...Y,widget:"text"};return{...Y,widget:"string"}}case"ZodNumber":return{...Y,widget:"number"};case"ZodBoolean":return{...Y,widget:"boolean"};case"ZodEnum":{let I=B._def.values;return{...Y,widget:"select",options:I}}case"ZodArray":{let I=B._def.type,X=ZJA("item",I);if(X.widget==="object"&&X.fields)return{...Y,widget:"list",fields:X.fields};return{...Y,widget:"list",field:{name:A,label:fI(A),widget:X.widget}}}case"ZodObject":{let I=B.shape,X=Object.entries(I).map(([H,W])=>ZJA(H,W));return{...Y,widget:"object",fields:X}}default:return{...Y,widget:"string"}}}function IS0(A,Q){let B=Object.entries(A.shape).map(([w,$])=>ZJA(w,$));if(Q)B.push({name:"body",label:"Body",widget:"markdown"});return B}function XS0(A){let Q=[],B=[];for(let w of A.entityTypes){let $=A.getFrontmatterSchema(w);if(!$)continue;let D=A.getAdapter(w),Y=D?.hasBody!==!1,I=A.entityDisplay?.[w],X=w===rv?"Note":fI(w),H=I?.label??X,W=I?.pluralName??DN2(H);if(D?.isSingleton){B.push({name:w,label:H,file:`${w}/${w}.md`,fields:IS0($,Y)});continue}if(w===rv){Q.push({name:w,label:W,folder:".",create:!0,extension:"md",format:"frontmatter",fields:[{name:"body",label:"Body",widget:"markdown"}]});continue}Q.push({name:w,label:W,folder:w,create:!0,extension:"md",format:"frontmatter",fields:IS0($,Y)})}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 FJA(A){return`<!doctype html>
2983
2983
  <html>
2984
2984
  <head>
2985
2985
  <meta charset="utf-8" />
@@ -2990,7 +2990,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,ez2,
2990
2990
  </head>
2991
2991
  <body></body>
2992
2992
  </html>
2993
- `}GA();var HS0={name:"@brains/cms",private:!0,version:"0.2.0-alpha.41",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 IN2=F.object({label:F.string().optional(),pluralName:F.string().optional()}).passthrough(),XN2=F.object({entityDisplay:F.record(IN2).optional(),routePath:F.string().default("/cms")});function HN2(A){return`${A.endsWith("/")?A:`${A}/`}config.yml`}function KN2(A,Q){let B=A.entityDisplay??Q?.entityDisplay;return B?{entityDisplay:B}:{}}async function UN2(A){let Q=await A.messaging.send("git-sync:get-repo-info",{});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 WN2(A,Q={}){let{repo:B,branch:w}=await UN2(A);return XS0({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 KS0(A,Q={}){return OI(await WN2(A,Q))}class qJA extends tB{constructor(A={}){super("cms",HS0,A,XN2)}async onRegister(A){await super.onRegister(A),A.endpoints.register({label:"CMS",url:this.config.routePath,priority:40})}getWebRoutes(){let A=HN2(this.config.routePath);return[{path:this.config.routePath,method:"GET",public:!0,handler:async()=>{return new Response(FJA({cmsConfigPath:A}),{headers:{"Content-Type":"text/html; charset=utf-8"}})}},{path:A,method:"GET",public:!0,handler:async()=>{try{let Q=await KS0(this.getContext(),KN2(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 $q(A){return new qJA(A)}B0();GA();GA();var vi=["StatsWidget","ListWidget","CustomWidget","PipelineWidget","IdentityWidget","ProfileWidget","SystemWidget"],GN2=new Set(vi);function zJA(A){return GN2.has(A)}var JN2=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()});class Si{widgets=new Map;logger;constructor(A){this.logger=A.child("DashboardWidgetRegistry")}register(A){let Q=`${A.pluginId}:${A.id}`;this.widgets.set(Q,A),this.logger.debug("Dashboard widget registered",{key:Q,title:A.title,rendererName:A.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){return Array.from(this.widgets.values()).filter((Q)=>!A||Q.section===A).sort((Q,B)=>Q.priority-B.priority)}get size(){return this.widgets.size}}GA();class hi{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(){let A={},Q=this.registry.list(),B=await Promise.allSettled(Q.map(async(w)=>{let $=await w.dataProvider(),{dataProvider:D,component:Y,...I}=w;return{key:`${w.pluginId}:${w.id}`,widget:I,data:$}}));for(let w=0;w<B.length;w++){let $=B[w],D=Q[w];if(!$||!D)continue;if($.status==="fulfilled")A[$.value.key]={widget:$.value.widget,data:$.value.data};else this.logger.error("Widget data provider failed",{widgetId:D.id,pluginId:D.pluginId,error:L0($.reason)})}return{widgets:A}}async fetch(A,Q,B){return await this.getDashboardData()}}import{render as mN2}from"preact-render-to-string";var US0=`
2993
+ `}GA();var HS0={name:"@brains/cms",private:!0,version:"0.2.0-alpha.42",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 IN2=F.object({label:F.string().optional(),pluralName:F.string().optional()}).passthrough(),XN2=F.object({entityDisplay:F.record(IN2).optional(),routePath:F.string().default("/cms")});function HN2(A){return`${A.endsWith("/")?A:`${A}/`}config.yml`}function KN2(A,Q){let B=A.entityDisplay??Q?.entityDisplay;return B?{entityDisplay:B}:{}}async function UN2(A){let Q=await A.messaging.send("git-sync:get-repo-info",{});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 WN2(A,Q={}){let{repo:B,branch:w}=await UN2(A);return XS0({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 KS0(A,Q={}){return OI(await WN2(A,Q))}class qJA extends tB{constructor(A={}){super("cms",HS0,A,XN2)}async onRegister(A){await super.onRegister(A),A.endpoints.register({label:"CMS",url:this.config.routePath,priority:40})}getWebRoutes(){let A=HN2(this.config.routePath);return[{path:this.config.routePath,method:"GET",public:!0,handler:async()=>{return new Response(FJA({cmsConfigPath:A}),{headers:{"Content-Type":"text/html; charset=utf-8"}})}},{path:A,method:"GET",public:!0,handler:async()=>{try{let Q=await KS0(this.getContext(),KN2(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 $q(A){return new qJA(A)}B0();GA();GA();var vi=["StatsWidget","ListWidget","CustomWidget","PipelineWidget","IdentityWidget","ProfileWidget","SystemWidget"],GN2=new Set(vi);function zJA(A){return GN2.has(A)}var JN2=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()});class Si{widgets=new Map;logger;constructor(A){this.logger=A.child("DashboardWidgetRegistry")}register(A){let Q=`${A.pluginId}:${A.id}`;this.widgets.set(Q,A),this.logger.debug("Dashboard widget registered",{key:Q,title:A.title,rendererName:A.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){return Array.from(this.widgets.values()).filter((Q)=>!A||Q.section===A).sort((Q,B)=>Q.priority-B.priority)}get size(){return this.widgets.size}}GA();class hi{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(){let A={},Q=this.registry.list(),B=await Promise.allSettled(Q.map(async(w)=>{let $=await w.dataProvider(),{dataProvider:D,component:Y,...I}=w;return{key:`${w.pluginId}:${w.id}`,widget:I,data:$}}));for(let w=0;w<B.length;w++){let $=B[w],D=Q[w];if(!$||!D)continue;if($.status==="fulfilled")A[$.value.key]={widget:$.value.widget,data:$.value.data};else this.logger.error("Widget data provider failed",{widgetId:D.id,pluginId:D.pluginId,error:L0($.reason)})}return{widgets:A}}async fetch(A,Q,B){return await this.getDashboardData()}}import{render as mN2}from"preact-render-to-string";var US0=`
2994
2994
  :root {
2995
2995
  --ink: #0a0819;
2996
2996
  --ink-raised: #14112b;
@@ -3924,7 +3924,7 @@ body::after {
3924
3924
  }
3925
3925
  });
3926
3926
  })();`;function dN2({input:A}){let Q=A.entityCounts.reduce((D,{count:Y})=>D+Y,0),B=cN2(A.widgets),w=Boolean(A.character.role)||Boolean(A.character.purpose)||A.character.values.length>0,$=A.appInfo.endpoints.length>0;return nB("html",{lang:"en","data-theme":"dark",children:[nB("head",{children:[nB("meta",{charSet:"utf-8"},void 0,!1,void 0,this),nB("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0"},void 0,!1,void 0,this),nB("title",{children:A.title},void 0,!1,void 0,this),nB("link",{rel:"preconnect",href:"https://fonts.googleapis.com"},void 0,!1,void 0,this),nB("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"},void 0,!1,void 0,this),nB("link",{href:uN2,rel:"stylesheet"},void 0,!1,void 0,this),nB("style",{dangerouslySetInnerHTML:{__html:US0}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),nB("body",{children:[nB("main",{class:"console","data-component":"dashboard:dashboard",children:[nB(GS0,{title:A.title,tagline:A.profile.description,appInfo:A.appInfo,now:new Date},void 0,!1,void 0,this),nB("section",{class:"layout",children:[nB("div",{class:"main-column",children:[nB(JS0,{total:Q,entityCounts:A.entityCounts},void 0,!1,void 0,this),B.primary.map((D)=>nB(gi,{widget:D},`${D.widget.pluginId}:${D.widget.id}`,!1,void 0,this)),B.secondary.map((D)=>nB(gi,{widget:D},`${D.widget.pluginId}:${D.widget.id}`,!1,void 0,this))]},void 0,!0,void 0,this),(w||B.sidebar.length>0||$)&&nB("div",{class:"sidebar-column",children:[nB(ZS0,{character:A.character},void 0,!1,void 0,this),B.sidebar.map((D)=>nB(gi,{widget:D},`${D.widget.pluginId}:${D.widget.id}`,!1,void 0,this)),nB(FS0,{endpoints:A.appInfo.endpoints,baseUrl:A.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),nB(VS0,{title:A.title,appInfo:A.appInfo},void 0,!1,void 0,this)]},void 0,!0,void 0,this),nB("button",{class:"theme-toggle",id:"themeToggle","aria-label":"Toggle theme",children:"Light mode"},void 0,!1,void 0,this),nB("script",{dangerouslySetInnerHTML:{__html:lN2}},void 0,!1,void 0,this),nB("script",{dangerouslySetInnerHTML:{__html:pN2}},void 0,!1,void 0,this),A.widgetScripts.map((D,Y)=>nB("script",{dangerouslySetInnerHTML:{__html:D}},`widget-script:${Y}`,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function LS0(A){return`<!doctype html>
3927
- ${mN2(nB(dN2,{input:A},void 0,!1,void 0,this))}`}function MS0(A,Q){let B={},w=new Set;for(let[$,D]of Object.entries(A)){let Y=Q?.get(D.widget.pluginId,D.widget.id);if(B[$]={...D,...Y?.component?{component:Y.component}:{}},Y?.clientScript)w.add(Y.clientScript)}return{widgets:B,widgetScripts:Array.from(w)}}var ES0={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.41",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/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 rN2=F.object({version:F.string().default("1.0.0"),routePath:F.string().default("/dashboard")}),nN2=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(),component:F.custom().optional(),clientScript:F.string().optional(),dataProvider:F.function().returns(F.promise(F.unknown()))}).superRefine((A,Q)=>{if(!zJA(A.rendererName)&&!A.component)Q.addIssue({code:F.ZodIssueCode.custom,message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),oN2=F.object({pluginId:F.string(),widgetId:F.string().optional()});function sN2(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,...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider}}class LJA extends tB{widgetRegistry=null;datasource=null;siteUrl;ctx;constructor(A){super("dashboard",ES0,A??{},rN2)}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new Si(this.logger),this.datasource=new hi(this.widgetRegistry,this.logger),A.entities.registerDataSource(this.datasource),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let B=nN2.parse(Q.payload),w=sN2(B);return this.widgetRegistry?.register(w),this.logger.debug("Widget registered via messaging",{widgetId:B.id,pluginId:B.pluginId,rendererName:B.rendererName,builtIn:vi.includes(B.rendererName)}),{success:!0}}catch(B){return this.logger.error("Failed to register widget",{error:L0(B),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{let B=oN2.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,w,$]=await Promise.all([this.datasource.getDashboardData(),Q.appInfo(),Q.entityService.getEntityCounts()]),D=Q.identity.get(),Y=Q.identity.getProfile(),I=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),X=Y.name||w.model||"Brain Dashboard",H=MS0(B.widgets,this.widgetRegistry),W={title:X,baseUrl:I,widgets:H.widgets,widgetScripts:H.widgetScripts,character:D,profile:Y,appInfo:w,entityCounts:$};return new Response(LS0(W),{headers:{"Content-Type":"text/html; charset=utf-8"}})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function IJ(A){return new LJA(A)}GA();var aN2=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(),component:F.custom().optional()}),tN2=F.object({widget:aN2,data:F.unknown()}),eN2=F.object({widgets:F.record(tN2)});GA();B0();GA();import{h as GV2}from"preact";GA();aD();B0();var tM=F.enum(["draft","queued","published","failed"]),Qb=F.object({subject:F.string(),status:tM,entityIds:F.array(F.string()).optional(),scheduledFor:F.string().datetime().optional(),sentAt:F.string().datetime().optional(),buttondownId:F.string().optional(),sourceEntityType:F.string().optional()}),CS0=Qb.pick({subject:!0,status:!0,entityIds:!0,scheduledFor:!0,sentAt:!0,buttondownId:!0,sourceEntityType:!0}),Bb=Q2.extend({entityType:F.literal("newsletter"),metadata:CS0});B0();class OS0 extends I2{constructor(){super({entityType:"newsletter",schema:Bb,frontmatterSchema:Qb})}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 fS0=new OS0;B0();B0();GA();var AV2=yI.extend({status:F.enum(["draft","queued","published","failed"]).optional()}),QV2=mI.extend({query:AV2.optional()});function RS0(A){try{let{content:Q}=G2(A.content,Qb);return Q}catch{return A.content}}class MJA extends s5{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=QV2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=RS0(A),B={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:JW(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 D=w.status,Y=D?{filter:{metadata:{status:D}}}:void 0,{items:I,pagination:X}=await this.fetchList(w,$,Y);return Q.parse(this.buildListResult(I,X,w))}async fetchSingleNewsletter(A,Q,B){let w=await B.getEntity(this.config.entityType,A);if(!w)throw Error(`Newsletter not found: ${A}`);let $=await this.resolveNavigation(w,B),D=[];if(w.metadata.entityIds?.length){let X=w.metadata.sourceEntityType??"post";D=(await Promise.all(w.metadata.entityIds.map(async(W)=>{let J=await B.getEntity(X,W);if(J){let Z=J.metadata;return{id:W,title:Z.title??W,url:`/${X}s/${Z.slug??W}`}}return null}))).filter((W)=>W!==null)}let Y=RS0(w),I={id:w.id,subject:w.metadata.subject,status:w.metadata.status,content:Y,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:D.length>0?D:void 0};return Q.parse(I)}}B0();GA();var BV2=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 EJA extends Q9{constructor(A,Q){super(A,Q,{schema:BV2,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let B=A.addToQueue??!1,{prompt:w,sourceEntityIds:$,sourceEntityType:D}=A,{content:Y,subject:I}=A;if(Y){if(!I)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if($&&$.length>0){let Z=D??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${$.length} source entities`});let V=(await Promise.all($.map((k)=>this.context.entityService.getEntity(Z,k)))).filter((k)=>k!=null);if(V.length===0)this.failEarly(`No source entities found for IDs: ${$.join(", ")}`);await this.reportProgress(Q,{progress:30,message:`Generating newsletter from ${V.length} posts`});let L=`Create an engaging newsletter that highlights these blog posts:
3927
+ ${mN2(nB(dN2,{input:A},void 0,!1,void 0,this))}`}function MS0(A,Q){let B={},w=new Set;for(let[$,D]of Object.entries(A)){let Y=Q?.get(D.widget.pluginId,D.widget.id);if(B[$]={...D,...Y?.component?{component:Y.component}:{}},Y?.clientScript)w.add(Y.clientScript)}return{widgets:B,widgetScripts:Array.from(w)}}var ES0={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.42",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/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 rN2=F.object({version:F.string().default("1.0.0"),routePath:F.string().default("/dashboard")}),nN2=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(),component:F.custom().optional(),clientScript:F.string().optional(),dataProvider:F.function().returns(F.promise(F.unknown()))}).superRefine((A,Q)=>{if(!zJA(A.rendererName)&&!A.component)Q.addIssue({code:F.ZodIssueCode.custom,message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),oN2=F.object({pluginId:F.string(),widgetId:F.string().optional()});function sN2(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,...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider}}class LJA extends tB{widgetRegistry=null;datasource=null;siteUrl;ctx;constructor(A){super("dashboard",ES0,A??{},rN2)}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new Si(this.logger),this.datasource=new hi(this.widgetRegistry,this.logger),A.entities.registerDataSource(this.datasource),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let B=nN2.parse(Q.payload),w=sN2(B);return this.widgetRegistry?.register(w),this.logger.debug("Widget registered via messaging",{widgetId:B.id,pluginId:B.pluginId,rendererName:B.rendererName,builtIn:vi.includes(B.rendererName)}),{success:!0}}catch(B){return this.logger.error("Failed to register widget",{error:L0(B),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{let B=oN2.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,w,$]=await Promise.all([this.datasource.getDashboardData(),Q.appInfo(),Q.entityService.getEntityCounts()]),D=Q.identity.get(),Y=Q.identity.getProfile(),I=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),X=Y.name||w.model||"Brain Dashboard",H=MS0(B.widgets,this.widgetRegistry),W={title:X,baseUrl:I,widgets:H.widgets,widgetScripts:H.widgetScripts,character:D,profile:Y,appInfo:w,entityCounts:$};return new Response(LS0(W),{headers:{"Content-Type":"text/html; charset=utf-8"}})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function IJ(A){return new LJA(A)}GA();var aN2=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(),component:F.custom().optional()}),tN2=F.object({widget:aN2,data:F.unknown()}),eN2=F.object({widgets:F.record(tN2)});GA();B0();GA();import{h as GV2}from"preact";GA();aD();B0();var tM=F.enum(["draft","queued","published","failed"]),Qb=F.object({subject:F.string(),status:tM,entityIds:F.array(F.string()).optional(),scheduledFor:F.string().datetime().optional(),sentAt:F.string().datetime().optional(),buttondownId:F.string().optional(),sourceEntityType:F.string().optional()}),CS0=Qb.pick({subject:!0,status:!0,entityIds:!0,scheduledFor:!0,sentAt:!0,buttondownId:!0,sourceEntityType:!0}),Bb=Q2.extend({entityType:F.literal("newsletter"),metadata:CS0});B0();class OS0 extends I2{constructor(){super({entityType:"newsletter",schema:Bb,frontmatterSchema:Qb})}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 fS0=new OS0;B0();B0();GA();var AV2=yI.extend({status:F.enum(["draft","queued","published","failed"]).optional()}),QV2=mI.extend({query:AV2.optional()});function RS0(A){try{let{content:Q}=G2(A.content,Qb);return Q}catch{return A.content}}class MJA extends s5{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=QV2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=RS0(A),B={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:JW(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 D=w.status,Y=D?{filter:{metadata:{status:D}}}:void 0,{items:I,pagination:X}=await this.fetchList(w,$,Y);return Q.parse(this.buildListResult(I,X,w))}async fetchSingleNewsletter(A,Q,B){let w=await B.getEntity(this.config.entityType,A);if(!w)throw Error(`Newsletter not found: ${A}`);let $=await this.resolveNavigation(w,B),D=[];if(w.metadata.entityIds?.length){let X=w.metadata.sourceEntityType??"post";D=(await Promise.all(w.metadata.entityIds.map(async(W)=>{let J=await B.getEntity(X,W);if(J){let Z=J.metadata;return{id:W,title:Z.title??W,url:`/${X}s/${Z.slug??W}`}}return null}))).filter((W)=>W!==null)}let Y=RS0(w),I={id:w.id,subject:w.metadata.subject,status:w.metadata.status,content:Y,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:D.length>0?D:void 0};return Q.parse(I)}}B0();GA();var BV2=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 EJA extends Q9{constructor(A,Q){super(A,Q,{schema:BV2,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let B=A.addToQueue??!1,{prompt:w,sourceEntityIds:$,sourceEntityType:D}=A,{content:Y,subject:I}=A;if(Y){if(!I)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if($&&$.length>0){let Z=D??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${$.length} source entities`});let V=(await Promise.all($.map((k)=>this.context.entityService.getEntity(Z,k)))).filter((k)=>k!=null);if(V.length===0)this.failEarly(`No source entities found for IDs: ${$.join(", ")}`);await this.reportProgress(Q,{progress:30,message:`Generating newsletter from ${V.length} posts`});let L=`Create an engaging newsletter that highlights these blog posts:
3928
3928
 
3929
3929
  ${V.map((k)=>`## ${k.metadata.title}
3930
3930
 
@@ -3993,12 +3993,12 @@ Newsletter-specific guidelines:
3993
3993
  - "Reply and let me know..."
3994
3994
  - "Until next time..."
3995
3995
 
3996
- The goal is to build a relationship with readers through valuable, authentic content.`});GA();B0();import{jsxDEV as K7,Fragment as IV2}from"preact/jsx-dev-runtime";var $V2=F.object({id:F.string(),subject:F.string(),status:tM,excerpt:F.string(),created:F.string(),sentAt:F.string().optional(),url:F.string()}),DV2=F.object({newsletters:F.array($V2),totalCount:F.number(),pagination:P7.nullable()}),YV2=({newsletters:A,totalCount:Q,pageTitle:B,pagination:w,baseUrl:$="/newsletters"})=>{let D=B??"Newsletters",Y=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return K7(IV2,{children:[K7(n2,{title:D,description:Y},void 0,!1,void 0,this),K7("div",{className:"newsletter-list bg-theme",children:K7("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[K7("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:D},void 0,!1,void 0,this),A.length===0?K7("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):K7("div",{className:"space-y-4",children:A.map((I)=>K7(MQ,{href:I.url,children:[K7(G9,{className:"text-lg",children:I.subject},void 0,!1,void 0,this),K7(D7,{children:K7("div",{className:"flex items-center gap-3",children:[K7(r7,{status:I.status},void 0,!1,void 0,this),K7("span",{className:"text-sm text-theme-muted",children:m8(I.sentAt??I.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),I.excerpt&&K7("p",{className:"text-theme-muted line-clamp-2",children:I.excerpt},void 0,!1,void 0,this)]},I.id,!0,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&K7(jY,{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)},kS0=M1({name:"newsletter-list",description:"Newsletter list page template",schema:DV2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:YV2}});GA();B0();import{jsxDEV as D8,Fragment as UV2}from"preact/jsx-dev-runtime";var XV2=F.object({id:F.string(),title:F.string(),url:F.string()}),PS0=F.object({id:F.string(),subject:F.string(),url:F.string()}),HV2=F.object({id:F.string(),subject:F.string(),status:tM,content:F.string(),created:F.string(),updated:F.string(),sentAt:F.string().optional(),scheduledFor:F.string().optional(),sourceEntities:F.array(XV2).optional(),prevNewsletter:PS0.nullable().optional(),nextNewsletter:PS0.nullable().optional()}),KV2=({subject:A,status:Q,content:B,created:w,sentAt:$,scheduledFor:D,sourceEntities:Y,prevNewsletter:I,nextNewsletter:X})=>{let H=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],W=$??w,J=$?"Sent":"Created";return D8(UV2,{children:[D8(n2,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),D8("section",{className:"newsletter-detail-section",children:D8("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:D8("div",{className:"max-w-3xl mx-auto",children:[D8(AD,{items:H},void 0,!1,void 0,this),D8("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),D8("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[D8(r7,{status:Q},void 0,!1,void 0,this),D8("span",{children:[J,": ",m8(W,{style:"long"})]},void 0,!0,void 0,this),D&&Q==="queued"&&D8("span",{children:["Scheduled for: ",m8(D,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Y&&Y.length>0&&D8(MQ,{variant:"compact",className:"mb-8",children:[D8("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),D8("ul",{className:"space-y-1",children:Y.map((Z)=>D8("li",{children:D8("a",{href:Z.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:Z.title},void 0,!1,void 0,this)},Z.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D8(RY,{markdown:B},void 0,!1,void 0,this),(I??X)&&D8("nav",{className:"mt-12 pt-8 border-t border-theme",children:D8("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[I?D8(MQ,{href:I.url,variant:"compact",children:[D8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),D8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:I.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this):D8("div",{},void 0,!1,void 0,this),X&&D8(MQ,{href:X.url,variant:"compact",className:"md:text-right",children:[D8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),D8("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)},_S0=M1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:HV2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:KV2}});var bS0={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.41",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/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 JV2=F.object({});class CJA extends HQ{entityType="newsletter";schema=Bb;adapter=fS0;constructor(A={}){super("newsletter",bS0,A,JV2)}createGenerationHandler(A){return new EJA(this.logger,A)}getTemplates(){return{generation:jS0,"newsletter-list":kS0,"newsletter-detail":_S0}}getDataSources(){return[new MJA(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("buttondown:is-configured",{});if(!("noop"in Q)&&Q.success)await A.messaging.send("plugin:site-builder:slot:register",{pluginId:this.id,slotName:"footer-top",render:()=>GV2(AKA,{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("publish:register",{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("newsletter",w);if(!$)return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:`Newsletter not found: ${w}`}),{success:!0};if($.metadata.status==="published")return{success:!0};let D=await A.messaging.send("buttondown:send",{entityId:w,subject:$.metadata.subject,content:$.content}),Y=new Date().toISOString(),I=!("noop"in D)&&D.data?D.data.emailId:void 0;return await A.entityService.updateEntity({...$,metadata:{...$.metadata,status:"published",sentAt:Y,buttondownId:I}}),await A.messaging.send("publish:report:success",{entityType:B,entityId:w,sentAt:Y}),this.logger.info(`Published newsletter: ${w}`),{success:!0}}catch($){let D=L0($);return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:D}),{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("post",{filter:{metadata:{status:"published"}},limit:10});if(B.length===0)return await A.messaging.send("generate:report:failure",{entityType:"newsletter",error:"No published posts available for newsletter"}),{success:!0};return await A.jobs.enqueue("newsletter:generation",{sourceEntityIds:B.map((w)=>w.id),sourceEntityType:"post",addToQueue:!1},{interfaceType:"job",userId:"system"}),{success:!0}}catch(B){return await A.messaging.send("generate:report:failure",{entityType:"newsletter",error:L0(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:
3996
+ The goal is to build a relationship with readers through valuable, authentic content.`});GA();B0();import{jsxDEV as K7,Fragment as IV2}from"preact/jsx-dev-runtime";var $V2=F.object({id:F.string(),subject:F.string(),status:tM,excerpt:F.string(),created:F.string(),sentAt:F.string().optional(),url:F.string()}),DV2=F.object({newsletters:F.array($V2),totalCount:F.number(),pagination:P7.nullable()}),YV2=({newsletters:A,totalCount:Q,pageTitle:B,pagination:w,baseUrl:$="/newsletters"})=>{let D=B??"Newsletters",Y=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return K7(IV2,{children:[K7(n2,{title:D,description:Y},void 0,!1,void 0,this),K7("div",{className:"newsletter-list bg-theme",children:K7("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[K7("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:D},void 0,!1,void 0,this),A.length===0?K7("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):K7("div",{className:"space-y-4",children:A.map((I)=>K7(MQ,{href:I.url,children:[K7(G9,{className:"text-lg",children:I.subject},void 0,!1,void 0,this),K7(D7,{children:K7("div",{className:"flex items-center gap-3",children:[K7(r7,{status:I.status},void 0,!1,void 0,this),K7("span",{className:"text-sm text-theme-muted",children:m8(I.sentAt??I.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),I.excerpt&&K7("p",{className:"text-theme-muted line-clamp-2",children:I.excerpt},void 0,!1,void 0,this)]},I.id,!0,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&K7(jY,{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)},kS0=M1({name:"newsletter-list",description:"Newsletter list page template",schema:DV2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:YV2}});GA();B0();import{jsxDEV as D8,Fragment as UV2}from"preact/jsx-dev-runtime";var XV2=F.object({id:F.string(),title:F.string(),url:F.string()}),PS0=F.object({id:F.string(),subject:F.string(),url:F.string()}),HV2=F.object({id:F.string(),subject:F.string(),status:tM,content:F.string(),created:F.string(),updated:F.string(),sentAt:F.string().optional(),scheduledFor:F.string().optional(),sourceEntities:F.array(XV2).optional(),prevNewsletter:PS0.nullable().optional(),nextNewsletter:PS0.nullable().optional()}),KV2=({subject:A,status:Q,content:B,created:w,sentAt:$,scheduledFor:D,sourceEntities:Y,prevNewsletter:I,nextNewsletter:X})=>{let H=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],W=$??w,J=$?"Sent":"Created";return D8(UV2,{children:[D8(n2,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),D8("section",{className:"newsletter-detail-section",children:D8("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:D8("div",{className:"max-w-3xl mx-auto",children:[D8(AD,{items:H},void 0,!1,void 0,this),D8("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),D8("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[D8(r7,{status:Q},void 0,!1,void 0,this),D8("span",{children:[J,": ",m8(W,{style:"long"})]},void 0,!0,void 0,this),D&&Q==="queued"&&D8("span",{children:["Scheduled for: ",m8(D,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Y&&Y.length>0&&D8(MQ,{variant:"compact",className:"mb-8",children:[D8("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),D8("ul",{className:"space-y-1",children:Y.map((Z)=>D8("li",{children:D8("a",{href:Z.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:Z.title},void 0,!1,void 0,this)},Z.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D8(RY,{markdown:B},void 0,!1,void 0,this),(I??X)&&D8("nav",{className:"mt-12 pt-8 border-t border-theme",children:D8("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[I?D8(MQ,{href:I.url,variant:"compact",children:[D8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),D8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:I.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this):D8("div",{},void 0,!1,void 0,this),X&&D8(MQ,{href:X.url,variant:"compact",className:"md:text-right",children:[D8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),D8("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)},_S0=M1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:HV2,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:KV2}});var bS0={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.42",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/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 JV2=F.object({});class CJA extends HQ{entityType="newsletter";schema=Bb;adapter=fS0;constructor(A={}){super("newsletter",bS0,A,JV2)}createGenerationHandler(A){return new EJA(this.logger,A)}getTemplates(){return{generation:jS0,"newsletter-list":kS0,"newsletter-detail":_S0}}getDataSources(){return[new MJA(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("buttondown:is-configured",{});if(!("noop"in Q)&&Q.success)await A.messaging.send("plugin:site-builder:slot:register",{pluginId:this.id,slotName:"footer-top",render:()=>GV2(AKA,{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("publish:register",{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("newsletter",w);if(!$)return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:`Newsletter not found: ${w}`}),{success:!0};if($.metadata.status==="published")return{success:!0};let D=await A.messaging.send("buttondown:send",{entityId:w,subject:$.metadata.subject,content:$.content}),Y=new Date().toISOString(),I=!("noop"in D)&&D.data?D.data.emailId:void 0;return await A.entityService.updateEntity({...$,metadata:{...$.metadata,status:"published",sentAt:Y,buttondownId:I}}),await A.messaging.send("publish:report:success",{entityType:B,entityId:w,sentAt:Y}),this.logger.info(`Published newsletter: ${w}`),{success:!0}}catch($){let D=L0($);return await A.messaging.send("publish:report:failure",{entityType:B,entityId:w,error:D}),{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("post",{filter:{metadata:{status:"published"}},limit:10});if(B.length===0)return await A.messaging.send("generate:report:failure",{entityType:"newsletter",error:"No published posts available for newsletter"}),{success:!0};return await A.jobs.enqueue("newsletter:generation",{sourceEntityIds:B.map((w)=>w.id),sourceEntityType:"post",addToQueue:!1},{interfaceType:"job",userId:"system"}),{success:!0}}catch(B){return await A.messaging.send("generate:report:failure",{entityType:"newsletter",error:L0(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:
3997
3997
 
3998
- ${w.content}`:w.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function OJA(A={}){return new CJA(A)}B0();GA();class eM{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(()=>({})),D=$.detail??$.message??`HTTP ${w.status}`;throw this.logger.error("Buttondown API error",{endpoint:A,status:w.status,error:D}),Error(`Buttondown API error: ${D}`)}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}}}B0();GA();var ZV2=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)")}),FV2=F.object({email:F.string().email().describe("Email address to unsubscribe")}),qV2=F.object({type:F.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:F.number().optional().describe("Maximum number of results")});function xS0(A,Q,B){let w=new eM(Q,B);return[yQ(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",ZV2,async($)=>{try{let D=await w.createSubscriber({email:$.email,...$.name&&{name:$.name},...$.tags&&{tags:$.tags}}),Y=D.subscriber_type==="already_subscribed";return O5({subscriberId:D.id,email:D.email,status:D.subscriber_type,message:Y?"already_subscribed":"subscribed"},Y?`${$.email} is already subscribed`:`Subscribed ${$.email} successfully`)}catch(D){return Ew(L0(D))}}),yQ(A,"unsubscribe","Unsubscribe an email address from the newsletter.",FV2,async($)=>{try{return await w.unsubscribe($.email),O5({email:$.email},`Unsubscribed ${$.email} successfully`)}catch(D){return Ew(L0(D))}}),yQ(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",qV2,async($)=>{try{let D=await w.listSubscribers({...$.type&&{type:$.type},...$.limit&&{limit:$.limit}});return O5({subscribers:D.results.map((Y)=>({id:Y.id,email:Y.email,status:Y.subscriber_type})),count:D.count},`Found ${D.count} subscribers`)}catch(D){return Ew(L0(D))}})]}GA();async function TS0(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("post",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 D=await Q.createEmail({subject:$.metadata.title,body:$.content,status:"about_to_send"});return w.info("Newsletter sent for post",{postId:$.id,emailId:D.id}),{success:!0,emailId:D.id}}catch(D){let Y=L0(D);return w.error("Failed to send newsletter for post",{postId:$.id,error:Y}),{success:!1,error:Y}}}var vS0={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.41",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 NV2=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 fJA extends tB{constructor(A={}){super("buttondown",vS0,A,NV2)}async onRegister(A){if(A.messaging.subscribe("buttondown:is-configured",async()=>{return{success:!!this.config.apiKey}}),this.config.apiKey){let Q=new eM({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:L0(w)}),{success:!1}}}),this.config.autoSendOnPublish)A.messaging.subscribe("publish:completed",async(B)=>{return await TS0(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 xS0(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 RJA(A={}){return new fJA(A)}var VV2=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 SS0(A={}){let Q=VV2.parse(A);return[OJA({}),RJA({...Q.apiKey!==void 0&&{apiKey:Q.apiKey},...Q.doubleOptIn!==void 0&&{doubleOptIn:Q.doubleOptIn},...Q.autoSendOnPublish!==void 0&&{autoSendOnPublish:Q.autoSendOnPublish}})]}B0();GA();import{existsSync as bV2,mkdirSync as xV2,writeFileSync as TV2}from"fs";import{join as QU}from"path";GA();var jJA=F.object({baseFolder:F.string().default("_obsidian")});GA();function LV2(A){let Q=A,B=!0,w=void 0,$=!1,D=!0;while(D){if(D=!1,Q instanceof F.ZodOptional)B=!1,Q=Q._def.innerType,D=!0;if(Q instanceof F.ZodDefault)B=!1,$=!0,w=Q._def.defaultValue(),Q=Q._def.innerType,D=!0;if(Q instanceof F.ZodNullable)B=!1,Q=Q._def.innerType,D=!0}let Y={inner:Q,required:B};if($)Y.defaultValue=w;return Y}function MV2(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 hS0(A){let Q=A.shape,B=[];for(let[w,$]of Object.entries(Q)){let{inner:D,required:Y,defaultValue:I}=LV2($),X=MV2(D),H={name:w,type:X.type,required:Y},W=I!==void 0?I:X.defaultValue;if(W!==void 0)H.defaultValue=W;if(X.enumValues)H.enumValues=X.enumValues;B.push(H)}return B}function EV2(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 gS0(A,Q,B=""){let w=["---"];for(let $ of Q){let D=EV2($,A);if(D==="")w.push(`${$.name}:`);else w.push(`${$.name}: ${D}`)}if(w.push("---"),w.push(""),B)w.push(B);else w.push("<!-- Write your content here -->"),w.push("");return w.join(`
3998
+ ${w.content}`:w.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function OJA(A={}){return new CJA(A)}B0();GA();class eM{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(()=>({})),D=$.detail??$.message??`HTTP ${w.status}`;throw this.logger.error("Buttondown API error",{endpoint:A,status:w.status,error:D}),Error(`Buttondown API error: ${D}`)}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}}}B0();GA();var ZV2=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)")}),FV2=F.object({email:F.string().email().describe("Email address to unsubscribe")}),qV2=F.object({type:F.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:F.number().optional().describe("Maximum number of results")});function xS0(A,Q,B){let w=new eM(Q,B);return[yQ(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",ZV2,async($)=>{try{let D=await w.createSubscriber({email:$.email,...$.name&&{name:$.name},...$.tags&&{tags:$.tags}}),Y=D.subscriber_type==="already_subscribed";return O5({subscriberId:D.id,email:D.email,status:D.subscriber_type,message:Y?"already_subscribed":"subscribed"},Y?`${$.email} is already subscribed`:`Subscribed ${$.email} successfully`)}catch(D){return Ew(L0(D))}}),yQ(A,"unsubscribe","Unsubscribe an email address from the newsletter.",FV2,async($)=>{try{return await w.unsubscribe($.email),O5({email:$.email},`Unsubscribed ${$.email} successfully`)}catch(D){return Ew(L0(D))}}),yQ(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",qV2,async($)=>{try{let D=await w.listSubscribers({...$.type&&{type:$.type},...$.limit&&{limit:$.limit}});return O5({subscribers:D.results.map((Y)=>({id:Y.id,email:Y.email,status:Y.subscriber_type})),count:D.count},`Found ${D.count} subscribers`)}catch(D){return Ew(L0(D))}})]}GA();async function TS0(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("post",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 D=await Q.createEmail({subject:$.metadata.title,body:$.content,status:"about_to_send"});return w.info("Newsletter sent for post",{postId:$.id,emailId:D.id}),{success:!0,emailId:D.id}}catch(D){let Y=L0(D);return w.error("Failed to send newsletter for post",{postId:$.id,error:Y}),{success:!1,error:Y}}}var vS0={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.42",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 NV2=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 fJA extends tB{constructor(A={}){super("buttondown",vS0,A,NV2)}async onRegister(A){if(A.messaging.subscribe("buttondown:is-configured",async()=>{return{success:!!this.config.apiKey}}),this.config.apiKey){let Q=new eM({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:L0(w)}),{success:!1}}}),this.config.autoSendOnPublish)A.messaging.subscribe("publish:completed",async(B)=>{return await TS0(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 xS0(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 RJA(A={}){return new fJA(A)}var VV2=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 SS0(A={}){let Q=VV2.parse(A);return[OJA({}),RJA({...Q.apiKey!==void 0&&{apiKey:Q.apiKey},...Q.doubleOptIn!==void 0&&{doubleOptIn:Q.doubleOptIn},...Q.autoSendOnPublish!==void 0&&{autoSendOnPublish:Q.autoSendOnPublish}})]}B0();GA();import{existsSync as bV2,mkdirSync as xV2,writeFileSync as TV2}from"fs";import{join as QU}from"path";GA();var jJA=F.object({baseFolder:F.string().default("_obsidian")});GA();function LV2(A){let Q=A,B=!0,w=void 0,$=!1,D=!0;while(D){if(D=!1,Q instanceof F.ZodOptional)B=!1,Q=Q._def.innerType,D=!0;if(Q instanceof F.ZodDefault)B=!1,$=!0,w=Q._def.defaultValue(),Q=Q._def.innerType,D=!0;if(Q instanceof F.ZodNullable)B=!1,Q=Q._def.innerType,D=!0}let Y={inner:Q,required:B};if($)Y.defaultValue=w;return Y}function MV2(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 hS0(A){let Q=A.shape,B=[];for(let[w,$]of Object.entries(Q)){let{inner:D,required:Y,defaultValue:I}=LV2($),X=MV2(D),H={name:w,type:X.type,required:Y},W=I!==void 0?I:X.defaultValue;if(W!==void 0)H.defaultValue=W;if(X.enumValues)H.enumValues=X.enumValues;B.push(H)}return B}function EV2(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 gS0(A,Q,B=""){let w=["---"];for(let $ of Q){let D=EV2($,A);if(D==="")w.push(`${$.name}:`);else w.push(`${$.name}: ${D}`)}if(w.push("---"),w.push(""),B)w.push(B);else w.push("<!-- Write your content here -->"),w.push("");return w.join(`
3999
3999
  `)}GA();var CV2={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function OV2(A){let Q={name:A.name,id:A.name,type:CV2[A.type]};if(A.type==="enum"&&A.enumValues){let B={};A.enumValues.forEach((w,$)=>{B[String($)]=w}),Q.options=B}return Q}function yS0(A,Q){let B={filesPaths:A,fields:Q.map(OV2)};return`---
4000
4000
  ${OI(B)}---
4001
- `}GA();var fV2=new Set(["entityType"]),RV2={base:"Notes"},jV2=new Set(["base"]);function kV2(A){let Q=["file.name"];for(let B of A)if(!fV2.has(B.name))Q.push(B.name);return Q}function PV2(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function mS0(A,Q){let B=RV2[A]??Qv(A),w=PV2(Q),$=kV2(Q),D=[{type:"table",name:`All ${B}`,order:$}];if(w)D.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:$});let I={filters:{and:[jV2.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:D};return{filename:`${B}.base`,content:OI(I),hasStatus:w}}function uS0(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 OI(B)}function cS0(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 OI(B)}var lS0={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.41",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 vV2={mkdir:xV2,writeFile:TV2,existsFile:bV2},SV2=F.object({entityTypes:F.array(F.string()).optional().describe("Entity types to generate templates for (default: all)")});class kJA extends tB{deps;constructor(A={},Q={}){super("obsidian-vault",lS0,A,jJA);this.deps={...vV2,...Q}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return this.logger.info("Auto-syncing Obsidian templates, fileClasses, and bases"),await this.sync(A),{success:!0}})}async getTools(){let A=this.getContext();return[yQ(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",SV2,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,$=QU(A.dataDir,this.config.baseFolder),D=QU($,"templates"),Y=QU($,"fileClasses"),I=QU($,"bases");this.deps.mkdir(D,{recursive:!0}),this.deps.mkdir(Y,{recursive:!0}),this.deps.mkdir(I,{recursive:!0});let X=[],H=[],W=[],J=[],Z=[],q=[];for(let L of w){let j=A.entities.getEffectiveFrontmatterSchema(L);if(!j){this.logger.debug(`Skipping ${L}: no frontmatter schema`),H.push(L);continue}let _=hS0(j),k=A.entities.getAdapter(L),r=k?.isSingleton===!0,n=yS0(L,_);if(this.deps.writeFile(QU(Y,`${L}.md`),n),W.push(L),r){Z.push(L),this.logger.debug(`Generated fileClass (singleton): ${L}`);continue}let h=k?.getBodyTemplate()??"",T=gS0(L,_,h);this.deps.writeFile(QU(D,`${L}.md`),T),X.push(L);let S=mS0(L,_),y=QU(I,S.filename);if(!this.deps.existsFile(y))this.deps.writeFile(y,S.content),J.push(L),this.logger.debug(`Generated base: ${S.filename}`);if(S.hasStatus)q.push({entityType:L,fields:_});this.logger.debug(`Generated template + fileClass: ${L}`)}let V=uS0(Z);if(V){let L=QU(I,"Settings.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,V),J.push("Settings"),this.logger.debug("Generated Settings.base")}let E=cS0(q);if(E){let L=QU(I,"Pipeline.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,E),J.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${X.length} templates, ${W.length} fileClasses, ${J.length} bases (${H.length} skipped)`),O5({generated:X,skipped:H,fileClasses:W,bases:J})}catch(B){return this.logger.error("Failed to sync",{error:B}),Ew(B instanceof Error?B.message:"Unknown error")}}}function PJA(A,Q){return new kJA(A,Q)}B0();GA();B0();var _JA=F.enum(["new","planned","in-progress","done","declined"]),bJA=F.enum(["low","medium","high","critical"]),wb=F.object({title:F.string(),status:_JA,priority:bJA.default("medium"),requested:F.number().int().default(1),declinedReason:F.string().optional()}),pS0=F.object({title:F.string(),status:_JA,priority:bJA,requested:F.number().int(),slug:F.string()}),$b=Q2.extend({entityType:F.literal("wish"),metadata:pS0}),xJA=F.object({});B0();GA();class Db extends I2{constructor(){super({entityType:"wish",schema:$b,frontmatterSchema:wb})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,wb);return{frontmatter:wb.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),B=e1(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:B}}}}var TJA=new Db;GA();GA();async function dS0(A,Q){let B=`${Q.title}: ${Q.description}`,$=(await A.search(B,{types:["wish"],limit:1}))[0];if($&&$.score>=A.similarityThreshold)return $.entity;let D=e1(Q.title);return A.getEntity("wish",D)}class yi{logger;context;adapter=new Db;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??"",D=await dS0({search:(H,W)=>this.context.entityService.search(H,W),getEntity:(H,W)=>this.context.entityService.getEntity(H,W),similarityThreshold:0.85},{title:w,description:$});if(D){let{frontmatter:H,description:W}=this.adapter.parseWishContent(D.content),J=H.requested+1,Z=this.adapter.createWishContent({...H,requested:J},W);return await this.context.entityService.updateEntity({...D,content:Z,metadata:{...D.metadata,requested:J}}),this.logger.info("Incremented wish request count",{id:D.id,requested:J}),{success:!0,entityId:D.id,existed:!0,requested:J}}let Y=e1(w),I=A.options?.priority??"medium",X=this.adapter.createWishContent({title:w,status:"new",priority:I,requested:1},$);return await this.context.entityService.createEntity({id:Y,entityType:"wish",content:X,metadata:{title:w,status:"new",priority:I,requested:1,slug:Y}}),this.logger.info("Created new wish",{id:Y,title:w}),{success:!0,entityId:Y,existed:!1,requested:1}}}var iS0={critical:0,high:1,medium:2,low:3};function rS0(A){A.sort((Q,B)=>{let w=B.metadata.requested-Q.metadata.requested;if(w!==0)return w;return iS0[Q.metadata.priority]-iS0[B.metadata.priority]})}var nS0={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.41",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 oS0 extends HQ{entityType=TJA.entityType;schema=$b;adapter=TJA;constructor(A={}){super("wishlist",nS0,A,xJA)}async interceptCreate(A,Q,B){let w=await new yi(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("dashboard:register-widget",{id:"top-wishes",pluginId:this.id,title:"Top Wishes",section:"secondary",priority:30,rendererName:"ListWidget",dataProvider:async()=>{let B=await A.entityService.listEntities("wish",{limit:10});return rS0(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 yi(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:(B)=>B})}async getInstructions(){return"**CRITICAL \u2014 Unfulfilled requests**: ALWAYS call `system_create` with entityType "+`"wish" BEFORE responding when you cannot fulfill a user's request. This applies to ALL unfulfillable requests: physical actions, missing integrations, and any 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. CRITICAL exception: for A2A agent-contact requests, never create a wish for a missing, ambiguous, archived, URL-only, unsaved-domain, or not-yet-saved local agent-directory target. 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". Those are save-first directory cases, not wishlist cases. In those cases, tell the user to add/save or clarify the agent first. Never call system_create with entityType "wish" for those agent-contact cases. Only create or save an agent entry if the user explicitly asks you to add or save that agent.'}}function gV2(A={}){return new oS0(A)}var mi=gV2;B0();GA();B0();var Yb=F.object({title:F.string(),target:F.string()}),sS0=F.object({title:F.string(),target:F.string(),slug:F.string().optional()}),Ib=Q2.extend({entityType:F.literal("prompt"),metadata:sS0});B0();GA();class vJA extends I2{constructor(){super({entityType:"prompt",schema:Ib,frontmatterSchema:Yb})}toMarkdown(A){let Q=this.extractBody(A.content),B=this.parseFrontMatter(A.content,Yb);return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Yb),B=e1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:B}}}}var ui=new vJA;var aS0={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.41",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 SJA extends HQ{entityType=ui.entityType;schema=Ib;adapter=ui;constructor(){super("prompt",aS0,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function Yq(){return new SJA}B0();GA();class ci{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(mV2),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function mV2(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}}GA();var tS0={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")},eS0={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 Qh0(A,Q){return[uV2(A,Q),cV2(A,Q)]}function uV2(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:tS0,handler:async(B)=>{let w=F.object(tS0).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 cV2(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:eS0,handler:async(B)=>{let w=F.object(eS0).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{photoId:$,downloadLocation:D,photographerName:Y,photographerUrl:I,sourceUrl:X,imageUrl:H,title:W,alt:J,targetEntityType:Z,targetEntityId:q}=w.data,V={photographerName:Y,photographerUrl:I,sourceUrl:X},E=await Q.entityService.listEntities("image",{limit:1,filter:{metadata:{sourceUrl:H}}});if(E[0]){let h={imageEntityId:E[0].id,alreadyExisted:!0,attribution:V};if(Z&&q)await Ah0(Q.entityService,Z,q,E[0].id),h.coverSet=!0;return{success:!0,data:h}}Q.provider.triggerDownload(D).catch(()=>{});let L;try{L=await Q.fetchImage(H)}catch(h){return{success:!1,error:h instanceof Error?h.message:"Image download failed"}}let j=W??`Stock photo ${$}`,_=rW.createImageEntity({dataUrl:L,title:j,alt:J??j}),k={id:$,..._,metadata:{..._.metadata,sourceUrl:H}},{entityId:r}=await Q.entityService.createEntity(k),n={imageEntityId:r,alreadyExisted:!1,attribution:V};if(Z&&q)await Ah0(Q.entityService,Z,q,r),n.coverSet=!0;return{success:!0,data:n}}}}async function Ah0(A,Q,B,w){let $=await A.getEntity(Q,B);if(!$)return;await A.updateEntity({...$,metadata:{...$.metadata,coverImageId:w}})}GA();var Bh0={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.41",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 pV2=F.object({provider:F.enum(["unsplash"]).default("unsplash"),apiKey:F.string().optional().describe("Stock photo provider API key")});class hJA extends tB{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",Bh0,A,pV2);this.deps=Q}async getTools(){if(!this.config.apiKey)return[];if(this.cachedTools)return this.cachedTools;let A=this.getContext(),Q=new ci(this.config.apiKey,this.deps.fetch??globalThis.fetch);return this.cachedTools=Qh0(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??f7}),this.cachedTools}}function gJA(A={},Q={}){return new hJA(A,Q)}GA();B0();GA();B0();var wh0=F.object({name:F.string(),description:F.string(),tags:F.array(F.string())}),Xb=F.enum(["discovered","approved"]).describe("Discovered for review or approved for calling"),pY=AY.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:Xb,discoveredAt:F.string().datetime().describe("When this agent was first discovered")}),$h0=pY.pick({name:!0,url:!0,status:!0}).extend({slug:F.string()}),AE=Q2.extend({entityType:F.literal("agent"),metadata:$h0}),Hb=AE.extend({frontmatter:pY,about:F.string(),skills:F.array(wh0),notes:F.string()}),QE=Hb.extend({url:F.string().optional(),typeLabel:F.string().optional()}),dV2=Hb.extend({url:F.string(),typeLabel:F.string()});B0();GA();var iV2=F.object({about:F.string(),skills:F.array(F.object({name:F.string(),description:F.string(),tags:F.array(F.string())})),notes:F.string()});function rV2(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(`
4001
+ `}GA();var fV2=new Set(["entityType"]),RV2={base:"Notes"},jV2=new Set(["base"]);function kV2(A){let Q=["file.name"];for(let B of A)if(!fV2.has(B.name))Q.push(B.name);return Q}function PV2(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function mS0(A,Q){let B=RV2[A]??Qv(A),w=PV2(Q),$=kV2(Q),D=[{type:"table",name:`All ${B}`,order:$}];if(w)D.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:$});let I={filters:{and:[jV2.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:D};return{filename:`${B}.base`,content:OI(I),hasStatus:w}}function uS0(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 OI(B)}function cS0(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 OI(B)}var lS0={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.42",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 vV2={mkdir:xV2,writeFile:TV2,existsFile:bV2},SV2=F.object({entityTypes:F.array(F.string()).optional().describe("Entity types to generate templates for (default: all)")});class kJA extends tB{deps;constructor(A={},Q={}){super("obsidian-vault",lS0,A,jJA);this.deps={...vV2,...Q}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return this.logger.info("Auto-syncing Obsidian templates, fileClasses, and bases"),await this.sync(A),{success:!0}})}async getTools(){let A=this.getContext();return[yQ(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",SV2,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,$=QU(A.dataDir,this.config.baseFolder),D=QU($,"templates"),Y=QU($,"fileClasses"),I=QU($,"bases");this.deps.mkdir(D,{recursive:!0}),this.deps.mkdir(Y,{recursive:!0}),this.deps.mkdir(I,{recursive:!0});let X=[],H=[],W=[],J=[],Z=[],q=[];for(let L of w){let j=A.entities.getEffectiveFrontmatterSchema(L);if(!j){this.logger.debug(`Skipping ${L}: no frontmatter schema`),H.push(L);continue}let _=hS0(j),k=A.entities.getAdapter(L),r=k?.isSingleton===!0,n=yS0(L,_);if(this.deps.writeFile(QU(Y,`${L}.md`),n),W.push(L),r){Z.push(L),this.logger.debug(`Generated fileClass (singleton): ${L}`);continue}let h=k?.getBodyTemplate()??"",T=gS0(L,_,h);this.deps.writeFile(QU(D,`${L}.md`),T),X.push(L);let S=mS0(L,_),y=QU(I,S.filename);if(!this.deps.existsFile(y))this.deps.writeFile(y,S.content),J.push(L),this.logger.debug(`Generated base: ${S.filename}`);if(S.hasStatus)q.push({entityType:L,fields:_});this.logger.debug(`Generated template + fileClass: ${L}`)}let V=uS0(Z);if(V){let L=QU(I,"Settings.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,V),J.push("Settings"),this.logger.debug("Generated Settings.base")}let E=cS0(q);if(E){let L=QU(I,"Pipeline.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,E),J.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${X.length} templates, ${W.length} fileClasses, ${J.length} bases (${H.length} skipped)`),O5({generated:X,skipped:H,fileClasses:W,bases:J})}catch(B){return this.logger.error("Failed to sync",{error:B}),Ew(B instanceof Error?B.message:"Unknown error")}}}function PJA(A,Q){return new kJA(A,Q)}B0();GA();B0();var _JA=F.enum(["new","planned","in-progress","done","declined"]),bJA=F.enum(["low","medium","high","critical"]),wb=F.object({title:F.string(),status:_JA,priority:bJA.default("medium"),requested:F.number().int().default(1),declinedReason:F.string().optional()}),pS0=F.object({title:F.string(),status:_JA,priority:bJA,requested:F.number().int(),slug:F.string()}),$b=Q2.extend({entityType:F.literal("wish"),metadata:pS0}),xJA=F.object({});B0();GA();class Db extends I2{constructor(){super({entityType:"wish",schema:$b,frontmatterSchema:wb})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,wb);return{frontmatter:wb.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),B=e1(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:B}}}}var TJA=new Db;GA();GA();async function dS0(A,Q){let B=`${Q.title}: ${Q.description}`,$=(await A.search(B,{types:["wish"],limit:1}))[0];if($&&$.score>=A.similarityThreshold)return $.entity;let D=e1(Q.title);return A.getEntity("wish",D)}class yi{logger;context;adapter=new Db;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??"",D=await dS0({search:(H,W)=>this.context.entityService.search(H,W),getEntity:(H,W)=>this.context.entityService.getEntity(H,W),similarityThreshold:0.85},{title:w,description:$});if(D){let{frontmatter:H,description:W}=this.adapter.parseWishContent(D.content),J=H.requested+1,Z=this.adapter.createWishContent({...H,requested:J},W);return await this.context.entityService.updateEntity({...D,content:Z,metadata:{...D.metadata,requested:J}}),this.logger.info("Incremented wish request count",{id:D.id,requested:J}),{success:!0,entityId:D.id,existed:!0,requested:J}}let Y=e1(w),I=A.options?.priority??"medium",X=this.adapter.createWishContent({title:w,status:"new",priority:I,requested:1},$);return await this.context.entityService.createEntity({id:Y,entityType:"wish",content:X,metadata:{title:w,status:"new",priority:I,requested:1,slug:Y}}),this.logger.info("Created new wish",{id:Y,title:w}),{success:!0,entityId:Y,existed:!1,requested:1}}}var iS0={critical:0,high:1,medium:2,low:3};function rS0(A){A.sort((Q,B)=>{let w=B.metadata.requested-Q.metadata.requested;if(w!==0)return w;return iS0[Q.metadata.priority]-iS0[B.metadata.priority]})}var nS0={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.42",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 oS0 extends HQ{entityType=TJA.entityType;schema=$b;adapter=TJA;constructor(A={}){super("wishlist",nS0,A,xJA)}async interceptCreate(A,Q,B){let w=await new yi(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("dashboard:register-widget",{id:"top-wishes",pluginId:this.id,title:"Top Wishes",section:"secondary",priority:30,rendererName:"ListWidget",dataProvider:async()=>{let B=await A.entityService.listEntities("wish",{limit:10});return rS0(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 yi(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:(B)=>B})}async getInstructions(){return"**CRITICAL \u2014 Unfulfilled requests**: ALWAYS call `system_create` with entityType "+`"wish" BEFORE responding when you cannot fulfill a user's request. This applies to ALL unfulfillable requests: physical actions, missing integrations, and any 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. CRITICAL exception: for A2A agent-contact requests, never create a wish for a missing, ambiguous, archived, URL-only, unsaved-domain, or not-yet-saved local agent-directory target. 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". Those are save-first directory cases, not wishlist cases. In those cases, tell the user to add/save or clarify the agent first. Never call system_create with entityType "wish" for those agent-contact cases. Only create or save an agent entry if the user explicitly asks you to add or save that agent.'}}function gV2(A={}){return new oS0(A)}var mi=gV2;B0();GA();B0();var Yb=F.object({title:F.string(),target:F.string()}),sS0=F.object({title:F.string(),target:F.string(),slug:F.string().optional()}),Ib=Q2.extend({entityType:F.literal("prompt"),metadata:sS0});B0();GA();class vJA extends I2{constructor(){super({entityType:"prompt",schema:Ib,frontmatterSchema:Yb})}toMarkdown(A){let Q=this.extractBody(A.content),B=this.parseFrontMatter(A.content,Yb);return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Yb),B=e1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:B}}}}var ui=new vJA;var aS0={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.42",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 SJA extends HQ{entityType=ui.entityType;schema=Ib;adapter=ui;constructor(){super("prompt",aS0,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function Yq(){return new SJA}B0();GA();class ci{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(mV2),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function mV2(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}}GA();var tS0={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")},eS0={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 Qh0(A,Q){return[uV2(A,Q),cV2(A,Q)]}function uV2(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:tS0,handler:async(B)=>{let w=F.object(tS0).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 cV2(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:eS0,handler:async(B)=>{let w=F.object(eS0).safeParse(B);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{photoId:$,downloadLocation:D,photographerName:Y,photographerUrl:I,sourceUrl:X,imageUrl:H,title:W,alt:J,targetEntityType:Z,targetEntityId:q}=w.data,V={photographerName:Y,photographerUrl:I,sourceUrl:X},E=await Q.entityService.listEntities("image",{limit:1,filter:{metadata:{sourceUrl:H}}});if(E[0]){let h={imageEntityId:E[0].id,alreadyExisted:!0,attribution:V};if(Z&&q)await Ah0(Q.entityService,Z,q,E[0].id),h.coverSet=!0;return{success:!0,data:h}}Q.provider.triggerDownload(D).catch(()=>{});let L;try{L=await Q.fetchImage(H)}catch(h){return{success:!1,error:h instanceof Error?h.message:"Image download failed"}}let j=W??`Stock photo ${$}`,_=rW.createImageEntity({dataUrl:L,title:j,alt:J??j}),k={id:$,..._,metadata:{..._.metadata,sourceUrl:H}},{entityId:r}=await Q.entityService.createEntity(k),n={imageEntityId:r,alreadyExisted:!1,attribution:V};if(Z&&q)await Ah0(Q.entityService,Z,q,r),n.coverSet=!0;return{success:!0,data:n}}}}async function Ah0(A,Q,B,w){let $=await A.getEntity(Q,B);if(!$)return;await A.updateEntity({...$,metadata:{...$.metadata,coverImageId:w}})}GA();var Bh0={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.42",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 pV2=F.object({provider:F.enum(["unsplash"]).default("unsplash"),apiKey:F.string().optional().describe("Stock photo provider API key")});class hJA extends tB{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",Bh0,A,pV2);this.deps=Q}async getTools(){if(!this.config.apiKey)return[];if(this.cachedTools)return this.cachedTools;let A=this.getContext(),Q=new ci(this.config.apiKey,this.deps.fetch??globalThis.fetch);return this.cachedTools=Qh0(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??f7}),this.cachedTools}}function gJA(A={},Q={}){return new hJA(A,Q)}GA();B0();GA();B0();var wh0=F.object({name:F.string(),description:F.string(),tags:F.array(F.string())}),Xb=F.enum(["discovered","approved"]).describe("Discovered for review or approved for calling"),pY=AY.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:Xb,discoveredAt:F.string().datetime().describe("When this agent was first discovered")}),$h0=pY.pick({name:!0,url:!0,status:!0}).extend({slug:F.string()}),AE=Q2.extend({entityType:F.literal("agent"),metadata:$h0}),Hb=AE.extend({frontmatter:pY,about:F.string(),skills:F.array(wh0),notes:F.string()}),QE=Hb.extend({url:F.string().optional(),typeLabel:F.string().optional()}),dV2=Hb.extend({url:F.string(),typeLabel:F.string()});B0();GA();var iV2=F.object({about:F.string(),skills:F.array(F.object({name:F.string(),description:F.string(),tags:F.array(F.string())})),notes:F.string()});function rV2(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(`
4002
4002
  `)}function nV2(A){if(!A.trim())return[];let Q=[];for(let B of A.split(`
4003
4003
  `)){let w=B.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/);if(w){let $=w[1]??"",D=w[2]??"",Y=w[3],I=Y?Y.split(",").map((X)=>X.trim()).filter(Boolean):[];Q.push({name:$,description:D,tags:I})}}return Q}var Dh0=new $B(iV2,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:rV2,parser:nV2},{key:"notes",label:"Notes",type:"string"}]});class HD extends I2{constructor(){super({entityType:"agent",schema:AE,frontmatterSchema:pY})}fromMarkdown(A){let Q=this.parseFrontMatter(A,pY),B=nz(Q.url);return{content:A,entityType:"agent",metadata:{name:Q.name,url:Q.url,status:Q.status,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:Xb.parse(A.status),discoveredAt:A.discoveredAt},B=Dh0.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=Dh0.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,pY),body:this.parseAgentContent(A.content)}}}B0();GA();var oV2=new HD,sV2=yI.extend({status:F.enum(["discovered","approved"]).optional()}),aV2=mI.extend({query:sV2.optional()});function tV2(A){let Q=G2(A.content,pY),B=oV2.parseAgentContent(A.content);return Hb.parse({...A,frontmatter:Q.metadata,about:B.about,skills:B.skills,notes:B.notes})}class li extends s5{id="agent-discovery:entities";name="Agent Directory DataSource";description="Fetches and transforms agent entities for rendering";config={entityType:"agent",defaultSort:[{field:"discoveredAt",direction:"desc"}],defaultLimit:50,lookupField:"slug",enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return tV2(A)}buildDetailResult(A,Q){return{agent:A,prevAgent:Q?.prev??null,nextAgent:Q?.next??null}}parseQuery(A){let Q=aV2.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}buildListResult(A,Q,B){return{agents:A,pagination:Q,baseUrl:B.baseUrl,selectedStatus:B.status==="discovered"||B.status==="approved"?B.status:"all"}}async fetch(A,Q,B){let{query:w}=this.parseQuery(A);if(w.id)return super.fetch(A,Q,B);let{items:$,pagination:D}=await this.fetchList(w,B.entityService,w.status?{filter:{metadata:{status:w.status}}}:void 0);return Q.parse(this.buildListResult($,D,w))}}B0();GA();B0();async function Yh0(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 D=await $.json();return mO(D)}catch{return null}}function pi(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""}GA();var eV2=new HD;function Ih0(A){return A.trim().toLowerCase().replace(/[_\s]+/g,"-")}function XJ(A){let Q=new Set,B=[];for(let w of A){let $=Ih0(w);if(!$||Q.has($))continue;Q.add($),B.push($)}return B}function AL2(A,Q){if(Q.count!==A.count)return Q.count-A.count;return A.tag.localeCompare(Q.tag)}async function Xh0(A,Q={}){let B=Q.minCount??1,w=Q.topN??12,$=new Map,[D,Y]=await Promise.all([A.entityService.listEntities("skill"),A.entityService.listEntities("agent")]),I=(X)=>{for(let H of XJ(X))$.set(H,($.get(H)??0)+1)};for(let X of D)I(X.metadata.tags);for(let X of Y){let H=eV2.parseAgentContent(X.content);I(H.skills.flatMap((W)=>W.tags))}return Array.from($.entries()).map(([X,H])=>({tag:X,count:H})).filter((X)=>X.count>=B).sort(AL2).slice(0,w)}function Hh0(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(`
4004
4004
  `)}var QL2=new HD;function Kh0(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 D=Q.status??"discovered";return{content:QL2.createAgentContent({name:B,kind:w,...A.anchor?.organization&&{organization:A.anchor.organization},brainName:A.brainName,url:A.url,status:D,discoveredAt:new Date().toISOString(),about:$.join(`
@@ -4098,7 +4098,7 @@ ${OI(B)}---
4098
4098
  setView("agents");
4099
4099
  setTagFilter("all");
4100
4100
  });
4101
- })();`;function VL2({item:A}){return XQ("li",{class:"list-item",children:[XQ("div",{class:"list-main",children:[XQ("span",{class:"list-name",children:A.name},void 0,!1,void 0,this),XQ("span",{class:"list-desc",children:A.description},void 0,!1,void 0,this),A.tags.length>0&&XQ("div",{class:"list-tags",children:A.tags.map((Q)=>XQ("span",{class:"tag",children:Q},`${A.id}:${Q}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),XQ("div",{class:"list-meta",children:A.status==="discovered"&&XQ("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 LL2({item:A}){return XQ("li",{class:"list-item agent-network-skill-row","data-agent-network-skill-row":!0,"data-agent-network-tags":JSON.stringify(A.tags),children:[XQ("div",{class:"list-main",children:XQ("span",{class:"list-name",children:A.name},void 0,!1,void 0,this)},void 0,!1,void 0,this),XQ("div",{class:"list-meta",children:XQ("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 ML2({kind:A,items:Q,active:B}){return XQ("div",{class:`agent-network-panel${B?" is-active":""}`,"data-agent-network-panel":A,children:Q.length>0?XQ("ul",{class:"list agent-network-list",children:Q.map((w)=>XQ(VL2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):XQ("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function EL2({skills:A,count:Q,filters:B}){return XQ("div",{class:"agent-network-panel","data-agent-network-panel":"skills",children:[XQ("div",{class:"agent-network-filter-row",role:"tablist","aria-label":"Filter skills by tag",children:[XQ("button",{class:"agent-network-filter is-active",type:"button","data-agent-network-tag-filter":"all","aria-pressed":"true",children:[XQ("span",{class:"count",children:Q},void 0,!1,void 0,this),XQ("span",{class:"label",children:"all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B.map((w)=>XQ("button",{class:`agent-network-filter${w.variant==="gap"?" is-gap":""}`,type:"button","data-agent-network-tag-filter":w.tag,"aria-pressed":"false",children:[XQ("span",{class:"count",children:w.count},void 0,!1,void 0,this),XQ("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?XQ("ul",{class:"list agent-network-list agent-network-skills-list",children:A.map((w)=>XQ(LL2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):XQ("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function lJA({data:A}){let Q=Wh0.safeParse(A);if(!Q.success)return XQ("p",{class:"muted",children:"Nothing to show yet."},void 0,!1,void 0,this);let B=Q.data;return XQ("div",{"data-agent-network-widget":!0,"data-agent-network-view":"agents",children:[XQ("div",{class:"agent-network-view-tabs",role:"tablist","aria-label":"Browse the agent network",children:[XQ("button",{class:"agent-network-view-tab is-active",type:"button","data-agent-network-view-tab":"agents","aria-pressed":"true",children:["Agents",XQ("span",{class:"agent-network-view-count",children:B.counts.agents},void 0,!1,void 0,this)]},void 0,!0,void 0,this),XQ("button",{class:"agent-network-view-tab",type:"button","data-agent-network-view-tab":"skills","aria-pressed":"false",children:["Skills",XQ("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),XQ("div",{class:"agent-network-kind-tabs",role:"tablist","aria-label":"Filter agents by kind",children:mJA.map((w)=>{let $=w==="all";return XQ("button",{class:`agent-network-kind-tab${$?" is-active":""}`,type:"button","data-agent-network-kind-tab":w,"aria-pressed":$?"true":"false",children:[XQ("span",{class:"agent-network-kind-count",children:B.agents[w].length},void 0,!1,void 0,this),XQ("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),mJA.map((w)=>XQ(ML2,{kind:w,items:B.agents[w],active:w==="all"},w,!1,void 0,this)),XQ(EL2,{skills:B.skills,count:B.counts.skills,filters:B.skillFilters},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var oi={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.41",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/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 OL2=new HD;class pJA extends HQ{entityType="agent";schema=AE;adapter=OL2;constructor(){super("agent-discovery",oi)}async interceptCreate(A,Q,B){if(A.url&&!A.prompt&&!A.content){let w=pi(A.url),$=w??A.url.trim().toLowerCase();if(w){let Y=await B.entityService.getEntity("agent",w);if(Y){if(Y.metadata.status!=="approved")await B.entityService.updateEntity({...Y,metadata:{...Y.metadata,status:"approved"}});return{kind:"handled",result:{success:!0,data:{status:"created",entityId:Y.id}}}}}return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await B.jobs.enqueue("agent:generation",{prompt:A.url,url:A.url,status:"approved"},Q,{source:this.id,metadata:{operationType:"data_processing"},deduplication:"coalesce",deduplicationKey:$,maxRetries:0})}}}}return{kind:"continue",input:A}}createGenerationHandler(A){return new yJA(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return zh0()}getDataSources(){return[new li(this.logger.child("AgentDataSource"))]}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("dashboard:register-widget",{id:"agent-network",pluginId:this.id,title:"Agent Network",section:"secondary",priority:15,rendererName:"AgentNetworkWidget",component:lJA,clientScript:cJA,dataProvider:async()=>Gh0(A)}),{success:!0}})}async getInstructions(){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 `confirmed: true`. Do not ask for another confirmation for that explicit approval request.\n- When the user explicitly says `archive`, `remove`, `archive it`, `remove it`, or `archive/remove <agent-id>` for a saved agent, call `system_update` immediately with `fields: { status: "archived" }` and `confirmed: true`. Do not send blank content, and do not omit `fields` for that archive 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. If it succeeds for an archive/remove request, answer plainly that the agent is now archived/removed from the directory. 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- 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 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 or ambiguous agent unless the user explicitly asks you to add or save that agent.'}}function dJA(){return new pJA}B0();GA();GA();B0();var BE=j$,Nh0=j$,Ub=Q2.extend({entityType:F.literal("skill"),metadata:Nh0});B0();class wE extends I2{constructor(){super({entityType:"skill",schema:Ub,frontmatterSchema:BE})}fromMarkdown(A){let Q=this.parseFrontMatter(A,BE);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}GA();function fL2(A){let Q=[];if(A.topicTitles.length>0)Q.push(`The brain's knowledge domains (from content analysis):
4101
+ })();`;function VL2({item:A}){return XQ("li",{class:"list-item",children:[XQ("div",{class:"list-main",children:[XQ("span",{class:"list-name",children:A.name},void 0,!1,void 0,this),XQ("span",{class:"list-desc",children:A.description},void 0,!1,void 0,this),A.tags.length>0&&XQ("div",{class:"list-tags",children:A.tags.map((Q)=>XQ("span",{class:"tag",children:Q},`${A.id}:${Q}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),XQ("div",{class:"list-meta",children:A.status==="discovered"&&XQ("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 LL2({item:A}){return XQ("li",{class:"list-item agent-network-skill-row","data-agent-network-skill-row":!0,"data-agent-network-tags":JSON.stringify(A.tags),children:[XQ("div",{class:"list-main",children:XQ("span",{class:"list-name",children:A.name},void 0,!1,void 0,this)},void 0,!1,void 0,this),XQ("div",{class:"list-meta",children:XQ("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 ML2({kind:A,items:Q,active:B}){return XQ("div",{class:`agent-network-panel${B?" is-active":""}`,"data-agent-network-panel":A,children:Q.length>0?XQ("ul",{class:"list agent-network-list",children:Q.map((w)=>XQ(VL2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):XQ("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function EL2({skills:A,count:Q,filters:B}){return XQ("div",{class:"agent-network-panel","data-agent-network-panel":"skills",children:[XQ("div",{class:"agent-network-filter-row",role:"tablist","aria-label":"Filter skills by tag",children:[XQ("button",{class:"agent-network-filter is-active",type:"button","data-agent-network-tag-filter":"all","aria-pressed":"true",children:[XQ("span",{class:"count",children:Q},void 0,!1,void 0,this),XQ("span",{class:"label",children:"all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B.map((w)=>XQ("button",{class:`agent-network-filter${w.variant==="gap"?" is-gap":""}`,type:"button","data-agent-network-tag-filter":w.tag,"aria-pressed":"false",children:[XQ("span",{class:"count",children:w.count},void 0,!1,void 0,this),XQ("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?XQ("ul",{class:"list agent-network-list agent-network-skills-list",children:A.map((w)=>XQ(LL2,{item:w},w.id,!1,void 0,this))},void 0,!1,void 0,this):XQ("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function lJA({data:A}){let Q=Wh0.safeParse(A);if(!Q.success)return XQ("p",{class:"muted",children:"Nothing to show yet."},void 0,!1,void 0,this);let B=Q.data;return XQ("div",{"data-agent-network-widget":!0,"data-agent-network-view":"agents",children:[XQ("div",{class:"agent-network-view-tabs",role:"tablist","aria-label":"Browse the agent network",children:[XQ("button",{class:"agent-network-view-tab is-active",type:"button","data-agent-network-view-tab":"agents","aria-pressed":"true",children:["Agents",XQ("span",{class:"agent-network-view-count",children:B.counts.agents},void 0,!1,void 0,this)]},void 0,!0,void 0,this),XQ("button",{class:"agent-network-view-tab",type:"button","data-agent-network-view-tab":"skills","aria-pressed":"false",children:["Skills",XQ("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),XQ("div",{class:"agent-network-kind-tabs",role:"tablist","aria-label":"Filter agents by kind",children:mJA.map((w)=>{let $=w==="all";return XQ("button",{class:`agent-network-kind-tab${$?" is-active":""}`,type:"button","data-agent-network-kind-tab":w,"aria-pressed":$?"true":"false",children:[XQ("span",{class:"agent-network-kind-count",children:B.agents[w].length},void 0,!1,void 0,this),XQ("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),mJA.map((w)=>XQ(ML2,{kind:w,items:B.agents[w],active:w==="all"},w,!1,void 0,this)),XQ(EL2,{skills:B.skills,count:B.counts.skills,filters:B.skillFilters},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var oi={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.42",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/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 OL2=new HD;class pJA extends HQ{entityType="agent";schema=AE;adapter=OL2;constructor(){super("agent-discovery",oi)}async interceptCreate(A,Q,B){if(A.url&&!A.prompt&&!A.content){let w=pi(A.url),$=w??A.url.trim().toLowerCase();if(w){let Y=await B.entityService.getEntity("agent",w);if(Y){if(Y.metadata.status!=="approved")await B.entityService.updateEntity({...Y,metadata:{...Y.metadata,status:"approved"}});return{kind:"handled",result:{success:!0,data:{status:"created",entityId:Y.id}}}}}return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await B.jobs.enqueue("agent:generation",{prompt:A.url,url:A.url,status:"approved"},Q,{source:this.id,metadata:{operationType:"data_processing"},deduplication:"coalesce",deduplicationKey:$,maxRetries:0})}}}}return{kind:"continue",input:A}}createGenerationHandler(A){return new yJA(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return zh0()}getDataSources(){return[new li(this.logger.child("AgentDataSource"))]}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send("dashboard:register-widget",{id:"agent-network",pluginId:this.id,title:"Agent Network",section:"secondary",priority:15,rendererName:"AgentNetworkWidget",component:lJA,clientScript:cJA,dataProvider:async()=>Gh0(A)}),{success:!0}})}async getInstructions(){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 `confirmed: true`. Do not ask for another confirmation for that explicit approval request.\n- When the user explicitly says `archive`, `remove`, `archive it`, `remove it`, or `archive/remove <agent-id>` for a saved agent, call `system_update` immediately with `fields: { status: "archived" }` and `confirmed: true`. Do not send blank content, and do not omit `fields` for that archive 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. If it succeeds for an archive/remove request, answer plainly that the agent is now archived/removed from the directory. 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- 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 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 or ambiguous agent unless the user explicitly asks you to add or save that agent.'}}function dJA(){return new pJA}B0();GA();GA();B0();var BE=j$,Nh0=j$,Ub=Q2.extend({entityType:F.literal("skill"),metadata:Nh0});B0();class wE extends I2{constructor(){super({entityType:"skill",schema:Ub,frontmatterSchema:BE})}fromMarkdown(A){let Q=this.parseFrontMatter(A,BE);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}GA();function fL2(A){let Q=[];if(A.topicTitles.length>0)Q.push(`The brain's knowledge domains (from content analysis):
4102
4102
  ${A.topicTitles.map((w)=>`- ${w}`).join(`
4103
4103
  `)}`);if(A.toolDescriptions.length>0)Q.push(`The brain has these capabilities:
4104
4104
  ${A.toolDescriptions.map((w)=>`- ${w}`).join(`
@@ -4244,9 +4244,9 @@ Context:
4244
4244
  ${JSON.stringify(w,null,2)}
4245
4245
 
4246
4246
  Draft SWOT:
4247
- ${JSON.stringify(B,null,2)}`}function wr(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function iL2(A,Q){let B=["strengths","weaknesses","opportunities","threats"];for(let w of B){let $=new Set(A[w].map((D)=>D.theme.trim().toLowerCase()));for(let D of Q[w]){let Y=D.sourceTheme.trim().toLowerCase();if(!$.has(Y))throw Error(`SWOT refinement invented theme "${D.sourceTheme}" in ${w}`)}}}class $r{logger;context;adapter=new BU;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=nJA.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 eJA(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:H}=await this.context.ai.generateObject(await lL2(this.context,w),oJA),W=oJA.parse(H);await B.report({progress:0.75,message:"Refining SWOT language"});let J=await this.context.ai.generateObject(await dL2(this.context,w,W),Ar);$=Ar.parse(J.object),iL2(W,$)}let Y=new Date().toISOString(),I=this.adapter.createSwotContent({strengths:wr($.strengths),weaknesses:wr($.weaknesses),opportunities:wr($.opportunities),threats:wr($.threats),derivedAt:Y});await B.report({progress:0.9,message:"Saving SWOT entity"});let X=await this.context.entityService.getEntity("swot","swot");if(X)await this.context.entityService.updateEntity({...X,content:I,metadata:{derivedAt:Y}});else await this.context.entityService.createEntity({id:"swot",entityType:"swot",content:I,metadata:{derivedAt:Y}});return this.logger.info("SWOT derivation complete",{derivedAt:Y,brainSkillCount:w.summary.brainSkillCount,approvedAgentCount:w.summary.approvedAgentCount,discoveredAgentCount:w.summary.discoveredAgentCount}),{entityId:"swot"}}}GA();import{jsxDEV as V9}from"preact/jsx-dev-runtime";var Dr=F.object({title:F.string(),detail:F.string().optional()}),rL2=F.discriminatedUnion("status",[F.object({status:F.literal("generating")}),F.object({status:F.literal("ready"),strengths:F.array(Dr).default([]),weaknesses:F.array(Dr).default([]),opportunities:F.array(Dr).default([]),threats:F.array(Dr).default([]),derivedAt:F.string()})]);function nL2({items:A}){if(A.length===0)return V9("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return V9("ul",{class:"swot-list",children:A.map((Q)=>V9("li",{class:"swot-item",children:[V9("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?V9("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 Yr({title:A,tone:Q,items:B}){return V9("section",{class:`swot-cell is-${Q}`,children:[V9("div",{class:"swot-head",children:A},void 0,!1,void 0,this),V9(nL2,{items:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function B3A({data:A}){let Q=rL2.safeParse(A);if(!Q.success||Q.data.status==="generating")return V9("div",{"data-swot-widget":!0,children:V9("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let B=Q.data;return V9("div",{"data-swot-widget":!0,children:V9("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[V9(Yr,{title:"Strengths",tone:"s",items:B.strengths},void 0,!1,void 0,this),V9(Yr,{title:"Weaknesses",tone:"w",items:B.weaknesses},void 0,!1,void 0,this),V9(Yr,{title:"Opportunities",tone:"o",items:B.opportunities},void 0,!1,void 0,this),V9(Yr,{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)}var w3A={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.41",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/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 jh0=new BU;class $3A extends HQ{entityType="swot";schema=$E;adapter=jh0;initialSyncComplete=!1;constructor(){super("swot",w3A)}async onRegister(A){let Q=new $r(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q);let B=async(D)=>{try{return await A.jobs.enqueue("derive",{reason:D},null,{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${D}`}})}catch(Y){return this.logger.error("Failed to queue SWOT derivation",{error:Y,reason:D}),null}},w=async(D)=>{if(!await A.entityService.getEntity("swot","swot"))await B(D)};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("dashboard:register-widget",{id:"swot",pluginId:this.id,title:"SWOT",section:"secondary",priority:14,rendererName:"SwotWidget",component:B3A,dataProvider:async()=>{let D=await A.entityService.getEntity("swot","swot");if(!D)return{status:"generating"};let{frontmatter:Y}=jh0.parseSwotContent(D.content);return{status:"ready",...Y}}}),{success:!0}});let $=async(D)=>{let{entityType:Y}=D.payload;if(!this.initialSyncComplete)return{success:!0};if(Y!=="agent"&&Y!=="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 D3A(){return new $3A}B0();GA();var GXB=new BU,kh0=F.object({name:F.string(),description:F.string(),tags:F.array(F.string())}),Y3A=F.enum(["discovered","approved"]),sL2=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:Y3A,discoveredAt:F.string().datetime()}),aL2=Q2.extend({entityType:F.literal("agent"),metadata:F.object({name:F.string(),url:F.string().url(),status:Y3A,slug:F.string()})}),tL2=Q2.extend({entityType:F.literal("skill"),metadata:j$}),eL2=F.object({about:F.string(),skills:F.array(kh0),notes:F.string()});function AM2(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(`
4247
+ ${JSON.stringify(B,null,2)}`}function wr(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function iL2(A,Q){let B=["strengths","weaknesses","opportunities","threats"];for(let w of B){let $=new Set(A[w].map((D)=>D.theme.trim().toLowerCase()));for(let D of Q[w]){let Y=D.sourceTheme.trim().toLowerCase();if(!$.has(Y))throw Error(`SWOT refinement invented theme "${D.sourceTheme}" in ${w}`)}}}class $r{logger;context;adapter=new BU;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=nJA.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 eJA(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:H}=await this.context.ai.generateObject(await lL2(this.context,w),oJA),W=oJA.parse(H);await B.report({progress:0.75,message:"Refining SWOT language"});let J=await this.context.ai.generateObject(await dL2(this.context,w,W),Ar);$=Ar.parse(J.object),iL2(W,$)}let Y=new Date().toISOString(),I=this.adapter.createSwotContent({strengths:wr($.strengths),weaknesses:wr($.weaknesses),opportunities:wr($.opportunities),threats:wr($.threats),derivedAt:Y});await B.report({progress:0.9,message:"Saving SWOT entity"});let X=await this.context.entityService.getEntity("swot","swot");if(X)await this.context.entityService.updateEntity({...X,content:I,metadata:{derivedAt:Y}});else await this.context.entityService.createEntity({id:"swot",entityType:"swot",content:I,metadata:{derivedAt:Y}});return this.logger.info("SWOT derivation complete",{derivedAt:Y,brainSkillCount:w.summary.brainSkillCount,approvedAgentCount:w.summary.approvedAgentCount,discoveredAgentCount:w.summary.discoveredAgentCount}),{entityId:"swot"}}}GA();import{jsxDEV as V9}from"preact/jsx-dev-runtime";var Dr=F.object({title:F.string(),detail:F.string().optional()}),rL2=F.discriminatedUnion("status",[F.object({status:F.literal("generating")}),F.object({status:F.literal("ready"),strengths:F.array(Dr).default([]),weaknesses:F.array(Dr).default([]),opportunities:F.array(Dr).default([]),threats:F.array(Dr).default([]),derivedAt:F.string()})]);function nL2({items:A}){if(A.length===0)return V9("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return V9("ul",{class:"swot-list",children:A.map((Q)=>V9("li",{class:"swot-item",children:[V9("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?V9("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 Yr({title:A,tone:Q,items:B}){return V9("section",{class:`swot-cell is-${Q}`,children:[V9("div",{class:"swot-head",children:A},void 0,!1,void 0,this),V9(nL2,{items:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function B3A({data:A}){let Q=rL2.safeParse(A);if(!Q.success||Q.data.status==="generating")return V9("div",{"data-swot-widget":!0,children:V9("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let B=Q.data;return V9("div",{"data-swot-widget":!0,children:V9("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[V9(Yr,{title:"Strengths",tone:"s",items:B.strengths},void 0,!1,void 0,this),V9(Yr,{title:"Weaknesses",tone:"w",items:B.weaknesses},void 0,!1,void 0,this),V9(Yr,{title:"Opportunities",tone:"o",items:B.opportunities},void 0,!1,void 0,this),V9(Yr,{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)}var w3A={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.42",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/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 jh0=new BU;class $3A extends HQ{entityType="swot";schema=$E;adapter=jh0;initialSyncComplete=!1;constructor(){super("swot",w3A)}async onRegister(A){let Q=new $r(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q);let B=async(D)=>{try{return await A.jobs.enqueue("derive",{reason:D},null,{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${D}`}})}catch(Y){return this.logger.error("Failed to queue SWOT derivation",{error:Y,reason:D}),null}},w=async(D)=>{if(!await A.entityService.getEntity("swot","swot"))await B(D)};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("dashboard:register-widget",{id:"swot",pluginId:this.id,title:"SWOT",section:"secondary",priority:14,rendererName:"SwotWidget",component:B3A,dataProvider:async()=>{let D=await A.entityService.getEntity("swot","swot");if(!D)return{status:"generating"};let{frontmatter:Y}=jh0.parseSwotContent(D.content);return{status:"ready",...Y}}}),{success:!0}});let $=async(D)=>{let{entityType:Y}=D.payload;if(!this.initialSyncComplete)return{success:!0};if(Y!=="agent"&&Y!=="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 D3A(){return new $3A}B0();GA();var GXB=new BU,kh0=F.object({name:F.string(),description:F.string(),tags:F.array(F.string())}),Y3A=F.enum(["discovered","approved"]),sL2=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:Y3A,discoveredAt:F.string().datetime()}),aL2=Q2.extend({entityType:F.literal("agent"),metadata:F.object({name:F.string(),url:F.string().url(),status:Y3A,slug:F.string()})}),tL2=Q2.extend({entityType:F.literal("skill"),metadata:j$}),eL2=F.object({about:F.string(),skills:F.array(kh0),notes:F.string()});function AM2(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(`
4248
4248
  `)}function QM2(A){if(!A.trim())return[];return A.split(`
4249
- `).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 BM2=new $B(eL2,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:AM2,parser:QM2},{key:"notes",label:"Notes",type:"string"}]});class Ph0 extends I2{constructor(){super({entityType:"agent",schema:aL2,frontmatterSchema:sL2})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=BM2.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 _h0 extends I2{constructor(){super({entityType:"skill",schema:tL2,frontmatterSchema:j$})}fromMarkdown(A){let Q=this.parseFrontMatter(A,j$);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var JXB=new Ph0,ZXB=new _h0,FXB=F.object({skills:F.array(j$),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:Y3A,discoveredAt:F.string().datetime().optional(),about:F.string(),skills:F.array(kh0),notes:F.string().default("")}))});var wM2=F.object({}).strict();function Ir(A={}){return wM2.parse(A),[D3A()]}B0();GA();s8();GA();B0();var Xr=QS.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.)")}),HJ=AY.extend(Xr.shape);B0();MW();GA();var $M2=new uI;class Hr{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,[$,D,Y,I]=await Promise.all([GN(w),w.listEntities("post",{limit:20}),w.listEntities("deck",{limit:20}),iK(w)]),X=$M2.parseProfileBody($,HJ),H=D.sort(DO).slice(0,3).map(h_),W=Y.sort(DO).slice(0,3).map(u_);if(!I.cta)throw Error("CTA not configured in site-info");let J={profile:X,posts:H,decks:W,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:I.cta};return Q.parse(J)}}B0();MW();var DM2=new uI;class Kr{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,B){let w=await GN(B.entityService),D={profile:DM2.parseProfileBody(w,HJ)};return Q.parse(D)}}import{jsxDEV as c6,Fragment as bh0}from"preact/jsx-dev-runtime";var I3A=({profile:A,posts:Q,decks:B,postsListUrl:w,decksListUrl:$,cta:D})=>{let Y=A.tagline||A.description,I=Q.map((J)=>({id:J.id,url:J.url,title:J.metadata.title,date:J.metadata.publishedAt||J.created,description:J.frontmatter.excerpt,series:J.frontmatter.seriesName&&J.frontmatter.seriesIndex?{name:J.frontmatter.seriesName,index:J.frontmatter.seriesIndex}:void 0})),X=B.map((J)=>({id:J.id,url:J.url,title:J.frontmatter.title||J.id,date:J.frontmatter.publishedAt??J.created,description:J.frontmatter.description})),H=A.name||"Home",W=A.intro||A.description||Y||"Professional site";return c6(bh0,{children:[c6(n2,{title:H,description:W,ogType:"website"},void 0,!1,void 0,this),c6("div",{className:"homepage-list bg-theme",children:[c6("header",{className:"hero-bg-pattern relative w-full min-h-[70vh] flex items-end px-6 md:px-12 bg-theme overflow-hidden",children:c6("div",{className:"relative z-10 max-w-6xl mx-auto w-full pb-16 md:pb-24",children:[Y&&c6("h1",{className:"text-5xl md:text-6xl lg:text-7xl font-semibold text-heading leading-[1.08] tracking-tight",children:Y},void 0,!1,void 0,this),A.intro&&c6(bh0,{children:[c6("div",{className:"w-12 border-t border-theme mt-8 mb-6 md:mt-10 md:mb-8"},void 0,!1,void 0,this),c6("p",{className:"text-lg md:text-xl text-theme-muted leading-relaxed max-w-xl md:max-w-lg",children:A.intro},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),c6("div",{className:"section-divider"},void 0,!1,void 0,this),c6("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[c6("div",{className:"content-section-reveal mb-20 md:mb-32",children:c6(bK,{title:"Essays",items:I,viewAllUrl:w},void 0,!1,void 0,this)},void 0,!1,void 0,this),X.length>0&&c6("div",{className:"content-section-reveal mb-20 md:mb-32",children:c6(bK,{title:"Presentations",items:X,viewAllUrl:$},void 0,!1,void 0,this)},void 0,!1,void 0,this),(A.description||A.expertise&&A.expertise.length>0)&&c6("div",{className:"content-section-reveal mb-20 md:mb-32",children:c6(bK,{title:"About",viewAllUrl:"/about",variant:"stacked",children:c6("div",{className:"space-y-6",children:[A.description&&c6("p",{className:"text-lg text-theme leading-relaxed",children:A.description},void 0,!1,void 0,this),A.expertise&&A.expertise.length>0&&c6(vG,{tags:A.expertise,variant:"accent",size:"sm"},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),c6(SHA,{cta:D,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 qB,Fragment as YM2}from"preact/jsx-dev-runtime";var X3A=({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 qB(YM2,{children:[qB(n2,{title:Q,description:B,ogType:"profile"},void 0,!1,void 0,this),qB("div",{className:"about-page bg-theme",children:[qB("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:qB("div",{className:"relative z-10 max-w-4xl mx-auto",children:[qB("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&&qB("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),qB("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&qB("section",{className:"content-section-reveal mb-20 md:mb-28",children:qB(RY,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&qB("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),qB("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map(($,D)=>qB("li",{className:MP({variant:"accent",size:"lg"}),children:$},D,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),qB("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&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),qB("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)&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),qB("div",{className:"space-y-4",children:[A.email&&qB("p",{className:"text-lg",children:qB("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&&qB("p",{className:"text-lg",children:qB("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&&qB("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map(($,D)=>qB(J5,{href:$.url,external:!0,variant:"secondary",size:"md",children:$.label||$.platform},D,!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 L9,Fragment as xh0}from"preact/jsx-dev-runtime";var H3A=()=>{return L9(xh0,{children:[L9(n2,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),L9("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:L9("div",{className:"text-center max-w-md",children:[L9("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),L9("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),L9("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),L9(J5,{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)},K3A=()=>{return L9(xh0,{children:[L9(n2,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),L9("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:L9("div",{className:"text-center max-w-md",children:[L9("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),L9("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),L9("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),L9(J5,{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)};GA();var Th0=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')")}),vh0=F.object({entityDisplay:F.object({post:Th0,deck:Th0}).describe("Display metadata for post and deck entity types (required for homepage)")});var Sh0={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.41",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-builder-plugin":"workspace:*","@brains/site-composition":"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 U3A extends tB{dependencies=["blog","decks"];constructor(A){super("professional-site",Sh0,A,vh0)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",Xr);let Q=this.config.entityDisplay.post,B=this.config.entityDisplay.deck,w=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,$=`/${B.pluralName??B.label.toLowerCase()+"s"}`,D=new Hr(w,$);A.entities.registerDataSource(D);let Y=new Kr;A.entities.registerDataSource(Y);let I=F.object({profile:HJ,posts:F.array(aK),decks:F.array(y_),postsListUrl:F.string(),decksListUrl:F.string(),cta:R_}),X=F.object({profile:HJ}),H=F.object({});A.templates.register({"homepage-list":M1({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:I,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:I3A}}),about:M1({name:"about",description:"About page with full profile information",schema:X,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:X3A}}),"subscribe-thanks":M1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:H,requiredPermission:"public",layout:{component:H3A}}),"subscribe-error":M1({name:"subscribe-error",description:"Newsletter subscription error page",schema:H,requiredPermission:"public",layout:{component:K3A}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function hh0(A){return new U3A(A??{})}var gh0=[{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 YE}from"preact/jsx-dev-runtime";function yh0({sections:A,siteInfo:Q,slots:B}){return YE("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[YE(mHA,{title:Q.title,navigation:Q.navigation.primary,...Q.logo!==void 0?{logo:Q.logo}:{}},void 0,!1,void 0,this),YE("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),YE("div",{className:"section-divider"},void 0,!1,void 0,this),YE(gHA,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,children:YE(aWA,{name:"footer-top",slots:B},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var XM2={layouts:{default:yh0},routes:gh0,plugin:hh0,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"}}}},Gb=XM2;var mh0=`/* Default font imports */
4249
+ `).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 BM2=new $B(eL2,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:AM2,parser:QM2},{key:"notes",label:"Notes",type:"string"}]});class Ph0 extends I2{constructor(){super({entityType:"agent",schema:aL2,frontmatterSchema:sL2})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=BM2.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 _h0 extends I2{constructor(){super({entityType:"skill",schema:tL2,frontmatterSchema:j$})}fromMarkdown(A){let Q=this.parseFrontMatter(A,j$);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var JXB=new Ph0,ZXB=new _h0,FXB=F.object({skills:F.array(j$),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:Y3A,discoveredAt:F.string().datetime().optional(),about:F.string(),skills:F.array(kh0),notes:F.string().default("")}))});var wM2=F.object({}).strict();function Ir(A={}){return wM2.parse(A),[D3A()]}B0();GA();s8();GA();B0();var Xr=QS.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.)")}),HJ=AY.extend(Xr.shape);B0();MW();GA();var $M2=new uI;class Hr{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,[$,D,Y,I]=await Promise.all([GN(w),w.listEntities("post",{limit:20}),w.listEntities("deck",{limit:20}),iK(w)]),X=$M2.parseProfileBody($,HJ),H=D.sort(DO).slice(0,3).map(h_),W=Y.sort(DO).slice(0,3).map(u_);if(!I.cta)throw Error("CTA not configured in site-info");let J={profile:X,posts:H,decks:W,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:I.cta};return Q.parse(J)}}B0();MW();var DM2=new uI;class Kr{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,B){let w=await GN(B.entityService),D={profile:DM2.parseProfileBody(w,HJ)};return Q.parse(D)}}import{jsxDEV as c6,Fragment as bh0}from"preact/jsx-dev-runtime";var I3A=({profile:A,posts:Q,decks:B,postsListUrl:w,decksListUrl:$,cta:D})=>{let Y=A.tagline||A.description,I=Q.map((J)=>({id:J.id,url:J.url,title:J.metadata.title,date:J.metadata.publishedAt||J.created,description:J.frontmatter.excerpt,series:J.frontmatter.seriesName&&J.frontmatter.seriesIndex?{name:J.frontmatter.seriesName,index:J.frontmatter.seriesIndex}:void 0})),X=B.map((J)=>({id:J.id,url:J.url,title:J.frontmatter.title||J.id,date:J.frontmatter.publishedAt??J.created,description:J.frontmatter.description})),H=A.name||"Home",W=A.intro||A.description||Y||"Professional site";return c6(bh0,{children:[c6(n2,{title:H,description:W,ogType:"website"},void 0,!1,void 0,this),c6("div",{className:"homepage-list bg-theme",children:[c6("header",{className:"hero-bg-pattern relative w-full min-h-[70vh] flex items-end px-6 md:px-12 bg-theme overflow-hidden",children:c6("div",{className:"relative z-10 max-w-6xl mx-auto w-full pb-16 md:pb-24",children:[Y&&c6("h1",{className:"text-5xl md:text-6xl lg:text-7xl font-semibold text-heading leading-[1.08] tracking-tight",children:Y},void 0,!1,void 0,this),A.intro&&c6(bh0,{children:[c6("div",{className:"w-12 border-t border-theme mt-8 mb-6 md:mt-10 md:mb-8"},void 0,!1,void 0,this),c6("p",{className:"text-lg md:text-xl text-theme-muted leading-relaxed max-w-xl md:max-w-lg",children:A.intro},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),c6("div",{className:"section-divider"},void 0,!1,void 0,this),c6("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[c6("div",{className:"content-section-reveal mb-20 md:mb-32",children:c6(bK,{title:"Essays",items:I,viewAllUrl:w},void 0,!1,void 0,this)},void 0,!1,void 0,this),X.length>0&&c6("div",{className:"content-section-reveal mb-20 md:mb-32",children:c6(bK,{title:"Presentations",items:X,viewAllUrl:$},void 0,!1,void 0,this)},void 0,!1,void 0,this),(A.description||A.expertise&&A.expertise.length>0)&&c6("div",{className:"content-section-reveal mb-20 md:mb-32",children:c6(bK,{title:"About",viewAllUrl:"/about",variant:"stacked",children:c6("div",{className:"space-y-6",children:[A.description&&c6("p",{className:"text-lg text-theme leading-relaxed",children:A.description},void 0,!1,void 0,this),A.expertise&&A.expertise.length>0&&c6(vG,{tags:A.expertise,variant:"accent",size:"sm"},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),c6(SHA,{cta:D,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 qB,Fragment as YM2}from"preact/jsx-dev-runtime";var X3A=({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 qB(YM2,{children:[qB(n2,{title:Q,description:B,ogType:"profile"},void 0,!1,void 0,this),qB("div",{className:"about-page bg-theme",children:[qB("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:qB("div",{className:"relative z-10 max-w-4xl mx-auto",children:[qB("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&&qB("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),qB("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&qB("section",{className:"content-section-reveal mb-20 md:mb-28",children:qB(RY,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&qB("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),qB("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map(($,D)=>qB("li",{className:MP({variant:"accent",size:"lg"}),children:$},D,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),qB("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&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),qB("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)&&qB("section",{children:[qB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),qB("div",{className:"space-y-4",children:[A.email&&qB("p",{className:"text-lg",children:qB("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&&qB("p",{className:"text-lg",children:qB("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&&qB("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map(($,D)=>qB(J5,{href:$.url,external:!0,variant:"secondary",size:"md",children:$.label||$.platform},D,!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 L9,Fragment as xh0}from"preact/jsx-dev-runtime";var H3A=()=>{return L9(xh0,{children:[L9(n2,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),L9("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:L9("div",{className:"text-center max-w-md",children:[L9("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),L9("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),L9("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),L9(J5,{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)},K3A=()=>{return L9(xh0,{children:[L9(n2,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),L9("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:L9("div",{className:"text-center max-w-md",children:[L9("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),L9("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),L9("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),L9(J5,{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)};GA();var Th0=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')")}),vh0=F.object({entityDisplay:F.object({post:Th0,deck:Th0}).describe("Display metadata for post and deck entity types (required for homepage)")});var Sh0={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.42",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-builder-plugin":"workspace:*","@brains/site-composition":"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 U3A extends tB{dependencies=["blog","decks"];constructor(A){super("professional-site",Sh0,A,vh0)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",Xr);let Q=this.config.entityDisplay.post,B=this.config.entityDisplay.deck,w=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,$=`/${B.pluralName??B.label.toLowerCase()+"s"}`,D=new Hr(w,$);A.entities.registerDataSource(D);let Y=new Kr;A.entities.registerDataSource(Y);let I=F.object({profile:HJ,posts:F.array(aK),decks:F.array(y_),postsListUrl:F.string(),decksListUrl:F.string(),cta:R_}),X=F.object({profile:HJ}),H=F.object({});A.templates.register({"homepage-list":M1({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:I,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:I3A}}),about:M1({name:"about",description:"About page with full profile information",schema:X,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:X3A}}),"subscribe-thanks":M1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:H,requiredPermission:"public",layout:{component:H3A}}),"subscribe-error":M1({name:"subscribe-error",description:"Newsletter subscription error page",schema:H,requiredPermission:"public",layout:{component:K3A}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function hh0(A){return new U3A(A??{})}var gh0=[{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 YE}from"preact/jsx-dev-runtime";function yh0({sections:A,siteInfo:Q,slots:B}){return YE("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[YE(mHA,{title:Q.title,navigation:Q.navigation.primary,...Q.logo!==void 0?{logo:Q.logo}:{}},void 0,!1,void 0,this),YE("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),YE("div",{className:"section-divider"},void 0,!1,void 0,this),YE(gHA,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,children:YE(aWA,{name:"footer-top",slots:B},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var XM2={layouts:{default:yh0},routes:gh0,plugin:hh0,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"}}}},Gb=XM2;var mh0=`/* Default font imports */
4250
4250
  @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,200..800;1,200..800&display=swap');
4251
4251
  @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300..700&display=swap');
4252
4252
 
@@ -4550,7 +4550,7 @@ ${JSON.stringify(B,null,2)}`}function wr(A){return A.map((Q)=>Q.detail===null?{t
4550
4550
  .btn-primary:hover { background-color: var(--color-brand-dark); }
4551
4551
  .btn-primary:disabled { opacity: 0.5; }
4552
4552
  }
4553
- `;var Ur=mh0;import{join as UM2}from"path";var uh0={name:"@brains/rover",version:"0.2.0-alpha.41",type:"module",private:!0,main:"./src/index.ts",files:["src","brain.eval.yaml","env.schema.template"],scripts:{"ensure:test-remote":"bun ./scripts/ensure-test-remote.ts","prestart:core":"bun run ensure:test-remote","start:core":"cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","prestart:default":"bun run ensure:test-remote","start:default":"cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","prestart:full":"bun run ensure:test-remote","start:full":"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/blog":"workspace:*","@brains/cms":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/portfolio":"workspace:*","@brains/prompt":"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/topics":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var ch0=["prompt","note","link","wishlist","topics","directory-sync","agents","assessment","cms","dashboard-root","mcp","webserver","discord","a2a"],lh0=[...ch0.filter((A)=>A!=="dashboard-root"),"image","dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],WM2=[...lh0,"portfolio","topics","content-pipeline","social-media","newsletter","stock-photo"],ph0=mW({name:"rover",version:uh0.version,model:"gpt-5.4-mini",site:Gb,theme:Ur,presets:{core:ch0,default:lh0,full:WM2},evalDisable:["discord","webserver","mcp","analytics","dashboard","dashboard-root"],capabilities:[["prompt",Yq,void 0],["image",$j,void 0],["cms",$q,{}],["dashboard",IJ,void 0],["dashboard-root",IJ,{routePath:"/"}],["blog",$GA,{}],["series",HGA,void 0],["decks",c_,void 0],["note",Aq,{}],["link",Bq,{}],["portfolio",mGA,{}],["topics",Ei,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",KJA,{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",t_,{autoGenerateOnBlogPublish:!0}],["newsletter",SS0,{doubleOptIn:!0}],["obsidian-vault",PJA,{autoSync:!0}],["wishlist",mi,{}],["stock-photo",gJA,{}],["agents",ai,void 0],["assessment",Ir,void 0],["directory-sync",zF,{seedContent:!0,seedContentPath:UM2(import.meta.dir,"..","seed-content"),initialSync:!0}],["analytics",Ti,{}],["site-info",dF,void 0],["site-builder",aF,{cms:{}}]],interfaces:[["mcp",nW,()=>({})],["discord",kG,()=>({})],["webserver",PG,()=>({})],["a2a",iL,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"public"},{pattern:"discord:*",level:"public"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});pW();B0();GA();GA();B0();var Wr=F.object({routeId:F.string(),sectionId:F.string()}),Jb=Q2.extend({entityType:F.literal("site-content"),template:F.string().optional(),content:F.string(),metadata:Wr});B0();class dh0 extends I2{constructor(){super({entityType:"site-content",schema:Jb,frontmatterSchema:Wr})}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 W3A=new dh0;GA();var Gr=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")}),fKB=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 G3A{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("site-builder:routes:list",{});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(),D=$;if(A.routeId){if(D=$.filter((W)=>W.id===A.routeId),D.length===0)throw Error(`Route not found: ${A.routeId}`)}let Y=[];for(let W of D)for(let J of W.sections){if(A.sectionId&&J.id!==A.sectionId)continue;if(J.content){w.debug("Section has static content, skipping",{routeId:W.id,sectionId:J.id});continue}if(J.template){let Z=this.context.templates.getCapabilities(J.template);if(!Z){w.warn("Template not found, skipping section",{routeId:W.id,sectionId:J.id,templateName:J.template});continue}if(!Z.canGenerate){w.debug("Template doesn't support generation, skipping",{routeId:W.id,sectionId:J.id,templateName:J.template,capabilities:Z});continue}}else{w.debug("Section has no template, skipping",{routeId:W.id,sectionId:J.id});continue}if(!A.force&&!A.dryRun){let Z=`${W.id}:${J.id}`;if(await this.context.entityService.getEntity("site-content",Z)){w.debug("Content already exists, skipping",{routeId:W.id,sectionId:J.id});continue}}Y.push({route:W,section:J})}let I=Y.length;if(A.dryRun)return{jobs:[],totalSections:I,queuedSections:I,batchId:`dry-run-${Date.now()}`};let X=[],H=[];for(let{route:W,section:J}of Y){let Z=`${W.id}:${J.id}`,q=J.template,V={routeId:W.id,sectionId:J.id,entityId:Z,entityType:"site-content",templateName:q,context:{prompt:typeof J.content==="string"?J.content:void 0,data:{routeId:W.id,sectionId:J.id,routeTitle:W.title||Q?.title||"",routeDescription:W.description||Q?.description||"",sectionContent:J.content},conversationId:"system"},siteConfig:Q};H.push({type:"shell:content-generation",data:V})}if(H.length>0){let W=this.createJobOptions(B,"site:content-generation"),J=await this.context.jobs.enqueueBatch(H,W);for(let Z=0;Z<Y.length;Z++){let q=Y[Z];if(q)X.push({jobId:`${J}-${Z}`,routeId:q.route.id,sectionId:q.section.id})}return{jobs:X,totalSections:I,queuedSections:X.length,batchId:J}}return{jobs:[],totalSections:I,queuedSections:0,batchId:`empty-${Date.now()}`}}}class J3A{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new G3A(A)}async generateContent(A,Q){let B=Gr.parse(A);return this.operations.generate(B,this.siteConfig,Q)}}GA();function Zb(A,Q){return Q?A.optional():A}function F3A(A){switch(A.type){case"string":return Zb(F.string(),A.optional);case"number":return Zb(F.number(),A.optional);case"enum":{let Q=[...A.options];return Zb(F.enum(Q),A.optional)}case"object":{let Q={};for(let[B,w]of Object.entries(A.fields))Q[B]=F3A(w);return Zb(F.object(Q),A.optional)}case"array":{let Q=F.array(GM2(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return Zb(Q,A.optional)}}}function GM2(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]=F3A($);return F.object(B)}}}function Z3A(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])=>Z3A(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,$])=>Z3A(w,$)),B}}}}function JM2(A,Q){let B={};for(let[D,Y]of Object.entries(Q.fields))B[D]=F3A(Y);let w=F.object(B),$=new $B(w,{title:Q.title,mappings:Object.entries(Q.fields).map(([D,Y])=>Z3A(D,Y))});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 q3A(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,B])=>[Q,JM2(Q,B)]))}GA();var ih0=F.object({namespace:F.string(),sections:F.record(F.any())}),rh0=F.object({definitions:F.union([ih0,F.array(ih0)]).optional()});B0();function nh0(A,Q){return[yQ(Q,"generate","Generate content for all routes, a specific route, or a specific section",Gr,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 D={rootJobId:`generate-${Date.now()}`,progressToken:w.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:w.interfaceType,channelId:w.channelId},Y=await $.generateContent(B,D);return{success:!0,message:`Generated ${Y.queuedSections} of ${Y.totalSections} sections. ${Y.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:Y.batchId,jobsQueued:Y.queuedSections,totalSections:Y.totalSections,jobs:Y.jobs}}})]}var oh0={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.41",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/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 z3A extends tB{siteContentService;constructor(A={}){super("site-content",oh0,A,rh0)}async onRegister(A){A.entities.register("site-content",Jb,W3A);for(let Q of vH(this.config.definitions))A.templates.register(q3A(Q),Q.namespace);this.siteContentService=new J3A(A)}async getTools(){return nh0(()=>this.siteContentService,this.id)}}function Fb(A={}){return new z3A(A)}B0();GA();s8();GA();B0();var sh0=F.enum(["available","early access","coming soon","planned"]),ah0=F.object({title:F.string(),description:F.string()}),wU=F.object({name:F.string(),availability:sh0,order:F.number()}),Jr=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(ah0).min(1).max(6),story:F.string()}),FM2=wU.pick({name:!0,availability:!0,order:!0}).extend({slug:F.string()}),IE=Q2.extend({entityType:F.literal("product"),metadata:FM2}),Zr=IE.extend({frontmatter:wU,body:Jr,labels:F.record(F.string(),F.string())}),Fr=Zr.extend({url:F.string().optional(),typeLabel:F.string().optional(),listUrl:F.string().optional(),listLabel:F.string().optional()});B0();GA();GA();class XE extends $B{constructor(){super(Jr,{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 N3A extends I2{constructor(){super({entityType:"product",schema:IE,frontmatterSchema:wU,bodyFormatter:new XE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,wU);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,wU),B=e1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:B,availability:Q.availability,order:Q.order}}}}var qr=new N3A;GA();B0();var th0=F.object({title:F.string(),description:F.string()}),eh0=F.object({title:F.string(),description:F.string()}),qM2=F.object({title:F.string(),description:F.string()}),Ag0=F.object({heading:F.string(),buttonText:F.string(),link:F.string()}),$U=F.object({headline:F.string(),tagline:F.string()}),zM2=F.object({title:F.string(),description:F.string()}),zr=F.object({vision:F.string(),pillars:F.array(th0).min(1).max(6),approach:F.array(zM2).min(1).max(6),productsIntro:F.string(),technologies:F.array(qM2).min(1).max(6),benefits:F.array(eh0).min(1).max(6),cta:Ag0}),Qg0=$U.pick({headline:!0}).extend({slug:F.string()}),HE=Q2.extend({entityType:F.literal("products-overview"),metadata:Qg0}),qb=HE.extend({frontmatter:$U,body:zr,labels:F.record(F.string(),F.string())});B0();GA();GA();class KE extends $B{constructor(){super(zr,{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 V3A extends I2{constructor(){super({entityType:"products-overview",schema:HE,frontmatterSchema:$U,bodyFormatter:new KE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,$U);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,$U),B=e1(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:B}}}}var L3A=new V3A;B0();GA();var NM2=F.object({entityType:F.string(),query:F.object({id:F.string().optional()}).optional()});function Bg0(A,Q){let B=G2(A.content,wU),w=Q.parse(B.content),$=Q.getLabels();return Zr.parse({...A,frontmatter:B.metadata,body:w,labels:$})}function wg0(A,Q){let B=G2(A.content,$U),w=Q.parse(B.content),$=Q.getLabels();return qb.parse({...A,frontmatter:B.metadata,body:w,labels:$})}class Nr{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new KE;productFormatter=new XE;constructor(A){this.logger=A;this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,B){let w=NM2.parse(A),$=B.entityService;if(w.entityType==="products-overview"){let H=(await $.listEntities("products-overview",{limit:1}))[0];if(!H)throw Error("Products overview entity not found");let W=wg0(H,this.overviewFormatter);return Q.parse(W)}if(w.query?.id){let H=(await $.listEntities("product",{filter:{metadata:{slug:w.query.id}},limit:1}))[0];if(!H)throw Error(`Product not found: ${w.query.id}`);return Q.parse({product:Bg0(H,this.productFormatter)})}let[D,Y]=await Promise.all([$.listEntities("products-overview",{limit:1}),$.listEntities("product",{sortFields:[{field:"order",direction:"asc"}]})]),I=D[0];if(!I)throw Error("Products overview entity not found");return Q.parse({overview:wg0(I,this.overviewFormatter),products:Y.map((X)=>Bg0(X,this.productFormatter))})}}import{jsxDEV as l0,Fragment as MM2}from"preact/jsx-dev-runtime";var $g0=({overview:A,products:Q})=>{let{frontmatter:B,body:w,labels:$}=A;return l0(MM2,{children:[l0(n2,{title:B.headline,description:B.tagline},void 0,!1,void 0,this),l0("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[l0("style",{children:`
4553
+ `;var Ur=mh0;import{join as UM2}from"path";var uh0={name:"@brains/rover",version:"0.2.0-alpha.42",type:"module",private:!0,main:"./src/index.ts",files:["src","brain.eval.yaml","env.schema.template"],scripts:{"ensure:test-remote":"bun ./scripts/ensure-test-remote.ts","prestart:core":"bun run ensure:test-remote","start:core":"cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","prestart:default":"bun run ensure:test-remote","start:default":"cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","prestart:full":"bun run ensure:test-remote","start:full":"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/blog":"workspace:*","@brains/cms":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/portfolio":"workspace:*","@brains/prompt":"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/topics":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var ch0=["prompt","note","link","wishlist","topics","directory-sync","agents","assessment","cms","dashboard-root","mcp","webserver","discord","a2a"],lh0=[...ch0.filter((A)=>A!=="dashboard-root"),"image","dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],WM2=[...lh0,"portfolio","topics","content-pipeline","social-media","newsletter","stock-photo"],ph0=mW({name:"rover",version:uh0.version,model:"gpt-5.4-mini",site:Gb,theme:Ur,presets:{core:ch0,default:lh0,full:WM2},evalDisable:["discord","webserver","mcp","analytics","dashboard","dashboard-root"],capabilities:[["prompt",Yq,void 0],["image",$j,void 0],["cms",$q,{}],["dashboard",IJ,void 0],["dashboard-root",IJ,{routePath:"/"}],["blog",$GA,{}],["series",HGA,void 0],["decks",c_,void 0],["note",Aq,{}],["link",Bq,{}],["portfolio",mGA,{}],["topics",Ei,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",KJA,{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",t_,{autoGenerateOnBlogPublish:!0}],["newsletter",SS0,{doubleOptIn:!0}],["obsidian-vault",PJA,{autoSync:!0}],["wishlist",mi,{}],["stock-photo",gJA,{}],["agents",ai,void 0],["assessment",Ir,void 0],["directory-sync",zF,{seedContent:!0,seedContentPath:UM2(import.meta.dir,"..","seed-content"),initialSync:!0}],["analytics",Ti,{}],["site-info",dF,void 0],["site-builder",aF,{cms:{}}]],interfaces:[["mcp",nW,()=>({})],["discord",kG,()=>({})],["webserver",PG,()=>({})],["a2a",iL,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"public"},{pattern:"discord:*",level:"public"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});pW();B0();GA();GA();B0();var Wr=F.object({routeId:F.string(),sectionId:F.string()}),Jb=Q2.extend({entityType:F.literal("site-content"),template:F.string().optional(),content:F.string(),metadata:Wr});B0();class dh0 extends I2{constructor(){super({entityType:"site-content",schema:Jb,frontmatterSchema:Wr})}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 W3A=new dh0;GA();var Gr=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")}),fKB=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 G3A{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("site-builder:routes:list",{});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(),D=$;if(A.routeId){if(D=$.filter((W)=>W.id===A.routeId),D.length===0)throw Error(`Route not found: ${A.routeId}`)}let Y=[];for(let W of D)for(let J of W.sections){if(A.sectionId&&J.id!==A.sectionId)continue;if(J.content){w.debug("Section has static content, skipping",{routeId:W.id,sectionId:J.id});continue}if(J.template){let Z=this.context.templates.getCapabilities(J.template);if(!Z){w.warn("Template not found, skipping section",{routeId:W.id,sectionId:J.id,templateName:J.template});continue}if(!Z.canGenerate){w.debug("Template doesn't support generation, skipping",{routeId:W.id,sectionId:J.id,templateName:J.template,capabilities:Z});continue}}else{w.debug("Section has no template, skipping",{routeId:W.id,sectionId:J.id});continue}if(!A.force&&!A.dryRun){let Z=`${W.id}:${J.id}`;if(await this.context.entityService.getEntity("site-content",Z)){w.debug("Content already exists, skipping",{routeId:W.id,sectionId:J.id});continue}}Y.push({route:W,section:J})}let I=Y.length;if(A.dryRun)return{jobs:[],totalSections:I,queuedSections:I,batchId:`dry-run-${Date.now()}`};let X=[],H=[];for(let{route:W,section:J}of Y){let Z=`${W.id}:${J.id}`,q=J.template,V={routeId:W.id,sectionId:J.id,entityId:Z,entityType:"site-content",templateName:q,context:{prompt:typeof J.content==="string"?J.content:void 0,data:{routeId:W.id,sectionId:J.id,routeTitle:W.title||Q?.title||"",routeDescription:W.description||Q?.description||"",sectionContent:J.content},conversationId:"system"},siteConfig:Q};H.push({type:"shell:content-generation",data:V})}if(H.length>0){let W=this.createJobOptions(B,"site:content-generation"),J=await this.context.jobs.enqueueBatch(H,W);for(let Z=0;Z<Y.length;Z++){let q=Y[Z];if(q)X.push({jobId:`${J}-${Z}`,routeId:q.route.id,sectionId:q.section.id})}return{jobs:X,totalSections:I,queuedSections:X.length,batchId:J}}return{jobs:[],totalSections:I,queuedSections:0,batchId:`empty-${Date.now()}`}}}class J3A{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new G3A(A)}async generateContent(A,Q){let B=Gr.parse(A);return this.operations.generate(B,this.siteConfig,Q)}}GA();function Zb(A,Q){return Q?A.optional():A}function F3A(A){switch(A.type){case"string":return Zb(F.string(),A.optional);case"number":return Zb(F.number(),A.optional);case"enum":{let Q=[...A.options];return Zb(F.enum(Q),A.optional)}case"object":{let Q={};for(let[B,w]of Object.entries(A.fields))Q[B]=F3A(w);return Zb(F.object(Q),A.optional)}case"array":{let Q=F.array(GM2(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return Zb(Q,A.optional)}}}function GM2(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]=F3A($);return F.object(B)}}}function Z3A(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])=>Z3A(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,$])=>Z3A(w,$)),B}}}}function JM2(A,Q){let B={};for(let[D,Y]of Object.entries(Q.fields))B[D]=F3A(Y);let w=F.object(B),$=new $B(w,{title:Q.title,mappings:Object.entries(Q.fields).map(([D,Y])=>Z3A(D,Y))});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 q3A(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,B])=>[Q,JM2(Q,B)]))}GA();var ih0=F.object({namespace:F.string(),sections:F.record(F.any())}),rh0=F.object({definitions:F.union([ih0,F.array(ih0)]).optional()});B0();function nh0(A,Q){return[yQ(Q,"generate","Generate content for all routes, a specific route, or a specific section",Gr,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 D={rootJobId:`generate-${Date.now()}`,progressToken:w.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:w.interfaceType,channelId:w.channelId},Y=await $.generateContent(B,D);return{success:!0,message:`Generated ${Y.queuedSections} of ${Y.totalSections} sections. ${Y.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:Y.batchId,jobsQueued:Y.queuedSections,totalSections:Y.totalSections,jobs:Y.jobs}}})]}var oh0={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.42",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/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 z3A extends tB{siteContentService;constructor(A={}){super("site-content",oh0,A,rh0)}async onRegister(A){A.entities.register("site-content",Jb,W3A);for(let Q of vH(this.config.definitions))A.templates.register(q3A(Q),Q.namespace);this.siteContentService=new J3A(A)}async getTools(){return nh0(()=>this.siteContentService,this.id)}}function Fb(A={}){return new z3A(A)}B0();GA();s8();GA();B0();var sh0=F.enum(["available","early access","coming soon","planned"]),ah0=F.object({title:F.string(),description:F.string()}),wU=F.object({name:F.string(),availability:sh0,order:F.number()}),Jr=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(ah0).min(1).max(6),story:F.string()}),FM2=wU.pick({name:!0,availability:!0,order:!0}).extend({slug:F.string()}),IE=Q2.extend({entityType:F.literal("product"),metadata:FM2}),Zr=IE.extend({frontmatter:wU,body:Jr,labels:F.record(F.string(),F.string())}),Fr=Zr.extend({url:F.string().optional(),typeLabel:F.string().optional(),listUrl:F.string().optional(),listLabel:F.string().optional()});B0();GA();GA();class XE extends $B{constructor(){super(Jr,{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 N3A extends I2{constructor(){super({entityType:"product",schema:IE,frontmatterSchema:wU,bodyFormatter:new XE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,wU);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,wU),B=e1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:B,availability:Q.availability,order:Q.order}}}}var qr=new N3A;GA();B0();var th0=F.object({title:F.string(),description:F.string()}),eh0=F.object({title:F.string(),description:F.string()}),qM2=F.object({title:F.string(),description:F.string()}),Ag0=F.object({heading:F.string(),buttonText:F.string(),link:F.string()}),$U=F.object({headline:F.string(),tagline:F.string()}),zM2=F.object({title:F.string(),description:F.string()}),zr=F.object({vision:F.string(),pillars:F.array(th0).min(1).max(6),approach:F.array(zM2).min(1).max(6),productsIntro:F.string(),technologies:F.array(qM2).min(1).max(6),benefits:F.array(eh0).min(1).max(6),cta:Ag0}),Qg0=$U.pick({headline:!0}).extend({slug:F.string()}),HE=Q2.extend({entityType:F.literal("products-overview"),metadata:Qg0}),qb=HE.extend({frontmatter:$U,body:zr,labels:F.record(F.string(),F.string())});B0();GA();GA();class KE extends $B{constructor(){super(zr,{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 V3A extends I2{constructor(){super({entityType:"products-overview",schema:HE,frontmatterSchema:$U,bodyFormatter:new KE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let B=this.parseFrontMatter(A.content,$U);return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,$U),B=e1(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:B}}}}var L3A=new V3A;B0();GA();var NM2=F.object({entityType:F.string(),query:F.object({id:F.string().optional()}).optional()});function Bg0(A,Q){let B=G2(A.content,wU),w=Q.parse(B.content),$=Q.getLabels();return Zr.parse({...A,frontmatter:B.metadata,body:w,labels:$})}function wg0(A,Q){let B=G2(A.content,$U),w=Q.parse(B.content),$=Q.getLabels();return qb.parse({...A,frontmatter:B.metadata,body:w,labels:$})}class Nr{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new KE;productFormatter=new XE;constructor(A){this.logger=A;this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,B){let w=NM2.parse(A),$=B.entityService;if(w.entityType==="products-overview"){let H=(await $.listEntities("products-overview",{limit:1}))[0];if(!H)throw Error("Products overview entity not found");let W=wg0(H,this.overviewFormatter);return Q.parse(W)}if(w.query?.id){let H=(await $.listEntities("product",{filter:{metadata:{slug:w.query.id}},limit:1}))[0];if(!H)throw Error(`Product not found: ${w.query.id}`);return Q.parse({product:Bg0(H,this.productFormatter)})}let[D,Y]=await Promise.all([$.listEntities("products-overview",{limit:1}),$.listEntities("product",{sortFields:[{field:"order",direction:"asc"}]})]),I=D[0];if(!I)throw Error("Products overview entity not found");return Q.parse({overview:wg0(I,this.overviewFormatter),products:Y.map((X)=>Bg0(X,this.productFormatter))})}}import{jsxDEV as l0,Fragment as MM2}from"preact/jsx-dev-runtime";var $g0=({overview:A,products:Q})=>{let{frontmatter:B,body:w,labels:$}=A;return l0(MM2,{children:[l0(n2,{title:B.headline,description:B.tagline},void 0,!1,void 0,this),l0("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[l0("style",{children:`
4554
4554
  @keyframes wave-drift {
4555
4555
  from { transform: translateX(0); }
4556
4556
  to { transform: translateX(-50%); }
@@ -4578,7 +4578,7 @@ ${JSON.stringify(B,null,2)}`}function wr(A){return A.map((Q)=>Q.detail===null?{t
4578
4578
  @media (prefers-reduced-motion: reduce) {
4579
4579
  .detail-wave { animation: none; }
4580
4580
  }
4581
- `},void 0,!1,void 0,this),b1("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:b1("svg",{preserveAspectRatio:"none",width:"200%",height:"100%",viewBox:"0 0 1600 400",className:"block absolute inset-0 detail-wave",children:[b1("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),b1("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),b1("div",{className:"absolute inset-0 cta-bg-pattern pointer-events-none"},void 0,!1,void 0,this),b1("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:[b1("nav",{"aria-label":"Breadcrumb",className:"text-sm text-white/50 mb-8 hero-stagger-1",children:b1("ol",{className:"flex flex-wrap items-center gap-1",children:[b1("li",{className:"flex items-center gap-1",children:b1("a",{href:"/",className:"hover:text-white transition-colors",children:"Home"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b1("li",{className:"flex items-center gap-1",children:[b1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),b1("a",{href:$,className:"hover:text-white transition-colors",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b1("li",{className:"flex items-center gap-1",children:[b1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),b1("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),b1("div",{className:"mb-6 hero-stagger-1",children:b1(r7,{status:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this),b1("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),b1("div",{className:"w-20 h-1.5 bg-accent mb-6 md:mb-8 hero-stagger-2"},void 0,!1,void 0,this),b1("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),b1("section",{className:"bg-theme-subtle py-20 md:py-28 px-6 md:px-12",children:b1("div",{className:"max-w-4xl mx-auto space-y-16",children:[b1("div",{children:[b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:w.promise},void 0,!1,void 0,this),b1("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),b1("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12 md:gap-16",children:[b1("div",{children:[b1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.role},void 0,!1,void 0,this),b1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.role},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b1("div",{children:[b1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.purpose},void 0,!1,void 0,this),b1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.purpose},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b1("div",{children:[b1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.audience},void 0,!1,void 0,this),b1("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),b1("div",{className:"flex flex-col md:flex-row md:items-center gap-6 md:gap-12",children:[b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted whitespace-nowrap",children:w.values},void 0,!1,void 0,this),b1(vG,{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),b1("section",{className:"cta-bg-pattern bg-brand py-20 md:py-32 px-6 md:px-12",children:b1("div",{className:"container mx-auto max-w-5xl",children:[b1("h2",{className:"text-sm tracking-widest uppercase text-white/50 mb-16",children:w.features},void 0,!1,void 0,this),b1("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 md:gap-16",children:B.features.map((I,X)=>b1("div",{children:b1("div",{className:"flex items-start gap-6",children:[b1("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),b1("div",{className:"pt-2",children:[b1("div",{className:"w-8 h-1 bg-accent mb-4"},void 0,!1,void 0,this),b1("h3",{className:"text-xl font-bold text-white mb-3",children:I.title},void 0,!1,void 0,this),b1("p",{className:"text-white/70 leading-relaxed",children:I.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},I.title,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b1("section",{className:"py-20 md:py-32 px-6 md:px-12",children:b1("div",{className:"max-w-3xl mx-auto",children:[b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-12",children:w.story},void 0,!1,void 0,this),b1("div",{className:"space-y-6",children:Y.map((I,X)=>b1("p",{className:X===0?"text-2xl md:text-3xl leading-relaxed text-heading font-light":"text-lg leading-relaxed text-theme-muted",children:I},X,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b1("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:b1("div",{className:"max-w-4xl mx-auto",children:[b1("p",{className:"text-sm tracking-widest uppercase text-white/60 mb-4",children:Q.name},void 0,!1,void 0,this),b1("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),b1("p",{className:"text-lg text-white/60 mb-10 max-w-xl",children:B.promise},void 0,!1,void 0,this),b1(J5,{href:$,variant:"outline-light",size:"lg",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};GA();var M3A=F.object({route:F.string().default("/products")});var Yg0={name:"@brains/products",private:!0,version:"0.2.0-alpha.41",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/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 OM2=F.object({overview:qb,products:F.array(Fr)}),fM2=F.object({product:Fr});class E3A extends HQ{entityType=qr.entityType;schema=IE;adapter=qr;constructor(A={}){super("products",Yg0,A,M3A)}getTemplates(){return{"product-list":M1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:OM2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:$g0}}),"product-detail":M1({name:"product-detail",description:"Individual product detail page",schema:fM2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Dg0}})}}getDataSources(){return[new Nr(this.logger.child("ProductsDataSource"))]}async onRegister(A){A.entities.register("products-overview",HE,L3A)}}function C3A(A={}){return new E3A(A)}import{join as iM2}from"path";import{jsxDEV as Vr,Fragment as RM2}from"preact/jsx-dev-runtime";var Lr=({children:A})=>Vr(RM2,{children:[Vr("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:Vr("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Vr("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 UWB}from"preact/jsx-dev-runtime";import{jsxDEV as FWB}from"preact/jsx-dev-runtime";var Mr="px-6 md:px-10 xl:px-20",JWB=`${Mr} relative z-[1]`;import{jsxDEV as LWB}from"preact/jsx-dev-runtime";import{jsxDEV as CWB}from"preact/jsx-dev-runtime";import{jsxDEV as jWB}from"preact/jsx-dev-runtime";import{jsxDEV as bWB}from"preact/jsx-dev-runtime";import{jsxDEV as SWB}from"preact/jsx-dev-runtime";import{Fragment as yWB}from"preact";import{jsxDEV as uWB}from"preact/jsx-dev-runtime";import{jsxDEV as pWB}from"preact/jsx-dev-runtime";import{jsxDEV as aWB}from"preact/jsx-dev-runtime";var jM2="pointer-events-none absolute h-[14px] w-[14px] opacity-85 before:content-[''] before:absolute before:left-0 before:top-0 before:h-[1.5px] before:w-full before:bg-current after:content-[''] after:absolute after:left-0 after:top-0 after:h-full after:w-[1.5px] after:bg-current",oWB=`${jM2} z-[2]`;import{jsxDEV as Xg0}from"preact/jsx-dev-runtime";var Er=({sections:A})=>Xg0(Lr,{children:Xg0("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);B0();GA();var Hg0=`/*
4581
+ `},void 0,!1,void 0,this),b1("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:b1("svg",{preserveAspectRatio:"none",width:"200%",height:"100%",viewBox:"0 0 1600 400",className:"block absolute inset-0 detail-wave",children:[b1("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),b1("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),b1("div",{className:"absolute inset-0 cta-bg-pattern pointer-events-none"},void 0,!1,void 0,this),b1("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:[b1("nav",{"aria-label":"Breadcrumb",className:"text-sm text-white/50 mb-8 hero-stagger-1",children:b1("ol",{className:"flex flex-wrap items-center gap-1",children:[b1("li",{className:"flex items-center gap-1",children:b1("a",{href:"/",className:"hover:text-white transition-colors",children:"Home"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b1("li",{className:"flex items-center gap-1",children:[b1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),b1("a",{href:$,className:"hover:text-white transition-colors",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b1("li",{className:"flex items-center gap-1",children:[b1("span",{className:"mx-1","aria-hidden":"true",children:"/"},void 0,!1,void 0,this),b1("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),b1("div",{className:"mb-6 hero-stagger-1",children:b1(r7,{status:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this),b1("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),b1("div",{className:"w-20 h-1.5 bg-accent mb-6 md:mb-8 hero-stagger-2"},void 0,!1,void 0,this),b1("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),b1("section",{className:"bg-theme-subtle py-20 md:py-28 px-6 md:px-12",children:b1("div",{className:"max-w-4xl mx-auto space-y-16",children:[b1("div",{children:[b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:w.promise},void 0,!1,void 0,this),b1("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),b1("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12 md:gap-16",children:[b1("div",{children:[b1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.role},void 0,!1,void 0,this),b1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.role},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b1("div",{children:[b1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.purpose},void 0,!1,void 0,this),b1("p",{className:"text-lg leading-relaxed text-theme-muted",children:B.purpose},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b1("div",{children:[b1("div",{className:"w-8 h-1 bg-accent mb-6"},void 0,!1,void 0,this),b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-4",children:w.audience},void 0,!1,void 0,this),b1("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),b1("div",{className:"flex flex-col md:flex-row md:items-center gap-6 md:gap-12",children:[b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted whitespace-nowrap",children:w.values},void 0,!1,void 0,this),b1(vG,{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),b1("section",{className:"cta-bg-pattern bg-brand py-20 md:py-32 px-6 md:px-12",children:b1("div",{className:"container mx-auto max-w-5xl",children:[b1("h2",{className:"text-sm tracking-widest uppercase text-white/50 mb-16",children:w.features},void 0,!1,void 0,this),b1("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 md:gap-16",children:B.features.map((I,X)=>b1("div",{children:b1("div",{className:"flex items-start gap-6",children:[b1("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),b1("div",{className:"pt-2",children:[b1("div",{className:"w-8 h-1 bg-accent mb-4"},void 0,!1,void 0,this),b1("h3",{className:"text-xl font-bold text-white mb-3",children:I.title},void 0,!1,void 0,this),b1("p",{className:"text-white/70 leading-relaxed",children:I.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},I.title,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b1("section",{className:"py-20 md:py-32 px-6 md:px-12",children:b1("div",{className:"max-w-3xl mx-auto",children:[b1("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-12",children:w.story},void 0,!1,void 0,this),b1("div",{className:"space-y-6",children:Y.map((I,X)=>b1("p",{className:X===0?"text-2xl md:text-3xl leading-relaxed text-heading font-light":"text-lg leading-relaxed text-theme-muted",children:I},X,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b1("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:b1("div",{className:"max-w-4xl mx-auto",children:[b1("p",{className:"text-sm tracking-widest uppercase text-white/60 mb-4",children:Q.name},void 0,!1,void 0,this),b1("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),b1("p",{className:"text-lg text-white/60 mb-10 max-w-xl",children:B.promise},void 0,!1,void 0,this),b1(J5,{href:$,variant:"outline-light",size:"lg",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};GA();var M3A=F.object({route:F.string().default("/products")});var Yg0={name:"@brains/products",private:!0,version:"0.2.0-alpha.42",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/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 OM2=F.object({overview:qb,products:F.array(Fr)}),fM2=F.object({product:Fr});class E3A extends HQ{entityType=qr.entityType;schema=IE;adapter=qr;constructor(A={}){super("products",Yg0,A,M3A)}getTemplates(){return{"product-list":M1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:OM2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:$g0}}),"product-detail":M1({name:"product-detail",description:"Individual product detail page",schema:fM2,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Dg0}})}}getDataSources(){return[new Nr(this.logger.child("ProductsDataSource"))]}async onRegister(A){A.entities.register("products-overview",HE,L3A)}}function C3A(A={}){return new E3A(A)}import{join as iM2}from"path";import{jsxDEV as Vr,Fragment as RM2}from"preact/jsx-dev-runtime";var Lr=({children:A})=>Vr(RM2,{children:[Vr("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:Vr("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Vr("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 UWB}from"preact/jsx-dev-runtime";import{jsxDEV as FWB}from"preact/jsx-dev-runtime";var Mr="px-6 md:px-10 xl:px-20",JWB=`${Mr} relative z-[1]`;import{jsxDEV as LWB}from"preact/jsx-dev-runtime";import{jsxDEV as CWB}from"preact/jsx-dev-runtime";import{jsxDEV as jWB}from"preact/jsx-dev-runtime";import{jsxDEV as bWB}from"preact/jsx-dev-runtime";import{jsxDEV as SWB}from"preact/jsx-dev-runtime";import{Fragment as yWB}from"preact";import{jsxDEV as uWB}from"preact/jsx-dev-runtime";import{jsxDEV as pWB}from"preact/jsx-dev-runtime";import{jsxDEV as aWB}from"preact/jsx-dev-runtime";var jM2="pointer-events-none absolute h-[14px] w-[14px] opacity-85 before:content-[''] before:absolute before:left-0 before:top-0 before:h-[1.5px] before:w-full before:bg-current after:content-[''] after:absolute after:left-0 after:top-0 after:h-full after:w-[1.5px] after:bg-current",oWB=`${jM2} z-[2]`;import{jsxDEV as Xg0}from"preact/jsx-dev-runtime";var Er=({sections:A})=>Xg0(Lr,{children:Xg0("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);B0();GA();var Hg0=`/*
4582
4582
  * Shared globals + helpers used by tree / constellation / roots canvas
4583
4583
  * scripts. Loaded as a shared static asset by the Rizom runtime package
4584
4584
  * so the variant canvases
@@ -6506,6 +6506,7 @@ function drawGlowNode(ctx, x, y, r, color, op, light) {
6506
6506
  /* All variants collapse to amber-dark in light mode for contrast (brand guide A2) */
6507
6507
  --color-accent: var(--palette-amber-dark);
6508
6508
  --color-accent-dark: #8b3a05;
6509
+ --color-accent-bright: var(--palette-amber);
6509
6510
  --color-secondary: var(--palette-purple);
6510
6511
 
6511
6512
  --color-brand: var(--color-accent);
@@ -7010,7 +7011,7 @@ Your task is to:
7010
7011
  2. Generate a clear, natural summary that captures key points, decisions, and action items
7011
7012
  3. Return structured data in the required JSON format
7012
7013
 
7013
- Be concise but comprehensive, focusing on the most important information.`});B0();GA();var tM2=F.object({entityType:F.literal("summary"),query:F.object({id:F.string().optional(),conversationId:F.string().optional(),limit:F.number().optional()}).optional()});class P3A{logger;id="summary:entities";name="Summary Entity DataSource";description="Fetches and transforms summary entities for rendering";adapter;constructor(A){this.logger=A;this.adapter=new mX,this.logger.debug("SummaryDataSource initialized")}async fetch(A,Q,B){let w=tM2.parse(A),$=B.entityService,D=w.query?.conversationId??w.query?.id;if(D){let H=await $.getEntity(w.query?.conversationId?"summary":w.entityType,D);if(!H)throw Error(`Summary not found: ${D}`);let W;try{let Z=G2(H.content,F.record(F.string(),F.unknown()));W=this.adapter.parseEntriesFromContent(Z.content)}catch{W=this.adapter.parseEntriesFromContent(H.content)}let J={conversationId:H.metadata.conversationId,channelName:H.metadata.channelName,entries:W,totalMessages:H.metadata.totalMessages,entryCount:W.length,updated:H.updated};return Q.parse(J)}let I=(await $.listEntities(w.entityType,{limit:w.query?.limit??100})).map((H)=>{let W;try{let Z=G2(H.content,F.record(F.string(),F.unknown()));W=this.adapter.parseEntriesFromContent(Z.content)}catch{W=this.adapter.parseEntriesFromContent(H.content)}let J=W[0];return{id:H.id,conversationId:H.metadata.conversationId,channelName:H.metadata.channelName,entryCount:W.length,totalMessages:H.metadata.totalMessages,latestEntry:J?.title??"No entries",updated:H.updated,created:H.created}}),X={summaries:I,totalCount:I.length};return this.logger.debug("Creating list data",{summaryCount:I.length,firstSummary:I[0]?.id}),Q.parse(X)}}var Ng0={name:"@brains/summary",private:!0,version:"0.2.0-alpha.41",description:"Plugin for generating entity summaries and digests",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts,.tsx","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};var AE2=new mX;class _3A extends HQ{entityType="summary";schema=zb;adapter=AE2;digestHandler=null;constructor(A){super("summary",Ng0,A??{},R3A)}getConfig(){return this.config}getTemplates(){return{"summary-list":Fg0,"summary-detail":qg0,"ai-response":zg0}}getDataSources(){return[new P3A(this.logger)]}async onRegister(A){if(this.digestHandler=YU.getInstance(A,this.logger),this.config.enableAutoSummary)A.messaging.subscribe("conversation:digest",async(Q)=>{let B=tv.parse(Q.payload);return await this.handleDigestMessage({...Q,payload:B}),{success:!0}}),this.logger.debug("Summary plugin subscribed to digest events")}async derive(A,Q,B){}async handleDigestMessage(A){if(!this.digestHandler){this.logger.error("Digest handler not initialized");return}try{await this.digestHandler.handleDigest(A.payload)}catch(Q){this.logger.error("Failed to handle digest message",{messageId:A.id,error:L0(Q)})}}}function b3A(A){return new _3A(A)}var Vg0=["prompt","directory-sync","note","link","topics","agents","assessment","cms","dashboard","mcp","webserver","discord","a2a"],BE2=[...Vg0,"image","site-info","site-content","site-builder"],Lg0=mW({name:"relay",version:"0.1.0",model:"gpt-5.4-mini",site:KJ,theme:WE,presets:{core:Vg0,default:BE2},evalDisable:["webserver","discord"],capabilities:[["prompt",Yq,void 0],["note",Aq,{}],["link",Bq,{}],["image",$j,void 0],["topics",Ei,{}],["summary",b3A,{}],["decks",c_,void 0],["agents",ai,void 0],["assessment",Ir,void 0],["cms",$q,{}],["dashboard",IJ,void 0],["directory-sync",zF,{seedContent:!0,seedContentPath:QE2(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",Fb,void 0],["site-info",dF,void 0],["site-builder",aF,{}]],interfaces:[["mcp",nW,()=>({})],["discord",kG,()=>({captureUrls:!0})],["a2a",iL,()=>({})],["webserver",PG,()=>({})]],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 Mf2}from"fs";import{join as Ef2}from"path";import{execSync as Cf2}from"child_process";import{parseArgs as DE2}from"util";var YE2={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"},remote:{type:"string"},token:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};function IU(A,Q){let B=A[Q];return typeof B==="string"?B:void 0}function GE(A,Q){let B=A[Q];return typeof B==="boolean"?B:void 0}function Mg0(A){let{values:Q,positionals:B}=DE2({args:A,options:YE2,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:IU(Q,"model"),domain:IU(Q,"domain"),"content-repo":IU(Q,"content-repo"),backend:IU(Q,"backend"),"push-to":IU(Q,"push-to"),"ai-api-key":IU(Q,"ai-api-key"),"no-interactive":GE(Q,"no-interactive"),preview:GE(Q,"preview"),deploy:GE(Q,"deploy"),regen:GE(Q,"regen"),all:GE(Q,"all"),only:IU(Q,"only"),"dry-run":GE(Q,"dry-run"),remote:IU(Q,"remote"),token:IU(Q,"token")}}}Lb();import{mkdirSync as Uf2}from"fs";import{join as Wf2}from"path";import{execSync as Gf2}from"child_process";var kr={name:"@rizom/brain",version:"0.2.0-alpha.41",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{"./cli":"./dist/brain.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:{"@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"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",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 jg0,writeFileSync as Eb,chmodSync as Cb,existsSync as br,readFileSync as xr,unlinkSync as PE2}from"fs";import{basename as h3A,dirname as g3A,join as O8,resolve as _E2}from"path";import{fileURLToPath as bE2}from"url";var v3A=`ARG BUN_VERSION=1.3.10
7014
+ Be concise but comprehensive, focusing on the most important information.`});B0();GA();var tM2=F.object({entityType:F.literal("summary"),query:F.object({id:F.string().optional(),conversationId:F.string().optional(),limit:F.number().optional()}).optional()});class P3A{logger;id="summary:entities";name="Summary Entity DataSource";description="Fetches and transforms summary entities for rendering";adapter;constructor(A){this.logger=A;this.adapter=new mX,this.logger.debug("SummaryDataSource initialized")}async fetch(A,Q,B){let w=tM2.parse(A),$=B.entityService,D=w.query?.conversationId??w.query?.id;if(D){let H=await $.getEntity(w.query?.conversationId?"summary":w.entityType,D);if(!H)throw Error(`Summary not found: ${D}`);let W;try{let Z=G2(H.content,F.record(F.string(),F.unknown()));W=this.adapter.parseEntriesFromContent(Z.content)}catch{W=this.adapter.parseEntriesFromContent(H.content)}let J={conversationId:H.metadata.conversationId,channelName:H.metadata.channelName,entries:W,totalMessages:H.metadata.totalMessages,entryCount:W.length,updated:H.updated};return Q.parse(J)}let I=(await $.listEntities(w.entityType,{limit:w.query?.limit??100})).map((H)=>{let W;try{let Z=G2(H.content,F.record(F.string(),F.unknown()));W=this.adapter.parseEntriesFromContent(Z.content)}catch{W=this.adapter.parseEntriesFromContent(H.content)}let J=W[0];return{id:H.id,conversationId:H.metadata.conversationId,channelName:H.metadata.channelName,entryCount:W.length,totalMessages:H.metadata.totalMessages,latestEntry:J?.title??"No entries",updated:H.updated,created:H.created}}),X={summaries:I,totalCount:I.length};return this.logger.debug("Creating list data",{summaryCount:I.length,firstSummary:I[0]?.id}),Q.parse(X)}}var Ng0={name:"@brains/summary",private:!0,version:"0.2.0-alpha.42",description:"Plugin for generating entity summaries and digests",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts,.tsx","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};var AE2=new mX;class _3A extends HQ{entityType="summary";schema=zb;adapter=AE2;digestHandler=null;constructor(A){super("summary",Ng0,A??{},R3A)}getConfig(){return this.config}getTemplates(){return{"summary-list":Fg0,"summary-detail":qg0,"ai-response":zg0}}getDataSources(){return[new P3A(this.logger)]}async onRegister(A){if(this.digestHandler=YU.getInstance(A,this.logger),this.config.enableAutoSummary)A.messaging.subscribe("conversation:digest",async(Q)=>{let B=tv.parse(Q.payload);return await this.handleDigestMessage({...Q,payload:B}),{success:!0}}),this.logger.debug("Summary plugin subscribed to digest events")}async derive(A,Q,B){}async handleDigestMessage(A){if(!this.digestHandler){this.logger.error("Digest handler not initialized");return}try{await this.digestHandler.handleDigest(A.payload)}catch(Q){this.logger.error("Failed to handle digest message",{messageId:A.id,error:L0(Q)})}}}function b3A(A){return new _3A(A)}var Vg0=["prompt","directory-sync","note","link","topics","agents","assessment","cms","dashboard","mcp","webserver","discord","a2a"],BE2=[...Vg0,"image","site-info","site-content","site-builder"],Lg0=mW({name:"relay",version:"0.1.0",model:"gpt-5.4-mini",site:KJ,theme:WE,presets:{core:Vg0,default:BE2},evalDisable:["webserver","discord"],capabilities:[["prompt",Yq,void 0],["note",Aq,{}],["link",Bq,{}],["image",$j,void 0],["topics",Ei,{}],["summary",b3A,{}],["decks",c_,void 0],["agents",ai,void 0],["assessment",Ir,void 0],["cms",$q,{}],["dashboard",IJ,void 0],["directory-sync",zF,{seedContent:!0,seedContentPath:QE2(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",Fb,void 0],["site-info",dF,void 0],["site-builder",aF,{}]],interfaces:[["mcp",nW,()=>({})],["discord",kG,()=>({captureUrls:!0})],["a2a",iL,()=>({})],["webserver",PG,()=>({})]],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 Mf2}from"fs";import{join as Ef2}from"path";import{execSync as Cf2}from"child_process";import{parseArgs as DE2}from"util";var YE2={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"},remote:{type:"string"},token:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};function IU(A,Q){let B=A[Q];return typeof B==="string"?B:void 0}function GE(A,Q){let B=A[Q];return typeof B==="boolean"?B:void 0}function Mg0(A){let{values:Q,positionals:B}=DE2({args:A,options:YE2,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:IU(Q,"model"),domain:IU(Q,"domain"),"content-repo":IU(Q,"content-repo"),backend:IU(Q,"backend"),"push-to":IU(Q,"push-to"),"ai-api-key":IU(Q,"ai-api-key"),"no-interactive":GE(Q,"no-interactive"),preview:GE(Q,"preview"),deploy:GE(Q,"deploy"),regen:GE(Q,"regen"),all:GE(Q,"all"),only:IU(Q,"only"),"dry-run":GE(Q,"dry-run"),remote:IU(Q,"remote"),token:IU(Q,"token")}}}Lb();import{mkdirSync as Uf2}from"fs";import{join as Wf2}from"path";import{execSync as Gf2}from"child_process";var kr={name:"@rizom/brain",version:"0.2.0-alpha.42",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{"./cli":"./dist/brain.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:{"@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"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",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 jg0,writeFileSync as Eb,chmodSync as Cb,existsSync as br,readFileSync as xr,unlinkSync as PE2}from"fs";import{basename as h3A,dirname as g3A,join as O8,resolve as _E2}from"path";import{fileURLToPath as bE2}from"url";var v3A=`ARG BUN_VERSION=1.3.10
7014
7015
  FROM oven/bun:\${BUN_VERSION}-slim AS runtime
7015
7016
 
7016
7017
  WORKDIR /app