@rizom/brain 0.2.0-alpha.135 → 0.2.0-alpha.136

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
@@ -398,7 +398,7 @@ ${Y}`:"")}function Gb0(A,Q,w,B){return async($,Y)=>{if(B){let D={toolName:A,args
398
398
  hash text NOT NULL,
399
399
  created_at numeric
400
400
  )
401
- `;await A.session.run($);let D=(await A.values(g0`SELECT id, hash, created_at FROM ${g0.identifier(B)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,X=[];for(let H of w)if(!D||Number(D[2])<H.folderMillis){for(let W of H.sql)X.push(A.run(g0.raw(W)));X.push(A.run(g0`INSERT INTO ${g0.identifier(B)} ("hash", "created_at") VALUES(${H.hash}, ${H.folderMillis})`))}await A.session.migrate(X)}var Fu=i(()=>{OVA();c$()});async function xVA(A,Q){let w=Q?.child("entity-migrate")??e2.getInstance().child("entity-migrate"),{db:B,client:$,url:Y}=xe(A);w.debug("Running entity database migrations...");try{await Re($,Y);let X=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),await he($),w.debug("Entity database migrations completed successfully")}catch(D){throw w.error("Entity database migration failed:",D),D}finally{$.close()}}var RVA=i(()=>{Fu();HU0();Z0()});async function hVA(A,Q){let w=Q?.child("job-queue-migrate")??e2.getInstance().child("job-queue-migrate"),{db:B,client:$,url:Y}=Pe(A);w.debug("Running job queue migrations...");try{await ke($,Y);let X=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),w.debug("Job queue migrations completed successfully")}catch(D){throw w.error("Job queue migration failed:",D),D}finally{$.close()}}var vVA=i(()=>{Fu();tK0();Z0()});async function CVA(A,Q){let w=Q?.child("conversation-migrate")??e2.getInstance().child("conversation-migrate"),{db:B,client:$,url:Y}=pe(A);w.debug("Running conversation database migrations...");try{if(Y.startsWith("file:"))await $.execute("PRAGMA journal_mode = WAL");let X=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),w.debug("Conversation database migrations completed successfully")}catch(D){throw w.error("Conversation database migration failed:",D),D}finally{$.close()}}var yVA=i(()=>{Fu();rU0();Z0()});async function EVA(A,Q){let w=Q?.child("runtime-state-migrate")??e2.getInstance().child("runtime-state-migrate"),{db:B,client:$,url:Y}=P10(A);w.debug("Running runtime state migrations...");try{await k10($,Y);let X=import.meta.url.includes("/dist/")?new URL("./migrations/runtime-state",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),w.debug("Runtime state migrations completed successfully")}catch(D){throw w.error("Runtime state migration failed:",D),D}finally{$.close()}}var gVA=i(()=>{Fu();Z0();Mb0()});class Vu{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:mS,migrateEntities:xVA,migrateJobQueue:hVA,migrateConversations:CVA,migrateRuntimeState:EVA}}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;if(A?.runtimeStateDatabase)Q.runtimeStateDatabase.url=A.runtimeStateDatabase;await this.migrateEntityDatabase(Q),await this.migrateJobQueueDatabase(Q),await this.migrateConversationDatabase(Q),await this.migrateRuntimeStateDatabase(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)}async migrateRuntimeStateDatabase(A){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:A.runtimeStateDatabase.url,...A.runtimeStateDatabase.authToken&&{authToken:A.runtimeStateDatabase.authToken}},this.logger)}}var pb0=i(()=>{C10();RVA();vVA();yVA();gVA()});function VR2(){return process.env[FR2]}function TVA(){return VR2()!=="production"}var FR2="NODE_ENV";var E10;var ib0=i(()=>{Z0();E10=K.object({theme:K.object({primaryColor:K.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:K.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})})});var mVA;var SVA=i(()=>{mVA={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.135",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{dev:"tsc --watch",typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/plugins":"workspace:*",chalk:"^5.4.1",ink:"^6.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^12.0.0",react:"^19.2.6"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/react":"^19.0.3",typescript:"^5.3.3"}}});var Ww=O((IR2,g10)=>{(function(){function A(X0,u0){Object.defineProperty(B.prototype,X0,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",u0[0],u0[1])}})}function Q(X0){if(X0===null||typeof X0!=="object")return null;return X0=C0&&X0[C0]||X0["@@iterator"],typeof X0==="function"?X0:null}function w(X0,u0){X0=(X0=X0.constructor)&&(X0.displayName||X0.name)||"ReactClass";var R0=X0+"."+u0;G0[R0]||(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.",u0,X0),G0[R0]=!0)}function B(X0,u0,R0){this.props=X0,this.context=u0,this.refs=p0,this.updater=R0||I0}function $(){}function Y(X0,u0,R0){this.props=X0,this.context=u0,this.refs=p0,this.updater=R0||I0}function D(){}function X(X0){return""+X0}function H(X0){try{X(X0);var u0=!1}catch(zA){u0=!0}if(u0){u0=console;var R0=u0.error,n0=typeof Symbol==="function"&&Symbol.toStringTag&&X0[Symbol.toStringTag]||X0.constructor.name||"Object";return R0.call(u0,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n0),X(X0)}}function W(X0){if(X0==null)return null;if(typeof X0==="function")return X0.$$typeof===XA?null:X0.displayName||X0.name||null;if(typeof X0==="string")return X0;switch(X0){case A0:return"Fragment";case K0:return"Profiler";case o:return"StrictMode";case YA:return"Suspense";case D0:return"SuspenseList";case z0:return"Activity"}if(typeof X0==="object")switch(typeof X0.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),X0.$$typeof){case p:return"Portal";case $0:return X0.displayName||"Context";case V0:return(X0._context.displayName||"Context")+".Consumer";case i0:var u0=X0.render;return X0=X0.displayName,X0||(X0=u0.displayName||u0.name||"",X0=X0!==""?"ForwardRef("+X0+")":"ForwardRef"),X0;case _0:return u0=X0.displayName||null,u0!==null?u0:W(X0.type)||"Memo";case x0:u0=X0._payload,X0=X0._init;try{return W(X0(u0))}catch(R0){}}return null}function f(X0){if(X0===A0)return"<>";if(typeof X0==="object"&&X0!==null&&X0.$$typeof===x0)return"<...>";try{var u0=W(X0);return u0?"<"+u0+">":"<...>"}catch(R0){return"<...>"}}function Z(){var X0=BA.A;return X0===null?null:X0.getOwner()}function G(){return Error("react-stack-top-frame")}function F(X0){if(k0.call(X0,"key")){var u0=Object.getOwnPropertyDescriptor(X0,"key").get;if(u0&&u0.isReactWarning)return!1}return X0.key!==void 0}function V(X0,u0){function R0(){W0||(W0=!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)",u0))}R0.isReactWarning=!0,Object.defineProperty(X0,"key",{get:R0,configurable:!0})}function b(){var X0=W(this.type);return Q1[X0]||(Q1[X0]=!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.")),X0=this.props.ref,X0!==void 0?X0:null}function L(X0,u0,R0,n0,zA,MA){var $A=R0.ref;return X0={$$typeof:l,type:X0,key:u0,props:R0,_owner:n0},($A!==void 0?$A:null)!==null?Object.defineProperty(X0,"ref",{enumerable:!1,get:b}):Object.defineProperty(X0,"ref",{enumerable:!1,value:null}),X0._store={},Object.defineProperty(X0._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(X0,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(X0,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:zA}),Object.defineProperty(X0,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:MA}),Object.freeze&&(Object.freeze(X0.props),Object.freeze(X0)),X0}function N(X0,u0){return u0=L(X0.type,u0,X0.props,X0._owner,X0._debugStack,X0._debugTask),X0._store&&(u0._store.validated=X0._store.validated),u0}function _(X0){j(X0)?X0._store&&(X0._store.validated=1):typeof X0==="object"&&X0!==null&&X0.$$typeof===x0&&(X0._payload.status==="fulfilled"?j(X0._payload.value)&&X0._payload.value._store&&(X0._payload.value._store.validated=1):X0._store&&(X0._store.validated=1))}function j(X0){return typeof X0==="object"&&X0!==null&&X0.$$typeof===l}function g(X0){var u0={"=":"=0",":":"=2"};return"$"+X0.replace(/[=:]/g,function(R0){return u0[R0]})}function E(X0,u0){return typeof X0==="object"&&X0!==null&&X0.key!=null?(H(X0.key),g(""+X0.key)):u0.toString(36)}function y(X0){switch(X0.status){case"fulfilled":return X0.value;case"rejected":throw X0.reason;default:switch(typeof X0.status==="string"?X0.then(D,D):(X0.status="pending",X0.then(function(u0){X0.status==="pending"&&(X0.status="fulfilled",X0.value=u0)},function(u0){X0.status==="pending"&&(X0.status="rejected",X0.reason=u0)})),X0.status){case"fulfilled":return X0.value;case"rejected":throw X0.reason}}throw X0}function h(X0,u0,R0,n0,zA){var MA=typeof X0;if(MA==="undefined"||MA==="boolean")X0=null;var $A=!1;if(X0===null)$A=!0;else switch(MA){case"bigint":case"string":case"number":$A=!0;break;case"object":switch(X0.$$typeof){case l:case p:$A=!0;break;case x0:return $A=X0._init,h($A(X0._payload),u0,R0,n0,zA)}}if($A){$A=X0,zA=zA($A);var tA=n0===""?"."+E($A,0):n0;return FA(zA)?(R0="",tA!=null&&(R0=tA.replace(y0,"$&/")+"/"),h(zA,u0,R0,"",function(l1){return l1})):zA!=null&&(j(zA)&&(zA.key!=null&&($A&&$A.key===zA.key||H(zA.key)),R0=N(zA,R0+(zA.key==null||$A&&$A.key===zA.key?"":(""+zA.key).replace(y0,"$&/")+"/")+tA),n0!==""&&$A!=null&&j($A)&&$A.key==null&&$A._store&&!$A._store.validated&&(R0._store.validated=2),zA=R0),u0.push(zA)),1}if($A=0,tA=n0===""?".":n0+":",FA(X0))for(var gA=0;gA<X0.length;gA++)n0=X0[gA],MA=tA+E(n0,gA),$A+=h(n0,u0,R0,MA,zA);else if(gA=Q(X0),typeof gA==="function")for(gA===X0.entries&&(o0||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),o0=!0),X0=gA.call(X0),gA=0;!(n0=X0.next()).done;)n0=n0.value,MA=tA+E(n0,gA++),$A+=h(n0,u0,R0,MA,zA);else if(MA==="object"){if(typeof X0.then==="function")return h(y(X0),u0,R0,n0,zA);throw u0=String(X0),Error("Objects are not valid as a React child (found: "+(u0==="[object Object]"?"object with keys {"+Object.keys(X0).join(", ")+"}":u0)+"). If you meant to render a collection of children, use an array instead.")}return $A}function T(X0,u0,R0){if(X0==null)return X0;var n0=[],zA=0;return h(X0,n0,"","",function(MA){return u0.call(R0,MA,zA++)}),n0}function S(X0){if(X0._status===-1){var u0=X0._ioInfo;u0!=null&&(u0.start=u0.end=performance.now()),u0=X0._result;var R0=u0();if(R0.then(function(zA){if(X0._status===0||X0._status===-1){X0._status=1,X0._result=zA;var MA=X0._ioInfo;MA!=null&&(MA.end=performance.now()),R0.status===void 0&&(R0.status="fulfilled",R0.value=zA)}},function(zA){if(X0._status===0||X0._status===-1){X0._status=2,X0._result=zA;var MA=X0._ioInfo;MA!=null&&(MA.end=performance.now()),R0.status===void 0&&(R0.status="rejected",R0.reason=zA)}}),u0=X0._ioInfo,u0!=null){u0.value=R0;var n0=R0.displayName;typeof n0==="string"&&(u0.name=n0)}X0._status===-1&&(X0._status=0,X0._result=R0)}if(X0._status===1)return u0=X0._result,u0===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
401
+ `;await A.session.run($);let D=(await A.values(g0`SELECT id, hash, created_at FROM ${g0.identifier(B)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,X=[];for(let H of w)if(!D||Number(D[2])<H.folderMillis){for(let W of H.sql)X.push(A.run(g0.raw(W)));X.push(A.run(g0`INSERT INTO ${g0.identifier(B)} ("hash", "created_at") VALUES(${H.hash}, ${H.folderMillis})`))}await A.session.migrate(X)}var Fu=i(()=>{OVA();c$()});async function xVA(A,Q){let w=Q?.child("entity-migrate")??e2.getInstance().child("entity-migrate"),{db:B,client:$,url:Y}=xe(A);w.debug("Running entity database migrations...");try{await Re($,Y);let X=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),await he($),w.debug("Entity database migrations completed successfully")}catch(D){throw w.error("Entity database migration failed:",D),D}finally{$.close()}}var RVA=i(()=>{Fu();HU0();Z0()});async function hVA(A,Q){let w=Q?.child("job-queue-migrate")??e2.getInstance().child("job-queue-migrate"),{db:B,client:$,url:Y}=Pe(A);w.debug("Running job queue migrations...");try{await ke($,Y);let X=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),w.debug("Job queue migrations completed successfully")}catch(D){throw w.error("Job queue migration failed:",D),D}finally{$.close()}}var vVA=i(()=>{Fu();tK0();Z0()});async function CVA(A,Q){let w=Q?.child("conversation-migrate")??e2.getInstance().child("conversation-migrate"),{db:B,client:$,url:Y}=pe(A);w.debug("Running conversation database migrations...");try{if(Y.startsWith("file:"))await $.execute("PRAGMA journal_mode = WAL");let X=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),w.debug("Conversation database migrations completed successfully")}catch(D){throw w.error("Conversation database migration failed:",D),D}finally{$.close()}}var yVA=i(()=>{Fu();rU0();Z0()});async function EVA(A,Q){let w=Q?.child("runtime-state-migrate")??e2.getInstance().child("runtime-state-migrate"),{db:B,client:$,url:Y}=P10(A);w.debug("Running runtime state migrations...");try{await k10($,Y);let X=import.meta.url.includes("/dist/")?new URL("./migrations/runtime-state",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await KJ(B,{migrationsFolder:X}),w.debug("Runtime state migrations completed successfully")}catch(D){throw w.error("Runtime state migration failed:",D),D}finally{$.close()}}var gVA=i(()=>{Fu();Z0();Mb0()});class Vu{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:mS,migrateEntities:xVA,migrateJobQueue:hVA,migrateConversations:CVA,migrateRuntimeState:EVA}}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;if(A?.runtimeStateDatabase)Q.runtimeStateDatabase.url=A.runtimeStateDatabase;await this.migrateEntityDatabase(Q),await this.migrateJobQueueDatabase(Q),await this.migrateConversationDatabase(Q),await this.migrateRuntimeStateDatabase(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)}async migrateRuntimeStateDatabase(A){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:A.runtimeStateDatabase.url,...A.runtimeStateDatabase.authToken&&{authToken:A.runtimeStateDatabase.authToken}},this.logger)}}var pb0=i(()=>{C10();RVA();vVA();yVA();gVA()});function VR2(){return process.env[FR2]}function TVA(){return VR2()!=="production"}var FR2="NODE_ENV";var E10;var ib0=i(()=>{Z0();E10=K.object({theme:K.object({primaryColor:K.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:K.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})})});var mVA;var SVA=i(()=>{mVA={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.136",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{dev:"tsc --watch",typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/plugins":"workspace:*",chalk:"^5.4.1",ink:"^6.0.1","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^12.0.0",react:"^19.2.6"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/react":"^19.0.3",typescript:"^5.3.3"}}});var Ww=O((IR2,g10)=>{(function(){function A(X0,u0){Object.defineProperty(B.prototype,X0,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",u0[0],u0[1])}})}function Q(X0){if(X0===null||typeof X0!=="object")return null;return X0=C0&&X0[C0]||X0["@@iterator"],typeof X0==="function"?X0:null}function w(X0,u0){X0=(X0=X0.constructor)&&(X0.displayName||X0.name)||"ReactClass";var R0=X0+"."+u0;G0[R0]||(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.",u0,X0),G0[R0]=!0)}function B(X0,u0,R0){this.props=X0,this.context=u0,this.refs=p0,this.updater=R0||I0}function $(){}function Y(X0,u0,R0){this.props=X0,this.context=u0,this.refs=p0,this.updater=R0||I0}function D(){}function X(X0){return""+X0}function H(X0){try{X(X0);var u0=!1}catch(zA){u0=!0}if(u0){u0=console;var R0=u0.error,n0=typeof Symbol==="function"&&Symbol.toStringTag&&X0[Symbol.toStringTag]||X0.constructor.name||"Object";return R0.call(u0,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n0),X(X0)}}function W(X0){if(X0==null)return null;if(typeof X0==="function")return X0.$$typeof===XA?null:X0.displayName||X0.name||null;if(typeof X0==="string")return X0;switch(X0){case A0:return"Fragment";case K0:return"Profiler";case o:return"StrictMode";case YA:return"Suspense";case D0:return"SuspenseList";case z0:return"Activity"}if(typeof X0==="object")switch(typeof X0.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),X0.$$typeof){case p:return"Portal";case $0:return X0.displayName||"Context";case V0:return(X0._context.displayName||"Context")+".Consumer";case i0:var u0=X0.render;return X0=X0.displayName,X0||(X0=u0.displayName||u0.name||"",X0=X0!==""?"ForwardRef("+X0+")":"ForwardRef"),X0;case _0:return u0=X0.displayName||null,u0!==null?u0:W(X0.type)||"Memo";case x0:u0=X0._payload,X0=X0._init;try{return W(X0(u0))}catch(R0){}}return null}function f(X0){if(X0===A0)return"<>";if(typeof X0==="object"&&X0!==null&&X0.$$typeof===x0)return"<...>";try{var u0=W(X0);return u0?"<"+u0+">":"<...>"}catch(R0){return"<...>"}}function Z(){var X0=BA.A;return X0===null?null:X0.getOwner()}function G(){return Error("react-stack-top-frame")}function F(X0){if(k0.call(X0,"key")){var u0=Object.getOwnPropertyDescriptor(X0,"key").get;if(u0&&u0.isReactWarning)return!1}return X0.key!==void 0}function V(X0,u0){function R0(){W0||(W0=!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)",u0))}R0.isReactWarning=!0,Object.defineProperty(X0,"key",{get:R0,configurable:!0})}function b(){var X0=W(this.type);return Q1[X0]||(Q1[X0]=!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.")),X0=this.props.ref,X0!==void 0?X0:null}function L(X0,u0,R0,n0,zA,MA){var $A=R0.ref;return X0={$$typeof:l,type:X0,key:u0,props:R0,_owner:n0},($A!==void 0?$A:null)!==null?Object.defineProperty(X0,"ref",{enumerable:!1,get:b}):Object.defineProperty(X0,"ref",{enumerable:!1,value:null}),X0._store={},Object.defineProperty(X0._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(X0,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(X0,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:zA}),Object.defineProperty(X0,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:MA}),Object.freeze&&(Object.freeze(X0.props),Object.freeze(X0)),X0}function N(X0,u0){return u0=L(X0.type,u0,X0.props,X0._owner,X0._debugStack,X0._debugTask),X0._store&&(u0._store.validated=X0._store.validated),u0}function _(X0){j(X0)?X0._store&&(X0._store.validated=1):typeof X0==="object"&&X0!==null&&X0.$$typeof===x0&&(X0._payload.status==="fulfilled"?j(X0._payload.value)&&X0._payload.value._store&&(X0._payload.value._store.validated=1):X0._store&&(X0._store.validated=1))}function j(X0){return typeof X0==="object"&&X0!==null&&X0.$$typeof===l}function g(X0){var u0={"=":"=0",":":"=2"};return"$"+X0.replace(/[=:]/g,function(R0){return u0[R0]})}function E(X0,u0){return typeof X0==="object"&&X0!==null&&X0.key!=null?(H(X0.key),g(""+X0.key)):u0.toString(36)}function y(X0){switch(X0.status){case"fulfilled":return X0.value;case"rejected":throw X0.reason;default:switch(typeof X0.status==="string"?X0.then(D,D):(X0.status="pending",X0.then(function(u0){X0.status==="pending"&&(X0.status="fulfilled",X0.value=u0)},function(u0){X0.status==="pending"&&(X0.status="rejected",X0.reason=u0)})),X0.status){case"fulfilled":return X0.value;case"rejected":throw X0.reason}}throw X0}function h(X0,u0,R0,n0,zA){var MA=typeof X0;if(MA==="undefined"||MA==="boolean")X0=null;var $A=!1;if(X0===null)$A=!0;else switch(MA){case"bigint":case"string":case"number":$A=!0;break;case"object":switch(X0.$$typeof){case l:case p:$A=!0;break;case x0:return $A=X0._init,h($A(X0._payload),u0,R0,n0,zA)}}if($A){$A=X0,zA=zA($A);var tA=n0===""?"."+E($A,0):n0;return FA(zA)?(R0="",tA!=null&&(R0=tA.replace(y0,"$&/")+"/"),h(zA,u0,R0,"",function(l1){return l1})):zA!=null&&(j(zA)&&(zA.key!=null&&($A&&$A.key===zA.key||H(zA.key)),R0=N(zA,R0+(zA.key==null||$A&&$A.key===zA.key?"":(""+zA.key).replace(y0,"$&/")+"/")+tA),n0!==""&&$A!=null&&j($A)&&$A.key==null&&$A._store&&!$A._store.validated&&(R0._store.validated=2),zA=R0),u0.push(zA)),1}if($A=0,tA=n0===""?".":n0+":",FA(X0))for(var gA=0;gA<X0.length;gA++)n0=X0[gA],MA=tA+E(n0,gA),$A+=h(n0,u0,R0,MA,zA);else if(gA=Q(X0),typeof gA==="function")for(gA===X0.entries&&(o0||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),o0=!0),X0=gA.call(X0),gA=0;!(n0=X0.next()).done;)n0=n0.value,MA=tA+E(n0,gA++),$A+=h(n0,u0,R0,MA,zA);else if(MA==="object"){if(typeof X0.then==="function")return h(y(X0),u0,R0,n0,zA);throw u0=String(X0),Error("Objects are not valid as a React child (found: "+(u0==="[object Object]"?"object with keys {"+Object.keys(X0).join(", ")+"}":u0)+"). If you meant to render a collection of children, use an array instead.")}return $A}function T(X0,u0,R0){if(X0==null)return X0;var n0=[],zA=0;return h(X0,n0,"","",function(MA){return u0.call(R0,MA,zA++)}),n0}function S(X0){if(X0._status===-1){var u0=X0._ioInfo;u0!=null&&(u0.start=u0.end=performance.now()),u0=X0._result;var R0=u0();if(R0.then(function(zA){if(X0._status===0||X0._status===-1){X0._status=1,X0._result=zA;var MA=X0._ioInfo;MA!=null&&(MA.end=performance.now()),R0.status===void 0&&(R0.status="fulfilled",R0.value=zA)}},function(zA){if(X0._status===0||X0._status===-1){X0._status=2,X0._result=zA;var MA=X0._ioInfo;MA!=null&&(MA.end=performance.now()),R0.status===void 0&&(R0.status="rejected",R0.reason=zA)}}),u0=X0._ioInfo,u0!=null){u0.value=R0;var n0=R0.displayName;typeof n0==="string"&&(u0.name=n0)}X0._status===-1&&(X0._status=0,X0._result=R0)}if(X0._status===1)return u0=X0._result,u0===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
402
402
 
403
403
  Your code should look like:
404
404
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -1695,7 +1695,7 @@ Example bad output: "A dreamlike crystal formation glowing with ethereal light i
1695
1695
  Title: "${A.entityTitle??X}"
1696
1696
 
1697
1697
  Content:
1698
- ${f}`,ag2);W=`${B.trim()} ${N.imagePrompt}`}catch(N){this.logger.warn("AI prompt distillation failed, using fallback",{error:vA(N)})}}await this.reportProgress(w,{progress:PQ.PROCESS,message:"Generating image"});let Z=this.context.identity.get(),G=this.context.identity.getProfile(),V=ZjA(Z,G)+W,b;try{b=await this.context.ai.generateImage(V,{...$&&{aspectRatio:$}})}catch(N){return this.logger.error("Image generation failed",{jobId:Q,error:vA(N)}),x6.failure(N)}await this.reportProgress(w,{progress:PQ.GENERATE,message:"Creating image entity"});let L=hX.createImageEntity({dataUrl:b.dataUrl,title:X,status:"draft",attachmentType:"generated",...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}});if(await LX({entityService:this.context.entityService,entity:{...L,id:H}}),this.logger.debug("Created image entity",{imageId:H}),Y&&D){await this.reportProgress(w,{progress:PQ.SAVE,message:`Updating ${Y} with cover image`});let N=await JN(this.context.entityService,Y,D,this.logger);if(!N)return x6.failure(Error(`Target entity not found: ${Y}/${D}`));let _=Wj(N,H);await this.context.entities.update(_),this.logger.debug("Updated target entity with cover image",{targetEntityType:Y,targetEntityId:D,imageId:H})}return await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:H,targetEntityType:Y,targetEntityId:D}),{success:!0,imageId:H}}catch(W){let f=vA(W);return this.logger.error("Image generation job failed",{jobId:Q,error:f}),await UU({entityService:this.context.entityService,entityType:"image",id:H,error:f}),x6.failure(W)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}c0();Z0();CB();D4();var eg2=K.object({sourceEntityType:K.string().min(1),sourceEntityId:K.string().min(1),attachmentType:K.string().min(1),imageId:K.string().min(1),dedupKey:K.string().min(1).optional(),replace:K.boolean().optional(),targetEntityType:K.string().min(1).optional(),targetEntityId:K.string().min(1).optional(),targetImageField:K.enum(["coverImageId","ogImageId"]).optional()});class Xj0 extends _w{context;constructor(A,Q){super(Q,{schema:eg2,jobTypeName:"image-render-source"});this.context=A}async process(A,Q,w){this.logger.debug("Starting source image render job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,imageId:A.imageId});try{if(A.replace!==!0&&A.dedupKey){let D=await this.findImageByDedupKey(A.dedupKey);if(D)return await this.updateTarget(A,D.id),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Reusing existing generated image"}),{success:!0,imageId:D.id,reused:!0}}await this.reportProgress(w,{progress:PQ.PROCESS,message:"Rendering source image"});let B=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!B)return x6.failure(Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`));if(B.type!=="image")return x6.failure(Error(`Attachment provider returned ${B.type}; expected image`));await this.reportProgress(w,{progress:PQ.GENERATE,message:"Creating image entity"});let $=B.mimeType.split("/")[1]??"png",Y=hX.createImageEntity({dataUrl:gb0(B.data.toString("base64"),$),title:A.imageId,status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,...A.dedupKey&&{dedupKey:A.dedupKey}});return await LX({entityService:this.context.entityService,entity:{...Y,id:A.imageId}}),await this.updateTarget(A,A.imageId),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Image render complete"}),{success:!0,imageId:A.imageId,reused:!1}}catch(B){let $=vA(B);return this.logger.error("Source image render job failed",{jobId:Q,error:$}),await UU({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:$}),x6.failure(B)}}async findImageByDedupKey(A){return(await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{dedupKey:A}}}})).find((w)=>w.metadata.status!=="pending"&&w.metadata.status!=="failed")}async updateTarget(A,Q){if(!A.targetEntityType||!A.targetEntityId)return;let w=await JN(this.context.entityService,A.targetEntityType,A.targetEntityId,this.logger);if(!w)throw Error(`Target entity not found: ${A.targetEntityType}/${A.targetEntityId}`);let $=(A.targetImageField??"coverImageId")==="ogImageId"?qu(w,Q):Wj(w,Q);await this.context.entities.update($)}}c0();Z0();CB();D4();Z0();var rR={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function $Q0(A){return["image/png","image/jpeg","image/webp","image/gif"].includes(A.toLowerCase())}function YQ0(A){let Q=AT2(A.title,A.filename),w=w1(Q);if(!w)throw Error("Could not derive an image id from the uploaded filename. Provide a title.");return{id:w,title:Q}}function KjA(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function AT2(A,Q){let w=A?.trim();if(w)return w;return Q.replace(/\.[^.]+$/,"").trim()||Q}var QT2=K.object({uploadId:K.string().min(1),imageId:K.string().min(1).optional(),title:K.string().optional()});class Hj0 extends _w{context;constructor(A,Q){super(A,{schema:QT2,jobTypeName:"upload-promote"});this.context=Q}async process(A,Q,w){try{await this.reportProgress(w,{progress:10,message:"Reading uploaded image"});let B=await this.context.uploads.scoped(rR).read(A.uploadId);if(!$Q0(B.record.mediaType))throw Error("Only image uploads can be promoted to image entities");let $=YQ0({filename:B.record.filename,...A.title!==void 0?{title:A.title}:{}}),Y=A.imageId??$.id;await this.reportProgress(w,{progress:60,message:"Saving uploaded image"});let D=new Date().toISOString(),X=hX.createImageEntity({dataUrl:KjA(B.record.mediaType,B.content),title:$.title,status:"draft",sourceUploadId:A.uploadId,sourceFilename:B.record.filename,sourceMediaType:B.record.mediaType,attachmentType:"uploaded"}),H=await LX({entityService:this.context.entityService,entity:{id:Y,...X,created:D,updated:D}});return await this.reportProgress(w,{progress:100,message:"Uploaded image promoted"}),{entityId:H.entityId,status:"created"}}catch(B){if(A.imageId)await UU({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:vA(B)});return x6.failure(B)}}summarizeDataForLog(A){return{uploadId:A.uploadId,imageId:A.imageId,hasTitle:A.title!==void 0}}}var UjA={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.135",description:"Plugin for AI-powered image generation and management",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var BT2="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",$T2=K.object({defaultAspectRatio:K.enum(["1:1","16:9","9:16","4:3","3:4"]).default("16:9").describe("Default aspect ratio for generated images")});function NZ(A){let Q=A?.trim();if(!Q)return;return Q}function YT2(A){let Q=NZ(A.prompt);if(Q)return Q;let w=NZ(A.content);if(w&&!Dj0(w))return w;return}function DT2(A){let Q=A.attachmentType==="og-image"?"og":A.attachmentType;return w1(`${Q}-${A.sourceEntityType}-${A.sourceEntityId}`)}function GjA(A){let Q=NZ(A.title)??(A.targetEntityId?`cover-${A.targetEntityId}`:A.prompt.slice(0,60).trim());return w1(Q)}async function XT2(A,Q){let w=`${Q.attachmentType}:${Q.sourceEntityType}:${Q.sourceEntityId}:resolved-attachment`,B=await A.entityService.getEntity({entityType:Q.sourceEntityType,id:Q.sourceEntityId});return B?`${w}:${B.contentHash}`:w}function Wj0(A,Q="generated"){let w=encodeURIComponent(A);return{mediaType:"image/png",url:`/api/chat/attachments/image?id=${w}`,downloadUrl:`/api/chat/attachments/image?id=${w}&download=1`,filename:`${A}.png`,source:{entityType:"image",entityId:A,attachmentType:Q}}}function HT2(A){let Q=encodeURIComponent(A.entityId);return{mediaType:A.mediaType,url:`/api/chat/attachments/image?id=${Q}`,downloadUrl:`/api/chat/attachments/image?id=${Q}&download=1`,filename:A.filename,source:{entityType:"image",entityId:A.entityId,attachmentType:"uploaded"}}}class fj0 extends kQ{entityType=hX.entityType;schema=Gu;adapter=hX;constructor(A={}){super("image",UjA,A,$T2)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,w){if(A.from?.kind===rR.refKind)return this.promoteUpload(A,w);let B=YT2(A),$=NZ(A.targetEntityType),Y=NZ(A.targetEntityId),D=$===this.entityType?Y:void 0,X=A.from;if(X?.kind==="entity-attachment")return this.enqueueSourceImageRender({...A,from:X},w);if(!$||!Y||D){if(!B)return{kind:"continue",input:A};let G=NZ(A.title)??D,F=GjA({prompt:B,...G&&{title:G}});await this.createPendingImage(w,{id:F,title:G??B.slice(0,60).trim(),alt:G??B.slice(0,60).trim(),attachmentType:"generated"});let V=await w.jobs.enqueue({type:"image-generate",data:{prompt:B,...G&&{title:G}}});return{kind:"handled",result:{success:!0,data:{entityId:F,status:"generating",jobId:V,attachment:Wj0(F)}}}}let H=await A4(w.entityService,$,Y,this.logger,"Target entity");if(!H.ok)return{kind:"handled",result:{success:!1,error:H.error}};if(!B)return{kind:"continue",input:{...A,targetEntityId:H.entity.id}};let W=wQ0(H.entity.content),f=GjA({prompt:B,...A.title&&{title:A.title},targetEntityId:H.entity.id});await this.createPendingImage(w,{id:f,title:A.title??`cover-${H.entity.id}`,alt:A.title??`cover-${H.entity.id}`,attachmentType:"generated",sourceEntityType:$,sourceEntityId:H.entity.id});let Z=await w.jobs.enqueue({type:"image-generate",data:{prompt:B,...A.title&&{title:A.title},targetEntityType:$,targetEntityId:H.entity.id,entityTitle:typeof H.entity.metadata.title==="string"?H.entity.metadata.title:H.entity.id,...W&&{entityContent:W}}});return{kind:"handled",result:{success:!0,data:{entityId:f,status:"generating",jobId:Z,attachment:Wj0(f)}}}}async promoteUpload(A,Q){let w=A.from;if(w?.kind!==rR.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let B=w.id,$;try{$=await Q.uploads.scoped(rR).readRecord(B)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}if(!$Q0($.mediaType))return{kind:"handled",result:{success:!1,error:"Only image uploads can be promoted to image entities"}};let Y;try{Y=YQ0({filename:$.filename,...A.title!==void 0?{title:A.title}:{}})}catch(X){return{kind:"handled",result:{success:!1,error:X instanceof Error?X.message:String(X)}}}await this.createPendingImage(Q,{id:Y.id,title:Y.title,alt:Y.title,sourceUploadId:B,sourceFilename:$.filename,sourceMediaType:$.mediaType,attachmentType:"uploaded"});let D=await Q.jobs.enqueue({type:"upload-promote",data:{uploadId:B,imageId:Y.id,title:Y.title}});return{kind:"handled",result:{success:!0,data:{entityId:Y.id,status:"generating",jobId:D,attachment:HT2({mediaType:$.mediaType,entityId:Y.id,filename:$.filename})}}}}async enqueueSourceImageRender(A,Q){let w=NZ(A.from.sourceEntityType),B=NZ(A.from.sourceEntityId),$=NZ(A.from.attachmentType);if(!w||!B||!$)return{kind:"handled",result:{success:!1,error:"Image source requires sourceEntityType, sourceEntityId, and attachmentType"}};let Y=await A4(Q.entityService,w,B,this.logger,"Source entity");if(!Y.ok)return{kind:"handled",result:{success:!1,error:Y.error}};let D=NZ(A.targetEntityType),X=NZ(A.targetEntityId),H;if(D&&X){let F=await A4(Q.entityService,D,X,this.logger,"Target entity");if(!F.ok)return{kind:"handled",result:{success:!1,error:F.error}};H=F.entity.id}let W={sourceEntityType:w,sourceEntityId:Y.entity.id,attachmentType:$},f=await XT2(Q,W),Z=DT2(W);await this.createPendingImage(Q,{id:Z,title:Z,alt:Z,sourceEntityType:W.sourceEntityType,sourceEntityId:W.sourceEntityId,attachmentType:$,dedupKey:f});let G=await Q.jobs.enqueue({type:"image-render-source",data:{...W,imageId:Z,dedupKey:f,...A.replace===!0&&{replace:!0},...D&&{targetEntityType:D},...H&&{targetEntityId:H},...$==="og-image"&&{targetImageField:"ogImageId"}}});return{kind:"handled",result:{success:!0,data:{entityId:Z,status:"generating",jobId:G,attachment:Wj0(Z,$)}}}}async createPendingImage(A,Q){let w=new Date().toISOString(),B=hX.createImageEntity({dataUrl:BT2,title:Q.title,alt:Q.alt,status:"pending",attachmentType:Q.attachmentType,...Q.sourceEntityType&&{sourceEntityType:Q.sourceEntityType},...Q.sourceEntityId&&{sourceEntityId:Q.sourceEntityId},...Q.sourceUploadId&&{sourceUploadId:Q.sourceUploadId},...Q.sourceFilename&&{sourceFilename:Q.sourceFilename},...Q.sourceMediaType&&{sourceMediaType:Q.sourceMediaType},...Q.dedupKey&&{dedupKey:Q.dedupKey}});await bN({entityService:A.entityService,entity:{id:Q.id,...B,created:w,updated:w}})}async getInstructions(){return"Image entities store durable images. Standalone generated images are valid system_generate image calls with a prompt source and no target fields. A prompt source creates a new image; never use it to describe, analyze, or discuss an existing uploaded image. For uploaded-image discussion, answer directly from the attachment/context; if the user later asks to save that discussion as a note, create entityType note from prior-response or exact text. targetEntityType and targetEntityId are only for attaching the result to an existing entity as coverImageId. Cover images and OG/social preview images are distinct domain concepts: cover-image fields use coverImageId, while OG/Open Graph/social preview fields use ogImageId. Rendered OG/social preview images are deterministic attachment-source images with attachmentType og-image."}createGenerationHandler(A){return new BQ0(A,this.logger)}async onRegister(A){A.entities.registerUploadSaveHandler({entityType:this.entityType,mediaTypes:["image/*"],handler:async(w)=>{let B=await this.promoteUpload({entityType:this.entityType,...w.title!==void 0?{title:w.title}:{},from:w.upload},A);return B.kind==="handled"?B.result:{success:!1,error:"Image upload save was not handled"}}});let Q=new BQ0(A,this.logger);A.jobs.registerHandler("image-generate",Q),A.jobs.registerHandler("image-render-source",new Xj0(A,this.logger)),A.jobs.registerHandler("upload-promote",new Hj0(this.logger.child("UploadPromotionJobHandler"),A))}}function Gc(A){return new fj0(A)}c0();import{StdioServerTransport as WT2}from"@modelcontextprotocol/sdk/server/stdio.js";function zjA(){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 Zj0(){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 DQ0(A){if(A&&typeof A==="object"&&"info"in A&&"debug"in A&&"error"in A&&"warn"in A){let Q=A;return{info:(w,...B)=>Q.info(w,...B),debug:(w,...B)=>Q.debug(w,...B),error:(w,...B)=>Q.error(w,...B),warn:(w,...B)=>Q.warn(w,...B)}}return Zj0()}class jZ{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return jZ.instance??=new jZ(A),jZ.instance}static resetInstance(){if(jZ.instance)jZ.instance.stop(),jZ.instance=null}static createFresh(A){return new jZ(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?DQ0(this.config.logger):zjA()}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 WT2,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 qjA}from"crypto";import{WebStandardStreamableHTTPServerTransport as fT2}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as ZT2}from"@modelcontextprotocol/sdk/types.js";c0();var KT2={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Session-Id, MCP-Protocol-Version, Last-Event-ID","Access-Control-Allow-Private-Network":"true","X-Content-Type-Options":"nosniff"};function UT2(A){let Q=new URL(A.url),B=A.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),$=A.headers.get("x-forwarded-host")??A.headers.get("host");if(!$)return Q.origin;return`${B??Q.protocol.replace(":","")}://${$}`}class mq{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?DQ0(this.config.logger):Zj0(),this.authConfig=A.auth??{},!this.authConfig.disabled&&!this.authConfig.token&&!this.authConfig.verifyBearerToken)throw Error("MCP HTTP transport requires an auth token or bearer token verifier. Set MCP_AUTH_TOKEN, configure OAuth verification, or pass auth: { disabled: true } for local dev.")}static getInstance(A){return mq.instance??=new mq(A),mq.instance}static resetInstance(){mq.instance=null}static createFresh(A){return new mq(A)}withCors(A){let Q=new Headers(A.headers);for(let[w,B]of Object.entries(KT2))Q.set(w,B);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}createJsonResponse(A,Q=200){return this.withCors(new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json"}}))}createTextResponse(A,Q=200){return this.withCors(new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8"}}))}getAuthErrorResponse(A,Q=401,w){let B=this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},Q);if(!w)return B;let $=new Headers(B.headers);return $.set("WWW-Authenticate",w),new Response(B.body,{status:B.status,statusText:B.statusText,headers:$})}getBearerChallenge(A,Q={}){let B={resource_metadata:`${UT2(A)}/.well-known/oauth-protected-resource`,...Q};return`Bearer ${Object.entries(B).map(([Y,D])=>`${Y}="${GT2(D)}"`).join(", ")}`}async authenticate(A){let Q=new URL(A.url).pathname;if(Q==="/health"||Q==="/status"||Q==="/mcp"&&A.method==="OPTIONS")return null;if(this.authConfig.disabled)return null;let w=A.headers.get("authorization");if(!w?.startsWith("Bearer "))return this.logger.warn("Authentication failed: Missing Bearer token"),this.getAuthErrorResponse("Unauthorized: Bearer token required",401,this.getBearerChallenge(A,{realm:"mcp"}));if(this.authConfig.token){if(w.substring(7)!==this.authConfig.token)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));return this.logger.debug("Authentication successful"),null}try{let B=await this.authConfig.verifyBearerToken?.(A);if(!B)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));let $=this.authConfig.requiredScopes??[],Y=$.filter((D)=>!B.scope?.includes(D));if(Y.length>0)return this.logger.warn(`Authentication failed: Missing required scope(s): ${Y.join(", ")}`),this.getAuthErrorResponse("Forbidden: Missing required scope",403,this.getBearerChallenge(A,{error:"insufficient_scope",scope:$.join(" ")}));return this.logger.debug("Authentication successful"),null}catch(B){return this.logger.warn("Authentication failed: Invalid token",B),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}))}}async handleMcpRequest(A){let Q=A.headers.get("mcp-session-id")??void 0;if(A.method==="GET"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.debug(`GET /mcp - SSE stream for session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="DELETE"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.info(`DELETE /mcp - Terminating session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="OPTIONS")return this.withCors(new Response(null,{status:204}));if(A.method!=="POST")return this.createTextResponse("Method Not Allowed",405);if(!this.mcpServer)return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Service Unavailable: MCP server not connected"},id:null},503);let w=await A.json();this.logger.debug(`POST /mcp - Session: ${Q??"new"}`);try{let B;if(Q&&this.transports[Q])B=this.transports[Q];else if(!Q&&ZT2(w))B=new fT2({sessionIdGenerator:()=>qjA(),onsessioninitialized:(Y)=>{this.logger.info(`Session initialized: ${Y}`),this.transports[Y]=B},onsessionclosed:(Y)=>{this.logger.info(`Session closed: ${Y}`),delete this.transports[Y]}}),await(this.mcpTransport?this.mcpTransport.createMcpServer():this.mcpServer).connect(B);else return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32000,message:"Bad Request: Server not initialized"},id:null},400);return this.withCors(await B.handleRequest(A,{parsedBody:w}))}catch(B){return this.logger.error("MCP transport error:",B),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:w}=await A.json();if(!Q||typeof Q!=="string")return this.createJsonResponse({error:"Missing or invalid 'message' field"},400);let B=w??qjA();this.logger.debug(`POST /api/chat - conversation: ${B}`);try{let $=await this.agentService.chat(Q,B);return this.createJsonResponse($)}catch($){return this.logger.error("Agent chat error:",$),this.createJsonResponse({error:$ instanceof Error?$.message:"Internal error"},500)}}async handleAgentConfirmRequest(A){if(!this.agentService)return this.createJsonResponse({error:"Agent service not connected"},503);let{conversationId:Q,confirmed:w,approvalId:B,context:$}=await A.json();if(!Q||typeof Q!=="string")return this.createJsonResponse({error:"Missing or invalid 'conversationId' field"},400);if(typeof w!=="boolean")return this.createJsonResponse({error:"Missing or invalid 'confirmed' field"},400);if(typeof B!=="string"||B.length===0)return this.createJsonResponse({error:"Missing or invalid 'approvalId' field"},400);let Y=AG0.safeParse($);if(!Y.success||!Y.data.userPermissionLevel)return this.createJsonResponse({error:"Missing or invalid 'context' field"},400);this.logger.debug(`POST /api/chat/confirm - conversation: ${Q}`);try{let D=await this.agentService.confirmPendingAction(Q,w,B,Y.data);return this.createJsonResponse(D)}catch(D){return this.logger.error("Agent confirm error:",D),this.createJsonResponse({error:D instanceof Error?D.message:"Internal error"},500)}}async handleRequest(A){let Q=new URL(A.url);this.logger.debug(`${A.method} ${Q.pathname}`);let w=await this.authenticate(A);if(w)return w;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);if(Q.pathname==="/api/chat/confirm"&&A.method==="POST")return this.handleAgentConfirmRequest(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:(w)=>this.handleRequest(w)}),this.boundPort=this.server.port??A,this.logger.info(`StreamableHTTP server listening on http://${Q}:${this.boundPort}/mcp`)}catch(w){if(w.code==="EADDRINUSE")this.logger.error(`Port ${A} is already in use`);throw w}}async stop(){for(let A in this.transports)try{let Q=this.transports[A];if(Q)this.logger.debug(`Closing transport for session ${A}`),await Q.close(),delete this.transports[A]}catch(Q){this.logger.error(`Error closing transport for session ${A}:`,Q)}if(this.server)await this.server.stop(),this.logger.info("StreamableHTTP server stopped"),this.server=null,this.boundPort=null}getPort(){if(this.boundPort===null)throw Error("Server is not running");return this.boundPort}getApp(){return{fetch:(A)=>this.handleRequest(A)}}isRunning(){return this.server!==null}getSessionCount(){return Object.keys(this.transports).length}}function GT2(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}import{randomUUID as qT2}from"crypto";import{mkdir as FT2,readFile as VT2,writeFile as JT2,chmod as IT2}from"fs/promises";import{dirname as bT2,join as LT2}from"path";function FjA(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function VjA(A){try{return new URL(A)}catch{return}}function Kj0(A,Q){if(A===Q)return!0;let w=VjA(A),B=VjA(Q);if(!w||!B)return!1;if(!FjA(w.hostname)||!FjA(B.hostname))return!1;return w.protocol===B.protocol&&w.port===B.port&&zT2(w.pathname,B.pathname)&&w.search===B.search&&w.hash===B.hash}function zT2(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function Uj0(A,Q){return A.some((w)=>Kj0(w,Q))}var NT2="oauth-auth-codes.json",jT2=600;function JjA(){return Math.floor(Date.now()/1000)}function MT2(A){if(!A||typeof A!=="object")return!1;let Q=A;return typeof Q.code==="string"&&typeof Q.client_id==="string"&&typeof Q.redirect_uri==="string"&&typeof Q.code_challenge==="string"&&Q.code_challenge_method==="S256"&&typeof Q.subject==="string"&&typeof Q.created_at==="number"&&typeof Q.expires_at==="number"}function _T2(A){if(!A||typeof A!=="object")return{codes:[]};let Q=A.codes;if(!Array.isArray(Q))return{codes:[]};return{codes:Q.filter(MT2)}}async function PT2(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class XQ0{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=LT2(A.storageDir,A.storeFile??NT2)}async createCode(A){let Q=JjA(),w={code:`ocd_${qT2()}`,client_id:A.clientId,redirect_uri:A.redirectUri,code_challenge:A.codeChallenge,code_challenge_method:"S256",...A.scope?{scope:A.scope}:{},subject:A.subject,created_at:Q,expires_at:Q+jT2};return await this.enqueueWrite(async()=>{let B=await this.readStore();B.codes=B.codes.filter(($)=>$.expires_at>Q),B.codes.push(w),await this.writeStore(B)}),w}async consumeCode(A){let Q=JjA(),w;if(await this.enqueueWrite(async()=>{let B=await this.readStore(),$=B.codes.findIndex((X)=>X.code===A.code),Y=$>=0?B.codes[$]:void 0;if(!Y)throw new MZ("Authorization code not found");if(Y.consumed_at!==void 0)throw new MZ("Authorization code already consumed");if(Y.expires_at<=Q)throw new MZ("Authorization code expired");if(Y.client_id!==A.clientId)throw new MZ("Authorization code client mismatch");if(!Kj0(Y.redirect_uri,A.redirectUri))throw new MZ("Authorization code redirect URI mismatch");let D=await PT2(A.codeVerifier);if(Y.code_challenge!==D)throw new MZ("PKCE verification failed");w={...Y,consumed_at:Q},B.codes[$]=w,await this.writeStore(B)}),!w)throw new MZ("Authorization code not consumed");return w}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return _T2(JSON.parse(await VT2(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{codes:[]};throw A}}async writeStore(A){await FT2(bT2(this.storeFile),{recursive:!0,mode:448}),await JT2(this.storeFile,`${JSON.stringify(A,null,2)}
1698
+ ${f}`,ag2);W=`${B.trim()} ${N.imagePrompt}`}catch(N){this.logger.warn("AI prompt distillation failed, using fallback",{error:vA(N)})}}await this.reportProgress(w,{progress:PQ.PROCESS,message:"Generating image"});let Z=this.context.identity.get(),G=this.context.identity.getProfile(),V=ZjA(Z,G)+W,b;try{b=await this.context.ai.generateImage(V,{...$&&{aspectRatio:$}})}catch(N){return this.logger.error("Image generation failed",{jobId:Q,error:vA(N)}),x6.failure(N)}await this.reportProgress(w,{progress:PQ.GENERATE,message:"Creating image entity"});let L=hX.createImageEntity({dataUrl:b.dataUrl,title:X,status:"draft",attachmentType:"generated",...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}});if(await LX({entityService:this.context.entityService,entity:{...L,id:H}}),this.logger.debug("Created image entity",{imageId:H}),Y&&D){await this.reportProgress(w,{progress:PQ.SAVE,message:`Updating ${Y} with cover image`});let N=await JN(this.context.entityService,Y,D,this.logger);if(!N)return x6.failure(Error(`Target entity not found: ${Y}/${D}`));let _=Wj(N,H);await this.context.entities.update(_),this.logger.debug("Updated target entity with cover image",{targetEntityType:Y,targetEntityId:D,imageId:H})}return await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:H,targetEntityType:Y,targetEntityId:D}),{success:!0,imageId:H}}catch(W){let f=vA(W);return this.logger.error("Image generation job failed",{jobId:Q,error:f}),await UU({entityService:this.context.entityService,entityType:"image",id:H,error:f}),x6.failure(W)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}c0();Z0();CB();D4();var eg2=K.object({sourceEntityType:K.string().min(1),sourceEntityId:K.string().min(1),attachmentType:K.string().min(1),imageId:K.string().min(1),dedupKey:K.string().min(1).optional(),replace:K.boolean().optional(),targetEntityType:K.string().min(1).optional(),targetEntityId:K.string().min(1).optional(),targetImageField:K.enum(["coverImageId","ogImageId"]).optional()});class Xj0 extends _w{context;constructor(A,Q){super(Q,{schema:eg2,jobTypeName:"image-render-source"});this.context=A}async process(A,Q,w){this.logger.debug("Starting source image render job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,imageId:A.imageId});try{if(A.replace!==!0&&A.dedupKey){let D=await this.findImageByDedupKey(A.dedupKey);if(D)return await this.updateTarget(A,D.id),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Reusing existing generated image"}),{success:!0,imageId:D.id,reused:!0}}await this.reportProgress(w,{progress:PQ.PROCESS,message:"Rendering source image"});let B=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!B)return x6.failure(Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`));if(B.type!=="image")return x6.failure(Error(`Attachment provider returned ${B.type}; expected image`));await this.reportProgress(w,{progress:PQ.GENERATE,message:"Creating image entity"});let $=B.mimeType.split("/")[1]??"png",Y=hX.createImageEntity({dataUrl:gb0(B.data.toString("base64"),$),title:A.imageId,status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,...A.dedupKey&&{dedupKey:A.dedupKey}});return await LX({entityService:this.context.entityService,entity:{...Y,id:A.imageId}}),await this.updateTarget(A,A.imageId),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Image render complete"}),{success:!0,imageId:A.imageId,reused:!1}}catch(B){let $=vA(B);return this.logger.error("Source image render job failed",{jobId:Q,error:$}),await UU({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:$}),x6.failure(B)}}async findImageByDedupKey(A){return(await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{dedupKey:A}}}})).find((w)=>w.metadata.status!=="pending"&&w.metadata.status!=="failed")}async updateTarget(A,Q){if(!A.targetEntityType||!A.targetEntityId)return;let w=await JN(this.context.entityService,A.targetEntityType,A.targetEntityId,this.logger);if(!w)throw Error(`Target entity not found: ${A.targetEntityType}/${A.targetEntityId}`);let $=(A.targetImageField??"coverImageId")==="ogImageId"?qu(w,Q):Wj(w,Q);await this.context.entities.update($)}}c0();Z0();CB();D4();Z0();var rR={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function $Q0(A){return["image/png","image/jpeg","image/webp","image/gif"].includes(A.toLowerCase())}function YQ0(A){let Q=AT2(A.title,A.filename),w=w1(Q);if(!w)throw Error("Could not derive an image id from the uploaded filename. Provide a title.");return{id:w,title:Q}}function KjA(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function AT2(A,Q){let w=A?.trim();if(w)return w;return Q.replace(/\.[^.]+$/,"").trim()||Q}var QT2=K.object({uploadId:K.string().min(1),imageId:K.string().min(1).optional(),title:K.string().optional()});class Hj0 extends _w{context;constructor(A,Q){super(A,{schema:QT2,jobTypeName:"upload-promote"});this.context=Q}async process(A,Q,w){try{await this.reportProgress(w,{progress:10,message:"Reading uploaded image"});let B=await this.context.uploads.scoped(rR).read(A.uploadId);if(!$Q0(B.record.mediaType))throw Error("Only image uploads can be promoted to image entities");let $=YQ0({filename:B.record.filename,...A.title!==void 0?{title:A.title}:{}}),Y=A.imageId??$.id;await this.reportProgress(w,{progress:60,message:"Saving uploaded image"});let D=new Date().toISOString(),X=hX.createImageEntity({dataUrl:KjA(B.record.mediaType,B.content),title:$.title,status:"draft",sourceUploadId:A.uploadId,sourceFilename:B.record.filename,sourceMediaType:B.record.mediaType,attachmentType:"uploaded"}),H=await LX({entityService:this.context.entityService,entity:{id:Y,...X,created:D,updated:D}});return await this.reportProgress(w,{progress:100,message:"Uploaded image promoted"}),{entityId:H.entityId,status:"created"}}catch(B){if(A.imageId)await UU({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:vA(B)});return x6.failure(B)}}summarizeDataForLog(A){return{uploadId:A.uploadId,imageId:A.imageId,hasTitle:A.title!==void 0}}}var UjA={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.136",description:"Plugin for AI-powered image generation and management",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var BT2="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",$T2=K.object({defaultAspectRatio:K.enum(["1:1","16:9","9:16","4:3","3:4"]).default("16:9").describe("Default aspect ratio for generated images")});function NZ(A){let Q=A?.trim();if(!Q)return;return Q}function YT2(A){let Q=NZ(A.prompt);if(Q)return Q;let w=NZ(A.content);if(w&&!Dj0(w))return w;return}function DT2(A){let Q=A.attachmentType==="og-image"?"og":A.attachmentType;return w1(`${Q}-${A.sourceEntityType}-${A.sourceEntityId}`)}function GjA(A){let Q=NZ(A.title)??(A.targetEntityId?`cover-${A.targetEntityId}`:A.prompt.slice(0,60).trim());return w1(Q)}async function XT2(A,Q){let w=`${Q.attachmentType}:${Q.sourceEntityType}:${Q.sourceEntityId}:resolved-attachment`,B=await A.entityService.getEntity({entityType:Q.sourceEntityType,id:Q.sourceEntityId});return B?`${w}:${B.contentHash}`:w}function Wj0(A,Q="generated"){let w=encodeURIComponent(A);return{mediaType:"image/png",url:`/api/chat/attachments/image?id=${w}`,downloadUrl:`/api/chat/attachments/image?id=${w}&download=1`,filename:`${A}.png`,source:{entityType:"image",entityId:A,attachmentType:Q}}}function HT2(A){let Q=encodeURIComponent(A.entityId);return{mediaType:A.mediaType,url:`/api/chat/attachments/image?id=${Q}`,downloadUrl:`/api/chat/attachments/image?id=${Q}&download=1`,filename:A.filename,source:{entityType:"image",entityId:A.entityId,attachmentType:"uploaded"}}}class fj0 extends kQ{entityType=hX.entityType;schema=Gu;adapter=hX;constructor(A={}){super("image",UjA,A,$T2)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,w){if(A.from?.kind===rR.refKind)return this.promoteUpload(A,w);let B=YT2(A),$=NZ(A.targetEntityType),Y=NZ(A.targetEntityId),D=$===this.entityType?Y:void 0,X=A.from;if(X?.kind==="entity-attachment")return this.enqueueSourceImageRender({...A,from:X},w);if(!$||!Y||D){if(!B)return{kind:"continue",input:A};let G=NZ(A.title)??D,F=GjA({prompt:B,...G&&{title:G}});await this.createPendingImage(w,{id:F,title:G??B.slice(0,60).trim(),alt:G??B.slice(0,60).trim(),attachmentType:"generated"});let V=await w.jobs.enqueue({type:"image-generate",data:{prompt:B,...G&&{title:G}}});return{kind:"handled",result:{success:!0,data:{entityId:F,status:"generating",jobId:V,attachment:Wj0(F)}}}}let H=await A4(w.entityService,$,Y,this.logger,"Target entity");if(!H.ok)return{kind:"handled",result:{success:!1,error:H.error}};if(!B)return{kind:"continue",input:{...A,targetEntityId:H.entity.id}};let W=wQ0(H.entity.content),f=GjA({prompt:B,...A.title&&{title:A.title},targetEntityId:H.entity.id});await this.createPendingImage(w,{id:f,title:A.title??`cover-${H.entity.id}`,alt:A.title??`cover-${H.entity.id}`,attachmentType:"generated",sourceEntityType:$,sourceEntityId:H.entity.id});let Z=await w.jobs.enqueue({type:"image-generate",data:{prompt:B,...A.title&&{title:A.title},targetEntityType:$,targetEntityId:H.entity.id,entityTitle:typeof H.entity.metadata.title==="string"?H.entity.metadata.title:H.entity.id,...W&&{entityContent:W}}});return{kind:"handled",result:{success:!0,data:{entityId:f,status:"generating",jobId:Z,attachment:Wj0(f)}}}}async promoteUpload(A,Q){let w=A.from;if(w?.kind!==rR.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let B=w.id,$;try{$=await Q.uploads.scoped(rR).readRecord(B)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}if(!$Q0($.mediaType))return{kind:"handled",result:{success:!1,error:"Only image uploads can be promoted to image entities"}};let Y;try{Y=YQ0({filename:$.filename,...A.title!==void 0?{title:A.title}:{}})}catch(X){return{kind:"handled",result:{success:!1,error:X instanceof Error?X.message:String(X)}}}await this.createPendingImage(Q,{id:Y.id,title:Y.title,alt:Y.title,sourceUploadId:B,sourceFilename:$.filename,sourceMediaType:$.mediaType,attachmentType:"uploaded"});let D=await Q.jobs.enqueue({type:"upload-promote",data:{uploadId:B,imageId:Y.id,title:Y.title}});return{kind:"handled",result:{success:!0,data:{entityId:Y.id,status:"generating",jobId:D,attachment:HT2({mediaType:$.mediaType,entityId:Y.id,filename:$.filename})}}}}async enqueueSourceImageRender(A,Q){let w=NZ(A.from.sourceEntityType),B=NZ(A.from.sourceEntityId),$=NZ(A.from.attachmentType);if(!w||!B||!$)return{kind:"handled",result:{success:!1,error:"Image source requires sourceEntityType, sourceEntityId, and attachmentType"}};let Y=await A4(Q.entityService,w,B,this.logger,"Source entity");if(!Y.ok)return{kind:"handled",result:{success:!1,error:Y.error}};let D=NZ(A.targetEntityType),X=NZ(A.targetEntityId),H;if(D&&X){let F=await A4(Q.entityService,D,X,this.logger,"Target entity");if(!F.ok)return{kind:"handled",result:{success:!1,error:F.error}};H=F.entity.id}let W={sourceEntityType:w,sourceEntityId:Y.entity.id,attachmentType:$},f=await XT2(Q,W),Z=DT2(W);await this.createPendingImage(Q,{id:Z,title:Z,alt:Z,sourceEntityType:W.sourceEntityType,sourceEntityId:W.sourceEntityId,attachmentType:$,dedupKey:f});let G=await Q.jobs.enqueue({type:"image-render-source",data:{...W,imageId:Z,dedupKey:f,...A.replace===!0&&{replace:!0},...D&&{targetEntityType:D},...H&&{targetEntityId:H},...$==="og-image"&&{targetImageField:"ogImageId"}}});return{kind:"handled",result:{success:!0,data:{entityId:Z,status:"generating",jobId:G,attachment:Wj0(Z,$)}}}}async createPendingImage(A,Q){let w=new Date().toISOString(),B=hX.createImageEntity({dataUrl:BT2,title:Q.title,alt:Q.alt,status:"pending",attachmentType:Q.attachmentType,...Q.sourceEntityType&&{sourceEntityType:Q.sourceEntityType},...Q.sourceEntityId&&{sourceEntityId:Q.sourceEntityId},...Q.sourceUploadId&&{sourceUploadId:Q.sourceUploadId},...Q.sourceFilename&&{sourceFilename:Q.sourceFilename},...Q.sourceMediaType&&{sourceMediaType:Q.sourceMediaType},...Q.dedupKey&&{dedupKey:Q.dedupKey}});await bN({entityService:A.entityService,entity:{id:Q.id,...B,created:w,updated:w}})}async getInstructions(){return"Image entities store durable images. Standalone generated images are valid system_generate image calls with a prompt source and no target fields. A prompt source creates a new image; never use it to describe, analyze, or discuss an existing uploaded image. For uploaded-image discussion, answer directly from the attachment/context; if the user later asks to save that discussion as a note, create entityType note from prior-response or exact text. targetEntityType and targetEntityId are only for attaching the result to an existing entity as coverImageId. Cover images and OG/social preview images are distinct domain concepts: cover-image fields use coverImageId, while OG/Open Graph/social preview fields use ogImageId. Rendered OG/social preview images are deterministic attachment-source images with attachmentType og-image."}createGenerationHandler(A){return new BQ0(A,this.logger)}async onRegister(A){A.entities.registerUploadSaveHandler({entityType:this.entityType,mediaTypes:["image/*"],handler:async(w)=>{let B=await this.promoteUpload({entityType:this.entityType,...w.title!==void 0?{title:w.title}:{},from:w.upload},A);return B.kind==="handled"?B.result:{success:!1,error:"Image upload save was not handled"}}});let Q=new BQ0(A,this.logger);A.jobs.registerHandler("image-generate",Q),A.jobs.registerHandler("image-render-source",new Xj0(A,this.logger)),A.jobs.registerHandler("upload-promote",new Hj0(this.logger.child("UploadPromotionJobHandler"),A))}}function Gc(A){return new fj0(A)}c0();import{StdioServerTransport as WT2}from"@modelcontextprotocol/sdk/server/stdio.js";function zjA(){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 Zj0(){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 DQ0(A){if(A&&typeof A==="object"&&"info"in A&&"debug"in A&&"error"in A&&"warn"in A){let Q=A;return{info:(w,...B)=>Q.info(w,...B),debug:(w,...B)=>Q.debug(w,...B),error:(w,...B)=>Q.error(w,...B),warn:(w,...B)=>Q.warn(w,...B)}}return Zj0()}class jZ{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return jZ.instance??=new jZ(A),jZ.instance}static resetInstance(){if(jZ.instance)jZ.instance.stop(),jZ.instance=null}static createFresh(A){return new jZ(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?DQ0(this.config.logger):zjA()}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 WT2,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 qjA}from"crypto";import{WebStandardStreamableHTTPServerTransport as fT2}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as ZT2}from"@modelcontextprotocol/sdk/types.js";c0();var KT2={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Session-Id, MCP-Protocol-Version, Last-Event-ID","Access-Control-Allow-Private-Network":"true","X-Content-Type-Options":"nosniff"};function UT2(A){let Q=new URL(A.url),B=A.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),$=A.headers.get("x-forwarded-host")??A.headers.get("host");if(!$)return Q.origin;return`${B??Q.protocol.replace(":","")}://${$}`}class mq{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?DQ0(this.config.logger):Zj0(),this.authConfig=A.auth??{},!this.authConfig.disabled&&!this.authConfig.token&&!this.authConfig.verifyBearerToken)throw Error("MCP HTTP transport requires an auth token or bearer token verifier. Set MCP_AUTH_TOKEN, configure OAuth verification, or pass auth: { disabled: true } for local dev.")}static getInstance(A){return mq.instance??=new mq(A),mq.instance}static resetInstance(){mq.instance=null}static createFresh(A){return new mq(A)}withCors(A){let Q=new Headers(A.headers);for(let[w,B]of Object.entries(KT2))Q.set(w,B);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}createJsonResponse(A,Q=200){return this.withCors(new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json"}}))}createTextResponse(A,Q=200){return this.withCors(new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8"}}))}getAuthErrorResponse(A,Q=401,w){let B=this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},Q);if(!w)return B;let $=new Headers(B.headers);return $.set("WWW-Authenticate",w),new Response(B.body,{status:B.status,statusText:B.statusText,headers:$})}getBearerChallenge(A,Q={}){let B={resource_metadata:`${UT2(A)}/.well-known/oauth-protected-resource`,...Q};return`Bearer ${Object.entries(B).map(([Y,D])=>`${Y}="${GT2(D)}"`).join(", ")}`}async authenticate(A){let Q=new URL(A.url).pathname;if(Q==="/health"||Q==="/status"||Q==="/mcp"&&A.method==="OPTIONS")return null;if(this.authConfig.disabled)return null;let w=A.headers.get("authorization");if(!w?.startsWith("Bearer "))return this.logger.warn("Authentication failed: Missing Bearer token"),this.getAuthErrorResponse("Unauthorized: Bearer token required",401,this.getBearerChallenge(A,{realm:"mcp"}));if(this.authConfig.token){if(w.substring(7)!==this.authConfig.token)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));return this.logger.debug("Authentication successful"),null}try{let B=await this.authConfig.verifyBearerToken?.(A);if(!B)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));let $=this.authConfig.requiredScopes??[],Y=$.filter((D)=>!B.scope?.includes(D));if(Y.length>0)return this.logger.warn(`Authentication failed: Missing required scope(s): ${Y.join(", ")}`),this.getAuthErrorResponse("Forbidden: Missing required scope",403,this.getBearerChallenge(A,{error:"insufficient_scope",scope:$.join(" ")}));return this.logger.debug("Authentication successful"),null}catch(B){return this.logger.warn("Authentication failed: Invalid token",B),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}))}}async handleMcpRequest(A){let Q=A.headers.get("mcp-session-id")??void 0;if(A.method==="GET"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.debug(`GET /mcp - SSE stream for session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="DELETE"){if(!Q||!this.transports[Q])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.info(`DELETE /mcp - Terminating session ${Q}`),this.withCors(await this.transports[Q].handleRequest(A))}if(A.method==="OPTIONS")return this.withCors(new Response(null,{status:204}));if(A.method!=="POST")return this.createTextResponse("Method Not Allowed",405);if(!this.mcpServer)return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Service Unavailable: MCP server not connected"},id:null},503);let w=await A.json();this.logger.debug(`POST /mcp - Session: ${Q??"new"}`);try{let B;if(Q&&this.transports[Q])B=this.transports[Q];else if(!Q&&ZT2(w))B=new fT2({sessionIdGenerator:()=>qjA(),onsessioninitialized:(Y)=>{this.logger.info(`Session initialized: ${Y}`),this.transports[Y]=B},onsessionclosed:(Y)=>{this.logger.info(`Session closed: ${Y}`),delete this.transports[Y]}}),await(this.mcpTransport?this.mcpTransport.createMcpServer():this.mcpServer).connect(B);else return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32000,message:"Bad Request: Server not initialized"},id:null},400);return this.withCors(await B.handleRequest(A,{parsedBody:w}))}catch(B){return this.logger.error("MCP transport error:",B),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:w}=await A.json();if(!Q||typeof Q!=="string")return this.createJsonResponse({error:"Missing or invalid 'message' field"},400);let B=w??qjA();this.logger.debug(`POST /api/chat - conversation: ${B}`);try{let $=await this.agentService.chat(Q,B);return this.createJsonResponse($)}catch($){return this.logger.error("Agent chat error:",$),this.createJsonResponse({error:$ instanceof Error?$.message:"Internal error"},500)}}async handleAgentConfirmRequest(A){if(!this.agentService)return this.createJsonResponse({error:"Agent service not connected"},503);let{conversationId:Q,confirmed:w,approvalId:B,context:$}=await A.json();if(!Q||typeof Q!=="string")return this.createJsonResponse({error:"Missing or invalid 'conversationId' field"},400);if(typeof w!=="boolean")return this.createJsonResponse({error:"Missing or invalid 'confirmed' field"},400);if(typeof B!=="string"||B.length===0)return this.createJsonResponse({error:"Missing or invalid 'approvalId' field"},400);let Y=AG0.safeParse($);if(!Y.success||!Y.data.userPermissionLevel)return this.createJsonResponse({error:"Missing or invalid 'context' field"},400);this.logger.debug(`POST /api/chat/confirm - conversation: ${Q}`);try{let D=await this.agentService.confirmPendingAction(Q,w,B,Y.data);return this.createJsonResponse(D)}catch(D){return this.logger.error("Agent confirm error:",D),this.createJsonResponse({error:D instanceof Error?D.message:"Internal error"},500)}}async handleRequest(A){let Q=new URL(A.url);this.logger.debug(`${A.method} ${Q.pathname}`);let w=await this.authenticate(A);if(w)return w;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);if(Q.pathname==="/api/chat/confirm"&&A.method==="POST")return this.handleAgentConfirmRequest(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:(w)=>this.handleRequest(w)}),this.boundPort=this.server.port??A,this.logger.info(`StreamableHTTP server listening on http://${Q}:${this.boundPort}/mcp`)}catch(w){if(w.code==="EADDRINUSE")this.logger.error(`Port ${A} is already in use`);throw w}}async stop(){for(let A in this.transports)try{let Q=this.transports[A];if(Q)this.logger.debug(`Closing transport for session ${A}`),await Q.close(),delete this.transports[A]}catch(Q){this.logger.error(`Error closing transport for session ${A}:`,Q)}if(this.server)await this.server.stop(),this.logger.info("StreamableHTTP server stopped"),this.server=null,this.boundPort=null}getPort(){if(this.boundPort===null)throw Error("Server is not running");return this.boundPort}getApp(){return{fetch:(A)=>this.handleRequest(A)}}isRunning(){return this.server!==null}getSessionCount(){return Object.keys(this.transports).length}}function GT2(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}import{randomUUID as qT2}from"crypto";import{mkdir as FT2,readFile as VT2,writeFile as JT2,chmod as IT2}from"fs/promises";import{dirname as bT2,join as LT2}from"path";function FjA(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function VjA(A){try{return new URL(A)}catch{return}}function Kj0(A,Q){if(A===Q)return!0;let w=VjA(A),B=VjA(Q);if(!w||!B)return!1;if(!FjA(w.hostname)||!FjA(B.hostname))return!1;return w.protocol===B.protocol&&w.port===B.port&&zT2(w.pathname,B.pathname)&&w.search===B.search&&w.hash===B.hash}function zT2(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function Uj0(A,Q){return A.some((w)=>Kj0(w,Q))}var NT2="oauth-auth-codes.json",jT2=600;function JjA(){return Math.floor(Date.now()/1000)}function MT2(A){if(!A||typeof A!=="object")return!1;let Q=A;return typeof Q.code==="string"&&typeof Q.client_id==="string"&&typeof Q.redirect_uri==="string"&&typeof Q.code_challenge==="string"&&Q.code_challenge_method==="S256"&&typeof Q.subject==="string"&&typeof Q.created_at==="number"&&typeof Q.expires_at==="number"}function _T2(A){if(!A||typeof A!=="object")return{codes:[]};let Q=A.codes;if(!Array.isArray(Q))return{codes:[]};return{codes:Q.filter(MT2)}}async function PT2(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class XQ0{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=LT2(A.storageDir,A.storeFile??NT2)}async createCode(A){let Q=JjA(),w={code:`ocd_${qT2()}`,client_id:A.clientId,redirect_uri:A.redirectUri,code_challenge:A.codeChallenge,code_challenge_method:"S256",...A.scope?{scope:A.scope}:{},subject:A.subject,created_at:Q,expires_at:Q+jT2};return await this.enqueueWrite(async()=>{let B=await this.readStore();B.codes=B.codes.filter(($)=>$.expires_at>Q),B.codes.push(w),await this.writeStore(B)}),w}async consumeCode(A){let Q=JjA(),w;if(await this.enqueueWrite(async()=>{let B=await this.readStore(),$=B.codes.findIndex((X)=>X.code===A.code),Y=$>=0?B.codes[$]:void 0;if(!Y)throw new MZ("Authorization code not found");if(Y.consumed_at!==void 0)throw new MZ("Authorization code already consumed");if(Y.expires_at<=Q)throw new MZ("Authorization code expired");if(Y.client_id!==A.clientId)throw new MZ("Authorization code client mismatch");if(!Kj0(Y.redirect_uri,A.redirectUri))throw new MZ("Authorization code redirect URI mismatch");let D=await PT2(A.codeVerifier);if(Y.code_challenge!==D)throw new MZ("PKCE verification failed");w={...Y,consumed_at:Q},B.codes[$]=w,await this.writeStore(B)}),!w)throw new MZ("Authorization code not consumed");return w}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return _T2(JSON.parse(await VT2(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{codes:[]};throw A}}async writeStore(A){await FT2(bT2(this.storeFile),{recursive:!0,mode:448}),await JT2(this.storeFile,`${JSON.stringify(A,null,2)}
1699
1699
  `,{mode:384}),await IT2(this.storeFile,384)}}class MZ extends Error{constructor(A){super(A);this.name="InvalidGrantError"}}Z0();import{randomUUID as IjA}from"crypto";import{mkdir as kT2,readFile as OT2,writeFile as xT2,chmod as RT2}from"fs/promises";import{dirname as hT2,join as vT2}from"path";var CT2="oauth-clients.json",yT2=K.enum(["none","client_secret_basic","client_secret_post"]),ET2=K.object({redirect_uris:K.array(K.string().url()).min(1),token_endpoint_auth_method:yT2.default("none"),grant_types:K.array(K.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),response_types:K.array(K.literal("code")).default(["code"]),scope:K.string().optional(),client_name:K.string().optional(),client_uri:K.string().url().optional(),logo_uri:K.string().url().optional(),contacts:K.array(K.string()).optional()});function gT2(){return Math.floor(Date.now()/1000)}function TT2(){return`ocs_${IjA().replaceAll("-","")}`}function ST2(A){if(!A||typeof A!=="object")return{clients:[]};let Q=A.clients;if(!Array.isArray(Q))return{clients:[]};return{clients:Q.filter(mT2)}}function mT2(A){if(!A||typeof A!=="object")return!1;let Q=A;return typeof Q.client_id==="string"&&Array.isArray(Q.redirect_uris)&&Q.redirect_uris.every((w)=>typeof w==="string")&&typeof Q.client_id_issued_at==="number"}class HQ0{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=vT2(A.storageDir,A.storeFile??CT2)}async registerClient(A){let Q=ET2.safeParse(A);if(!Q.success)throw new zc(Q.error.message);let w=Q.data,B=gT2(),$=`oc_${IjA()}`,Y=w.token_endpoint_auth_method==="none",D={client_id:$,client_id_issued_at:B,redirect_uris:w.redirect_uris,token_endpoint_auth_method:w.token_endpoint_auth_method,grant_types:w.grant_types,response_types:w.response_types,...w.scope?{scope:w.scope}:{},...w.client_name?{client_name:w.client_name}:{},...w.client_uri?{client_uri:w.client_uri}:{},...w.logo_uri?{logo_uri:w.logo_uri}:{},...w.contacts?{contacts:w.contacts}:{},...!Y?{client_secret:TT2(),client_secret_expires_at:0}:{}};return await this.enqueueWrite(async()=>{let X=await this.readStore();X.clients.push(D),await this.writeStore(X)}),D}async getClient(A){return(await this.readStore()).clients.find((w)=>w.client_id===A)}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return ST2(JSON.parse(await OT2(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{clients:[]};throw A}}async writeStore(A){await kT2(hT2(this.storeFile),{recursive:!0,mode:448}),await xT2(this.storeFile,`${JSON.stringify(A,null,2)}
1700
1700
  `,{mode:384}),await RT2(this.storeFile,384)}}class zc extends Error{constructor(A){super(A);this.name="InvalidClientMetadataError"}}import{createHash as uT2}from"crypto";import{mkdir as cT2,readFile as lT2,writeFile as pT2,chmod as iT2}from"fs/promises";import{dirname as dT2,join as nT2}from"path";var rT2="oauth-signing-key.jwk";function bjA(A){if(!A||typeof A!=="object")return!1;let Q=A;return Q.kty==="EC"&&Q.crv==="P-256"&&typeof Q.x==="string"&&typeof Q.y==="string"&&typeof Q.d==="string"}function LjA(A){let Q=JSON.stringify({crv:A.crv,kty:A.kty,x:A.x,y:A.y});return uT2("sha256").update(Q).digest("base64url")}function oT2(A){return{kty:"EC",crv:"P-256",x:A.x,y:A.y,kid:A.kid,use:"sig",alg:"ES256"}}async function sT2(){let A=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),Q=await crypto.subtle.exportKey("jwk",A.privateKey);if(!bjA(Q))throw Error("Generated OAuth signing key is not a P-256 private JWK");let w=LjA(Q);return{...Q,kid:w,use:"sig",alg:"ES256"}}class WQ0{keyFile;cachedKey;loadPromise;constructor(A){this.keyFile=nT2(A.storageDir,A.keyFile??rT2)}async getPrivateJwk(){if(this.cachedKey)return this.cachedKey;this.loadPromise??=this.loadOrCreateKey();try{return this.cachedKey=await this.loadPromise,this.cachedKey}catch(A){throw this.loadPromise=void 0,A}}async loadOrCreateKey(){let A=await this.readExistingKey();if(A)return A;let Q=await sT2();return await cT2(dT2(this.keyFile),{recursive:!0,mode:448}),await pT2(this.keyFile,`${JSON.stringify(Q,null,2)}
1701
1701
  `,{mode:384}),await iT2(this.keyFile,384),Q}async getPublicJwk(){return oT2(await this.getPrivateJwk())}async readExistingKey(){try{let A=JSON.parse(await lT2(this.keyFile,"utf8"));if(!bjA(A))throw Error(`OAuth signing key at ${this.keyFile} is not a private P-256 JWK`);let Q=typeof A.kid==="string"?A.kid:LjA(A);return{...A,kid:Q,use:"sig",alg:"ES256"}}catch(A){if(A.code==="ENOENT")return;throw A}}}var $Q={};sw($Q,{trimPadding:()=>jjA,toUTF8String:()=>YS2,toBuffer:()=>QS2,toBase64:()=>BS2,isBase64URL:()=>XS2,isBase64:()=>DS2,fromUTF8String:()=>$S2,fromBuffer:()=>wS2});var NjA=(A)=>{let Q=typeof Uint8Array>"u"?[]:new Uint8Array(256),w=64;for(let B=0;B<64;B++)Q[A.charCodeAt(B)]=B;return Q},aT2=NjA("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),tT2=NjA("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),eT2=/^[-A-Za-z0-9\-_]*$/,AS2=/^[-A-Za-z0-9+/]*={0,3}$/,yU={};yU.toArrayBuffer=(A,Q)=>{let w=A.length,B=A.length*0.75,$,Y=0,D,X,H,W;if(A[A.length-1]==="="){if(B--,A[A.length-2]==="=")B--}let f=new ArrayBuffer(B),Z=new Uint8Array(f),G=Q?tT2:aT2;for($=0;$<w;$+=4)D=G[A.charCodeAt($)],X=G[A.charCodeAt($+1)],H=G[A.charCodeAt($+2)],W=G[A.charCodeAt($+3)],Z[Y++]=D<<2|X>>4,Z[Y++]=(X&15)<<4|H>>2,Z[Y++]=(H&3)<<6|W&63;return f};yU.fromArrayBuffer=(A,Q)=>{let w=new Uint8Array(A),B,$="",Y=w.length,D=Q?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(B=0;B<Y;B+=3)$+=D[w[B]>>2],$+=D[(w[B]&3)<<4|w[B+1]>>4],$+=D[(w[B+1]&15)<<2|w[B+2]>>6],$+=D[w[B+2]&63];let X=Y%3;if(X===2)$=$.substring(0,$.length-1)+(Q?"":"=");else if(X===1)$=$.substring(0,$.length-2)+(Q?"":"==");return $};yU.toString=(A,Q)=>{return new TextDecoder().decode(yU.toArrayBuffer(A,Q))};yU.fromString=(A,Q)=>{return yU.fromArrayBuffer(new TextEncoder().encode(A),Q)};yU.validate=(A,Q)=>{if(!(typeof A==="string"||A instanceof String))return!1;try{return Q?eT2.test(A):AS2.test(A)}catch(w){return!1}};yU.base64=yU;var uq=yU;function QS2(A,Q="base64url"){let w=uq.toArrayBuffer(A,Q==="base64url");return new Uint8Array(w)}function wS2(A,Q="base64url"){let w=new Uint8Array(A);return uq.fromArrayBuffer(w.buffer,Q==="base64url")}function BS2(A){let Q=uq.toArrayBuffer(A,!0);return uq.fromArrayBuffer(Q)}function $S2(A){return uq.fromString(A,!0)}function YS2(A){return uq.toString(A,!0)}function DS2(A){return uq.validate(A,!1)}function XS2(A){return A=jjA(A),uq.validate(A,!0)}function jjA(A){return A.replace(/=/g,"")}var XY={};sw(XY,{encode:()=>kS2,decodeFirst:()=>PS2});function oR(A,Q,w){if(Q<24)return[Q,1];let B=A.byteLength-w-1,$=new DataView(A.buffer,w+1),Y,D=0;switch(Q){case 24:{if(B>0)Y=$.getUint8(0),D=2;break}case 25:{if(B>1)Y=$.getUint16(0,!1),D=3;break}case 26:{if(B>3)Y=$.getUint32(0,!1),D=5;break}case 27:{if(B>7){let X=$.getBigUint64(0,!1);if(X>=24n&&X<=Number.MAX_SAFE_INTEGER)return[Number(X),9]}break}}if(Y&&Y>=24)return[Y,D];throw Error("Length not supported or not well formed")}var fQ0=0,qc=1,Gj0=2,zj0=3,qj0=4,Fj0=5,Vj0=6,MjA=7;function EU(A,Q){let w=A<<5;if(Q<0)throw Error("CBOR Data Item argument must not be negative");let B;if(typeof Q=="number"){if(!Number.isInteger(Q))throw Error("CBOR Data Item argument must be an integer");B=BigInt(Q)}else B=Q;if(A==qc){if(B==0n)throw Error("CBOR Data Item argument cannot be zero when negative");B=B-1n}if(B>18446744073709551615n)throw Error("CBOR number out of range");let $=new Uint8Array(8);if(new DataView($.buffer).setBigUint64(0,B,!1),B<=23)return[w|$[7]];else if(B<=255)return[w|24,$[7]];else if(B<=65535)return[w|25,...$.slice(6)];else if(B<=4294967295)return[w|26,...$.slice(4)];else return[w|27,...$]}class KQ0{constructor(A,Q){Object.defineProperty(this,"tagId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tagValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tagId=A,this.tagValue=Q}get tag(){return this.tagId}get value(){return this.tagValue}}function _jA(A,Q,w){return oR(A,Q,w)}function HS2(A,Q,w){let[B,$]=_jA(A,Q,w);return[-B-1,$]}function PjA(A,Q,w){let[B,$]=oR(A,Q,w),Y=w+$;return[new Uint8Array(A.buffer.slice(Y,Y+B)),$+B]}var WS2=new TextDecoder;function fS2(A,Q,w){let[B,$]=PjA(A,Q,w);return[WS2.decode(B),$]}function ZS2(A,Q,w){if(Q===0)return[[],1];let[B,$]=oR(A,Q,w),Y=$,D=[];for(let X=0;X<B;X++){if(A.byteLength-w-Y<=0)throw Error("array is not supported or well formed");let[W,f]=Pj(A,w+Y);D.push(W),Y+=f}return[D,Y]}var ZQ0="Map is not supported or well formed";function KS2(A,Q,w){if(Q===0)return[new Map,1];let[B,$]=oR(A,Q,w),Y=$,D=new Map;for(let X=0;X<B;X++){let H=A.byteLength-w-Y;if(H<=0)throw Error(ZQ0);let[W,f]=Pj(A,w+Y);if(Y+=f,H-=f,H<=0)throw Error(ZQ0);if(typeof W!=="string"&&typeof W!=="number")throw Error(ZQ0);if(D.has(W))throw Error(ZQ0);let[Z,G]=Pj(A,w+Y);Y+=G,D.set(W,Z)}return[D,Y]}function US2(A,Q){if(Q+3>A.byteLength)throw Error("CBOR stream ended before end of Float 16");let w=A.getUint16(Q+1,!1);if(w==31744)return[1/0,3];else if(w==32256)return[NaN,3];else if(w==64512)return[-1/0,3];throw Error("Float16 data is unsupported")}function GS2(A,Q){if(Q+5>A.byteLength)throw Error("CBOR stream ended before end of Float 32");return[A.getFloat32(Q+1,!1),5]}function zS2(A,Q){if(Q+9>A.byteLength)throw Error("CBOR stream ended before end of Float 64");return[A.getFloat64(Q+1,!1),9]}function qS2(A,Q,w){let[B,$]=oR(A,Q,w),[Y,D]=Pj(A,w+$);return[new KQ0(B,Y),$+D]}function Pj(A,Q){if(Q>=A.byteLength)throw Error("CBOR stream ended before tag value");let w=A.getUint8(Q),B=w>>5,$=w&31;switch(B){case fQ0:return _jA(A,$,Q);case qc:return HS2(A,$,Q);case Gj0:return PjA(A,$,Q);case zj0:return fS2(A,$,Q);case qj0:return ZS2(A,$,Q);case Fj0:return KS2(A,$,Q);case Vj0:return qS2(A,$,Q);case MjA:switch($){case 20:return[!1,1];case 21:return[!0,1];case 22:return[null,1];case 23:return[void 0,1];case 25:return US2(A,Q);case 26:return GS2(A,Q);case 27:return zS2(A,Q)}}throw Error(`Unsupported or not well formed at ${Q}`)}function FS2(A){if(A===!0)return 245;else if(A===!1)return 244;else if(A===null)return 246;return 247}function VS2(A){if(Math.fround(A)==A||!Number.isFinite(A)||Number.isNaN(A)){let Q=new Uint8Array(5);return Q[0]=250,new DataView(Q.buffer).setFloat32(1,A,!1),Q}else{let Q=new Uint8Array(9);return Q[0]=251,new DataView(Q.buffer).setFloat64(1,A,!1),Q}}function JS2(A){if(typeof A=="number"){if(Number.isSafeInteger(A))if(A<0)return EU(qc,Math.abs(A));else return EU(fQ0,A);return[VS2(A)]}else if(A<0n)return EU(qc,A*-1n);else return EU(fQ0,A)}var IS2=new TextEncoder;function bS2(A,Q){Q.push(...EU(zj0,A.length)),Q.push(IS2.encode(A))}function LS2(A,Q){Q.push(...EU(Gj0,A.length)),Q.push(A)}function NS2(A,Q){Q.push(...EU(qj0,A.length));for(let w of A)Fc(w,Q)}function jS2(A,Q){Q.push(new Uint8Array(EU(Fj0,A.size)));for(let[w,B]of A.entries())Fc(w,Q),Fc(B,Q)}function MS2(A,Q){Q.push(...EU(Vj0,A.tag)),Fc(A.value,Q)}function Fc(A,Q){if(typeof A=="boolean"||A===null||A==null){Q.push(FS2(A));return}if(typeof A=="number"||typeof A=="bigint"){Q.push(...JS2(A));return}if(typeof A=="string"){bS2(A,Q);return}if(A instanceof Uint8Array){LS2(A,Q);return}if(Array.isArray(A)){NS2(A,Q);return}if(A instanceof Map){jS2(A,Q);return}if(A instanceof KQ0){MS2(A,Q);return}throw Error("Not implemented")}function Jj0(A,Q){if(A.byteLength===0||A.byteLength<=Q||Q<0)throw Error("No data");if(A instanceof Uint8Array)return Pj(new DataView(A.buffer),Q);else if(A instanceof ArrayBuffer)return Pj(new DataView(A),Q);return Pj(A,Q)}function Ij0(A){let Q=[];Fc(A,Q);let w=0;for(let Y of Q)if(typeof Y=="number")w+=1;else w+=Y.length;let B=new Uint8Array(w),$=0;for(let Y of Q)if(typeof Y=="number")B[$]=Y,$+=1;else B.set(Y,$),$+=Y.length;return B}function PS2(A){let Q=new Uint8Array(A),w=Jj0(Q,0),[B]=w;return B}function kS2(A){return Ij0(A)}var TU={};sw(TU,{verify:()=>HOA,getRandomValues:()=>hjA,digest:()=>RjA});function kjA(A){let Q=A.get(QQ.kty);return bj0(Q)&&Q===yX.OKP}function _J(A){let Q=A.get(QQ.kty);return bj0(Q)&&Q===yX.EC2}function sR(A){let Q=A.get(QQ.kty);return bj0(Q)&&Q===yX.RSA}var QQ;(function(A){A[A.kty=1]="kty",A[A.alg=3]="alg",A[A.crv=-1]="crv",A[A.x=-2]="x",A[A.y=-3]="y",A[A.n=-1]="n",A[A.e=-2]="e"})(QQ||(QQ={}));var yX;(function(A){A[A.OKP=1]="OKP",A[A.EC2=2]="EC2",A[A.RSA=3]="RSA"})(yX||(yX={}));function bj0(A){return Object.values(yX).indexOf(A)>=0}var H4;(function(A){A[A.P256=1]="P256",A[A.P384=2]="P384",A[A.P521=3]="P521",A[A.ED25519=6]="ED25519",A[A.SECP256K1=8]="SECP256K1"})(H4||(H4={}));function OjA(A){return Object.values(H4).indexOf(A)>=0}var hQ;(function(A){A[A.ES256=-7]="ES256",A[A.EdDSA=-8]="EdDSA",A[A.ES384=-35]="ES384",A[A.ES512=-36]="ES512",A[A.PS256=-37]="PS256",A[A.PS384=-38]="PS384",A[A.PS512=-39]="PS512",A[A.ES256K=-47]="ES256K",A[A.RS256=-257]="RS256",A[A.RS384=-258]="RS384",A[A.RS512=-259]="RS512",A[A.RS1=-65535]="RS1"})(hQ||(hQ={}));function gU(A){return Object.values(hQ).indexOf(A)>=0}function PJ(A){if([hQ.RS1].indexOf(A)>=0)return"SHA-1";else if([hQ.ES256,hQ.PS256,hQ.RS256].indexOf(A)>=0)return"SHA-256";else if([hQ.ES384,hQ.PS384,hQ.RS384].indexOf(A)>=0)return"SHA-384";else if([hQ.ES512,hQ.PS512,hQ.RS512,hQ.EdDSA].indexOf(A)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${A} to a WebCrypto alg`)}var Vc=void 0;function BD(){return new Promise((Q,w)=>{if(Vc)return Q(Vc);let B=xS2.stubThisGlobalThisCrypto();if(B)return Vc=B,Q(Vc);return w(new xjA)})}class xjA extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}}var xS2={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(A)=>{Vc=A}};async function RjA(A,Q){let w=await BD(),B=PJ(Q),$=await w.subtle.digest(B,A);return new Uint8Array($)}async function hjA(A){return(await BD()).getRandomValues(A),A}async function aR(A){let Q=await BD(),{keyData:w,algorithm:B}=A;return Q.subtle.importKey("jwk",w,B,!1,["verify"])}async function UQ0(A){let{cosePublicKey:Q,signature:w,data:B,shaHashOverride:$}=A,Y=await BD(),D=Q.get(QQ.alg),X=Q.get(QQ.crv),H=Q.get(QQ.x),W=Q.get(QQ.y);if(!D)throw Error("Public key was missing alg (EC2)");if(!X)throw Error("Public key was missing crv (EC2)");if(!H)throw Error("Public key was missing x (EC2)");if(!W)throw Error("Public key was missing y (EC2)");let f;if(X===H4.P256)f="P-256";else if(X===H4.P384)f="P-384";else if(X===H4.P521)f="P-521";else throw Error(`Unexpected COSE crv value of ${X} (EC2)`);let Z={kty:"EC",crv:f,x:$Q.fromBuffer(H),y:$Q.fromBuffer(W),ext:!1},F=await aR({keyData:Z,algorithm:{name:"ECDSA",namedCurve:f}}),V=PJ(D);if($)V=PJ($);let b={name:"ECDSA",hash:{name:V}};return Y.subtle.verify(b,F,w,B)}function Lj0(A){if([hQ.EdDSA].indexOf(A)>=0)return"Ed25519";else if([hQ.ES256,hQ.ES384,hQ.ES512,hQ.ES256K].indexOf(A)>=0)return"ECDSA";else if([hQ.RS256,hQ.RS384,hQ.RS512,hQ.RS1].indexOf(A)>=0)return"RSASSA-PKCS1-v1_5";else if([hQ.PS256,hQ.PS384,hQ.PS512].indexOf(A)>=0)return"RSA-PSS";throw Error(`Could not map COSE alg value of ${A} to a WebCrypto key alg name`)}async function GQ0(A){let{cosePublicKey:Q,signature:w,data:B,shaHashOverride:$}=A,Y=await BD(),D=Q.get(QQ.alg),X=Q.get(QQ.n),H=Q.get(QQ.e);if(!D)throw Error("Public key was missing alg (RSA)");if(!gU(D))throw Error(`Public key had invalid alg ${D} (RSA)`);if(!X)throw Error("Public key was missing n (RSA)");if(!H)throw Error("Public key was missing e (RSA)");let W={kty:"RSA",alg:"",n:$Q.fromBuffer(X),e:$Q.fromBuffer(H),ext:!1},f={name:Lj0(D),hash:{name:PJ(D)}},Z={name:Lj0(D)};if($)f.hash.name=PJ($);if(f.name==="RSASSA-PKCS1-v1_5"){if(f.hash.name==="SHA-256")W.alg="RS256";else if(f.hash.name==="SHA-384")W.alg="RS384";else if(f.hash.name==="SHA-512")W.alg="RS512";else if(f.hash.name==="SHA-1")W.alg="RS1"}else if(f.name==="RSA-PSS"){let F=0;if(f.hash.name==="SHA-256")W.alg="PS256",F=32;else if(f.hash.name==="SHA-384")W.alg="PS384",F=48;else if(f.hash.name==="SHA-512")W.alg="PS512",F=64;Z.saltLength=F}else throw Error(`Unexpected RSA key algorithm ${D} (${f.name})`);let G=await aR({keyData:W,algorithm:f});return Y.subtle.verify(Z,G,w,B)}function zQ0(A){let Q=q2.toHex(A);return[Q.slice(0,8),Q.slice(8,12),Q.slice(12,16),Q.slice(16,20),Q.slice(20,32)].join("-")}function G$(A){let Q;if(typeof A==="string")if($Q.isBase64URL(A))Q=$Q.toBase64(A);else if($Q.isBase64(A))Q=A;else throw Error("Certificate is not a valid base64 or base64url string");else Q=$Q.fromBuffer(A,"base64");let w="";for(let B=0;B<Math.ceil(Q.length/64);B+=1){let $=64*B;w+=`${Q.substr($,64)}
@@ -2274,8 +2274,8 @@ ${N}`)}if(B!==void 0&&Y?.algorithms!==void 0){let L=Y.algorithms.map((N)=>N.alg)
2274
2274
  </form>
2275
2275
  </main>
2276
2276
  </body>
2277
- </html>`}function Bp(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(gP0(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function eU(A){return A.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}import{randomUUID as Hl2}from"crypto";function bxA(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function Xl2(A){let Q=new Uint8Array(A);if(Q.length===64)return Q;if(Q[0]!==48)return Q;let w=2;if(Q[1]&&Q[1]>128)w+=Q[1]-128;if(Q[w]!==2)throw Error("Invalid DER ECDSA signature");let B=Q[w+1];if(B===void 0)throw Error("Invalid DER ECDSA signature");let $=w+2,Y=Q.slice($,$+B);if(w=$+B,Q[w]!==2)throw Error("Invalid DER ECDSA signature");let D=Q[w+1];if(D===void 0)throw Error("Invalid DER ECDSA signature");let X=w+2,H=Q.slice(X,X+D);return new Uint8Array([...LxA(Y),...LxA(H)])}function LxA(A){let Q=A;while(Q.length>32&&Q[0]===0)Q=Q.slice(1);if(Q.length>32)throw Error("Invalid P-256 signature component length");if(Q.length===32)return Q;let w=new Uint8Array(32);return w.set(Q,32-Q.length),w}async function SP0(A,Q){let w={typ:"JWT",alg:"ES256",kid:A.kid},B=`${bxA(w)}.${bxA(Q)}`,$=await crypto.subtle.importKey("jwk",A,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),Y=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},$,new TextEncoder().encode(B));return`${B}.${Buffer.from(Xl2(Y)).toString("base64url")}`}var Wl2=600;class mP0{clientStore;authCodeStore;refreshTokenStore;sessionStore;keyStore;authorizationApprovalTokens=new Map;constructor(A){this.clientStore=A.clientStore,this.authCodeStore=A.authCodeStore,this.refreshTokenStore=A.refreshTokenStore,this.sessionStore=A.sessionStore,this.keyStore=A.keyStore}async handleAuthorizePage(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return Bp(A);let w=await this.validateAuthorizationRequest(new URL(A.url).searchParams);if(!w.success)return new Response(w.error,{status:400});let B=this.createAuthorizationApprovalToken(Q,w.params);return Fv(IxA(w.params,B))}async handleAuthorizeApproval(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return Bp(A);let w=await A.formData(),B=await this.validateAuthorizationRequest(new URLSearchParams(vP0(w)));if(!B.success)return new Response(B.error,{status:400});let $=w.get("approval_token"),Y=typeof $==="string"?$:void 0;if(!Y||!this.consumeAuthorizationApprovalToken(Y,Q,B.params))return new Response("Invalid authorization approval token",{status:400});let D=await this.authCodeStore.createCode({clientId:B.params.clientId,redirectUri:B.params.redirectUri,codeChallenge:B.params.codeChallenge,...B.params.scope?{scope:B.params.scope}:{},subject:Q.subject}),X=new URL(B.params.redirectUri);if(X.searchParams.set("code",D.code),B.params.state)X.searchParams.set("state",B.params.state);return Response.redirect(X.toString(),302)}createAuthorizationApprovalToken(A,Q){this.pruneExpiredAuthorizationApprovalTokens();let w=`oat_${Hl2()}`;return this.authorizationApprovalTokens.set(w,{token:w,sessionId:A.id,clientId:Q.clientId,redirectUri:Q.redirectUri,codeChallenge:Q.codeChallenge,...Q.scope?{scope:Q.scope}:{},...Q.state?{state:Q.state}:{},expiresAt:Math.floor(Date.now()/1000)+Wl2}),w}consumeAuthorizationApprovalToken(A,Q,w){this.pruneExpiredAuthorizationApprovalTokens();let B=this.authorizationApprovalTokens.get(A);if(!B)return!1;return this.authorizationApprovalTokens.delete(A),B.sessionId===Q.id&&B.clientId===w.clientId&&B.redirectUri===w.redirectUri&&B.codeChallenge===w.codeChallenge&&B.scope===w.scope&&B.state===w.state}pruneExpiredAuthorizationApprovalTokens(){let A=Math.floor(Date.now()/1000);for(let[Q,w]of this.authorizationApprovalTokens.entries())if(w.expiresAt<=A)this.authorizationApprovalTokens.delete(Q)}async validateAuthorizationRequest(A){let Q=A.get("response_type"),w=A.get("client_id"),B=A.get("redirect_uri"),$=A.get("code_challenge"),Y=A.get("code_challenge_method"),D=A.get("scope")??void 0,X=A.get("state")??void 0;if(Q!=="code")return{success:!1,error:"Unsupported response_type"};if(!w)return{success:!1,error:"Missing client_id"};if(!B)return{success:!1,error:"Missing redirect_uri"};if(!$)return{success:!1,error:"Missing code_challenge"};if(Y!=="S256")return{success:!1,error:"Unsupported code_challenge_method"};let H=await this.clientStore.getClient(w);if(!H)return{success:!1,error:"Unknown client_id"};if(!Uj0(H.redirect_uris,B))return{success:!1,error:"Unregistered redirect_uri"};let W=D??H.scope;return{success:!0,params:{clientId:w,redirectUri:B,codeChallenge:$,...W?{scope:W}:{},...X?{state:X}:{},clientName:H.client_name??H.client_id}}}async handleClientRegistration(A){let Q;try{Q=await A.json()}catch{return y6("invalid_client_metadata","Request body must be JSON")}try{let w=await this.clientStore.registerClient(Q);return lX(w,201)}catch(w){if(w instanceof zc)return y6("invalid_client_metadata",w.message);throw w}}async handleTokenRequest(A,Q){let w=await hP0(A),B=w.get("grant_type"),$=yP0(A,w),Y=$.clientId??w.get("client_id");if($.error)return y6("invalid_client",$.error);if(!Y)return y6("invalid_request","client_id is required");let D=await this.clientStore.getClient(Y),X=CP0(D,$);if(X)return y6("invalid_client",X);if(B==="authorization_code")return this.handleAuthorizationCodeGrant(w,Y,Q);if(B==="refresh_token")return this.handleRefreshTokenGrant(w,Y,Q);return y6("unsupported_grant_type","Only authorization_code and refresh_token are supported")}async handleAuthorizationCodeGrant(A,Q,w){let B=A.get("code"),$=A.get("redirect_uri"),Y=A.get("code_verifier");if(!B||!$||!Y)return y6("invalid_request","code, redirect_uri, and code_verifier are required");let D=await this.clientStore.getClient(Q);if(!D||!Uj0(D.redirect_uris,$))return y6("invalid_grant","Unregistered redirect_uri");try{let X=await this.authCodeStore.consumeCode({code:B,clientId:Q,redirectUri:$,codeVerifier:Y});return await this.createTokenResponse({issuer:w,clientId:Q,subject:X.subject,...X.scope?{scope:X.scope}:{}})}catch(X){if(X instanceof MZ)return y6("invalid_grant",X.message);throw X}}async handleRefreshTokenGrant(A,Q,w){let B=A.get("refresh_token");if(!B)return y6("invalid_request","refresh_token is required");try{let $=await this.refreshTokenStore.rotateToken(B,Q);return await this.createTokenResponse({issuer:w,clientId:Q,subject:$.consumed.subject,...$.consumed.scope?{scope:$.consumed.scope}:{},refreshToken:$.replacement.token})}catch($){if($ instanceof f3)return y6("invalid_grant",$.message);throw $}}async createTokenResponse(A){let Q=Math.floor(Date.now()/1000),w=900,B=await SP0(await this.keyStore.getPrivateJwk(),{iss:A.issuer,sub:A.subject,aud:A.clientId,iat:Q,exp:Q+900,...A.scope?{scope:A.scope}:{}}),$=A.refreshToken??(await this.refreshTokenStore.issueToken({clientId:A.clientId,subject:A.subject,...A.scope?{scope:A.scope}:{}})).token;return lX({access_token:B,token_type:"Bearer",expires_in:900,...A.scope?{scope:A.scope}:{},refresh_token:$})}async handleRevokeRequest(A){let Q=await hP0(A),w=yP0(A,Q),B=w.clientId??Q.get("client_id")??void 0,$=Q.get("token");if(w.error)return y6("invalid_client",w.error);if(!$)return y6("invalid_request","token is required");if(B){let Y=await this.clientStore.getClient(B),D=CP0(Y,w);if(D)return y6("invalid_client",D)}return await this.refreshTokenStore.revokeToken($,B),new Response(null,{status:200})}}class uP0{passkeyService;sessionStore;setupFlow;constructor(A){this.passkeyService=A.passkeyService,this.sessionStore=A.sessionStore,this.setupFlow=A.setupFlow}async handleRegistrationOptions(A){if(await this.passkeyService.hasCredentials())return y6("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return y6("access_denied","Invalid setup token");let Q=await this.passkeyService.generateRegistrationOptions(nw0(A));return lX(Q)}async handleRegistrationVerify(A){if(await this.passkeyService.hasCredentials())return y6("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return y6("access_denied","Invalid setup token");let Q=await this.passkeyService.verifyRegistrationResponse(await A.json(),nw0(A));if(!Q.verified)return y6("access_denied","Passkey registration failed");await this.setupFlow.clearSetupState();let w=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:el(A)});return lX({verified:!0},200,{"Set-Cookie":w.cookie})}async handleAuthenticationOptions(A){if(!await this.passkeyService.hasCredentials())return y6("access_denied","No passkey registered");let Q=await this.passkeyService.generateAuthenticationOptions(nw0(A));return lX(Q)}async handleAuthenticationVerify(A){let Q=await this.passkeyService.verifyAuthenticationResponse(await A.json(),nw0(A));if(!Q.verified)return y6("access_denied","Passkey authentication failed");let w=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:el(A)});return lX({verified:!0},200,{"Set-Cookie":w.cookie})}}function nw0(A){let Q=fv(A),w=new URL(Q);return{origin:w.origin,rpID:w.hostname}}import{randomUUID as fl2}from"crypto";var $p=86400;class cP0{setupStateStore;passkeyService;setupTokenTtlSeconds;setupToken;constructor(A){this.setupStateStore=A.setupStateStore,this.passkeyService=A.passkeyService,this.setupTokenTtlSeconds=A.setupTokenTtlSeconds??$p}async ensureSetupToken(){let A=this.getValidSetupToken();if(A)return A;let Q=await this.setupStateStore.getValidSetupToken(Math.floor(Date.now()/1000));if(Q)return this.setupToken=Q,Q;return this.createSetupToken()}async createSetupToken(){return this.setupToken={token:`setup_${fl2()}`,expiresAt:Math.floor(Date.now()/1000)+this.setupTokenTtlSeconds},await this.setupStateStore.saveSetupToken(this.setupToken),this.setupToken}getValidSetupToken(){if(!this.setupToken)return;if(this.setupToken.expiresAt<=Math.floor(Date.now()/1000)){this.setupToken=void 0;return}return this.setupToken}hasValidSetupToken(A){let Q=this.getValidSetupToken();if(!Q)return!1;let w=new URL(A.url);return(w.searchParams.get("setup_token")??w.searchParams.get("token"))===Q.token}async clearSetupState(){this.setupToken=void 0,await this.setupStateStore.clearSetupState()}getSetupUrl(A){let Q=this.getValidSetupToken();if(!Q)return;return tU(A,`/setup?token=${encodeURIComponent(Q.token)}`)}async getOperatorSetupRequired(A){if(await this.passkeyService.hasCredentials())return;let Q=this.getValidSetupToken();if(!Q)return;return{setupUrl:tU(A,`/setup?token=${encodeURIComponent(Q.token)}`),expiresAt:Q.expiresAt,setupTokenId:ZP0(Q.token)}}async handleSetupPage(A){if(await this.passkeyService.hasCredentials())return new Response("Setup already completed",{status:404});if(!this.hasValidSetupToken(A))return new Response("Not Found",{status:404});let Q=new URL(A.url).searchParams.get("token")??"";return Fv(VxA(Q))}async hasSetupEmailDelivery(A,Q){return this.setupStateStore.hasDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,w={}){await this.setupStateStore.recordDelivery(A,Q,w)}}class rw0{issuer;trustedIssuers;allowLocalhostIssuers;keyStore;clientStore;authCodeStore;sessionStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;logger;constructor(A){this.issuer=EZ(A.issuer),this.trustedIssuers=new Set([this.issuer,...(A.trustedIssuers??[]).map((Q)=>EZ(Q))]),this.allowLocalhostIssuers=A.allowLocalhostIssuers??Wv(this.issuer),this.keyStore=new WQ0({storageDir:A.storageDir}),this.clientStore=new HQ0({storageDir:A.storageDir}),this.authCodeStore=new XQ0({storageDir:A.storageDir}),this.sessionStore=new cw0({storageDir:A.storageDir}),this.passkeyService=new gw0({storageDir:A.storageDir,...A.logger?{logger:A.logger}:{}}),this.setupFlow=new cP0({setupStateStore:new KP0({storageDir:A.storageDir}),passkeyService:this.passkeyService,setupTokenTtlSeconds:A.setupTokenTtlSeconds??$p}),this.oauthEndpoints=new mP0({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:new Sw0({storageDir:A.storageDir}),sessionStore:this.sessionStore,keyStore:this.keyStore}),this.webauthnEndpoints=new uP0({passkeyService:this.passkeyService,sessionStore:this.sessionStore,setupFlow:this.setupFlow}),this.logger=A.logger}getIssuer(){return this.issuer}async initialize(){if(await this.keyStore.getPrivateJwk(),this.logger?.debug("Auth service signing key loaded"),!await this.hasPasskeyCredentials()){await this.setupFlow.ensureSetupToken();let A=this.getSetupUrl();if(A)if(Wv(this.issuer))this.logger?.warn(`Passkey setup required: ${A}`);else this.logger?.warn("Passkey setup required. Ask through an anchor-visible interface for the setup URL.")}}async hasPasskeyCredentials(){return this.passkeyService.hasCredentials()}async getJwks(){return{keys:[await this.keyStore.getPublicJwk()]}}getAuthorizationServerMetadata(A=this.issuer){let Q=EZ(A);return{issuer:Q,authorization_endpoint:tU(Q,"/authorize"),token_endpoint:tU(Q,"/token"),registration_endpoint:tU(Q,"/register"),revocation_endpoint:tU(Q,"/revoke"),jwks_uri:tU(Q,"/.well-known/jwks.json"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none","client_secret_basic","client_secret_post"],scopes_supported:["openid","profile","email","offline_access","mcp"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["ES256"]}}getProtectedResourceMetadata(A,Q=this.issuer){return{resource:A,authorization_servers:[EZ(Q)],bearer_methods_supported:["header"],resource_signing_alg_values_supported:["ES256"],scopes_supported:["mcp"]}}async registerClient(A){return this.clientStore.registerClient(A)}async getRegisteredClient(A){return this.clientStore.getClient(A)}async createOperatorSession(A="single-operator",Q={}){return this.sessionStore.createSession(A,Q)}async getOperatorSession(A){return this.sessionStore.getSessionFromRequest(A)}createOperatorLoginResponse(A){return Bp(A)}async verifyBearerToken(A,Q={}){let w=RP0(A);if(!w)return;let B=Q.issuer?EZ(Q.issuer):this.resolveRequestIssuer(A);return xP0(w,await this.getJwks(),{issuer:B,...Q.audience?{audience:Q.audience}:{}})}getSetupUrl(A=this.issuer){return this.setupFlow.getSetupUrl(A)}async getOperatorSetupRequired(A=this.issuer){return this.setupFlow.getOperatorSetupRequired(A)}async hasSetupEmailDelivery(A,Q){return this.setupFlow.hasSetupEmailDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,w={}){await this.setupFlow.recordSetupEmailDelivery(A,Q,w)}async handleRequest(A){let Q;try{Q=this.resolveRequestIssuer(A)}catch(B){return this.logger?.warn("Rejected OAuth request from untrusted issuer",{error:B instanceof Error?B.message:String(B)}),new Response("Untrusted OAuth issuer",{status:400})}let w=new URL(A.url).pathname;if(A.method==="OPTIONS"&&zxA(w))return qxA();if(A.method==="GET"){if(w==="/.well-known/oauth-authorization-server")return wI(lX(this.getAuthorizationServerMetadata(Q)));if(w==="/.well-known/jwks.json")return wI(lX(await this.getJwks()));if(w==="/.well-known/oauth-protected-resource")return wI(lX(this.getProtectedResourceMetadata(Q,Q)))}if(A.method==="GET"&&w==="/setup")return this.setupFlow.handleSetupPage(A);if(A.method==="GET"&&w==="/login")return this.handleLoginPage(A);if((A.method==="GET"||A.method==="POST")&&w==="/logout")return this.handleLogout(A);if(A.method==="POST"&&w==="/webauthn/register/options")return this.webauthnEndpoints.handleRegistrationOptions(A);if(A.method==="POST"&&w==="/webauthn/register/verify")return this.webauthnEndpoints.handleRegistrationVerify(A);if(A.method==="POST"&&w==="/webauthn/auth/options")return this.webauthnEndpoints.handleAuthenticationOptions(A);if(A.method==="POST"&&w==="/webauthn/auth/verify")return this.webauthnEndpoints.handleAuthenticationVerify(A);if(A.method==="GET"&&w==="/authorize")return this.oauthEndpoints.handleAuthorizePage(A);if(A.method==="POST"&&w==="/authorize")return this.oauthEndpoints.handleAuthorizeApproval(A);if(A.method==="POST"&&w==="/register")return wI(await this.oauthEndpoints.handleClientRegistration(A));if(A.method==="POST"&&w==="/token")return wI(await this.oauthEndpoints.handleTokenRequest(A,Q));if(A.method==="POST"&&w==="/revoke")return wI(await this.oauthEndpoints.handleRevokeRequest(A));return new Response("Not Found",{status:404})}async handleWellKnownRequest(A){return this.handleRequest(A)}resolveRequestIssuer(A){let Q=fv(A,this.issuer);if(this.trustedIssuers.has(Q)||this.allowLocalhostIssuers&&Wv(Q))return Q;throw Error(`Request issuer ${Q} is not in trusted issuers`)}handleLoginPage(A){let Q=EP0(new URL(A.url).searchParams.get("return_to"));return Fv(gP0(Q))}async handleLogout(A){await this.sessionStore.revokeSessionFromRequest(A);let Q=EP0(new URL(A.url).searchParams.get("return_to"));return new Response(null,{status:302,headers:{Location:Q,"Set-Cookie":zP0(el(A)),"Cache-Control":"no-store"}})}}Z0();var ow0="email:send",NxA=K.object({to:K.string().email(),subject:K.string().min(1),text:K.string().min(1),html:K.string().min(1).optional(),sensitivity:K.enum(["normal","secret"]).default("normal")}).strict();c0();Z0();var jxA={name:"@brains/notifications",private:!0,version:"0.2.0-alpha.135",description:"Generic notification routing for transactional and administrative messages",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var lP0="notifications:send",Kl2=K.object({}),Ul2=K.discriminatedUnion("type",[K.object({type:K.literal("email"),address:K.string().email()}).strict()]),Gl2=K.object({recipient:Ul2,title:K.string().min(1),body:K.string().min(1),html:K.string().min(1).optional(),sensitivity:K.enum(["normal","secret"]).default("normal")}).strict(),MxA=K.discriminatedUnion("status",[K.object({status:K.literal("sent"),deliveryId:K.string().optional()}).strict(),K.object({status:K.literal("failed")}).strict()]);class _xA extends IQ{constructor(A={}){super("notifications",jxA,A,Kl2)}async onRegister(A){A.messaging.subscribe(lP0,async(Q)=>{let w=Gl2.parse(Q.payload),B={to:w.recipient.address,subject:w.title,text:w.body,...w.html?{html:w.html}:{},sensitivity:w.sensitivity},$=await A.messaging.send({type:ow0,payload:B});if(!("success"in $)||!$.success||!$.data)return{success:!1,error:"Notification delivery failed"};let Y=$.data;if(Y.status!=="sent")return{success:!1,error:"Notification delivery failed"};return{success:!0,data:Y.id?{status:"sent",deliveryId:Y.id}:{status:"sent"}}})}}function sw0(A={}){return new _xA(A)}c0();Z0();var PxA={name:"@brains/auth-service",private:!0,version:"0.2.0-alpha.135",description:"Embedded OAuth/OIDC auth service for brain operator authentication",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@simplewebauthn/server":"^13.3.0",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},files:["src"]};var ql2=K.union([K.string().email(),K.object({to:K.string().email(),subject:K.string().min(1),body:K.string().min(1)}).strict()]),Fl2=K.object({issuer:K.string().optional(),trustedIssuers:K.array(K.string()).default([]),allowLocalhostIssuers:K.boolean().optional(),storageDir:K.string().default("./data/auth"),setupTokenTtlSeconds:K.number().int().positive().default($p),setupEmail:ql2.optional()}),Vl2=K.object({}),aw0;function EW(){return aw0}class pP0 extends IQ{service;constructor(A={}){super("auth-service",PxA,A,Fl2)}async onRegister(A){await super.onRegister(A);let Q=this.config.issuer??(A.preferLocalUrls?A.localSiteUrl??A.siteUrl:A.siteUrl??A.localSiteUrl);this.service=new rw0({storageDir:this.config.storageDir,...Q?{issuer:Q}:{},trustedIssuers:this.config.trustedIssuers,...this.config.allowLocalhostIssuers!==void 0?{allowLocalhostIssuers:this.config.allowLocalhostIssuers}:{},setupTokenTtlSeconds:this.config.setupTokenTtlSeconds,logger:A.logger}),await this.service.initialize(),aw0=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(aw0===this.service)aw0=void 0;this.service=void 0}async getTools(){return[Sw(this.id,"get_passkey_setup_url","Get the first-passkey setup URL when operator setup is required. Anchor-only.",Vl2,async()=>{let A=this.getService();if(await A.hasPasskeyCredentials())return l8({status:"complete"});let Q=await A.getOperatorSetupRequired();if(Q)return l8({status:"setup_required",setupUrl:Q.setupUrl,expiresAt:Q.expiresAt});return l8({status:"unavailable",reason:"Passkey setup URL is not available."})},{visibility:"anchor",sideEffects:"none"})]}getWebRoutes(){let A=(Q)=>this.getService().handleRequest(Q);return[{path:"/.well-known/oauth-authorization-server",method:"GET",public:!0,handler:A},{path:"/.well-known/oauth-authorization-server",method:"OPTIONS",public:!0,handler:A},{path:"/.well-known/jwks.json",method:"GET",public:!0,handler:A},{path:"/.well-known/jwks.json",method:"OPTIONS",public:!0,handler:A},{path:"/.well-known/oauth-protected-resource",method:"GET",public:!0,handler:A},{path:"/.well-known/oauth-protected-resource",method:"OPTIONS",public:!0,handler:A},{path:"/setup",method:"GET",public:!0,handler:A},{path:"/login",method:"GET",public:!0,handler:A},{path:"/logout",method:"GET",public:!0,handler:A},{path:"/logout",method:"POST",public:!0,handler:A},{path:"/authorize",method:"GET",public:!0,handler:A},{path:"/authorize",method:"POST",public:!0,handler:A},{path:"/register",method:"POST",public:!0,handler:A},{path:"/register",method:"OPTIONS",public:!0,handler:A},{path:"/token",method:"POST",public:!0,handler:A},{path:"/token",method:"OPTIONS",public:!0,handler:A},{path:"/revoke",method:"POST",public:!0,handler:A},{path:"/revoke",method:"OPTIONS",public:!0,handler:A},{path:"/webauthn/register/options",method:"POST",public:!0,handler:A},{path:"/webauthn/register/verify",method:"POST",public:!0,handler:A},{path:"/webauthn/auth/options",method:"POST",public:!0,handler:A},{path:"/webauthn/auth/verify",method:"POST",public:!0,handler:A}]}getService(){if(!this.service)throw Error("AuthServicePlugin has not been registered");return this.service}async requestSetupEmailIfNeeded(A){if(!this.config.setupEmail)return;let Q=this.getService();if(await Q.hasPasskeyCredentials())return;let w=await Q.getOperatorSetupRequired();if(!w)return;let B=Jl2(this.config.setupEmail,w);if(await Q.hasSetupEmailDelivery(w.setupTokenId,B.to))return;let $=await A.messaging.send({type:lP0,payload:{recipient:{type:"email",address:B.to},title:B.subject,body:B.body,sensitivity:"secret"}});if(!("success"in $)||!$.success||!$.data){A.logger.warn("Passkey setup email delivery was not confirmed");return}let Y=MxA.safeParse($.data);if(!Y.success||Y.data.status!=="sent"){A.logger.warn("Passkey setup email delivery was not confirmed");return}await Q.recordSetupEmailDelivery(w.setupTokenId,B.to,Y.data.deliveryId?{deliveryId:Y.data.deliveryId}:{})}}function Jl2(A,Q){if(typeof A==="string"){let w=new Date(Q.expiresAt*1000).toISOString(),B=new URL(Q.setupUrl).origin;return{to:A,subject:"Set up your brain passkey",body:["Set up your brain passkey using this single-use link:","",Q.setupUrl,"",`This link expires at ${w}.`,`Dashboard: ${B}/`,`MCP endpoint: ${B}/mcp`,"The first successful passkey registration completes setup and closes this link."].join(`
2278
- `)}}return{to:A.to,subject:kxA(A.subject,Q),body:kxA(A.body,Q)}}function kxA(A,Q){let w=new Date(Q.expiresAt*1000).toISOString(),B=new URL(Q.setupUrl).origin;return A.replaceAll("{{setupUrl}}",Q.setupUrl).replaceAll("{{expiresAt}}",w).replaceAll("{{origin}}",B)}function Yp(A){return new pP0(A)}Z0();var iP0=K.object({transport:K.enum(["stdio","http"]).default("http"),httpPort:K.number().describe("Port for HTTP transport (only used when transport is 'http')").default(3333),authToken:K.string().describe("Bearer token for HTTP transport authentication").optional()});function OxA(A,Q){return[]}c0();function dP0(A,Q){A.messaging.subscribe("job-progress",async(w)=>{let B=CO.safeParse(w.payload);if(!B.success)return Q.warn("Received invalid job-progress message",{error:B.error.message}),{success:!1};let $=B.data,Y=$.type,D=$.status,X=$.id;if(Q.debug(`${Y} ${X} - ${D}:`,{id:$.id,message:$.message,progress:$.progress,metadata:$.metadata}),$.batchDetails)Q.debug(`Batch details for ${X}:`,{totalOperations:$.batchDetails.totalOperations,completedOperations:$.batchDetails.completedOperations,failedOperations:$.batchDetails.failedOperations,currentOperation:$.batchDetails.currentOperation,errors:$.batchDetails.errors});if($.jobDetails)Q.debug(`Job details for ${X}:`,{jobType:$.jobDetails.jobType,priority:$.jobDetails.priority,retryCount:$.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var xxA={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.135",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/auth-service":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@modelcontextprotocol/sdk":"^1.24.0",cors:"^2.8.5",express:"^4.18.0","express-async-handler":"^1.2.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/cors":"^2.8.17","@types/express":"^4.17.21",typescript:"^5.3.3"}};class BI extends GU{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",xxA,Q,iP0)}async getTools(){return OxA(this.id,()=>this.context)}async getResources(){return[]}async onRegister(A){if(this.domain=A.domain,this.config.transport==="http"&&!A.plugins.has("webserver"))throw Error("MCP HTTP transport requires the webserver interface. Standalone HTTP listeners have been removed.");if(this.logger.debug(`MCP interface initialized with ${this.config.transport} transport`),this.config.transport==="http")A.endpoints.register({label:"MCP",url:"/mcp",priority:30,visibility:"trusted"}),A.interactions.register({id:"mcp",label:"MCP",description:"Connect a trusted client through the Model Context Protocol.",href:"/mcp",kind:"protocol",priority:30,visibility:"trusted"});dP0(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=EW();return this.httpServer=mq.createFresh({port:this.config.httpPort,logger:this.logger,auth:this.config.authToken?{token:this.config.authToken}:A?{requiredScopes:["mcp"],verifyBearerToken:async(Q)=>A.verifyBearerToken(Q)}:{disabled:!0}}),this.httpServer}getWebRoutes(){if(this.config.transport!=="http")return[];let A=(Q)=>this.getOrCreateHttpServer().handleRequest(Q);return[{path:"/status",method:"GET",public:!0,handler:A},{path:"/mcp",method:"GET",public:!0,handler:A},{path:"/mcp",method:"POST",public:!0,handler:A},{path:"/mcp",method:"DELETE",public:!0,handler:A},{path:"/mcp",method:"OPTIONS",public:!0,handler:A}]}createDaemon(){return{start:async()=>{await this.startServer()},stop:async()=>{await this.stopServer()},healthCheck:async()=>{let A=this.isServerRunning(),Q="MCP server not running";if(A)if(this.config.transport==="http")Q=`MCP HTTP: ${this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp"}`;else Q="MCP stdio server running";return{status:A?"healthy":"error",message:Q,lastCheck:new Date,details:{transport:this.config.transport,url:this.config.transport==="http"?this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp":void 0,running:A}}}}}isServerRunning(){if(this.config.transport==="stdio")return this.stdioServer!==void 0&&this.mcpTransport!==void 0;else return this.httpServer!==void 0&&this.mcpTransport!==void 0}async startServer(){if(!this.context)throw Error("Context not initialized");let A=this.context;this.mcpTransport=A.mcpTransport;let Q=this.config.transport==="stdio"?"stdio":"http",w=this.context.permissions.getUserLevel("mcp",Q);if(this.config.transport==="http"&&(this.config.authToken||EW()))w="anchor",this.logger.debug("HTTP authentication configured - authenticated users will have anchor permissions");if(this.mcpTransport.setPermissionLevel(w),this.logger.debug(`Starting MCP ${this.config.transport} transport with ${w} permissions`),this.config.transport==="stdio"){this.stdioServer=jZ.createFresh();let B=this.mcpTransport.getMcpServer();this.stdioServer.connectMCPServer(B),await this.stdioServer.start(),this.logger.debug("MCP STDIO transport started")}else{this.httpServer=this.getOrCreateHttpServer();let B=this.mcpTransport.getMcpServer();this.httpServer.connectMCPServer(B,this.mcpTransport),this.httpServer.connectAgentService(A.agent),this.logger.debug("MCP HTTP transport mounted on shared webserver host")}}async stopServer(){if(this.logger.debug(`Stopping MCP ${this.config.transport} transport`),this.stdioServer)this.stdioServer.stop(),this.stdioServer=void 0;if(this.httpServer)await this.httpServer.stop(),this.httpServer=void 0;this.mcpTransport=void 0}async handleProgressEvent(A,Q){}async onShutdown(){jZ.resetInstance(),mq.resetInstance()}}c0();Z0();var eX=X1(Qy0(),1);Z0();c0();var wy0=K.object({botToken:K.string().min(1).describe("Discord bot token"),allowedChannels:K.array(K.string()).default([]),requireMention:K.boolean().default(!0),allowDMs:K.boolean().default(!0),showTypingIndicator:K.boolean().default(!0),statusMessage:K.string().default("Mention me to chat"),useThreads:K.boolean().default(!0),threadAutoArchive:K.union([K.literal(60),K.literal(1440),K.literal(4320),K.literal(10080)]).default(1440),...kN.shape,captureUrlEmoji:K.string().default("\uD83D\uDD16")});var OW1={name:"@brains/discord",private:!0,version:"0.2.0-alpha.135",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 li=2000,ubQ=8388608,cbQ=8000,lbQ=100;function Q50(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class uI extends AZ{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",OW1,A,wy0);this.fetchText=Q.fetchText??Mt}async onRegister(A){await super.onRegister(A),this.client=new eX.Client({intents:[eX.GatewayIntentBits.Guilds,eX.GatewayIntentBits.GuildMessages,eX.GatewayIntentBits.MessageContent,eX.GatewayIntentBits.DirectMessages],partials:[eX.Partials.Channel]}),this.client.on(eX.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.on(eX.Events.InteractionCreate,(Q)=>{this.handleInteraction(Q)}),this.client.once(eX.Events.ClientReady,()=>{this.logger.info("Discord bot connected",{tag:this.client?.user?.tag})})}createDaemon(){return{start:async()=>{if(!this.client)throw Error("Discord client not initialized");await this.client.login(this.config.botToken)},stop:async()=>{for(let A of this.typingIntervals.values())clearInterval(A);if(this.typingIntervals.clear(),this.client)await this.client.destroy(),this.client=null},healthCheck:async()=>({status:this.client?.user?"healthy":"error",message:this.client?.user?`Connected as ${this.client.user.tag}`:"Not connected",lastCheck:new Date})}}sendMessageToChannel({channelId:A,message:Q}){if(!A||!this.client)return;let w=this.client.channels.cache.get(A);if(!Q50(w))return;let B=AN(Q,li);for(let $ of B)w.send($).catch((Y)=>this.logger.error("Failed to send message",{error:Y}))}async sendMessageWithId({channelId:A,message:Q,approvalCard:w,approvalCards:B}){let $=B??(w?[w]:[]),Y=$.length>0?this.buildApprovalMessagePayload(Q,$):Q;return this.sendPayloadWithId(A,Y)}async sendPayloadWithId(A,Q){if(!A||!this.client)return;let w=this.client.channels.cache.get(A);if(!Q50(w))return;if(typeof Q!=="string")return(await w.send(Q)).id;let B=AN(Q,li),$;for(let Y of B)$=(await w.send(Y)).id;return $}async editMessage({channelId:A,messageId:Q,newMessage:w}){if(!A||!this.client)return!1;let B=this.client.channels.cache.get(A);if(!Q50(B))return!1;try{return await(await B.messages.fetch(Q)).edit(w.slice(0,li)),!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,w=A.channel.isThread();if(Q&&!this.config.allowDMs)return;let B=!!this.client?.user&&A.mentions.has(this.client.user,{ignoreEveryone:!0});if(A.author.bot&&!B)return;let $=w&&"ownerId"in A.channel&&A.channel.ownerId===this.client?.user?.id,Y=this.getSpaceChannelId(A),D=!Q&&this.isConfiguredSpace(Y),X={channelId:Y,isBot:A.author.bot};if(this.config.allowedChannels.length>0&&!Q&&!this.isAllowedChannel(A.channel.id,Y))return;let H=Q||$||!this.config.requireMention||B;if(D&&(!H||this.willRouteUseNonSpaceConversation(A)))await this.capturePassiveSpaceMessage(A,Y).catch((Z)=>this.logger.error("Passive Discord space capture failed",{error:Z,channelId:Y}));if(!H){if(this.config.captureUrls){let Z=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(Z.length>0){await A.react(this.config.captureUrlEmoji).catch((G)=>this.logger.debug("React failed",{error:G}));for(let G of Z)await this.captureUrlViaAgent(G,A.channel.id,A.author.id,"discord",X).catch((F)=>this.logger.error("URL capture failed",{error:F,url:G}))}}return}let W=this.stripMention(A.content);if(A.attachments.size>0){let Z=this.context.permissions.getUserLevel("discord",A.author.id,X);if(Z==="anchor"||Z==="trusted")for(let F of A.attachments.values()){let V=F.name,b=F.contentType??void 0,L=F.size;if(!this.isUploadableTextFile(V,b))continue;if(!this.isFileSizeAllowed(L))continue;try{let N=await this.fetchText(F.url);W+=`
2277
+ </html>`}function Bp(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(gP0(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function eU(A){return A.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}import{randomUUID as Hl2}from"crypto";function bxA(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function Xl2(A){let Q=new Uint8Array(A);if(Q.length===64)return Q;if(Q[0]!==48)return Q;let w=2;if(Q[1]&&Q[1]>128)w+=Q[1]-128;if(Q[w]!==2)throw Error("Invalid DER ECDSA signature");let B=Q[w+1];if(B===void 0)throw Error("Invalid DER ECDSA signature");let $=w+2,Y=Q.slice($,$+B);if(w=$+B,Q[w]!==2)throw Error("Invalid DER ECDSA signature");let D=Q[w+1];if(D===void 0)throw Error("Invalid DER ECDSA signature");let X=w+2,H=Q.slice(X,X+D);return new Uint8Array([...LxA(Y),...LxA(H)])}function LxA(A){let Q=A;while(Q.length>32&&Q[0]===0)Q=Q.slice(1);if(Q.length>32)throw Error("Invalid P-256 signature component length");if(Q.length===32)return Q;let w=new Uint8Array(32);return w.set(Q,32-Q.length),w}async function SP0(A,Q){let w={typ:"JWT",alg:"ES256",kid:A.kid},B=`${bxA(w)}.${bxA(Q)}`,$=await crypto.subtle.importKey("jwk",A,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),Y=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},$,new TextEncoder().encode(B));return`${B}.${Buffer.from(Xl2(Y)).toString("base64url")}`}var Wl2=600;class mP0{clientStore;authCodeStore;refreshTokenStore;sessionStore;keyStore;authorizationApprovalTokens=new Map;constructor(A){this.clientStore=A.clientStore,this.authCodeStore=A.authCodeStore,this.refreshTokenStore=A.refreshTokenStore,this.sessionStore=A.sessionStore,this.keyStore=A.keyStore}async handleAuthorizePage(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return Bp(A);let w=await this.validateAuthorizationRequest(new URL(A.url).searchParams);if(!w.success)return new Response(w.error,{status:400});let B=this.createAuthorizationApprovalToken(Q,w.params);return Fv(IxA(w.params,B))}async handleAuthorizeApproval(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return Bp(A);let w=await A.formData(),B=await this.validateAuthorizationRequest(new URLSearchParams(vP0(w)));if(!B.success)return new Response(B.error,{status:400});let $=w.get("approval_token"),Y=typeof $==="string"?$:void 0;if(!Y||!this.consumeAuthorizationApprovalToken(Y,Q,B.params))return new Response("Invalid authorization approval token",{status:400});let D=await this.authCodeStore.createCode({clientId:B.params.clientId,redirectUri:B.params.redirectUri,codeChallenge:B.params.codeChallenge,...B.params.scope?{scope:B.params.scope}:{},subject:Q.subject}),X=new URL(B.params.redirectUri);if(X.searchParams.set("code",D.code),B.params.state)X.searchParams.set("state",B.params.state);return Response.redirect(X.toString(),302)}createAuthorizationApprovalToken(A,Q){this.pruneExpiredAuthorizationApprovalTokens();let w=`oat_${Hl2()}`;return this.authorizationApprovalTokens.set(w,{token:w,sessionId:A.id,clientId:Q.clientId,redirectUri:Q.redirectUri,codeChallenge:Q.codeChallenge,...Q.scope?{scope:Q.scope}:{},...Q.state?{state:Q.state}:{},expiresAt:Math.floor(Date.now()/1000)+Wl2}),w}consumeAuthorizationApprovalToken(A,Q,w){this.pruneExpiredAuthorizationApprovalTokens();let B=this.authorizationApprovalTokens.get(A);if(!B)return!1;return this.authorizationApprovalTokens.delete(A),B.sessionId===Q.id&&B.clientId===w.clientId&&B.redirectUri===w.redirectUri&&B.codeChallenge===w.codeChallenge&&B.scope===w.scope&&B.state===w.state}pruneExpiredAuthorizationApprovalTokens(){let A=Math.floor(Date.now()/1000);for(let[Q,w]of this.authorizationApprovalTokens.entries())if(w.expiresAt<=A)this.authorizationApprovalTokens.delete(Q)}async validateAuthorizationRequest(A){let Q=A.get("response_type"),w=A.get("client_id"),B=A.get("redirect_uri"),$=A.get("code_challenge"),Y=A.get("code_challenge_method"),D=A.get("scope")??void 0,X=A.get("state")??void 0;if(Q!=="code")return{success:!1,error:"Unsupported response_type"};if(!w)return{success:!1,error:"Missing client_id"};if(!B)return{success:!1,error:"Missing redirect_uri"};if(!$)return{success:!1,error:"Missing code_challenge"};if(Y!=="S256")return{success:!1,error:"Unsupported code_challenge_method"};let H=await this.clientStore.getClient(w);if(!H)return{success:!1,error:"Unknown client_id"};if(!Uj0(H.redirect_uris,B))return{success:!1,error:"Unregistered redirect_uri"};let W=D??H.scope;return{success:!0,params:{clientId:w,redirectUri:B,codeChallenge:$,...W?{scope:W}:{},...X?{state:X}:{},clientName:H.client_name??H.client_id}}}async handleClientRegistration(A){let Q;try{Q=await A.json()}catch{return y6("invalid_client_metadata","Request body must be JSON")}try{let w=await this.clientStore.registerClient(Q);return lX(w,201)}catch(w){if(w instanceof zc)return y6("invalid_client_metadata",w.message);throw w}}async handleTokenRequest(A,Q){let w=await hP0(A),B=w.get("grant_type"),$=yP0(A,w),Y=$.clientId??w.get("client_id");if($.error)return y6("invalid_client",$.error);if(!Y)return y6("invalid_request","client_id is required");let D=await this.clientStore.getClient(Y),X=CP0(D,$);if(X)return y6("invalid_client",X);if(B==="authorization_code")return this.handleAuthorizationCodeGrant(w,Y,Q);if(B==="refresh_token")return this.handleRefreshTokenGrant(w,Y,Q);return y6("unsupported_grant_type","Only authorization_code and refresh_token are supported")}async handleAuthorizationCodeGrant(A,Q,w){let B=A.get("code"),$=A.get("redirect_uri"),Y=A.get("code_verifier");if(!B||!$||!Y)return y6("invalid_request","code, redirect_uri, and code_verifier are required");let D=await this.clientStore.getClient(Q);if(!D||!Uj0(D.redirect_uris,$))return y6("invalid_grant","Unregistered redirect_uri");try{let X=await this.authCodeStore.consumeCode({code:B,clientId:Q,redirectUri:$,codeVerifier:Y});return await this.createTokenResponse({issuer:w,clientId:Q,subject:X.subject,...X.scope?{scope:X.scope}:{}})}catch(X){if(X instanceof MZ)return y6("invalid_grant",X.message);throw X}}async handleRefreshTokenGrant(A,Q,w){let B=A.get("refresh_token");if(!B)return y6("invalid_request","refresh_token is required");try{let $=await this.refreshTokenStore.rotateToken(B,Q);return await this.createTokenResponse({issuer:w,clientId:Q,subject:$.consumed.subject,...$.consumed.scope?{scope:$.consumed.scope}:{},refreshToken:$.replacement.token})}catch($){if($ instanceof f3)return y6("invalid_grant",$.message);throw $}}async createTokenResponse(A){let Q=Math.floor(Date.now()/1000),w=900,B=await SP0(await this.keyStore.getPrivateJwk(),{iss:A.issuer,sub:A.subject,aud:A.clientId,iat:Q,exp:Q+900,...A.scope?{scope:A.scope}:{}}),$=A.refreshToken??(await this.refreshTokenStore.issueToken({clientId:A.clientId,subject:A.subject,...A.scope?{scope:A.scope}:{}})).token;return lX({access_token:B,token_type:"Bearer",expires_in:900,...A.scope?{scope:A.scope}:{},refresh_token:$})}async handleRevokeRequest(A){let Q=await hP0(A),w=yP0(A,Q),B=w.clientId??Q.get("client_id")??void 0,$=Q.get("token");if(w.error)return y6("invalid_client",w.error);if(!$)return y6("invalid_request","token is required");if(B){let Y=await this.clientStore.getClient(B),D=CP0(Y,w);if(D)return y6("invalid_client",D)}return await this.refreshTokenStore.revokeToken($,B),new Response(null,{status:200})}}class uP0{passkeyService;sessionStore;setupFlow;constructor(A){this.passkeyService=A.passkeyService,this.sessionStore=A.sessionStore,this.setupFlow=A.setupFlow}async handleRegistrationOptions(A){if(await this.passkeyService.hasCredentials())return y6("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return y6("access_denied","Invalid setup token");let Q=await this.passkeyService.generateRegistrationOptions(nw0(A));return lX(Q)}async handleRegistrationVerify(A){if(await this.passkeyService.hasCredentials())return y6("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return y6("access_denied","Invalid setup token");let Q=await this.passkeyService.verifyRegistrationResponse(await A.json(),nw0(A));if(!Q.verified)return y6("access_denied","Passkey registration failed");await this.setupFlow.clearSetupState();let w=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:el(A)});return lX({verified:!0},200,{"Set-Cookie":w.cookie})}async handleAuthenticationOptions(A){if(!await this.passkeyService.hasCredentials())return y6("access_denied","No passkey registered");let Q=await this.passkeyService.generateAuthenticationOptions(nw0(A));return lX(Q)}async handleAuthenticationVerify(A){let Q=await this.passkeyService.verifyAuthenticationResponse(await A.json(),nw0(A));if(!Q.verified)return y6("access_denied","Passkey authentication failed");let w=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:el(A)});return lX({verified:!0},200,{"Set-Cookie":w.cookie})}}function nw0(A){let Q=fv(A),w=new URL(Q);return{origin:w.origin,rpID:w.hostname}}import{randomUUID as fl2}from"crypto";var $p=86400;class cP0{setupStateStore;passkeyService;setupTokenTtlSeconds;setupToken;constructor(A){this.setupStateStore=A.setupStateStore,this.passkeyService=A.passkeyService,this.setupTokenTtlSeconds=A.setupTokenTtlSeconds??$p}async ensureSetupToken(){let A=this.getValidSetupToken();if(A)return A;let Q=await this.setupStateStore.getValidSetupToken(Math.floor(Date.now()/1000));if(Q)return this.setupToken=Q,Q;return this.createSetupToken()}async createSetupToken(){return this.setupToken={token:`setup_${fl2()}`,expiresAt:Math.floor(Date.now()/1000)+this.setupTokenTtlSeconds},await this.setupStateStore.saveSetupToken(this.setupToken),this.setupToken}getValidSetupToken(){if(!this.setupToken)return;if(this.setupToken.expiresAt<=Math.floor(Date.now()/1000)){this.setupToken=void 0;return}return this.setupToken}hasValidSetupToken(A){let Q=this.getValidSetupToken();if(!Q)return!1;let w=new URL(A.url);return(w.searchParams.get("setup_token")??w.searchParams.get("token"))===Q.token}async clearSetupState(){this.setupToken=void 0,await this.setupStateStore.clearSetupState()}getSetupUrl(A){let Q=this.getValidSetupToken();if(!Q)return;return tU(A,`/setup?token=${encodeURIComponent(Q.token)}`)}async getOperatorSetupRequired(A){if(await this.passkeyService.hasCredentials())return;let Q=this.getValidSetupToken();if(!Q)return;return{setupUrl:tU(A,`/setup?token=${encodeURIComponent(Q.token)}`),expiresAt:Q.expiresAt,setupTokenId:ZP0(Q.token)}}async handleSetupPage(A){if(await this.passkeyService.hasCredentials())return new Response("Setup already completed",{status:404});if(!this.hasValidSetupToken(A))return new Response("Not Found",{status:404});let Q=new URL(A.url).searchParams.get("token")??"";return Fv(VxA(Q))}async hasSetupEmailDelivery(A,Q){return this.setupStateStore.hasDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,w={}){await this.setupStateStore.recordDelivery(A,Q,w)}}class rw0{issuer;trustedIssuers;allowLocalhostIssuers;keyStore;clientStore;authCodeStore;sessionStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;logger;constructor(A){this.issuer=EZ(A.issuer),this.trustedIssuers=new Set([this.issuer,...(A.trustedIssuers??[]).map((Q)=>EZ(Q))]),this.allowLocalhostIssuers=A.allowLocalhostIssuers??Wv(this.issuer),this.keyStore=new WQ0({storageDir:A.storageDir}),this.clientStore=new HQ0({storageDir:A.storageDir}),this.authCodeStore=new XQ0({storageDir:A.storageDir}),this.sessionStore=new cw0({storageDir:A.storageDir}),this.passkeyService=new gw0({storageDir:A.storageDir,...A.logger?{logger:A.logger}:{}}),this.setupFlow=new cP0({setupStateStore:new KP0({storageDir:A.storageDir}),passkeyService:this.passkeyService,setupTokenTtlSeconds:A.setupTokenTtlSeconds??$p}),this.oauthEndpoints=new mP0({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:new Sw0({storageDir:A.storageDir}),sessionStore:this.sessionStore,keyStore:this.keyStore}),this.webauthnEndpoints=new uP0({passkeyService:this.passkeyService,sessionStore:this.sessionStore,setupFlow:this.setupFlow}),this.logger=A.logger}getIssuer(){return this.issuer}async initialize(){if(await this.keyStore.getPrivateJwk(),this.logger?.debug("Auth service signing key loaded"),!await this.hasPasskeyCredentials()){await this.setupFlow.ensureSetupToken();let A=this.getSetupUrl();if(A)if(Wv(this.issuer))this.logger?.warn(`Passkey setup required: ${A}`);else this.logger?.warn("Passkey setup required. Ask through an anchor-visible interface for the setup URL.")}}async hasPasskeyCredentials(){return this.passkeyService.hasCredentials()}async getJwks(){return{keys:[await this.keyStore.getPublicJwk()]}}getAuthorizationServerMetadata(A=this.issuer){let Q=EZ(A);return{issuer:Q,authorization_endpoint:tU(Q,"/authorize"),token_endpoint:tU(Q,"/token"),registration_endpoint:tU(Q,"/register"),revocation_endpoint:tU(Q,"/revoke"),jwks_uri:tU(Q,"/.well-known/jwks.json"),response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"],token_endpoint_auth_methods_supported:["none","client_secret_basic","client_secret_post"],scopes_supported:["openid","profile","email","offline_access","mcp"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["ES256"]}}getProtectedResourceMetadata(A,Q=this.issuer){return{resource:A,authorization_servers:[EZ(Q)],bearer_methods_supported:["header"],resource_signing_alg_values_supported:["ES256"],scopes_supported:["mcp"]}}async registerClient(A){return this.clientStore.registerClient(A)}async getRegisteredClient(A){return this.clientStore.getClient(A)}async createOperatorSession(A="single-operator",Q={}){return this.sessionStore.createSession(A,Q)}async getOperatorSession(A){return this.sessionStore.getSessionFromRequest(A)}createOperatorLoginResponse(A){return Bp(A)}async verifyBearerToken(A,Q={}){let w=RP0(A);if(!w)return;let B=Q.issuer?EZ(Q.issuer):this.resolveRequestIssuer(A);return xP0(w,await this.getJwks(),{issuer:B,...Q.audience?{audience:Q.audience}:{}})}getSetupUrl(A=this.issuer){return this.setupFlow.getSetupUrl(A)}async getOperatorSetupRequired(A=this.issuer){return this.setupFlow.getOperatorSetupRequired(A)}async hasSetupEmailDelivery(A,Q){return this.setupFlow.hasSetupEmailDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,w={}){await this.setupFlow.recordSetupEmailDelivery(A,Q,w)}async handleRequest(A){let Q;try{Q=this.resolveRequestIssuer(A)}catch(B){return this.logger?.warn("Rejected OAuth request from untrusted issuer",{error:B instanceof Error?B.message:String(B)}),new Response("Untrusted OAuth issuer",{status:400})}let w=new URL(A.url).pathname;if(A.method==="OPTIONS"&&zxA(w))return qxA();if(A.method==="GET"){if(w==="/.well-known/oauth-authorization-server")return wI(lX(this.getAuthorizationServerMetadata(Q)));if(w==="/.well-known/jwks.json")return wI(lX(await this.getJwks()));if(w==="/.well-known/oauth-protected-resource")return wI(lX(this.getProtectedResourceMetadata(Q,Q)))}if(A.method==="GET"&&w==="/setup")return this.setupFlow.handleSetupPage(A);if(A.method==="GET"&&w==="/login")return this.handleLoginPage(A);if((A.method==="GET"||A.method==="POST")&&w==="/logout")return this.handleLogout(A);if(A.method==="POST"&&w==="/webauthn/register/options")return this.webauthnEndpoints.handleRegistrationOptions(A);if(A.method==="POST"&&w==="/webauthn/register/verify")return this.webauthnEndpoints.handleRegistrationVerify(A);if(A.method==="POST"&&w==="/webauthn/auth/options")return this.webauthnEndpoints.handleAuthenticationOptions(A);if(A.method==="POST"&&w==="/webauthn/auth/verify")return this.webauthnEndpoints.handleAuthenticationVerify(A);if(A.method==="GET"&&w==="/authorize")return this.oauthEndpoints.handleAuthorizePage(A);if(A.method==="POST"&&w==="/authorize")return this.oauthEndpoints.handleAuthorizeApproval(A);if(A.method==="POST"&&w==="/register")return wI(await this.oauthEndpoints.handleClientRegistration(A));if(A.method==="POST"&&w==="/token")return wI(await this.oauthEndpoints.handleTokenRequest(A,Q));if(A.method==="POST"&&w==="/revoke")return wI(await this.oauthEndpoints.handleRevokeRequest(A));return new Response("Not Found",{status:404})}async handleWellKnownRequest(A){return this.handleRequest(A)}resolveRequestIssuer(A){let Q=fv(A,this.issuer);if(this.trustedIssuers.has(Q)||this.allowLocalhostIssuers&&Wv(Q))return Q;throw Error(`Request issuer ${Q} is not in trusted issuers`)}handleLoginPage(A){let Q=EP0(new URL(A.url).searchParams.get("return_to"));return Fv(gP0(Q))}async handleLogout(A){await this.sessionStore.revokeSessionFromRequest(A);let Q=EP0(new URL(A.url).searchParams.get("return_to"));return new Response(null,{status:302,headers:{Location:Q,"Set-Cookie":zP0(el(A)),"Cache-Control":"no-store"}})}}Z0();var ow0="email:send",NxA=K.object({to:K.string().email(),subject:K.string().min(1),text:K.string().min(1),html:K.string().min(1).optional(),sensitivity:K.enum(["normal","secret"]).default("normal")}).strict();c0();Z0();var jxA={name:"@brains/notifications",private:!0,version:"0.2.0-alpha.136",description:"Generic notification routing for transactional and administrative messages",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var lP0="notifications:send",Kl2=K.object({}),Ul2=K.discriminatedUnion("type",[K.object({type:K.literal("email"),address:K.string().email()}).strict()]),Gl2=K.object({recipient:Ul2,title:K.string().min(1),body:K.string().min(1),html:K.string().min(1).optional(),sensitivity:K.enum(["normal","secret"]).default("normal")}).strict(),MxA=K.discriminatedUnion("status",[K.object({status:K.literal("sent"),deliveryId:K.string().optional()}).strict(),K.object({status:K.literal("failed")}).strict()]);class _xA extends IQ{constructor(A={}){super("notifications",jxA,A,Kl2)}async onRegister(A){A.messaging.subscribe(lP0,async(Q)=>{let w=Gl2.parse(Q.payload),B={to:w.recipient.address,subject:w.title,text:w.body,...w.html?{html:w.html}:{},sensitivity:w.sensitivity},$=await A.messaging.send({type:ow0,payload:B});if(!("success"in $)||!$.success||!$.data)return{success:!1,error:"Notification delivery failed"};let Y=$.data;if(Y.status!=="sent")return{success:!1,error:"Notification delivery failed"};return{success:!0,data:Y.id?{status:"sent",deliveryId:Y.id}:{status:"sent"}}})}}function sw0(A={}){return new _xA(A)}c0();Z0();var PxA={name:"@brains/auth-service",private:!0,version:"0.2.0-alpha.136",description:"Embedded OAuth/OIDC auth service for brain operator authentication",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@simplewebauthn/server":"^13.3.0",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},files:["src"]};var ql2=K.union([K.string().email(),K.object({to:K.string().email(),subject:K.string().min(1),body:K.string().min(1)}).strict()]),Fl2=K.object({issuer:K.string().optional(),trustedIssuers:K.array(K.string()).default([]),allowLocalhostIssuers:K.boolean().optional(),storageDir:K.string().default("./data/auth"),setupTokenTtlSeconds:K.number().int().positive().default($p),setupEmail:ql2.optional()}),Vl2=K.object({}),aw0;function EW(){return aw0}class pP0 extends IQ{service;constructor(A={}){super("auth-service",PxA,A,Fl2)}async onRegister(A){await super.onRegister(A);let Q=this.config.issuer??(A.preferLocalUrls?A.localSiteUrl??A.siteUrl:A.siteUrl??A.localSiteUrl);this.service=new rw0({storageDir:this.config.storageDir,...Q?{issuer:Q}:{},trustedIssuers:this.config.trustedIssuers,...this.config.allowLocalhostIssuers!==void 0?{allowLocalhostIssuers:this.config.allowLocalhostIssuers}:{},setupTokenTtlSeconds:this.config.setupTokenTtlSeconds,logger:A.logger}),await this.service.initialize(),aw0=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(aw0===this.service)aw0=void 0;this.service=void 0}async getTools(){return[Sw(this.id,"get_passkey_setup_url","Get the first-passkey setup URL when operator setup is required. Anchor-only.",Vl2,async()=>{let A=this.getService();if(await A.hasPasskeyCredentials())return l8({status:"complete"});let Q=await A.getOperatorSetupRequired();if(Q)return l8({status:"setup_required",setupUrl:Q.setupUrl,expiresAt:Q.expiresAt});return l8({status:"unavailable",reason:"Passkey setup URL is not available."})},{visibility:"anchor",sideEffects:"none"})]}getWebRoutes(){let A=(Q)=>this.getService().handleRequest(Q);return[{path:"/.well-known/oauth-authorization-server",method:"GET",public:!0,handler:A},{path:"/.well-known/oauth-authorization-server",method:"OPTIONS",public:!0,handler:A},{path:"/.well-known/jwks.json",method:"GET",public:!0,handler:A},{path:"/.well-known/jwks.json",method:"OPTIONS",public:!0,handler:A},{path:"/.well-known/oauth-protected-resource",method:"GET",public:!0,handler:A},{path:"/.well-known/oauth-protected-resource",method:"OPTIONS",public:!0,handler:A},{path:"/setup",method:"GET",public:!0,handler:A},{path:"/login",method:"GET",public:!0,handler:A},{path:"/logout",method:"GET",public:!0,handler:A},{path:"/logout",method:"POST",public:!0,handler:A},{path:"/authorize",method:"GET",public:!0,handler:A},{path:"/authorize",method:"POST",public:!0,handler:A},{path:"/register",method:"POST",public:!0,handler:A},{path:"/register",method:"OPTIONS",public:!0,handler:A},{path:"/token",method:"POST",public:!0,handler:A},{path:"/token",method:"OPTIONS",public:!0,handler:A},{path:"/revoke",method:"POST",public:!0,handler:A},{path:"/revoke",method:"OPTIONS",public:!0,handler:A},{path:"/webauthn/register/options",method:"POST",public:!0,handler:A},{path:"/webauthn/register/verify",method:"POST",public:!0,handler:A},{path:"/webauthn/auth/options",method:"POST",public:!0,handler:A},{path:"/webauthn/auth/verify",method:"POST",public:!0,handler:A}]}getService(){if(!this.service)throw Error("AuthServicePlugin has not been registered");return this.service}async requestSetupEmailIfNeeded(A){if(!this.config.setupEmail)return;let Q=this.getService();if(await Q.hasPasskeyCredentials())return;let w=await Q.getOperatorSetupRequired();if(!w)return;let B=Jl2(this.config.setupEmail,w);if(await Q.hasSetupEmailDelivery(w.setupTokenId,B.to))return;let $=await A.messaging.send({type:lP0,payload:{recipient:{type:"email",address:B.to},title:B.subject,body:B.body,sensitivity:"secret"}});if(!("success"in $)||!$.success||!$.data){A.logger.warn("Passkey setup email delivery was not confirmed");return}let Y=MxA.safeParse($.data);if(!Y.success||Y.data.status!=="sent"){A.logger.warn("Passkey setup email delivery was not confirmed");return}await Q.recordSetupEmailDelivery(w.setupTokenId,B.to,Y.data.deliveryId?{deliveryId:Y.data.deliveryId}:{})}}function Jl2(A,Q){if(typeof A==="string"){let w=new Date(Q.expiresAt*1000).toISOString(),B=new URL(Q.setupUrl).origin;return{to:A,subject:"Set up your brain passkey",body:["Set up your brain passkey using this single-use link:","",Q.setupUrl,"",`This link expires at ${w}.`,`Dashboard: ${B}/`,`MCP endpoint: ${B}/mcp`,"The first successful passkey registration completes setup and closes this link."].join(`
2278
+ `)}}return{to:A.to,subject:kxA(A.subject,Q),body:kxA(A.body,Q)}}function kxA(A,Q){let w=new Date(Q.expiresAt*1000).toISOString(),B=new URL(Q.setupUrl).origin;return A.replaceAll("{{setupUrl}}",Q.setupUrl).replaceAll("{{expiresAt}}",w).replaceAll("{{origin}}",B)}function Yp(A){return new pP0(A)}Z0();var iP0=K.object({transport:K.enum(["stdio","http"]).default("http"),httpPort:K.number().describe("Port for HTTP transport (only used when transport is 'http')").default(3333),authToken:K.string().describe("Bearer token for HTTP transport authentication").optional()});function OxA(A,Q){return[]}c0();function dP0(A,Q){A.messaging.subscribe("job-progress",async(w)=>{let B=CO.safeParse(w.payload);if(!B.success)return Q.warn("Received invalid job-progress message",{error:B.error.message}),{success:!1};let $=B.data,Y=$.type,D=$.status,X=$.id;if(Q.debug(`${Y} ${X} - ${D}:`,{id:$.id,message:$.message,progress:$.progress,metadata:$.metadata}),$.batchDetails)Q.debug(`Batch details for ${X}:`,{totalOperations:$.batchDetails.totalOperations,completedOperations:$.batchDetails.completedOperations,failedOperations:$.batchDetails.failedOperations,currentOperation:$.batchDetails.currentOperation,errors:$.batchDetails.errors});if($.jobDetails)Q.debug(`Job details for ${X}:`,{jobType:$.jobDetails.jobType,priority:$.jobDetails.priority,retryCount:$.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var xxA={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.136",type:"module",main:"./src/index.ts",module:"./src/index.ts",types:"./src/index.ts",files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint --max-warnings 0 .","lint:fix":"eslint --fix .",test:"bun test"},dependencies:{"@brains/auth-service":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@modelcontextprotocol/sdk":"^1.24.0",cors:"^2.8.5",express:"^4.18.0","express-async-handler":"^1.2.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/cors":"^2.8.17","@types/express":"^4.17.21",typescript:"^5.3.3"}};class BI extends GU{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",xxA,Q,iP0)}async getTools(){return OxA(this.id,()=>this.context)}async getResources(){return[]}async onRegister(A){if(this.domain=A.domain,this.config.transport==="http"&&!A.plugins.has("webserver"))throw Error("MCP HTTP transport requires the webserver interface. Standalone HTTP listeners have been removed.");if(this.logger.debug(`MCP interface initialized with ${this.config.transport} transport`),this.config.transport==="http")A.endpoints.register({label:"MCP",url:"/mcp",priority:30,visibility:"trusted"}),A.interactions.register({id:"mcp",label:"MCP",description:"Connect a trusted client through the Model Context Protocol.",href:"/mcp",kind:"protocol",priority:30,visibility:"trusted"});dP0(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=EW();return this.httpServer=mq.createFresh({port:this.config.httpPort,logger:this.logger,auth:this.config.authToken?{token:this.config.authToken}:A?{requiredScopes:["mcp"],verifyBearerToken:async(Q)=>A.verifyBearerToken(Q)}:{disabled:!0}}),this.httpServer}getWebRoutes(){if(this.config.transport!=="http")return[];let A=(Q)=>this.getOrCreateHttpServer().handleRequest(Q);return[{path:"/status",method:"GET",public:!0,handler:A},{path:"/mcp",method:"GET",public:!0,handler:A},{path:"/mcp",method:"POST",public:!0,handler:A},{path:"/mcp",method:"DELETE",public:!0,handler:A},{path:"/mcp",method:"OPTIONS",public:!0,handler:A}]}createDaemon(){return{start:async()=>{await this.startServer()},stop:async()=>{await this.stopServer()},healthCheck:async()=>{let A=this.isServerRunning(),Q="MCP server not running";if(A)if(this.config.transport==="http")Q=`MCP HTTP: ${this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp"}`;else Q="MCP stdio server running";return{status:A?"healthy":"error",message:Q,lastCheck:new Date,details:{transport:this.config.transport,url:this.config.transport==="http"?this.domain?`https://${this.domain}/mcp`:"http://localhost:8080/mcp":void 0,running:A}}}}}isServerRunning(){if(this.config.transport==="stdio")return this.stdioServer!==void 0&&this.mcpTransport!==void 0;else return this.httpServer!==void 0&&this.mcpTransport!==void 0}async startServer(){if(!this.context)throw Error("Context not initialized");let A=this.context;this.mcpTransport=A.mcpTransport;let Q=this.config.transport==="stdio"?"stdio":"http",w=this.context.permissions.getUserLevel("mcp",Q);if(this.config.transport==="http"&&(this.config.authToken||EW()))w="anchor",this.logger.debug("HTTP authentication configured - authenticated users will have anchor permissions");if(this.mcpTransport.setPermissionLevel(w),this.logger.debug(`Starting MCP ${this.config.transport} transport with ${w} permissions`),this.config.transport==="stdio"){this.stdioServer=jZ.createFresh();let B=this.mcpTransport.getMcpServer();this.stdioServer.connectMCPServer(B),await this.stdioServer.start(),this.logger.debug("MCP STDIO transport started")}else{this.httpServer=this.getOrCreateHttpServer();let B=this.mcpTransport.getMcpServer();this.httpServer.connectMCPServer(B,this.mcpTransport),this.httpServer.connectAgentService(A.agent),this.logger.debug("MCP HTTP transport mounted on shared webserver host")}}async stopServer(){if(this.logger.debug(`Stopping MCP ${this.config.transport} transport`),this.stdioServer)this.stdioServer.stop(),this.stdioServer=void 0;if(this.httpServer)await this.httpServer.stop(),this.httpServer=void 0;this.mcpTransport=void 0}async handleProgressEvent(A,Q){}async onShutdown(){jZ.resetInstance(),mq.resetInstance()}}c0();Z0();var eX=X1(Qy0(),1);Z0();c0();var wy0=K.object({botToken:K.string().min(1).describe("Discord bot token"),allowedChannels:K.array(K.string()).default([]),requireMention:K.boolean().default(!0),allowDMs:K.boolean().default(!0),showTypingIndicator:K.boolean().default(!0),statusMessage:K.string().default("Mention me to chat"),useThreads:K.boolean().default(!0),threadAutoArchive:K.union([K.literal(60),K.literal(1440),K.literal(4320),K.literal(10080)]).default(1440),...kN.shape,captureUrlEmoji:K.string().default("\uD83D\uDD16")});var OW1={name:"@brains/discord",private:!0,version:"0.2.0-alpha.136",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 li=2000,ubQ=8388608,cbQ=8000,lbQ=100;function Q50(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class uI extends AZ{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",OW1,A,wy0);this.fetchText=Q.fetchText??Mt}async onRegister(A){await super.onRegister(A),this.client=new eX.Client({intents:[eX.GatewayIntentBits.Guilds,eX.GatewayIntentBits.GuildMessages,eX.GatewayIntentBits.MessageContent,eX.GatewayIntentBits.DirectMessages],partials:[eX.Partials.Channel]}),this.client.on(eX.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.on(eX.Events.InteractionCreate,(Q)=>{this.handleInteraction(Q)}),this.client.once(eX.Events.ClientReady,()=>{this.logger.info("Discord bot connected",{tag:this.client?.user?.tag})})}createDaemon(){return{start:async()=>{if(!this.client)throw Error("Discord client not initialized");await this.client.login(this.config.botToken)},stop:async()=>{for(let A of this.typingIntervals.values())clearInterval(A);if(this.typingIntervals.clear(),this.client)await this.client.destroy(),this.client=null},healthCheck:async()=>({status:this.client?.user?"healthy":"error",message:this.client?.user?`Connected as ${this.client.user.tag}`:"Not connected",lastCheck:new Date})}}sendMessageToChannel({channelId:A,message:Q}){if(!A||!this.client)return;let w=this.client.channels.cache.get(A);if(!Q50(w))return;let B=AN(Q,li);for(let $ of B)w.send($).catch((Y)=>this.logger.error("Failed to send message",{error:Y}))}async sendMessageWithId({channelId:A,message:Q,approvalCard:w,approvalCards:B}){let $=B??(w?[w]:[]),Y=$.length>0?this.buildApprovalMessagePayload(Q,$):Q;return this.sendPayloadWithId(A,Y)}async sendPayloadWithId(A,Q){if(!A||!this.client)return;let w=this.client.channels.cache.get(A);if(!Q50(w))return;if(typeof Q!=="string")return(await w.send(Q)).id;let B=AN(Q,li),$;for(let Y of B)$=(await w.send(Y)).id;return $}async editMessage({channelId:A,messageId:Q,newMessage:w}){if(!A||!this.client)return!1;let B=this.client.channels.cache.get(A);if(!Q50(B))return!1;try{return await(await B.messages.fetch(Q)).edit(w.slice(0,li)),!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,w=A.channel.isThread();if(Q&&!this.config.allowDMs)return;let B=!!this.client?.user&&A.mentions.has(this.client.user,{ignoreEveryone:!0});if(A.author.bot&&!B)return;let $=w&&"ownerId"in A.channel&&A.channel.ownerId===this.client?.user?.id,Y=this.getSpaceChannelId(A),D=!Q&&this.isConfiguredSpace(Y),X={channelId:Y,isBot:A.author.bot};if(this.config.allowedChannels.length>0&&!Q&&!this.isAllowedChannel(A.channel.id,Y))return;let H=Q||$||!this.config.requireMention||B;if(D&&(!H||this.willRouteUseNonSpaceConversation(A)))await this.capturePassiveSpaceMessage(A,Y).catch((Z)=>this.logger.error("Passive Discord space capture failed",{error:Z,channelId:Y}));if(!H){if(this.config.captureUrls){let Z=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(Z.length>0){await A.react(this.config.captureUrlEmoji).catch((G)=>this.logger.debug("React failed",{error:G}));for(let G of Z)await this.captureUrlViaAgent(G,A.channel.id,A.author.id,"discord",X).catch((F)=>this.logger.error("URL capture failed",{error:F,url:G}))}}return}let W=this.stripMention(A.content);if(A.attachments.size>0){let Z=this.context.permissions.getUserLevel("discord",A.author.id,X);if(Z==="anchor"||Z==="trusted")for(let F of A.attachments.values()){let V=F.name,b=F.contentType??void 0,L=F.size;if(!this.isUploadableTextFile(V,b))continue;if(!this.isFileSizeAllowed(L))continue;try{let N=await this.fetchText(F.url);W+=`
2279
2279
 
2280
2280
  `+this.formatFileUploadMessage(V,N)}catch(N){this.logger.error("Failed to download attachment",{error:N,filename:V})}}}if(W=W.trim(),!W)return;let f=A.channel.id;await this.routeToAgent(W,f,A,X)}async handleInteraction(A){if(!this.context||!A.isButton())return;let Q=this.parseApprovalButtonCustomId(A.customId);if(!Q)return;let w=`discord-${A.channelId}`;if(!this.pendingConfirmations.get(w)?.has(Q.approvalId)){await A.reply({content:"This approval is no longer pending or has changed.",ephemeral:!0}).catch((D)=>this.logger.debug("Failed to reply to stale approval button",{error:D}));return}await A.deferUpdate().catch((D)=>this.logger.debug("Failed to defer approval button",{error:D})),await this.clearApprovalInteractionComponents(A);let $=this.buildInteractionConfirmationContext(A),Y=await this.context.agent.confirmPendingAction(w,Q.confirmed,Q.approvalId,$);await this.handleAgentResponseToolStatuses(Y,w),this.syncPendingApprovalsAfterResolution(w,Q.approvalId,Y),await this.sendApprovalResultMessage({channelId:A.channelId,response:Y,userPermissionLevel:$.userPermissionLevel??"public"})}async clearApprovalInteractionComponents(A){await A.message.edit({components:[]}).catch((Q)=>this.logger.debug("Failed to clear approval buttons",{error:Q}))}buildInteractionConfirmationContext(A){if(!this.context)throw Error("Discord context is not registered");return{userPermissionLevel:this.context.permissions.getUserLevel("discord",A.user.id,{channelId:A.channelId}),interfaceType:"discord",channelId:A.channelId,actor:{actorId:`discord:${A.user.id}`,interfaceType:"discord",role:"user",displayName:A.user.displayName,username:A.user.username,isBot:Boolean(A.user.bot)}}}async capturePassiveSpaceMessage(A,Q){if(!this.context)return;let w=this.stripMention(A.content).trim();if(!w)return;let B=`discord-${Q}`,$=this.getChannelName(A);await this.context.conversations.start({sessionId:B,interfaceType:"discord",channelId:Q,metadata:{channelName:$,interfaceType:"discord",channelId:Q}}),await this.context.conversations.addMessage({conversationId:B,role:"user",content:w,metadata:this.buildUserMessageMetadata(A,Q,$,{threadId:A.channel.isThread()?A.channel.id:void 0})})}async routeToAgent(A,Q,w,B){if(!this.context)return;let $=this.context.agent,Y=Q;if(this.config.useThreads&&w.guild&&!w.channel.isThread())try{Y=(await w.startThread({name:X7(A,lbQ),autoArchiveDuration:this.config.threadAutoArchive})).id}catch(W){this.logger.error("Failed to create thread",{error:W})}let D=`discord-${Y}`,X=this.context.permissions.getUserLevel("discord",w.author.id,B),H=this.getChannelName(w);this.startProcessingInput(Y);try{let W=this.client?.channels.cache.get(Y);if(Q50(W))this.startTypingIndicator(W);if(this.pendingConfirmations.has(D)){await this.handleConfirmationResponse(A,D,Y,w,B);return}let f=await $.chat(A,D,{userPermissionLevel:X,interfaceType:"discord",channelId:Y,channelName:H,...this.buildUserMessageMetadata(w,Q,H,{threadId:Y!==Q||w.channel.isThread()?Y:void 0})});await this.handleAgentResponseToolStatuses(f,D);let Z=this.getPendingApprovalCards(f.cards);if(Z.length>0)this.pendingConfirmations.set(D,new Set(Z.map((F)=>F.id)));else if(f.pendingConfirmations)this.pendingConfirmations.set(D,new Set(f.pendingConfirmations.map((F)=>F.id)));let G=await this.sendMessageWithId({channelId:Y,message:this.formatAgentResponseText(f.text,Z),approvalCards:Z});if(G&&f.toolResults){for(let F of f.toolResults)if(F.jobId)this.trackAgentResponseForJob(F.jobId,G,Y)}}catch(W){this.logger.error("Error handling message",{error:W,channelId:Y}),this.sendMessageToChannel({channelId:Y,message:`**Error:** ${W instanceof Error?W.message:"Unknown error"}`})}finally{this.endProcessingInput(),this.stopTypingIndicator(Y)}}buildApprovalMessagePayload(A,Q){let w=Q.length>1;return{content:X7(A.trim().length>0?`${A}
2281
2281
 
@@ -2343,7 +2343,7 @@ ${A.value}
2343
2343
  `);if(Y50(A))return this.renderList(A,0,(Q)=>this.nodeToDiscordMarkdown(Q));if(A.type==="break")return`
2344
2344
  `;if(A.type==="thematicBreak")return"---";if(KE0(A))return`\`\`\`
2345
2345
  ${UE0(A)}
2346
- \`\`\``;return this.defaultNodeToText(A,(Q)=>this.nodeToDiscordMarkdown(Q))}},cJ1={DeferredChannelMessageWithSource:5,DeferredUpdateMessage:6},z50="https://discord.com/api/v10",lJ1=2000,JOQ=/^[0-9a-f]{64}$/,IOQ=/^[0-9a-f]+$/,bOQ=class A{name="discord";userName;botUserId;apiBaseUrl;botToken;publicKey;applicationId;mentionRoleIds;chat=null;logger;formatConverter=new VOQ;requestContext=new HOQ;threadParentCache=new Map;static THREAD_PARENT_CACHE_TTL=300000;constructor(Q={}){let w=Q.botToken??process.env.DISCORD_BOT_TOKEN;if(!w)throw new nW("discord","botToken is required. Set DISCORD_BOT_TOKEN or provide it in config.");let B=Q.publicKey??process.env.DISCORD_PUBLIC_KEY;if(!B)throw new nW("discord","publicKey is required. Set DISCORD_PUBLIC_KEY or provide it in config.");let $=Q.applicationId??process.env.DISCORD_APPLICATION_ID;if(!$)throw new nW("discord","applicationId is required. Set DISCORD_APPLICATION_ID or provide it in config.");if(this.apiBaseUrl=Q.apiUrl??process.env.DISCORD_API_URL??z50,this.botToken=w,this.publicKey=B.trim().toLowerCase(),this.applicationId=$,this.mentionRoleIds=Q.mentionRoleIds??(process.env.DISCORD_MENTION_ROLE_IDS?process.env.DISCORD_MENTION_ROLE_IDS.split(",").map((Y)=>Y.trim()):[]),this.botUserId=$,this.logger=Q.logger??new K50("info").child("discord"),this.userName=Q.userName??"bot",!JOQ.test(this.publicKey))this.logger.error("Invalid Discord public key format",{length:this.publicKey.length,isHex:IOQ.test(this.publicKey)})}async initialize(Q){this.chat=Q,this.logger.info("Discord adapter initialized")}async getUser(Q){try{let B=await(await this.discordFetch(`/users/${Q}`,"GET")).json();return{avatarUrl:B.avatar?`https://cdn.discordapp.com/avatars/${B.id}/${B.avatar}.png`:void 0,email:void 0,fullName:B.global_name||B.username,isBot:B.bot??!1,userId:B.id,userName:B.username}}catch{return null}}async handleWebhook(Q,w){let B=await Q.arrayBuffer(),$=new Uint8Array(B),Y=new TextDecoder().decode($),D=Q.headers.get("x-discord-gateway-token");if(D){if(D!==this.botToken)return this.logger.warn("Invalid gateway token"),new Response("Invalid gateway token",{status:401});this.logger.info("Discord forwarded Gateway event received");try{let Z=JSON.parse(Y);return this.handleForwardedGatewayEvent(Z,w)}catch{return new Response("Invalid JSON",{status:400})}}this.logger.info("Discord webhook received",{bodyLength:Y.length,bodyBytesLength:$.length,hasSignature:!!Q.headers.get("x-signature-ed25519"),hasTimestamp:!!Q.headers.get("x-signature-timestamp")});let X=Q.headers.get("x-signature-ed25519"),H=Q.headers.get("x-signature-timestamp");if(!await this.verifySignature($,X,H))return this.logger.warn("Discord signature verification failed, returning 401"),new Response("Invalid signature",{status:401});this.logger.info("Discord signature verification passed");let f;try{f=JSON.parse(Y)}catch{return new Response("Invalid JSON",{status:400})}if(this.logger.info("Discord interaction parsed",{type:f.type,typeIsPing:f.type===RC.Ping,expectedPingType:RC.Ping,id:f.id}),f.type===RC.Ping){let Z=JSON.stringify({type:Qd.InteractionResponseType.PONG});return this.logger.info("Discord PING received, responding with PONG",{responseBody:Z,responseType:Qd.InteractionResponseType.PONG}),new Response(Z,{status:200,headers:{"Content-Type":"application/json"}})}if(f.type===RC.MessageComponent)return this.handleComponentInteraction(f,w),this.respondToInteraction({type:cJ1.DeferredUpdateMessage});if(f.type===RC.ApplicationCommand)return this.handleApplicationCommandInteraction(f,w),this.respondToInteraction({type:cJ1.DeferredChannelMessageWithSource});return new Response("Unknown interaction type",{status:400})}async verifySignature(Q,w,B){if(!(w&&B))return this.logger.warn("Discord signature verification failed: missing headers",{hasSignature:!!w,hasTimestamp:!!B}),!1;try{this.logger.info("Discord signature verification attempt",{bodyBytesLength:Q.length,signatureLength:w.length,timestampLength:B.length,publicKeyLength:this.publicKey.length,timestamp:B,signaturePrefix:w.slice(0,16),publicKey:this.publicKey});let $=await Qd.verifyKey(Q,w,B,this.publicKey);if(!$){let Y=new TextDecoder().decode(Q);this.logger.warn("Discord signature verification failed: invalid signature",{publicKeyLength:this.publicKey.length,signatureLength:w.length,publicKeyPrefix:this.publicKey.slice(0,8),publicKeySuffix:this.publicKey.slice(-8),timestamp:B,bodyLength:Q.length,bodyPrefix:Y.slice(0,50)})}return $}catch($){return this.logger.warn("Discord signature verification failed: exception",{error:$}),!1}}respondToInteraction(Q){return Response.json(Q)}handleComponentInteraction(Q,w){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}let B=Q.data?.custom_id;if(!B){this.logger.warn("No custom_id in component interaction");return}let $=Q.member?.user||Q.user;if(!$){this.logger.warn("No user in component interaction");return}let Y=Q.channel_id,D=Q.guild_id||"@me",X=Q.message?.id;if(!(Y&&X)){this.logger.warn("Missing channel_id or message_id in interaction");return}let H=Q.channel,W=H?.type===11||H?.type===12,f=W&&H?.parent_id?H.parent_id:Y,Z=W?this.encodeThreadId({guildId:D,channelId:f,threadId:Y}):this.encodeThreadId({guildId:D,channelId:Y}),G=fOQ(B),F={actionId:G.actionId,value:G.value??G.actionId,user:{userId:$.id,userName:$.username,fullName:$.global_name||$.username,isBot:$.bot??!1,isMe:!1},messageId:X,threadId:Z,adapter:this,raw:Q};this.logger.debug("Processing Discord button action",{actionId:B,messageId:X,threadId:Z}),this.chat.processAction(F,w)}handleApplicationCommandInteraction(Q,w){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}let B=Q.data?.name;if(!B){this.logger.warn("No command name in application command interaction");return}let $=Q.member?.user||Q.user;if(!$){this.logger.warn("No user in application command interaction");return}let Y=Q.channel_id;if(!Y){this.logger.warn("Missing channel_id in application command interaction");return}let D=Q.guild_id||"@me",X=Q.channel,H=X?.type===11||X?.type===12,W=H&&X?.parent_id?X.parent_id:Y,f=H?this.encodeThreadId({guildId:D,channelId:W,threadId:Y}):this.encodeThreadId({guildId:D,channelId:Y}),{command:Z,text:G}=this.parseSlashCommand(B,Q.data?.options);this.logger.debug("Processing Discord slash command",{command:Z,text:G,userId:$.id,channelId:f}),this.requestContext.run({slashCommand:{channelId:f,interactionToken:Q.token,initialResponseSent:!1}},()=>{this.chat?.processSlashCommand({command:Z,text:G,user:{userId:$.id,userName:$.username,fullName:$.global_name||$.username,isBot:$.bot??!1,isMe:$.id===this.applicationId},adapter:this,raw:Q,channelId:f},w)})}parseSlashCommand(Q,w){let B=[Q.startsWith("/")?Q:`/${Q}`],$=[],Y=(D)=>{for(let X of D){if(X.value!==void 0){$.push(String(X.value));continue}if(X.options&&X.options.length>0)B.push(X.name),Y(X.options)}};if(w&&w.length>0)Y(w);return{command:B.join(" "),text:$.join(" ").trim()}}async handleGatewayInteraction(Q){if(Q.isChatInputCommand()){await Q.deferReply(),this.handleApplicationCommandInteraction(this.normalizeGatewaySlashCommandInteraction(Q));return}if(Q.isMessageComponent())await Q.deferUpdate(),this.handleComponentInteraction(this.normalizeGatewayComponentInteraction(Q))}normalizeGatewaySlashCommandInteraction(Q){return{application_id:Q.applicationId,channel:this.normalizeGatewayChannel(Q),channel_id:Q.channelId??void 0,data:{name:Q.commandName,options:this.normalizeGatewayCommandOptions(Q.options.data),type:Q.commandType},guild_id:Q.guildId??void 0,id:Q.id,token:Q.token,type:Q.type,user:this.normalizeGatewayUser(Q.user),version:Q.version}}normalizeGatewayComponentInteraction(Q){let w="values"in Q&&Array.isArray(Q.values)?Q.values:void 0;return{application_id:Q.applicationId,channel:this.normalizeGatewayChannel(Q),channel_id:Q.channelId??void 0,data:{component_type:Q.componentType,custom_id:Q.customId,values:w},guild_id:Q.guildId??void 0,id:Q.id,message:{id:Q.message.id},token:Q.token,type:Q.type,user:this.normalizeGatewayUser(Q.user),version:Q.version}}normalizeGatewayChannel(Q){if(!Q.channel)return;let w="parentId"in Q.channel&&typeof Q.channel.parentId==="string"?Q.channel.parentId:void 0;return{id:Q.channel.id,parent_id:w,type:Q.channel.type}}normalizeGatewayCommandOptions(Q){return Q.map((w)=>({name:w.name,options:w.options?this.normalizeGatewayCommandOptions(w.options):void 0,type:w.type,value:w.value}))}normalizeGatewayUser(Q){return{avatar:Q.avatar??void 0,bot:Q.bot,discriminator:Q.discriminator,global_name:Q.globalName??void 0,id:Q.id,username:Q.username}}async handleForwardedGatewayEvent(Q,w){switch(this.logger.info("Processing forwarded Gateway event",{type:Q.type,timestamp:Q.timestamp}),Q.type){case"GATEWAY_MESSAGE_CREATE":await this.handleForwardedMessage(Q.data,w);break;case"GATEWAY_MESSAGE_REACTION_ADD":await this.handleForwardedReaction(Q.data,!0,w);break;case"GATEWAY_MESSAGE_REACTION_REMOVE":await this.handleForwardedReaction(Q.data,!1,w);break;default:this.logger.debug("Forwarded Gateway event (no handler)",{type:Q.type})}return new Response(JSON.stringify({ok:!0}),{status:200,headers:{"Content-Type":"application/json"}})}async handleForwardedMessage(Q,w){if(!this.chat)return;let B=Q.guild_id||"@me",$=Q.channel_id,Y,D=$;if(Q.thread)Y=Q.thread.id,D=Q.thread.parent_id;else if(Q.channel_type===11||Q.channel_type===12)try{let F=await(await this.discordFetch(`/channels/${$}`,"GET")).json();if(F.parent_id)Y=$,D=F.parent_id,this.logger.debug("Fetched thread parent for forwarded message",{threadId:$,parentId:F.parent_id})}catch(G){this.logger.error("Failed to fetch thread parent",{error:String(G),channelId:$})}let X=Q.is_mention||Q.mentions.some((G)=>G.id===this.applicationId),H=this.mentionRoleIds.length>0&&Q.mention_roles?.some((G)=>this.mentionRoleIds.includes(G)),W=X||H;if(!Y&&W)try{let G=await this.createDiscordThread($,Q.id);Y=G.id,this.logger.debug("Created Discord thread for forwarded mention",{channelId:$,messageId:Q.id,threadId:G.id})}catch(G){this.logger.error("Failed to create Discord thread for mention",{error:String(G),messageId:Q.id})}let f=this.encodeThreadId({guildId:B,channelId:D,threadId:Y}),Z=new x5({id:Q.id,threadId:f,text:Q.content,formatted:this.formatConverter.toAst(Q.content),author:{userId:Q.author.id,userName:Q.author.username,fullName:Q.author.global_name||Q.author.username,isBot:Q.author.bot===!0,isMe:Q.author.id===this.applicationId},metadata:{dateSent:new Date(Q.timestamp),edited:!1},attachments:Q.attachments.map((G)=>({type:this.getAttachmentType(G.content_type),url:G.url,name:G.filename,mimeType:G.content_type,size:G.size})),raw:Q,isMention:W});try{await this.chat.handleIncomingMessage(this,f,Z)}catch(G){this.logger.error("Error handling forwarded message",{error:String(G),messageId:Q.id})}}async handleForwardedReaction(Q,w,B){if(!this.chat)return;let $=Q.guild_id||"@me",Y=Q.channel_id,D,X=Y;if(Q.channel_type===f_.GuildPublicThread||Q.channel_type===f_.GuildPrivateThread){let F=this.threadParentCache.get(Y);if(F&&F.expiresAt>Date.now())D=Y,X=F.parentId;else try{let b=await(await this.discordFetch(`/channels/${Y}`,"GET")).json();if(b.parent_id)D=Y,X=b.parent_id,this.threadParentCache.set(Y,{parentId:b.parent_id,expiresAt:Date.now()+A.THREAD_PARENT_CACHE_TTL})}catch(V){this.logger.error("Failed to fetch thread parent for reaction",{error:String(V),channelId:Y})}}let H=this.encodeThreadId({guildId:$,channelId:X,threadId:D}),W=Q.emoji.name||"unknown",f=this.normalizeDiscordEmoji(W),Z=Q.user??Q.member?.user;if(!Z){this.logger.warn("Reaction event missing user info",{data:Q});return}let G={adapter:this,threadId:H,messageId:Q.message_id,emoji:f,rawEmoji:Q.emoji.id?`<:${W}:${Q.emoji.id}>`:W,added:w,user:{userId:Z.id,userName:Z.username,fullName:Z.username,isBot:Z.bot===!0,isMe:Z.id===this.applicationId},raw:Q};this.chat.processReaction(G)}async postMessage(Q,w){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=Q;if($)B=$;let D={},X=[],H=[],W=G50(w);if(W){let V=sE0(W);X.push(...V.embeds),H.push(...V.components)}else D.content=this.truncateContent(D_(this.formatConverter.renderPostable(w),"discord"));if(X.length>0)D.embeds=X;if(H.length>0)D.components=H;let f=OE0(w),Z=this.tryPostSlashResponse(Y,D,f);if(Z)return Z;if(f.length>0)return this.postMessageWithFiles(B,Y,D,f);this.logger.debug("Discord API: POST message",{channelId:B,contentLength:D.content?.length||0,embedCount:X.length,componentCount:H.length});let F=await(await this.discordFetch(`/channels/${B}/messages`,"POST",D)).json();return this.logger.debug("Discord API: POST message response",{messageId:F.id}),{id:F.id,threadId:Y,raw:F}}tryPostSlashResponse(Q,w,B){let $=this.requestContext.getStore()?.slashCommand;if(!$||$.channelId!==Q)return;return this.postSlashCommandResponse($,Q,w,B)}async postSlashCommandResponse(Q,w,B,$){let Y=!Q.initialResponseSent;Q.initialResponseSent=!0;let D=Y?`/webhooks/${this.applicationId}/${Q.interactionToken}/messages/@original`:`/webhooks/${this.applicationId}/${Q.interactionToken}?wait=true`,X=Y?"PATCH":"POST";this.logger.debug("Discord interaction webhook: responding to slash command",{threadId:w,isInitialResponse:Y,hasFiles:$.length>0});let W=await($.length>0?await this.discordInteractionFetchWithFiles(D,X,B,$):await this.discordInteractionFetch(D,X,B)).json();return{id:W.id,threadId:w,raw:W}}async createDiscordThread(Q,w){let B=`Thread ${new Date().toLocaleString()}`;this.logger.debug("Discord API: POST thread",{channelId:Q,messageId:w,threadName:B});try{let Y=await(await this.discordFetch(`/channels/${Q}/messages/${w}/threads`,"POST",{name:B,auto_archive_duration:1440})).json();return this.logger.debug("Discord API: POST thread response",{threadId:Y.id,threadName:Y.name}),Y}catch($){if($ instanceof kC&&typeof $.message==="string"&&$.message.includes('"code"')&&$.message.includes("160004"))return this.logger.debug("Thread already exists for message, reusing existing thread",{channelId:Q,messageId:w}),{id:w,name:B};throw $}}truncateContent(Q){if(Q.length<=lJ1)return Q;return`${Q.slice(0,lJ1-3)}...`}async postMessageWithFiles(Q,w,B,$){let Y=new FormData;Y.append("payload_json",JSON.stringify(B));for(let H=0;H<$.length;H++){let W=$[H];if(!W)continue;let f=await xE0(W.data,{platform:"discord"});if(!f)continue;let Z=new Blob([new Uint8Array(f)],{type:W.mimeType||"application/octet-stream"});Y.append(`files[${H}]`,Z,W.filename)}let D=await fetch(`${z50}/channels/${Q}/messages`,{method:"POST",headers:{Authorization:`Bot ${this.botToken}`},body:Y});if(!D.ok){let H=await D.text();throw new kC("discord",`Failed to post message: ${D.status} ${H}`)}let X=await D.json();return{id:X.id,threadId:w,raw:X}}async discordInteractionFetch(Q,w,B){let $=await fetch(`${z50}${Q}`,{method:w,headers:B?{"Content-Type":"application/json"}:void 0,body:B?JSON.stringify(B):void 0});if(!$.ok){let Y=await $.text();throw this.logger.error("Discord interaction API error",{path:Q,method:w,status:$.status,error:Y}),new kC("discord",`Discord interaction API error: ${$.status} ${Y}`)}return $}async discordInteractionFetchWithFiles(Q,w,B,$){let Y=new FormData;Y.append("payload_json",JSON.stringify(B));for(let X=0;X<$.length;X++){let H=$[X];if(!H)continue;let W=await xE0(H.data,{platform:"discord"});if(!W)continue;let f=new Blob([new Uint8Array(W)],{type:H.mimeType||"application/octet-stream"});Y.append(`files[${X}]`,f,H.filename)}let D=await fetch(`${z50}${Q}`,{method:w,body:Y});if(!D.ok){let X=await D.text();throw this.logger.error("Discord interaction API error",{path:Q,method:w,status:D.status,error:X}),new kC("discord",`Discord interaction API error: ${D.status} ${X}`)}return D}async editMessage(Q,w,B){let{channelId:$,threadId:Y}=this.decodeThreadId(Q),D=Y||$,X={},H=[],W=[],f=G50(B);if(f){let F=sE0(f);H.push(...F.embeds),W.push(...F.components),X.content=""}else X.content=this.truncateContent(D_(this.formatConverter.renderPostable(B),"discord"));if(H.length>0)X.embeds=H;if(W.length>0)X.components=W;this.logger.debug("Discord API: PATCH message",{channelId:D,messageId:w,contentLength:X.content?.length||0});let G=await(await this.discordFetch(`/channels/${D}/messages/${w}`,"PATCH",X)).json();return this.logger.debug("Discord API: PATCH message response",{messageId:G.id}),{id:G.id,threadId:Q,raw:G}}async deleteMessage(Q,w){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=$||B;this.logger.debug("Discord API: DELETE message",{channelId:Y,messageId:w}),await this.discordFetch(`/channels/${Y}/messages/${w}`,"DELETE"),this.logger.debug("Discord API: DELETE message response",{ok:!0})}async addReaction(Q,w,B){let{channelId:$,threadId:Y}=this.decodeThreadId(Q),D=Y||$,X=this.encodeEmoji(B);this.logger.debug("Discord API: PUT reaction",{channelId:D,messageId:w,emoji:X}),await this.discordFetch(`/channels/${D}/messages/${w}/reactions/${X}/@me`,"PUT"),this.logger.debug("Discord API: PUT reaction response",{ok:!0})}async removeReaction(Q,w,B){let{channelId:$,threadId:Y}=this.decodeThreadId(Q),D=Y||$,X=this.encodeEmoji(B);this.logger.debug("Discord API: DELETE reaction",{channelId:D,messageId:w,emoji:X}),await this.discordFetch(`/channels/${D}/messages/${w}/reactions/${X}/@me`,"DELETE"),this.logger.debug("Discord API: DELETE reaction response",{ok:!0})}encodeEmoji(Q){let w=si.toDiscord?si.toDiscord(Q):String(Q);return encodeURIComponent(w)}async startTyping(Q,w){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=$||B;this.logger.debug("Discord API: POST typing",{channelId:Y}),await this.discordFetch(`/channels/${Y}/typing`,"POST")}async fetchMessages(Q,w={}){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=$||B,D=w.limit||50,X=w.direction??"backward",H=new URLSearchParams;if(H.set("limit",String(D)),w.cursor)if(X==="backward")H.set("before",w.cursor);else H.set("after",w.cursor);this.logger.debug("Discord API: GET messages",{channelId:Y,limit:D,direction:X,cursor:w.cursor});let f=await(await this.discordFetch(`/channels/${Y}/messages?${H.toString()}`,"GET")).json();this.logger.debug("Discord API: GET messages response",{messageCount:f.length});let G=[...f].reverse().map((V)=>this.parseDiscordMessage(V,Q)),F;if(f.length===D)if(X==="backward")F=f.at(-1)?.id;else F=f[0]?.id;return{messages:G,nextCursor:F}}async fetchThread(Q){let{channelId:w,guildId:B}=this.decodeThreadId(Q);this.logger.debug("Discord API: GET channel",{channelId:w});let Y=await(await this.discordFetch(`/channels/${w}`,"GET")).json();return{id:Q,channelId:w,channelName:Y.name,isDM:Y.type===f_.DM||Y.type===f_.GroupDM,metadata:{guildId:B,channelType:Y.type,raw:Y}}}async openDM(Q){this.logger.debug("Discord API: POST DM channel",{userId:Q});let B=await(await this.discordFetch("/users/@me/channels","POST",{recipient_id:Q})).json();return this.logger.debug("Discord API: POST DM channel response",{channelId:B.id}),this.encodeThreadId({guildId:"@me",channelId:B.id})}isDM(Q){let{guildId:w}=this.decodeThreadId(Q);return w==="@me"}encodeThreadId(Q){let w=Q.threadId?`:${Q.threadId}`:"";return`discord:${Q.guildId}:${Q.channelId}${w}`}decodeThreadId(Q){let w=Q.split(":");if(w.length<3||w[0]!=="discord")throw new nW("discord",`Invalid Discord thread ID: ${Q}`);return{guildId:w[1],channelId:w[2],threadId:w[3]}}parseMessage(Q){let w=Q,B=w.guild_id||"@me",$=this.encodeThreadId({guildId:B,channelId:w.channel_id});return this.parseDiscordMessage(w,$)}parseDiscordMessage(Q,w){let B=Q.type===mz1.ThreadStarterMessage&&Q.referenced_message?Q.referenced_message:Q,$=B.author,Y=$.bot??!1,D=$.id===this.botUserId;return new x5({id:B.id,threadId:w,text:this.formatConverter.extractPlainText(B.content),formatted:this.formatConverter.toAst(B.content),raw:Q,author:{userId:$.id,userName:$.username,fullName:$.global_name||$.username,isBot:Y,isMe:D},metadata:{dateSent:new Date(B.timestamp),edited:B.edited_timestamp!==null,editedAt:B.edited_timestamp?new Date(B.edited_timestamp):void 0},attachments:(B.attachments||[]).map((X)=>({type:this.getAttachmentType(X.content_type),url:X.url,name:X.filename,mimeType:X.content_type,size:X.size,width:X.width??void 0,height:X.height??void 0}))})}getAttachmentType(Q){if(!Q)return"file";if(Q.startsWith("image/"))return"image";if(Q.startsWith("video/"))return"video";if(Q.startsWith("audio/"))return"audio";return"file"}renderFormatted(Q){return this.formatConverter.fromAst(Q)}async discordFetch(Q,w,B){let $=`${this.apiBaseUrl}${Q}`,Y={Authorization:`Bot ${this.botToken}`};if(B)Y["Content-Type"]="application/json";let D=await fetch($,{method:w,headers:Y,body:B?JSON.stringify(B):void 0});if(!D.ok){let X=await D.text();throw this.logger.error("Discord API error",{path:Q,method:w,status:D.status,error:X}),new kC("discord",`Discord API error: ${D.status} ${X}`)}return D}async startGatewayListener(Q,w=180000,B,$){if(!this.chat)return new Response("Chat instance not initialized",{status:500});if(!Q.waitUntil)return new Response("waitUntil not provided",{status:500});this.logger.info("Starting Discord Gateway listener",{durationMs:w,webhookUrl:$?"configured":"not configured"});let Y=this.runGatewayListener(w,B,$);return Q.waitUntil(Y),new Response(JSON.stringify({status:"listening",durationMs:w,message:`Gateway listener started, will run for ${w/1000} seconds`}),{status:200,headers:{"Content-Type":"application/json"}})}async runGatewayListener(Q,w,B){let $=new S9.Client({intents:[S9.GatewayIntentBits.Guilds,S9.GatewayIntentBits.GuildMessages,S9.GatewayIntentBits.MessageContent,S9.GatewayIntentBits.DirectMessages,S9.GatewayIntentBits.GuildMessageReactions,S9.GatewayIntentBits.DirectMessageReactions],partials:[S9.Partials.Channel]}),Y=!1;if(B)$.on("raw",async(D)=>{if(Y)return;if(!D.t)return;this.logger.info("Discord Gateway forwarding event",{type:D.t}),await this.forwardGatewayEvent(B,{type:`GATEWAY_${D.t}`,timestamp:Date.now(),data:D.d})});else this.setupLegacyGatewayHandlers($,()=>Y);$.on(S9.Events.ClientReady,()=>{this.logger.info("Discord Gateway connected",{username:$.user?.username,id:$.user?.id})}),$.on(S9.Events.Error,(D)=>{this.logger.error("Discord Gateway error",{error:String(D)})});try{await $.login(this.botToken),await new Promise((D)=>{let X=setTimeout(D,Q);if(w){if(w.aborted){clearTimeout(X),D();return}w.addEventListener("abort",()=>{this.logger.info("Discord Gateway listener received abort signal (new listener started)"),clearTimeout(X),D()},{once:!0})}}),this.logger.info("Discord Gateway listener duration elapsed, disconnecting")}catch(D){this.logger.error("Discord Gateway listener error",{error:String(D)})}finally{Y=!0,$.destroy(),this.logger.info("Discord Gateway listener stopped")}}setupLegacyGatewayHandlers(Q,w){Q.on(S9.Events.MessageCreate,async(B)=>{if(w()){this.logger.debug("Ignoring message - Gateway is shutting down");return}if(B.author.bot){this.logger.debug("Ignoring message from bot",{authorId:B.author.id,authorName:B.author.username,isMe:B.author.id===Q.user?.id});return}let $=B.mentions.has(Q.user?.id??""),Y=this.mentionRoleIds.length>0&&B.mentions.roles.some((X)=>this.mentionRoleIds.includes(X.id)),D=$||Y;this.logger.info("Discord Gateway message received",{channelId:B.channelId,guildId:B.guildId,authorId:B.author.id,isMentioned:D,isUserMentioned:$,isRoleMentioned:Y,content:B.content.slice(0,100)}),await this.handleGatewayMessage(B,D)}),Q.on(S9.Events.InteractionCreate,async(B)=>{if(w()){this.logger.debug("Ignoring interaction - Gateway is shutting down");return}this.logger.info("Discord Gateway interaction received",{id:B.id,type:B.type});try{await this.handleGatewayInteraction(B)}catch($){this.logger.error("Error handling Gateway interaction",{error:String($),interactionId:B.id})}}),Q.on(S9.Events.MessageReactionAdd,async(B,$)=>{if(w()){this.logger.debug("Ignoring reaction - Gateway is shutting down");return}if($.bot){this.logger.debug("Ignoring reaction from bot",{userId:$.id,isMe:$.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction added",{emoji:B.emoji.name,messageId:B.message.id,channelId:B.message.channelId,userId:$.id}),$.username)await this.handleGatewayReaction(B,$,!0)}),Q.on(S9.Events.MessageReactionRemove,async(B,$)=>{if(w()){this.logger.debug("Ignoring reaction removal - Gateway is shutting down");return}if($.bot){this.logger.debug("Ignoring reaction removal from bot",{userId:$.id,isMe:$.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction removed",{emoji:B.emoji.name,messageId:B.message.id,channelId:B.message.channelId,userId:$.id}),$.username)await this.handleGatewayReaction(B,$,!1)})}async forwardGatewayEvent(Q,w){try{this.logger.debug("Forwarding Gateway event to webhook",{type:w.type,webhookUrl:Q});let B=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/json","x-discord-gateway-token":this.botToken},body:JSON.stringify(w)});if(B.ok)this.logger.debug("Gateway event forwarded successfully",{type:w.type});else{let $=await B.text();this.logger.error("Failed to forward Gateway event",{type:w.type,status:B.status,error:$})}}catch(B){this.logger.error("Error forwarding Gateway event",{type:w.type,error:String(B)})}}async handleGatewayMessage(Q,w){if(!this.chat)return;let B=Q.guildId||"@me",$=Q.channelId,Y=Q.channel.isThread(),D,X=$;if(Y&&"parentId"in Q.channel&&Q.channel.parentId)D=$,X=Q.channel.parentId;if(!D&&w)try{let f=await this.createDiscordThread($,Q.id);D=f.id,this.logger.debug("Created Discord thread for incoming mention",{channelId:$,messageId:Q.id,threadId:f.id})}catch(f){this.logger.error("Failed to create Discord thread for mention",{error:String(f),messageId:Q.id})}let H=this.encodeThreadId({guildId:B,channelId:X,threadId:D}),W=new x5({id:Q.id,threadId:H,text:Q.content,formatted:this.formatConverter.toAst(Q.content),author:{userId:Q.author.id,userName:Q.author.username,fullName:Q.author.displayName||Q.author.username,isBot:Q.author.bot,isMe:!1},metadata:{dateSent:Q.createdAt,edited:Q.editedAt!==null,editedAt:Q.editedAt??void 0},attachments:Q.attachments.map((f)=>({type:this.getAttachmentType(f.contentType),url:f.url,name:f.name,mimeType:f.contentType??void 0,size:f.size})),raw:{id:Q.id,channel_id:$,guild_id:B,content:Q.content,author:{id:Q.author.id,username:Q.author.username},timestamp:Q.createdAt.toISOString()},isMention:w});try{await this.chat.handleIncomingMessage(this,H,W)}catch(f){this.logger.error("Error handling Gateway message",{error:String(f),messageId:Q.id})}}async handleGatewayReaction(Q,w,B){if(!this.chat)return;let $=Q.message.guildId||"@me",Y=Q.message.channelId,D=Q.message.channel?.isThread?.(),X=Y,H;if(D&&Q.message.channel?.parentId)H=Y,X=Q.message.channel.parentId;let W=this.encodeThreadId({guildId:$,channelId:X,threadId:H}),f=Q.emoji.name||"unknown",Z=this.normalizeDiscordEmoji(f),G={adapter:this,threadId:W,messageId:Q.message.id,emoji:Z,rawEmoji:Q.emoji.id?`<:${f}:${Q.emoji.id}>`:f,added:B,user:{userId:w.id,userName:w.username,fullName:w.username,isBot:w.bot===!0,isMe:w.id===this.applicationId},raw:{emoji:Q.emoji,message_id:Q.message.id,channel_id:Q.message.channelId,guild_id:Q.message.guildId,user_id:w.id}};this.chat.processReaction(G)}channelIdFromThreadId(Q){return Q.split(":").slice(0,3).join(":")}async fetchChannelMessages(Q,w={}){let $=Q.split(":")[2];if(!$)throw new nW("discord",`Invalid Discord channel ID: ${Q}`);let Y=w.limit||50,D=w.direction??"backward",X=new URLSearchParams;if(X.set("limit",String(Y)),w.cursor)if(D==="backward")X.set("before",w.cursor);else X.set("after",w.cursor);this.logger.debug("Discord API: GET channel messages",{channelId:$,limit:Y,direction:D,cursor:w.cursor});let W=await(await this.discordFetch(`/channels/${$}/messages?${X.toString()}`,"GET")).json();this.logger.debug("Discord API: GET channel messages response",{messageCount:W.length});let Z=[...W].reverse().map((F)=>this.parseDiscordMessage(F,Q)),G;if(W.length===Y)if(D==="backward")G=W.at(-1)?.id;else G=W[0]?.id;return{messages:Z,nextCursor:G}}async listThreads(Q,w={}){let B=Q.split(":"),$=B[1],Y=B[2];if(!($&&Y))throw new nW("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET threads",{guildId:$,channelId:Y});let H=((await(await this.discordFetch(`/guilds/${$}/threads/active`,"GET")).json()).threads||[]).filter((L)=>L.parent_id===Y),W=[];try{W=(await(await this.discordFetch(`/channels/${Y}/threads/archived/public?limit=${w.limit||50}`,"GET")).json()).threads||[]}catch{this.logger.debug("Could not fetch archived threads (may lack permissions)")}let f=[...H,...W],Z=new Set,G=f.filter((L)=>{if(Z.has(L.id))return!1;return Z.add(L.id),!0}),F=w.limit||50,V=G.slice(0,F),b=[];for(let L of V){let N=this.encodeThreadId({guildId:$,channelId:Y,threadId:L.id});try{let g=(await(await this.discordFetch(`/channels/${L.id}/messages?limit=1&after=0`,"GET")).json())[0];if(g)b.push({id:N,rootMessage:this.parseDiscordMessage(g,N),replyCount:L.total_message_sent??L.message_count,lastReplyAt:L.thread_metadata?.archive_timestamp?new Date(L.thread_metadata.archive_timestamp):void 0})}catch{b.push({id:N,rootMessage:new x5({id:L.id,threadId:N,text:L.name,formatted:this.formatConverter.toAst(L.name),raw:L,author:{userId:"unknown",userName:"unknown",fullName:"unknown",isBot:!1,isMe:!1},metadata:{dateSent:new Date,edited:!1},attachments:[]}),replyCount:L.total_message_sent??L.message_count})}}return this.logger.debug("Discord API: listThreads result",{threadCount:b.length}),{threads:b,nextCursor:G.length>F?String(F):void 0}}async fetchChannelInfo(Q){let B=Q.split(":")[2];if(!B)throw new nW("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET channel info",{channelId:B});let Y=await(await this.discordFetch(`/channels/${B}`,"GET")).json();return{id:Q,name:Y.name,isDM:Y.type===f_.DM||Y.type===f_.GroupDM,memberCount:Y.member_count,metadata:{channelType:Y.type,raw:Y}}}async postChannelMessage(Q,w){let $=Q.split(":")[2];if(!$)throw new nW("discord",`Invalid Discord channel ID: ${Q}`);let Y={},D=[],X=[],H=G50(w);if(H){let F=sE0(H);D.push(...F.embeds),X.push(...F.components)}else Y.content=this.truncateContent(D_(this.formatConverter.renderPostable(w),"discord"));if(D.length>0)Y.embeds=D;if(X.length>0)Y.components=X;let W=OE0(w),f=this.tryPostSlashResponse(Q,Y,W);if(f)return f;if(W.length>0)return this.postMessageWithFiles($,Q,Y,W);this.logger.debug("Discord API: POST channel message",{channelId:$,contentLength:Y.content?.length||0});let G=await(await this.discordFetch(`/channels/${$}/messages`,"POST",Y)).json();return{id:G.id,threadId:Q,raw:G}}normalizeDiscordEmoji(Q){let B={"\uD83D\uDC4D":"thumbs_up","\uD83D\uDC4E":"thumbs_down","\u2764\uFE0F":"heart","\u2764":"heart","\uD83D\uDD25":"fire","\uD83D\uDE80":"rocket","\uD83D\uDE4C":"raised_hands","\u2705":"check","\u274C":"x","\uD83D\uDC4B":"wave","\uD83E\uDD14":"thinking","\uD83D\uDE0A":"smile","\uD83D\uDE02":"laugh","\uD83C\uDF89":"party","\u2B50":"star","\u2728":"sparkles","\uD83D\uDC40":"eyes","\uD83D\uDCAF":"100"}[Q]||Q;return pI(B)}};function dJ1(A){return new bOQ(A??{})}var LOQ=class{subscriptions=new Set;locks=new Map;cache=new Map;queues=new Map;connected=!1;connectPromise=null;async connect(){if(this.connected)return;if(!this.connectPromise)this.connectPromise=Promise.resolve().then(()=>{this.connected=!0});await this.connectPromise}async disconnect(){this.connected=!1,this.connectPromise=null,this.subscriptions.clear(),this.locks.clear(),this.queues.clear()}async subscribe(A){this.ensureConnected(),this.subscriptions.add(A)}async unsubscribe(A){this.ensureConnected(),this.subscriptions.delete(A)}async isSubscribed(A){return this.ensureConnected(),this.subscriptions.has(A)}async acquireLock(A,Q){this.ensureConnected(),this.cleanExpiredLocks();let w=this.locks.get(A);if(w&&w.expiresAt>Date.now())return null;let B={threadId:A,token:NOQ(),expiresAt:Date.now()+Q};return this.locks.set(A,B),B}async forceReleaseLock(A){this.ensureConnected(),this.locks.delete(A)}async releaseLock(A){this.ensureConnected();let Q=this.locks.get(A.threadId);if(Q&&Q.token===A.token)this.locks.delete(A.threadId)}async extendLock(A,Q){this.ensureConnected();let w=this.locks.get(A.threadId);if(!w||w.token!==A.token)return!1;if(w.expiresAt<Date.now())return this.locks.delete(A.threadId),!1;return w.expiresAt=Date.now()+Q,!0}async get(A){this.ensureConnected();let Q=this.cache.get(A);if(!Q)return null;if(Q.expiresAt!==null&&Q.expiresAt<=Date.now())return this.cache.delete(A),null;return Q.value}async set(A,Q,w){this.ensureConnected(),this.cache.set(A,{value:Q,expiresAt:w?Date.now()+w:null})}async setIfNotExists(A,Q,w){this.ensureConnected();let B=this.cache.get(A);if(B)if(B.expiresAt!==null&&B.expiresAt<=Date.now())this.cache.delete(A);else return!1;return this.cache.set(A,{value:Q,expiresAt:w?Date.now()+w:null}),!0}async delete(A){this.ensureConnected(),this.cache.delete(A)}async appendToList(A,Q,w){this.ensureConnected();let B=this.cache.get(A),$;if(B&&B.expiresAt!==null&&B.expiresAt<=Date.now())$=[];else if(B&&Array.isArray(B.value))$=B.value;else $=[];if($.push(Q),w?.maxLength&&$.length>w.maxLength)$=$.slice($.length-w.maxLength);this.cache.set(A,{value:$,expiresAt:w?.ttlMs?Date.now()+w.ttlMs:null})}async enqueue(A,Q,w){this.ensureConnected();let B=this.queues.get(A);if(!B)B=[],this.queues.set(A,B);if(B.push(Q),B.length>w)B.splice(0,B.length-w);return B.length}async dequeue(A){this.ensureConnected();let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let w=Q.shift();if(Q.length===0)this.queues.delete(A);return w??null}async queueDepth(A){return this.ensureConnected(),this.queues.get(A)?.length??0}async getList(A){this.ensureConnected();let Q=this.cache.get(A);if(!Q)return[];if(Q.expiresAt!==null&&Q.expiresAt<=Date.now())return this.cache.delete(A),[];if(Array.isArray(Q.value))return Q.value;return[]}ensureConnected(){if(!this.connected)throw Error("MemoryStateAdapter is not connected. Call connect() first.")}cleanExpiredLocks(){let A=Date.now();for(let[Q,w]of this.locks)if(w.expiresAt<=A)this.locks.delete(Q)}_getSubscriptionCount(){return this.subscriptions.size}_getLockCount(){return this.cleanExpiredLocks(),this.locks.size}};function NOQ(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function q50(A){return new LOQ}Z0();var jOQ=K.object({subscribedAt:K.string().datetime(),routingMode:K.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:K.boolean().optional()}),MOQ="chat.discord.subscriptions";function aE0(A){return A.scoped({namespace:MOQ,schema:jOQ})}function nJ1(A,Q=q50()){let w=aE0(A);return new rJ1(Q,w)}class rJ1{memoryState;subscriptions;constructor(A,Q){this.memoryState=A;this.subscriptions=Q}connect(){return this.memoryState.connect()}disconnect(){return this.memoryState.disconnect()}async subscribe(A){await this.subscriptions.set(A,{subscribedAt:new Date().toISOString()})}async unsubscribe(A){await this.subscriptions.delete(A)}isSubscribed(A){return this.subscriptions.has(A)}acquireLock(A,Q){return this.memoryState.acquireLock(A,Q)}appendToList(A,Q,w){return this.memoryState.appendToList(A,Q,w)}delete(A){return this.memoryState.delete(A)}dequeue(A){return this.memoryState.dequeue(A)}enqueue(A,Q,w){return this.memoryState.enqueue(A,Q,w)}extendLock(A,Q){return this.memoryState.extendLock(A,Q)}forceReleaseLock(A){return this.memoryState.forceReleaseLock(A)}get(A){return this.memoryState.get(A)}getList(A){return this.memoryState.getList(A)}queueDepth(A){return this.memoryState.queueDepth(A)}releaseLock(A){return this.memoryState.releaseLock(A)}set(A,Q,w){return this.memoryState.set(A,Q,w)}setIfNotExists(A,Q,w){return this.memoryState.setIfNotExists(A,Q,w)}}function oJ1(A){let{discord:Q}=A;if(!Q)return new PE0({userName:A.userName,adapters:{},state:q50()});let w=dJ1({botToken:Q.botToken,publicKey:Q.publicKey,applicationId:Q.applicationId,mentionRoleIds:Q.mentionRoleIds});return A.gatewayLoop.setAdapter(w),new PE0({userName:A.userName,adapters:{discord:w},concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"},state:nJ1(A.runtimeState)})}class tE0{deps;constructor(A){this.deps=A}async subscribeOwnedThread(A,Q){if(!this.deps.isBotCreatedThread(A,Q))return;try{await A.subscribe(),await this.deps.getSubscriptions()?.set(A.id,{subscribedAt:new Date().toISOString()})}catch(w){this.deps.logger.debug("Discord thread subscription failed",{error:w,threadId:A.id})}}async shouldRouteSubscribedMessage(A,Q){if(this.deps.getPlatform(A)!=="discord")return!1;if(A.isDM)return!0;let w=await this.deps.getSubscriptions()?.get(A.id);if(!w)return!1;if(w.routingMode==="mention-required"){if(!Q.isMention&&!w.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,w);return Boolean(Q.isMention)}if(!await this.shouldRequireMentionInSubscribedThread(A))return!0;let $={...w,routingMode:"mention-required"};if(!Q.isMention&&!w.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,$);else await this.deps.getSubscriptions()?.set(A.id,$);return Boolean(Q.isMention)}async postMentionRequiredNotice(A,Q){await A.post("I\u2019ll stop auto-replying now that more people joined. Mention me if you need me."),await this.deps.getSubscriptions()?.set(A.id,{...Q,routingMode:"mention-required",mentionRequiredNoticeSent:!0})}async shouldRequireMentionInSubscribedThread(A){try{return(await A.getParticipants()).filter((B)=>!B.isBot&&!B.isMe).length>1}catch(Q){return this.deps.logger.debug("Failed to inspect Discord thread participants",{error:Q,threadId:A.id}),!1}}}c0();class eE0{deps;constructor(A){this.deps=A}async build(A,Q,w,B){let $={message:w.text.trim(),attachments:[],notices:[]};if(w.attachments.length===0)return $;if(!(B==="anchor"||B==="trusted"))return $;let D=this.deps.getUploadStore();if(!D)return $;for(let X of w.attachments){let H=X.name;if(!H)continue;let W=Gq(H,"upload"),f=sV(W,X.mimeType),Z=X.size??0,G=f00(W,f);if(!G){$.notices.push(`Unsupported file upload type: ${W}`);continue}if(!Z00(G,Z)){$.notices.push(`File upload too large: ${W}`);continue}try{let F=await this.readAttachmentData(X);if(!F)continue;let V=zq({filename:W,mediaType:f,content:F,fallbackFilename:"upload"});if(!V.ok){$.notices.push(V.message);continue}let b=await D.save({filename:V.filename,mediaType:V.mediaType,content:F,metadata:this.buildMetadata(A,Q,w)});$.attachments.push(aJ1(b.filename,b.mediaType,F,b.ref,V.kind==="text"))}catch(F){this.deps.logger.error("Failed to read chat attachment",{error:F,filename:W}),$.notices.push(`Could not read file upload: ${W}`)}}return $}async readAttachmentData(A){if(A.fetchData)return A.fetchData();if(!A.url)return;let Q=await fetch(A.url);if(!Q.ok)throw Error(`Attachment download failed with status ${Q.status}`);let w=await Q.arrayBuffer();return Buffer.from(new Uint8Array(w))}buildMetadata(A,Q,w){let B=this.deps.getThreadIdParts(Q.id);return{interfaceType:A,channelId:Q.id,parentChannelId:Q.channelId,messageId:w.id,uploaderId:w.author.userId,uploaderUsername:w.author.userName,...B.guildId?{guildId:B.guildId}:{},...B.threadId?{threadId:B.threadId}:{}}}}function sJ1(A,Q,w,B){return aJ1(A,Q,w,B,aV(A,Q))}function aJ1(A,Q,w,B,$){if($)return{kind:"text",filename:A,mediaType:Q,content:w.toString("utf8").replace(/^\uFEFF/,""),sizeBytes:w.byteLength,source:B};return{kind:"file",filename:A,mediaType:Q,data:w,sizeBytes:w.byteLength,source:B}}function wd(){return{namespace:"discord-chat",refKind:"discord-chat-upload",routePath:"/api/webhooks/chat/discord/uploads"}}var tJ1={name:"@brains/chat",private:!0,version:"0.2.0-alpha.135",description:"Discord Chat SDK 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:*","@chat-adapter/discord":"^4.29.0","@chat-adapter/state-memory":"^4.29.0",chat:"^4.29.0"},devDependencies:{"@brains/core":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest"}};var POQ=/https?:\/\/\S+/i,kOQ=/[\s\S]+/,OOQ="https://discord.com/api/v10",xOQ=K.object({type:K.literal("card"),children:K.array(K.object({type:K.string()}).passthrough()),imageUrl:K.string().optional(),subtitle:K.string().optional(),title:K.string().optional()}).passthrough(),ROQ=K.object({card:K.custom((A)=>xOQ.safeParse(A).success),fallbackText:K.string().optional()});class F50 extends AZ{threadRegistry=new w50;pendingApprovals;uploadContinuity;promptActions=new Map;toolStatusMessenger=new $y0(this.threadRegistry);cardBuilder=new Hy0({getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),registerPromptAction:(A,Q)=>this.registerPromptAction(A,Q)});artifactDelivery=new fy0({getContext:()=>this.context,getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),logger:this.logger});approvalCards=new Zy0({cardBuilder:this.cardBuilder,clearMessageComponents:(A,Q)=>this.clearDiscordMessageComponents(A,Q)});subscriptionRouter=new tE0({getSubscriptions:()=>this.discordSubscriptions,getPlatform:(A)=>this.getPlatform(A),isBotCreatedThread:(A,Q)=>this.isBotCreatedDiscordThread(A,Q),logger:this.logger});chatInputBuilder=new eE0({getUploadStore:()=>this.context?.uploads.scoped(wd()),getThreadIdParts:(A)=>this.getThreadIdParts(A),logger:this.logger});gatewayLoop;discordApp;discordSubscriptions;constructor(A={}){super("chat",tJ1,A,By0);this.gatewayLoop=new Ky0({getApp:()=>this.discordApp.instance,gatewayRunMs:this.config.gatewayRunMs,gatewayRestartDelayMs:this.config.gatewayRestartDelayMs,logger:this.logger}),this.discordApp=new Uy0({discord:this.config.adapters.discord,getUploadStore:()=>this.context?.uploads.scoped(wd()),buildApp:(Q)=>oJ1({userName:this.config.userName,discord:this.config.adapters.discord,gatewayLoop:this.gatewayLoop,runtimeState:Q})}),this.pendingApprovals=new xS({loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},onRestoreError:(Q,w)=>{this.logger.debug("Failed to load pending chat approvals",{error:Q,conversationId:w})}}),this.uploadContinuity=new ES({sourceKind:"discord-chat-upload",loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},restoreAttachment:async(Q)=>{let w=this.context?.uploads.scoped(wd());if(!w)throw Error("Chat upload store unavailable");let B=await w.read(Q);return sJ1(B.record.filename,B.record.mediaType,B.content,B.record.ref)},onLoadError:(Q,w)=>{this.logger.debug("Failed to load prior chat uploads",{error:Q,conversationId:w})},onRestoreError:(Q,w)=>{this.logger.debug("Failed to restore prior chat upload",{error:Q,uploadId:w})}})}async onRegister(A){await super.onRegister(A),this.discordSubscriptions=aE0(A.runtimeState),this.registerChatHandlers(this.discordApp.build(A.runtimeState))}getWebRoutes(){return this.discordApp.getWebRoutes()}createDaemon(){if(!this.config.adapters.discord)return;return{start:async()=>{await this.discordApp.initialize(),this.gatewayLoop.start()},stop:async()=>{await this.gatewayLoop.stop(),this.threadRegistry.clear(),this.uploadContinuity.clear(),this.toolStatusMessenger.clear(),await this.discordApp.shutdown()},healthCheck:async()=>({status:this.gatewayLoop.isRunning()?"healthy":"error",message:this.gatewayLoop.isRunning()?"Chat gateway loop running":"Chat gateway loop stopped",lastCheck:new Date})}}sendMessageToChannel({channelId:A,message:Q}){let w=this.threadRegistry.get(A);if(!w)return;let B=this.toDiscordCardOutput(Q);if(B){w.post(B).catch(($)=>this.logger.error("Failed to send chat message",{error:$,channelId:A}));return}if(typeof Q!=="string")return;for(let $ of pi(A,Q))w.post($).catch((Y)=>this.logger.error("Failed to send chat message",{error:Y,channelId:A}))}async sendMessageWithId({channelId:A,message:Q}){let w=this.threadRegistry.get(A);if(!w)return;let B=this.toDiscordCardOutput(Q);if(B){let Y=await w.post(B);return this.threadRegistry.trackMessage(w.id,Y),Y.id}if(typeof Q!=="string")return;let $;for(let Y of pi(A,Q))$=await w.post(Y),this.threadRegistry.trackMessage(w.id,$);return $?.id}async editMessage({channelId:A,messageId:Q,newMessage:w}){let B=this.threadRegistry.getMessage(A,Q);if(!B)return!1;try{let $=await B.edit(this.toDiscordCardOutput(w)??(typeof w==="string"?w:""));if(A)this.threadRegistry.trackMessage(A,$);return!0}catch{return!1}}supportsMessageEditing(){return!0}toDiscordCardOutput(A){let Q=ROQ.safeParse(A);if(!Q.success)return;let{card:w,fallbackText:B}=Q.data;if(B===void 0)return{card:w};return{card:w,fallbackText:B}}formatProgressOutput(A){return Xy0(A)}formatCompletionOutput(A){return Xy0(A)}async handleProgressEvent(A,Q){let w=A.metadata.interfaceType;if(w&&w!==this.id){if(!this.isEnabledPlatform(w))return;let B={...A,metadata:{...A.metadata,interfaceType:this.id}};await super.handleProgressEvent(B,B.metadata);return}await super.handleProgressEvent(A,Q)}async handleToolActivityEvent(A){if(A.interfaceType===this.id){await super.handleToolActivityEvent(A);return}if(!this.isEnabledPlatform(A.interfaceType))return;await super.handleToolActivityEvent({...A,interfaceType:this.id})}async handleToolStatusUpdate(A){if(A.interfaceType!==this.id||!A.channelId)return;await this.toolStatusMessenger.handle(A)}isEnabledPlatform(A){return vW1(A,Boolean(this.config.adapters.discord))}registerChatHandlers(A){if(A.onDirectMessage(async(Q,w,B,$)=>{await this.handleRoutedMessage(Q,w,$)}),A.onNewMention(async(Q,w,B)=>{let $=this.getPlatformConfig(Q);if($&&this.shouldRouteDiscordMessage(Q,w,$)&&!Q.isDM&&$.useThreads)await this.subscriptionRouter.subscribeOwnedThread(Q,w);await this.handleRoutedMessage(Q,w,B)}),A.onSubscribedMessage(async(Q,w,B)=>{if(!await this.subscriptionRouter.shouldRouteSubscribedMessage(Q,w))return;await this.handleRoutedMessage(Q,w,B)}),this.config.adapters.discord&&!this.config.adapters.discord.requireMention)A.onNewMessage(kOQ,async(Q,w,B)=>{await this.handleRoutedMessage(Q,w,B)});A.onNewMessage(POQ,async(Q,w)=>{await this.handlePassiveUrlCapture(Q,w)}),A.onAction([B50,Yy0],async(Q)=>{await this.handleApprovalAction(Q)}),A.onAction(Dy0,async(Q)=>{await this.handlePromptAction(Q)})}async handlePromptAction(A){if(!this.context||!A.thread||!A.value)return;let Q=A.adapter.name;if(!this.isEnabledPlatform(Q))return;let w=A.thread;if(!this.shouldHandleDiscordAction(w,Q))return;let B=this.promptActions.get(A.value);if(B?.threadId!==w.id){await w.post(this.formatNoticePayload("That suggested action is no longer available.","Action unavailable"));return}let $=this.getThreadIdParts(w.id),Y=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:$.channelId??w.channelId,isBot:Boolean(A.user.isBot)}),D=this.getConversationId(Q,w.id),X=w.id;await this.runAgentTurn({thread:w,channelId:X,logLabel:"Error handling chat prompt action",body:async()=>{if(!this.context)return;let H=await this.context.agent.chat(B.prompt,D,{userPermissionLevel:Y,interfaceType:Q,channelId:X,channelName:w.isDM?"DM":w.channelId,...this.buildActionEventMetadata(Q,w,A)});await this.renderAgentResponse({thread:w,channelId:X,conversationId:D,response:H,userPermissionLevel:Y})}})}async handleApprovalAction(A){if(!this.context||!A.thread||!A.value)return;let Q=A.adapter.name;if(!this.isEnabledPlatform(Q))return;let w=this.getConversationId(Q,A.thread.id);if(!(await this.getPendingApprovalIds(w)).has(A.value)){await A.thread.post(this.formatNoticePayload("That approval is no longer pending."));return}let $=A.thread;if(!this.shouldHandleDiscordAction($,Q))return;let Y=this.getThreadIdParts($.id),D=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:Y.channelId??$.channelId,isBot:Boolean(A.user.isBot)});await this.confirmApproval({thread:$,conversationId:w,approvalId:A.value,confirmed:A.actionId===B50,userPermissionLevel:D,metadata:this.buildActionEventMetadata(Q,$,A)})}shouldHandleDiscordAction(A,Q){if(Q!=="discord")return!0;let w=this.config.adapters.discord;if(!w)return!1;if(A.isDM&&!w.allowDMs)return!1;return this.isAllowedChannel(A,w)}isBotCreatedDiscordThread(A,Q){if(A.isDM)return!1;let w=this.getThreadIdParts(A.id);if(!w.threadId)return!1;let B=this.getRawDiscordChannelId(Q);return B!==void 0&&B!==w.threadId}getRawDiscordChannelId(A){let Q=A.raw;if(typeof Q!=="object"||Q===null)return;let w=Q.channel_id;return typeof w==="string"?w:void 0}async handleRoutedMessage(A,Q,w){if(!this.context)return;let B=this.getPlatform(A);if(B!=="discord")return;let $=this.getPlatformConfig(A);if(!$)return;if(!this.shouldRouteDiscordMessage(A,Q,$))return;await this.routeToAgent(B,A,Q,w)}shouldRouteDiscordMessage(A,Q,w){if(A.isDM&&!w.allowDMs)return!1;if(Q.author.isMe)return!1;if(Q.author.isBot&&!Q.isMention)return!1;if(!this.isAllowedChannel(A,w))return!1;return!0}async runAgentTurn(A){this.startProcessingInput(A.channelId);try{if(this.getPlatformConfig(A.thread)?.showTypingIndicator)await A.thread.startTyping().catch((Q)=>this.logger.debug("Typing indicator failed",{error:Q,channelId:A.channelId}));await A.body()}catch(Q){this.logger.error(A.logLabel,{error:Q,channelId:A.channelId}),await this.postTurnError(A.thread,A.channelId,Q)}finally{this.endProcessingInput()}}async postTurnError(A,Q,w){let B=this.formatErrorPayload(w),$=this.toDiscordCardOutput(B);if($){await A.post($);return}let Y=typeof B==="string"?B:"Message failed.";for(let D of pi(Q,Y))await A.post(D)}async routeToAgent(A,Q,w,B){if(!this.context)return;this.threadRegistry.set(Q);let $=this.getConversationId(A,Q.id),Y=Q.id,D=this.getPermissionContext(Q,w),X=this.context.permissions.getUserLevel(A,w.author.userId,D),H=await this.chatInputBuilder.build(A,Q,w,X),W=[...H.attachments];if(await this.attachPriorUploads($,H,X),await this.postUploadNotices(Q,H.notices),!H.message&&H.attachments.length===0)return;this.rememberUploadAttachments($,W),await this.runAgentTurn({thread:Q,channelId:Y,logLabel:"Error handling chat message",body:async()=>{if(!this.context)return;let f=await this.getPendingApprovalIds($);if(f.size>0){await this.handleConfirmationResponse(H.message,$,Q,f,X,this.buildUserMessageMetadata(A,Q,w));return}let Z=this.buildCoalescedAgentInput(H.message,B),G=await this.context.agent.chat(Z.message,$,{userPermissionLevel:X,interfaceType:A,channelId:Y,channelName:this.getChannelName(Q),...this.buildUserMessageMetadata(A,Q,w,Z.metadata),...H.attachments.length>0?{attachments:H.attachments}:{}});await this.renderAgentResponse({thread:Q,channelId:Y,conversationId:$,response:G,userPermissionLevel:X})}})}async renderAgentResponse(A){if(A.confirmation)this.syncPendingConfirmationsFromResponse(A.conversationId,A.response,A.confirmation.approvalId);else this.rememberPendingConfirmationsFromResponse(A.conversationId,A.response);await this.handleAgentResponseToolStatuses(A.response,A.conversationId);let Q=await this.artifactDelivery.resolve(A.response.cards,A.userPermissionLevel);if(A.confirmation)await this.approvalCards.resolve(A.conversationId,A.confirmation.approvalId,A.confirmation.confirmed);let w=A.confirmation?this.formatConfirmationResponsePayload(A.response,A.confirmation.confirmed,this.getRemainingApprovalHelp(A.conversationId,A.response),Q.deniedCardIds):this.formatAgentResponseText(A.response.text,A.response.cards,A.response.pendingConfirmations,Q.deniedCardIds),B=await this.sendAgentResponseWithFiles({thread:A.thread,channelId:A.channelId,message:w,files:Q.files}),$=await this.sendArtifactCards(A.thread,A.response.cards,Q.deniedCardIds);await this.sendSupplementalCards(A.thread,A.response.cards,A.response.pendingConfirmations),await this.approvalCards.trackPendingConfirmations(A.thread,A.conversationId,A.response.pendingConfirmations);let Y=$??B;if(Y)for(let D of D00(A.response))this.trackAgentResponseForJob(D,Y,A.channelId)}rememberPendingConfirmationsFromResponse(A,Q){this.pendingApprovals.rememberFromResponse(A,Q)}async getPendingApprovalIds(A){return this.pendingApprovals.getApprovalIds(A)}async handleConfirmationResponse(A,Q,w,B,$,Y){let D=re({message:A,approvalIds:B});if(D.kind==="not-confirmation"){this.pendingApprovals.deleteConversation(Q),await w.post(this.formatNoticePayload("No pending approval to resolve."));return}if(D.kind==="notice"){await w.post(this.formatNoticePayload(D.message));return}await this.confirmApproval({thread:w,conversationId:Q,approvalId:D.approvalId,confirmed:D.confirmed,userPermissionLevel:$,...Y?{metadata:Y}:{}})}async confirmApproval(A){let Q=await this.context?.agent.confirmPendingAction(A.conversationId,A.confirmed,A.approvalId,{userPermissionLevel:A.userPermissionLevel,interfaceType:"discord",channelId:A.thread.id,channelName:A.thread.isDM?"DM":A.thread.channelId,...A.metadata});if(this.removePendingApproval(A.conversationId,A.approvalId),!Q)return;await this.renderAgentResponse({thread:A.thread,channelId:A.thread.id,conversationId:A.conversationId,response:Q,userPermissionLevel:A.userPermissionLevel,confirmation:{approvalId:A.approvalId,confirmed:A.confirmed}})}formatNoticePayload(A,Q="Approval notice"){return{card:{type:"card",title:Q,children:[{type:"text",content:A}]},fallbackText:A}}formatErrorPayload(A){let Q=A instanceof Error?A.message:"Unknown error";return{card:{type:"card",title:"Message failed",children:[{type:"text",content:Q}]},fallbackText:`Message failed: ${Q}`}}formatAgentResponseText(A,Q,w,B){return w00({text:A,cards:Q,pendingConfirmations:w,deniedCardIds:B,formatCard:($)=>this.cardBuilder.formatStructuredCard($,B)}).join(`
2346
+ \`\`\``;return this.defaultNodeToText(A,(Q)=>this.nodeToDiscordMarkdown(Q))}},cJ1={DeferredChannelMessageWithSource:5,DeferredUpdateMessage:6},z50="https://discord.com/api/v10",lJ1=2000,JOQ=/^[0-9a-f]{64}$/,IOQ=/^[0-9a-f]+$/,bOQ=class A{name="discord";userName;botUserId;apiBaseUrl;botToken;publicKey;applicationId;mentionRoleIds;chat=null;logger;formatConverter=new VOQ;requestContext=new HOQ;threadParentCache=new Map;static THREAD_PARENT_CACHE_TTL=300000;constructor(Q={}){let w=Q.botToken??process.env.DISCORD_BOT_TOKEN;if(!w)throw new nW("discord","botToken is required. Set DISCORD_BOT_TOKEN or provide it in config.");let B=Q.publicKey??process.env.DISCORD_PUBLIC_KEY;if(!B)throw new nW("discord","publicKey is required. Set DISCORD_PUBLIC_KEY or provide it in config.");let $=Q.applicationId??process.env.DISCORD_APPLICATION_ID;if(!$)throw new nW("discord","applicationId is required. Set DISCORD_APPLICATION_ID or provide it in config.");if(this.apiBaseUrl=Q.apiUrl??process.env.DISCORD_API_URL??z50,this.botToken=w,this.publicKey=B.trim().toLowerCase(),this.applicationId=$,this.mentionRoleIds=Q.mentionRoleIds??(process.env.DISCORD_MENTION_ROLE_IDS?process.env.DISCORD_MENTION_ROLE_IDS.split(",").map((Y)=>Y.trim()):[]),this.botUserId=$,this.logger=Q.logger??new K50("info").child("discord"),this.userName=Q.userName??"bot",!JOQ.test(this.publicKey))this.logger.error("Invalid Discord public key format",{length:this.publicKey.length,isHex:IOQ.test(this.publicKey)})}async initialize(Q){this.chat=Q,this.logger.info("Discord adapter initialized")}async getUser(Q){try{let B=await(await this.discordFetch(`/users/${Q}`,"GET")).json();return{avatarUrl:B.avatar?`https://cdn.discordapp.com/avatars/${B.id}/${B.avatar}.png`:void 0,email:void 0,fullName:B.global_name||B.username,isBot:B.bot??!1,userId:B.id,userName:B.username}}catch{return null}}async handleWebhook(Q,w){let B=await Q.arrayBuffer(),$=new Uint8Array(B),Y=new TextDecoder().decode($),D=Q.headers.get("x-discord-gateway-token");if(D){if(D!==this.botToken)return this.logger.warn("Invalid gateway token"),new Response("Invalid gateway token",{status:401});this.logger.info("Discord forwarded Gateway event received");try{let Z=JSON.parse(Y);return this.handleForwardedGatewayEvent(Z,w)}catch{return new Response("Invalid JSON",{status:400})}}this.logger.info("Discord webhook received",{bodyLength:Y.length,bodyBytesLength:$.length,hasSignature:!!Q.headers.get("x-signature-ed25519"),hasTimestamp:!!Q.headers.get("x-signature-timestamp")});let X=Q.headers.get("x-signature-ed25519"),H=Q.headers.get("x-signature-timestamp");if(!await this.verifySignature($,X,H))return this.logger.warn("Discord signature verification failed, returning 401"),new Response("Invalid signature",{status:401});this.logger.info("Discord signature verification passed");let f;try{f=JSON.parse(Y)}catch{return new Response("Invalid JSON",{status:400})}if(this.logger.info("Discord interaction parsed",{type:f.type,typeIsPing:f.type===RC.Ping,expectedPingType:RC.Ping,id:f.id}),f.type===RC.Ping){let Z=JSON.stringify({type:Qd.InteractionResponseType.PONG});return this.logger.info("Discord PING received, responding with PONG",{responseBody:Z,responseType:Qd.InteractionResponseType.PONG}),new Response(Z,{status:200,headers:{"Content-Type":"application/json"}})}if(f.type===RC.MessageComponent)return this.handleComponentInteraction(f,w),this.respondToInteraction({type:cJ1.DeferredUpdateMessage});if(f.type===RC.ApplicationCommand)return this.handleApplicationCommandInteraction(f,w),this.respondToInteraction({type:cJ1.DeferredChannelMessageWithSource});return new Response("Unknown interaction type",{status:400})}async verifySignature(Q,w,B){if(!(w&&B))return this.logger.warn("Discord signature verification failed: missing headers",{hasSignature:!!w,hasTimestamp:!!B}),!1;try{this.logger.info("Discord signature verification attempt",{bodyBytesLength:Q.length,signatureLength:w.length,timestampLength:B.length,publicKeyLength:this.publicKey.length,timestamp:B,signaturePrefix:w.slice(0,16),publicKey:this.publicKey});let $=await Qd.verifyKey(Q,w,B,this.publicKey);if(!$){let Y=new TextDecoder().decode(Q);this.logger.warn("Discord signature verification failed: invalid signature",{publicKeyLength:this.publicKey.length,signatureLength:w.length,publicKeyPrefix:this.publicKey.slice(0,8),publicKeySuffix:this.publicKey.slice(-8),timestamp:B,bodyLength:Q.length,bodyPrefix:Y.slice(0,50)})}return $}catch($){return this.logger.warn("Discord signature verification failed: exception",{error:$}),!1}}respondToInteraction(Q){return Response.json(Q)}handleComponentInteraction(Q,w){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}let B=Q.data?.custom_id;if(!B){this.logger.warn("No custom_id in component interaction");return}let $=Q.member?.user||Q.user;if(!$){this.logger.warn("No user in component interaction");return}let Y=Q.channel_id,D=Q.guild_id||"@me",X=Q.message?.id;if(!(Y&&X)){this.logger.warn("Missing channel_id or message_id in interaction");return}let H=Q.channel,W=H?.type===11||H?.type===12,f=W&&H?.parent_id?H.parent_id:Y,Z=W?this.encodeThreadId({guildId:D,channelId:f,threadId:Y}):this.encodeThreadId({guildId:D,channelId:Y}),G=fOQ(B),F={actionId:G.actionId,value:G.value??G.actionId,user:{userId:$.id,userName:$.username,fullName:$.global_name||$.username,isBot:$.bot??!1,isMe:!1},messageId:X,threadId:Z,adapter:this,raw:Q};this.logger.debug("Processing Discord button action",{actionId:B,messageId:X,threadId:Z}),this.chat.processAction(F,w)}handleApplicationCommandInteraction(Q,w){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}let B=Q.data?.name;if(!B){this.logger.warn("No command name in application command interaction");return}let $=Q.member?.user||Q.user;if(!$){this.logger.warn("No user in application command interaction");return}let Y=Q.channel_id;if(!Y){this.logger.warn("Missing channel_id in application command interaction");return}let D=Q.guild_id||"@me",X=Q.channel,H=X?.type===11||X?.type===12,W=H&&X?.parent_id?X.parent_id:Y,f=H?this.encodeThreadId({guildId:D,channelId:W,threadId:Y}):this.encodeThreadId({guildId:D,channelId:Y}),{command:Z,text:G}=this.parseSlashCommand(B,Q.data?.options);this.logger.debug("Processing Discord slash command",{command:Z,text:G,userId:$.id,channelId:f}),this.requestContext.run({slashCommand:{channelId:f,interactionToken:Q.token,initialResponseSent:!1}},()=>{this.chat?.processSlashCommand({command:Z,text:G,user:{userId:$.id,userName:$.username,fullName:$.global_name||$.username,isBot:$.bot??!1,isMe:$.id===this.applicationId},adapter:this,raw:Q,channelId:f},w)})}parseSlashCommand(Q,w){let B=[Q.startsWith("/")?Q:`/${Q}`],$=[],Y=(D)=>{for(let X of D){if(X.value!==void 0){$.push(String(X.value));continue}if(X.options&&X.options.length>0)B.push(X.name),Y(X.options)}};if(w&&w.length>0)Y(w);return{command:B.join(" "),text:$.join(" ").trim()}}async handleGatewayInteraction(Q){if(Q.isChatInputCommand()){await Q.deferReply(),this.handleApplicationCommandInteraction(this.normalizeGatewaySlashCommandInteraction(Q));return}if(Q.isMessageComponent())await Q.deferUpdate(),this.handleComponentInteraction(this.normalizeGatewayComponentInteraction(Q))}normalizeGatewaySlashCommandInteraction(Q){return{application_id:Q.applicationId,channel:this.normalizeGatewayChannel(Q),channel_id:Q.channelId??void 0,data:{name:Q.commandName,options:this.normalizeGatewayCommandOptions(Q.options.data),type:Q.commandType},guild_id:Q.guildId??void 0,id:Q.id,token:Q.token,type:Q.type,user:this.normalizeGatewayUser(Q.user),version:Q.version}}normalizeGatewayComponentInteraction(Q){let w="values"in Q&&Array.isArray(Q.values)?Q.values:void 0;return{application_id:Q.applicationId,channel:this.normalizeGatewayChannel(Q),channel_id:Q.channelId??void 0,data:{component_type:Q.componentType,custom_id:Q.customId,values:w},guild_id:Q.guildId??void 0,id:Q.id,message:{id:Q.message.id},token:Q.token,type:Q.type,user:this.normalizeGatewayUser(Q.user),version:Q.version}}normalizeGatewayChannel(Q){if(!Q.channel)return;let w="parentId"in Q.channel&&typeof Q.channel.parentId==="string"?Q.channel.parentId:void 0;return{id:Q.channel.id,parent_id:w,type:Q.channel.type}}normalizeGatewayCommandOptions(Q){return Q.map((w)=>({name:w.name,options:w.options?this.normalizeGatewayCommandOptions(w.options):void 0,type:w.type,value:w.value}))}normalizeGatewayUser(Q){return{avatar:Q.avatar??void 0,bot:Q.bot,discriminator:Q.discriminator,global_name:Q.globalName??void 0,id:Q.id,username:Q.username}}async handleForwardedGatewayEvent(Q,w){switch(this.logger.info("Processing forwarded Gateway event",{type:Q.type,timestamp:Q.timestamp}),Q.type){case"GATEWAY_MESSAGE_CREATE":await this.handleForwardedMessage(Q.data,w);break;case"GATEWAY_MESSAGE_REACTION_ADD":await this.handleForwardedReaction(Q.data,!0,w);break;case"GATEWAY_MESSAGE_REACTION_REMOVE":await this.handleForwardedReaction(Q.data,!1,w);break;default:this.logger.debug("Forwarded Gateway event (no handler)",{type:Q.type})}return new Response(JSON.stringify({ok:!0}),{status:200,headers:{"Content-Type":"application/json"}})}async handleForwardedMessage(Q,w){if(!this.chat)return;let B=Q.guild_id||"@me",$=Q.channel_id,Y,D=$;if(Q.thread)Y=Q.thread.id,D=Q.thread.parent_id;else if(Q.channel_type===11||Q.channel_type===12)try{let F=await(await this.discordFetch(`/channels/${$}`,"GET")).json();if(F.parent_id)Y=$,D=F.parent_id,this.logger.debug("Fetched thread parent for forwarded message",{threadId:$,parentId:F.parent_id})}catch(G){this.logger.error("Failed to fetch thread parent",{error:String(G),channelId:$})}let X=Q.is_mention||Q.mentions.some((G)=>G.id===this.applicationId),H=this.mentionRoleIds.length>0&&Q.mention_roles?.some((G)=>this.mentionRoleIds.includes(G)),W=X||H;if(!Y&&W)try{let G=await this.createDiscordThread($,Q.id);Y=G.id,this.logger.debug("Created Discord thread for forwarded mention",{channelId:$,messageId:Q.id,threadId:G.id})}catch(G){this.logger.error("Failed to create Discord thread for mention",{error:String(G),messageId:Q.id})}let f=this.encodeThreadId({guildId:B,channelId:D,threadId:Y}),Z=new x5({id:Q.id,threadId:f,text:Q.content,formatted:this.formatConverter.toAst(Q.content),author:{userId:Q.author.id,userName:Q.author.username,fullName:Q.author.global_name||Q.author.username,isBot:Q.author.bot===!0,isMe:Q.author.id===this.applicationId},metadata:{dateSent:new Date(Q.timestamp),edited:!1},attachments:Q.attachments.map((G)=>({type:this.getAttachmentType(G.content_type),url:G.url,name:G.filename,mimeType:G.content_type,size:G.size})),raw:Q,isMention:W});try{await this.chat.handleIncomingMessage(this,f,Z)}catch(G){this.logger.error("Error handling forwarded message",{error:String(G),messageId:Q.id})}}async handleForwardedReaction(Q,w,B){if(!this.chat)return;let $=Q.guild_id||"@me",Y=Q.channel_id,D,X=Y;if(Q.channel_type===f_.GuildPublicThread||Q.channel_type===f_.GuildPrivateThread){let F=this.threadParentCache.get(Y);if(F&&F.expiresAt>Date.now())D=Y,X=F.parentId;else try{let b=await(await this.discordFetch(`/channels/${Y}`,"GET")).json();if(b.parent_id)D=Y,X=b.parent_id,this.threadParentCache.set(Y,{parentId:b.parent_id,expiresAt:Date.now()+A.THREAD_PARENT_CACHE_TTL})}catch(V){this.logger.error("Failed to fetch thread parent for reaction",{error:String(V),channelId:Y})}}let H=this.encodeThreadId({guildId:$,channelId:X,threadId:D}),W=Q.emoji.name||"unknown",f=this.normalizeDiscordEmoji(W),Z=Q.user??Q.member?.user;if(!Z){this.logger.warn("Reaction event missing user info",{data:Q});return}let G={adapter:this,threadId:H,messageId:Q.message_id,emoji:f,rawEmoji:Q.emoji.id?`<:${W}:${Q.emoji.id}>`:W,added:w,user:{userId:Z.id,userName:Z.username,fullName:Z.username,isBot:Z.bot===!0,isMe:Z.id===this.applicationId},raw:Q};this.chat.processReaction(G)}async postMessage(Q,w){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=Q;if($)B=$;let D={},X=[],H=[],W=G50(w);if(W){let V=sE0(W);X.push(...V.embeds),H.push(...V.components)}else D.content=this.truncateContent(D_(this.formatConverter.renderPostable(w),"discord"));if(X.length>0)D.embeds=X;if(H.length>0)D.components=H;let f=OE0(w),Z=this.tryPostSlashResponse(Y,D,f);if(Z)return Z;if(f.length>0)return this.postMessageWithFiles(B,Y,D,f);this.logger.debug("Discord API: POST message",{channelId:B,contentLength:D.content?.length||0,embedCount:X.length,componentCount:H.length});let F=await(await this.discordFetch(`/channels/${B}/messages`,"POST",D)).json();return this.logger.debug("Discord API: POST message response",{messageId:F.id}),{id:F.id,threadId:Y,raw:F}}tryPostSlashResponse(Q,w,B){let $=this.requestContext.getStore()?.slashCommand;if(!$||$.channelId!==Q)return;return this.postSlashCommandResponse($,Q,w,B)}async postSlashCommandResponse(Q,w,B,$){let Y=!Q.initialResponseSent;Q.initialResponseSent=!0;let D=Y?`/webhooks/${this.applicationId}/${Q.interactionToken}/messages/@original`:`/webhooks/${this.applicationId}/${Q.interactionToken}?wait=true`,X=Y?"PATCH":"POST";this.logger.debug("Discord interaction webhook: responding to slash command",{threadId:w,isInitialResponse:Y,hasFiles:$.length>0});let W=await($.length>0?await this.discordInteractionFetchWithFiles(D,X,B,$):await this.discordInteractionFetch(D,X,B)).json();return{id:W.id,threadId:w,raw:W}}async createDiscordThread(Q,w){let B=`Thread ${new Date().toLocaleString()}`;this.logger.debug("Discord API: POST thread",{channelId:Q,messageId:w,threadName:B});try{let Y=await(await this.discordFetch(`/channels/${Q}/messages/${w}/threads`,"POST",{name:B,auto_archive_duration:1440})).json();return this.logger.debug("Discord API: POST thread response",{threadId:Y.id,threadName:Y.name}),Y}catch($){if($ instanceof kC&&typeof $.message==="string"&&$.message.includes('"code"')&&$.message.includes("160004"))return this.logger.debug("Thread already exists for message, reusing existing thread",{channelId:Q,messageId:w}),{id:w,name:B};throw $}}truncateContent(Q){if(Q.length<=lJ1)return Q;return`${Q.slice(0,lJ1-3)}...`}async postMessageWithFiles(Q,w,B,$){let Y=new FormData;Y.append("payload_json",JSON.stringify(B));for(let H=0;H<$.length;H++){let W=$[H];if(!W)continue;let f=await xE0(W.data,{platform:"discord"});if(!f)continue;let Z=new Blob([new Uint8Array(f)],{type:W.mimeType||"application/octet-stream"});Y.append(`files[${H}]`,Z,W.filename)}let D=await fetch(`${z50}/channels/${Q}/messages`,{method:"POST",headers:{Authorization:`Bot ${this.botToken}`},body:Y});if(!D.ok){let H=await D.text();throw new kC("discord",`Failed to post message: ${D.status} ${H}`)}let X=await D.json();return{id:X.id,threadId:w,raw:X}}async discordInteractionFetch(Q,w,B){let $=await fetch(`${z50}${Q}`,{method:w,headers:B?{"Content-Type":"application/json"}:void 0,body:B?JSON.stringify(B):void 0});if(!$.ok){let Y=await $.text();throw this.logger.error("Discord interaction API error",{path:Q,method:w,status:$.status,error:Y}),new kC("discord",`Discord interaction API error: ${$.status} ${Y}`)}return $}async discordInteractionFetchWithFiles(Q,w,B,$){let Y=new FormData;Y.append("payload_json",JSON.stringify(B));for(let X=0;X<$.length;X++){let H=$[X];if(!H)continue;let W=await xE0(H.data,{platform:"discord"});if(!W)continue;let f=new Blob([new Uint8Array(W)],{type:H.mimeType||"application/octet-stream"});Y.append(`files[${X}]`,f,H.filename)}let D=await fetch(`${z50}${Q}`,{method:w,body:Y});if(!D.ok){let X=await D.text();throw this.logger.error("Discord interaction API error",{path:Q,method:w,status:D.status,error:X}),new kC("discord",`Discord interaction API error: ${D.status} ${X}`)}return D}async editMessage(Q,w,B){let{channelId:$,threadId:Y}=this.decodeThreadId(Q),D=Y||$,X={},H=[],W=[],f=G50(B);if(f){let F=sE0(f);H.push(...F.embeds),W.push(...F.components),X.content=""}else X.content=this.truncateContent(D_(this.formatConverter.renderPostable(B),"discord"));if(H.length>0)X.embeds=H;if(W.length>0)X.components=W;this.logger.debug("Discord API: PATCH message",{channelId:D,messageId:w,contentLength:X.content?.length||0});let G=await(await this.discordFetch(`/channels/${D}/messages/${w}`,"PATCH",X)).json();return this.logger.debug("Discord API: PATCH message response",{messageId:G.id}),{id:G.id,threadId:Q,raw:G}}async deleteMessage(Q,w){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=$||B;this.logger.debug("Discord API: DELETE message",{channelId:Y,messageId:w}),await this.discordFetch(`/channels/${Y}/messages/${w}`,"DELETE"),this.logger.debug("Discord API: DELETE message response",{ok:!0})}async addReaction(Q,w,B){let{channelId:$,threadId:Y}=this.decodeThreadId(Q),D=Y||$,X=this.encodeEmoji(B);this.logger.debug("Discord API: PUT reaction",{channelId:D,messageId:w,emoji:X}),await this.discordFetch(`/channels/${D}/messages/${w}/reactions/${X}/@me`,"PUT"),this.logger.debug("Discord API: PUT reaction response",{ok:!0})}async removeReaction(Q,w,B){let{channelId:$,threadId:Y}=this.decodeThreadId(Q),D=Y||$,X=this.encodeEmoji(B);this.logger.debug("Discord API: DELETE reaction",{channelId:D,messageId:w,emoji:X}),await this.discordFetch(`/channels/${D}/messages/${w}/reactions/${X}/@me`,"DELETE"),this.logger.debug("Discord API: DELETE reaction response",{ok:!0})}encodeEmoji(Q){let w=si.toDiscord?si.toDiscord(Q):String(Q);return encodeURIComponent(w)}async startTyping(Q,w){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=$||B;this.logger.debug("Discord API: POST typing",{channelId:Y}),await this.discordFetch(`/channels/${Y}/typing`,"POST")}async fetchMessages(Q,w={}){let{channelId:B,threadId:$}=this.decodeThreadId(Q),Y=$||B,D=w.limit||50,X=w.direction??"backward",H=new URLSearchParams;if(H.set("limit",String(D)),w.cursor)if(X==="backward")H.set("before",w.cursor);else H.set("after",w.cursor);this.logger.debug("Discord API: GET messages",{channelId:Y,limit:D,direction:X,cursor:w.cursor});let f=await(await this.discordFetch(`/channels/${Y}/messages?${H.toString()}`,"GET")).json();this.logger.debug("Discord API: GET messages response",{messageCount:f.length});let G=[...f].reverse().map((V)=>this.parseDiscordMessage(V,Q)),F;if(f.length===D)if(X==="backward")F=f.at(-1)?.id;else F=f[0]?.id;return{messages:G,nextCursor:F}}async fetchThread(Q){let{channelId:w,guildId:B}=this.decodeThreadId(Q);this.logger.debug("Discord API: GET channel",{channelId:w});let Y=await(await this.discordFetch(`/channels/${w}`,"GET")).json();return{id:Q,channelId:w,channelName:Y.name,isDM:Y.type===f_.DM||Y.type===f_.GroupDM,metadata:{guildId:B,channelType:Y.type,raw:Y}}}async openDM(Q){this.logger.debug("Discord API: POST DM channel",{userId:Q});let B=await(await this.discordFetch("/users/@me/channels","POST",{recipient_id:Q})).json();return this.logger.debug("Discord API: POST DM channel response",{channelId:B.id}),this.encodeThreadId({guildId:"@me",channelId:B.id})}isDM(Q){let{guildId:w}=this.decodeThreadId(Q);return w==="@me"}encodeThreadId(Q){let w=Q.threadId?`:${Q.threadId}`:"";return`discord:${Q.guildId}:${Q.channelId}${w}`}decodeThreadId(Q){let w=Q.split(":");if(w.length<3||w[0]!=="discord")throw new nW("discord",`Invalid Discord thread ID: ${Q}`);return{guildId:w[1],channelId:w[2],threadId:w[3]}}parseMessage(Q){let w=Q,B=w.guild_id||"@me",$=this.encodeThreadId({guildId:B,channelId:w.channel_id});return this.parseDiscordMessage(w,$)}parseDiscordMessage(Q,w){let B=Q.type===mz1.ThreadStarterMessage&&Q.referenced_message?Q.referenced_message:Q,$=B.author,Y=$.bot??!1,D=$.id===this.botUserId;return new x5({id:B.id,threadId:w,text:this.formatConverter.extractPlainText(B.content),formatted:this.formatConverter.toAst(B.content),raw:Q,author:{userId:$.id,userName:$.username,fullName:$.global_name||$.username,isBot:Y,isMe:D},metadata:{dateSent:new Date(B.timestamp),edited:B.edited_timestamp!==null,editedAt:B.edited_timestamp?new Date(B.edited_timestamp):void 0},attachments:(B.attachments||[]).map((X)=>({type:this.getAttachmentType(X.content_type),url:X.url,name:X.filename,mimeType:X.content_type,size:X.size,width:X.width??void 0,height:X.height??void 0}))})}getAttachmentType(Q){if(!Q)return"file";if(Q.startsWith("image/"))return"image";if(Q.startsWith("video/"))return"video";if(Q.startsWith("audio/"))return"audio";return"file"}renderFormatted(Q){return this.formatConverter.fromAst(Q)}async discordFetch(Q,w,B){let $=`${this.apiBaseUrl}${Q}`,Y={Authorization:`Bot ${this.botToken}`};if(B)Y["Content-Type"]="application/json";let D=await fetch($,{method:w,headers:Y,body:B?JSON.stringify(B):void 0});if(!D.ok){let X=await D.text();throw this.logger.error("Discord API error",{path:Q,method:w,status:D.status,error:X}),new kC("discord",`Discord API error: ${D.status} ${X}`)}return D}async startGatewayListener(Q,w=180000,B,$){if(!this.chat)return new Response("Chat instance not initialized",{status:500});if(!Q.waitUntil)return new Response("waitUntil not provided",{status:500});this.logger.info("Starting Discord Gateway listener",{durationMs:w,webhookUrl:$?"configured":"not configured"});let Y=this.runGatewayListener(w,B,$);return Q.waitUntil(Y),new Response(JSON.stringify({status:"listening",durationMs:w,message:`Gateway listener started, will run for ${w/1000} seconds`}),{status:200,headers:{"Content-Type":"application/json"}})}async runGatewayListener(Q,w,B){let $=new S9.Client({intents:[S9.GatewayIntentBits.Guilds,S9.GatewayIntentBits.GuildMessages,S9.GatewayIntentBits.MessageContent,S9.GatewayIntentBits.DirectMessages,S9.GatewayIntentBits.GuildMessageReactions,S9.GatewayIntentBits.DirectMessageReactions],partials:[S9.Partials.Channel]}),Y=!1;if(B)$.on("raw",async(D)=>{if(Y)return;if(!D.t)return;this.logger.info("Discord Gateway forwarding event",{type:D.t}),await this.forwardGatewayEvent(B,{type:`GATEWAY_${D.t}`,timestamp:Date.now(),data:D.d})});else this.setupLegacyGatewayHandlers($,()=>Y);$.on(S9.Events.ClientReady,()=>{this.logger.info("Discord Gateway connected",{username:$.user?.username,id:$.user?.id})}),$.on(S9.Events.Error,(D)=>{this.logger.error("Discord Gateway error",{error:String(D)})});try{await $.login(this.botToken),await new Promise((D)=>{let X=setTimeout(D,Q);if(w){if(w.aborted){clearTimeout(X),D();return}w.addEventListener("abort",()=>{this.logger.info("Discord Gateway listener received abort signal (new listener started)"),clearTimeout(X),D()},{once:!0})}}),this.logger.info("Discord Gateway listener duration elapsed, disconnecting")}catch(D){this.logger.error("Discord Gateway listener error",{error:String(D)})}finally{Y=!0,$.destroy(),this.logger.info("Discord Gateway listener stopped")}}setupLegacyGatewayHandlers(Q,w){Q.on(S9.Events.MessageCreate,async(B)=>{if(w()){this.logger.debug("Ignoring message - Gateway is shutting down");return}if(B.author.bot){this.logger.debug("Ignoring message from bot",{authorId:B.author.id,authorName:B.author.username,isMe:B.author.id===Q.user?.id});return}let $=B.mentions.has(Q.user?.id??""),Y=this.mentionRoleIds.length>0&&B.mentions.roles.some((X)=>this.mentionRoleIds.includes(X.id)),D=$||Y;this.logger.info("Discord Gateway message received",{channelId:B.channelId,guildId:B.guildId,authorId:B.author.id,isMentioned:D,isUserMentioned:$,isRoleMentioned:Y,content:B.content.slice(0,100)}),await this.handleGatewayMessage(B,D)}),Q.on(S9.Events.InteractionCreate,async(B)=>{if(w()){this.logger.debug("Ignoring interaction - Gateway is shutting down");return}this.logger.info("Discord Gateway interaction received",{id:B.id,type:B.type});try{await this.handleGatewayInteraction(B)}catch($){this.logger.error("Error handling Gateway interaction",{error:String($),interactionId:B.id})}}),Q.on(S9.Events.MessageReactionAdd,async(B,$)=>{if(w()){this.logger.debug("Ignoring reaction - Gateway is shutting down");return}if($.bot){this.logger.debug("Ignoring reaction from bot",{userId:$.id,isMe:$.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction added",{emoji:B.emoji.name,messageId:B.message.id,channelId:B.message.channelId,userId:$.id}),$.username)await this.handleGatewayReaction(B,$,!0)}),Q.on(S9.Events.MessageReactionRemove,async(B,$)=>{if(w()){this.logger.debug("Ignoring reaction removal - Gateway is shutting down");return}if($.bot){this.logger.debug("Ignoring reaction removal from bot",{userId:$.id,isMe:$.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction removed",{emoji:B.emoji.name,messageId:B.message.id,channelId:B.message.channelId,userId:$.id}),$.username)await this.handleGatewayReaction(B,$,!1)})}async forwardGatewayEvent(Q,w){try{this.logger.debug("Forwarding Gateway event to webhook",{type:w.type,webhookUrl:Q});let B=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/json","x-discord-gateway-token":this.botToken},body:JSON.stringify(w)});if(B.ok)this.logger.debug("Gateway event forwarded successfully",{type:w.type});else{let $=await B.text();this.logger.error("Failed to forward Gateway event",{type:w.type,status:B.status,error:$})}}catch(B){this.logger.error("Error forwarding Gateway event",{type:w.type,error:String(B)})}}async handleGatewayMessage(Q,w){if(!this.chat)return;let B=Q.guildId||"@me",$=Q.channelId,Y=Q.channel.isThread(),D,X=$;if(Y&&"parentId"in Q.channel&&Q.channel.parentId)D=$,X=Q.channel.parentId;if(!D&&w)try{let f=await this.createDiscordThread($,Q.id);D=f.id,this.logger.debug("Created Discord thread for incoming mention",{channelId:$,messageId:Q.id,threadId:f.id})}catch(f){this.logger.error("Failed to create Discord thread for mention",{error:String(f),messageId:Q.id})}let H=this.encodeThreadId({guildId:B,channelId:X,threadId:D}),W=new x5({id:Q.id,threadId:H,text:Q.content,formatted:this.formatConverter.toAst(Q.content),author:{userId:Q.author.id,userName:Q.author.username,fullName:Q.author.displayName||Q.author.username,isBot:Q.author.bot,isMe:!1},metadata:{dateSent:Q.createdAt,edited:Q.editedAt!==null,editedAt:Q.editedAt??void 0},attachments:Q.attachments.map((f)=>({type:this.getAttachmentType(f.contentType),url:f.url,name:f.name,mimeType:f.contentType??void 0,size:f.size})),raw:{id:Q.id,channel_id:$,guild_id:B,content:Q.content,author:{id:Q.author.id,username:Q.author.username},timestamp:Q.createdAt.toISOString()},isMention:w});try{await this.chat.handleIncomingMessage(this,H,W)}catch(f){this.logger.error("Error handling Gateway message",{error:String(f),messageId:Q.id})}}async handleGatewayReaction(Q,w,B){if(!this.chat)return;let $=Q.message.guildId||"@me",Y=Q.message.channelId,D=Q.message.channel?.isThread?.(),X=Y,H;if(D&&Q.message.channel?.parentId)H=Y,X=Q.message.channel.parentId;let W=this.encodeThreadId({guildId:$,channelId:X,threadId:H}),f=Q.emoji.name||"unknown",Z=this.normalizeDiscordEmoji(f),G={adapter:this,threadId:W,messageId:Q.message.id,emoji:Z,rawEmoji:Q.emoji.id?`<:${f}:${Q.emoji.id}>`:f,added:B,user:{userId:w.id,userName:w.username,fullName:w.username,isBot:w.bot===!0,isMe:w.id===this.applicationId},raw:{emoji:Q.emoji,message_id:Q.message.id,channel_id:Q.message.channelId,guild_id:Q.message.guildId,user_id:w.id}};this.chat.processReaction(G)}channelIdFromThreadId(Q){return Q.split(":").slice(0,3).join(":")}async fetchChannelMessages(Q,w={}){let $=Q.split(":")[2];if(!$)throw new nW("discord",`Invalid Discord channel ID: ${Q}`);let Y=w.limit||50,D=w.direction??"backward",X=new URLSearchParams;if(X.set("limit",String(Y)),w.cursor)if(D==="backward")X.set("before",w.cursor);else X.set("after",w.cursor);this.logger.debug("Discord API: GET channel messages",{channelId:$,limit:Y,direction:D,cursor:w.cursor});let W=await(await this.discordFetch(`/channels/${$}/messages?${X.toString()}`,"GET")).json();this.logger.debug("Discord API: GET channel messages response",{messageCount:W.length});let Z=[...W].reverse().map((F)=>this.parseDiscordMessage(F,Q)),G;if(W.length===Y)if(D==="backward")G=W.at(-1)?.id;else G=W[0]?.id;return{messages:Z,nextCursor:G}}async listThreads(Q,w={}){let B=Q.split(":"),$=B[1],Y=B[2];if(!($&&Y))throw new nW("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET threads",{guildId:$,channelId:Y});let H=((await(await this.discordFetch(`/guilds/${$}/threads/active`,"GET")).json()).threads||[]).filter((L)=>L.parent_id===Y),W=[];try{W=(await(await this.discordFetch(`/channels/${Y}/threads/archived/public?limit=${w.limit||50}`,"GET")).json()).threads||[]}catch{this.logger.debug("Could not fetch archived threads (may lack permissions)")}let f=[...H,...W],Z=new Set,G=f.filter((L)=>{if(Z.has(L.id))return!1;return Z.add(L.id),!0}),F=w.limit||50,V=G.slice(0,F),b=[];for(let L of V){let N=this.encodeThreadId({guildId:$,channelId:Y,threadId:L.id});try{let g=(await(await this.discordFetch(`/channels/${L.id}/messages?limit=1&after=0`,"GET")).json())[0];if(g)b.push({id:N,rootMessage:this.parseDiscordMessage(g,N),replyCount:L.total_message_sent??L.message_count,lastReplyAt:L.thread_metadata?.archive_timestamp?new Date(L.thread_metadata.archive_timestamp):void 0})}catch{b.push({id:N,rootMessage:new x5({id:L.id,threadId:N,text:L.name,formatted:this.formatConverter.toAst(L.name),raw:L,author:{userId:"unknown",userName:"unknown",fullName:"unknown",isBot:!1,isMe:!1},metadata:{dateSent:new Date,edited:!1},attachments:[]}),replyCount:L.total_message_sent??L.message_count})}}return this.logger.debug("Discord API: listThreads result",{threadCount:b.length}),{threads:b,nextCursor:G.length>F?String(F):void 0}}async fetchChannelInfo(Q){let B=Q.split(":")[2];if(!B)throw new nW("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET channel info",{channelId:B});let Y=await(await this.discordFetch(`/channels/${B}`,"GET")).json();return{id:Q,name:Y.name,isDM:Y.type===f_.DM||Y.type===f_.GroupDM,memberCount:Y.member_count,metadata:{channelType:Y.type,raw:Y}}}async postChannelMessage(Q,w){let $=Q.split(":")[2];if(!$)throw new nW("discord",`Invalid Discord channel ID: ${Q}`);let Y={},D=[],X=[],H=G50(w);if(H){let F=sE0(H);D.push(...F.embeds),X.push(...F.components)}else Y.content=this.truncateContent(D_(this.formatConverter.renderPostable(w),"discord"));if(D.length>0)Y.embeds=D;if(X.length>0)Y.components=X;let W=OE0(w),f=this.tryPostSlashResponse(Q,Y,W);if(f)return f;if(W.length>0)return this.postMessageWithFiles($,Q,Y,W);this.logger.debug("Discord API: POST channel message",{channelId:$,contentLength:Y.content?.length||0});let G=await(await this.discordFetch(`/channels/${$}/messages`,"POST",Y)).json();return{id:G.id,threadId:Q,raw:G}}normalizeDiscordEmoji(Q){let B={"\uD83D\uDC4D":"thumbs_up","\uD83D\uDC4E":"thumbs_down","\u2764\uFE0F":"heart","\u2764":"heart","\uD83D\uDD25":"fire","\uD83D\uDE80":"rocket","\uD83D\uDE4C":"raised_hands","\u2705":"check","\u274C":"x","\uD83D\uDC4B":"wave","\uD83E\uDD14":"thinking","\uD83D\uDE0A":"smile","\uD83D\uDE02":"laugh","\uD83C\uDF89":"party","\u2B50":"star","\u2728":"sparkles","\uD83D\uDC40":"eyes","\uD83D\uDCAF":"100"}[Q]||Q;return pI(B)}};function dJ1(A){return new bOQ(A??{})}var LOQ=class{subscriptions=new Set;locks=new Map;cache=new Map;queues=new Map;connected=!1;connectPromise=null;async connect(){if(this.connected)return;if(!this.connectPromise)this.connectPromise=Promise.resolve().then(()=>{this.connected=!0});await this.connectPromise}async disconnect(){this.connected=!1,this.connectPromise=null,this.subscriptions.clear(),this.locks.clear(),this.queues.clear()}async subscribe(A){this.ensureConnected(),this.subscriptions.add(A)}async unsubscribe(A){this.ensureConnected(),this.subscriptions.delete(A)}async isSubscribed(A){return this.ensureConnected(),this.subscriptions.has(A)}async acquireLock(A,Q){this.ensureConnected(),this.cleanExpiredLocks();let w=this.locks.get(A);if(w&&w.expiresAt>Date.now())return null;let B={threadId:A,token:NOQ(),expiresAt:Date.now()+Q};return this.locks.set(A,B),B}async forceReleaseLock(A){this.ensureConnected(),this.locks.delete(A)}async releaseLock(A){this.ensureConnected();let Q=this.locks.get(A.threadId);if(Q&&Q.token===A.token)this.locks.delete(A.threadId)}async extendLock(A,Q){this.ensureConnected();let w=this.locks.get(A.threadId);if(!w||w.token!==A.token)return!1;if(w.expiresAt<Date.now())return this.locks.delete(A.threadId),!1;return w.expiresAt=Date.now()+Q,!0}async get(A){this.ensureConnected();let Q=this.cache.get(A);if(!Q)return null;if(Q.expiresAt!==null&&Q.expiresAt<=Date.now())return this.cache.delete(A),null;return Q.value}async set(A,Q,w){this.ensureConnected(),this.cache.set(A,{value:Q,expiresAt:w?Date.now()+w:null})}async setIfNotExists(A,Q,w){this.ensureConnected();let B=this.cache.get(A);if(B)if(B.expiresAt!==null&&B.expiresAt<=Date.now())this.cache.delete(A);else return!1;return this.cache.set(A,{value:Q,expiresAt:w?Date.now()+w:null}),!0}async delete(A){this.ensureConnected(),this.cache.delete(A)}async appendToList(A,Q,w){this.ensureConnected();let B=this.cache.get(A),$;if(B&&B.expiresAt!==null&&B.expiresAt<=Date.now())$=[];else if(B&&Array.isArray(B.value))$=B.value;else $=[];if($.push(Q),w?.maxLength&&$.length>w.maxLength)$=$.slice($.length-w.maxLength);this.cache.set(A,{value:$,expiresAt:w?.ttlMs?Date.now()+w.ttlMs:null})}async enqueue(A,Q,w){this.ensureConnected();let B=this.queues.get(A);if(!B)B=[],this.queues.set(A,B);if(B.push(Q),B.length>w)B.splice(0,B.length-w);return B.length}async dequeue(A){this.ensureConnected();let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let w=Q.shift();if(Q.length===0)this.queues.delete(A);return w??null}async queueDepth(A){return this.ensureConnected(),this.queues.get(A)?.length??0}async getList(A){this.ensureConnected();let Q=this.cache.get(A);if(!Q)return[];if(Q.expiresAt!==null&&Q.expiresAt<=Date.now())return this.cache.delete(A),[];if(Array.isArray(Q.value))return Q.value;return[]}ensureConnected(){if(!this.connected)throw Error("MemoryStateAdapter is not connected. Call connect() first.")}cleanExpiredLocks(){let A=Date.now();for(let[Q,w]of this.locks)if(w.expiresAt<=A)this.locks.delete(Q)}_getSubscriptionCount(){return this.subscriptions.size}_getLockCount(){return this.cleanExpiredLocks(),this.locks.size}};function NOQ(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function q50(A){return new LOQ}Z0();var jOQ=K.object({subscribedAt:K.string().datetime(),routingMode:K.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:K.boolean().optional()}),MOQ="chat.discord.subscriptions";function aE0(A){return A.scoped({namespace:MOQ,schema:jOQ})}function nJ1(A,Q=q50()){let w=aE0(A);return new rJ1(Q,w)}class rJ1{memoryState;subscriptions;constructor(A,Q){this.memoryState=A;this.subscriptions=Q}connect(){return this.memoryState.connect()}disconnect(){return this.memoryState.disconnect()}async subscribe(A){await this.subscriptions.set(A,{subscribedAt:new Date().toISOString()})}async unsubscribe(A){await this.subscriptions.delete(A)}isSubscribed(A){return this.subscriptions.has(A)}acquireLock(A,Q){return this.memoryState.acquireLock(A,Q)}appendToList(A,Q,w){return this.memoryState.appendToList(A,Q,w)}delete(A){return this.memoryState.delete(A)}dequeue(A){return this.memoryState.dequeue(A)}enqueue(A,Q,w){return this.memoryState.enqueue(A,Q,w)}extendLock(A,Q){return this.memoryState.extendLock(A,Q)}forceReleaseLock(A){return this.memoryState.forceReleaseLock(A)}get(A){return this.memoryState.get(A)}getList(A){return this.memoryState.getList(A)}queueDepth(A){return this.memoryState.queueDepth(A)}releaseLock(A){return this.memoryState.releaseLock(A)}set(A,Q,w){return this.memoryState.set(A,Q,w)}setIfNotExists(A,Q,w){return this.memoryState.setIfNotExists(A,Q,w)}}function oJ1(A){let{discord:Q}=A;if(!Q)return new PE0({userName:A.userName,adapters:{},state:q50()});let w=dJ1({botToken:Q.botToken,publicKey:Q.publicKey,applicationId:Q.applicationId,mentionRoleIds:Q.mentionRoleIds});return A.gatewayLoop.setAdapter(w),new PE0({userName:A.userName,adapters:{discord:w},concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"},state:nJ1(A.runtimeState)})}class tE0{deps;constructor(A){this.deps=A}async subscribeOwnedThread(A,Q){if(!this.deps.isBotCreatedThread(A,Q))return;try{await A.subscribe(),await this.deps.getSubscriptions()?.set(A.id,{subscribedAt:new Date().toISOString()})}catch(w){this.deps.logger.debug("Discord thread subscription failed",{error:w,threadId:A.id})}}async shouldRouteSubscribedMessage(A,Q){if(this.deps.getPlatform(A)!=="discord")return!1;if(A.isDM)return!0;let w=await this.deps.getSubscriptions()?.get(A.id);if(!w)return!1;if(w.routingMode==="mention-required"){if(!Q.isMention&&!w.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,w);return Boolean(Q.isMention)}if(!await this.shouldRequireMentionInSubscribedThread(A))return!0;let $={...w,routingMode:"mention-required"};if(!Q.isMention&&!w.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,$);else await this.deps.getSubscriptions()?.set(A.id,$);return Boolean(Q.isMention)}async postMentionRequiredNotice(A,Q){await A.post("I\u2019ll stop auto-replying now that more people joined. Mention me if you need me."),await this.deps.getSubscriptions()?.set(A.id,{...Q,routingMode:"mention-required",mentionRequiredNoticeSent:!0})}async shouldRequireMentionInSubscribedThread(A){try{return(await A.getParticipants()).filter((B)=>!B.isBot&&!B.isMe).length>1}catch(Q){return this.deps.logger.debug("Failed to inspect Discord thread participants",{error:Q,threadId:A.id}),!1}}}c0();class eE0{deps;constructor(A){this.deps=A}async build(A,Q,w,B){let $={message:w.text.trim(),attachments:[],notices:[]};if(w.attachments.length===0)return $;if(!(B==="anchor"||B==="trusted"))return $;let D=this.deps.getUploadStore();if(!D)return $;for(let X of w.attachments){let H=X.name;if(!H)continue;let W=Gq(H,"upload"),f=sV(W,X.mimeType),Z=X.size??0,G=f00(W,f);if(!G){$.notices.push(`Unsupported file upload type: ${W}`);continue}if(!Z00(G,Z)){$.notices.push(`File upload too large: ${W}`);continue}try{let F=await this.readAttachmentData(X);if(!F)continue;let V=zq({filename:W,mediaType:f,content:F,fallbackFilename:"upload"});if(!V.ok){$.notices.push(V.message);continue}let b=await D.save({filename:V.filename,mediaType:V.mediaType,content:F,metadata:this.buildMetadata(A,Q,w)});$.attachments.push(aJ1(b.filename,b.mediaType,F,b.ref,V.kind==="text"))}catch(F){this.deps.logger.error("Failed to read chat attachment",{error:F,filename:W}),$.notices.push(`Could not read file upload: ${W}`)}}return $}async readAttachmentData(A){if(A.fetchData)return A.fetchData();if(!A.url)return;let Q=await fetch(A.url);if(!Q.ok)throw Error(`Attachment download failed with status ${Q.status}`);let w=await Q.arrayBuffer();return Buffer.from(new Uint8Array(w))}buildMetadata(A,Q,w){let B=this.deps.getThreadIdParts(Q.id);return{interfaceType:A,channelId:Q.id,parentChannelId:Q.channelId,messageId:w.id,uploaderId:w.author.userId,uploaderUsername:w.author.userName,...B.guildId?{guildId:B.guildId}:{},...B.threadId?{threadId:B.threadId}:{}}}}function sJ1(A,Q,w,B){return aJ1(A,Q,w,B,aV(A,Q))}function aJ1(A,Q,w,B,$){if($)return{kind:"text",filename:A,mediaType:Q,content:w.toString("utf8").replace(/^\uFEFF/,""),sizeBytes:w.byteLength,source:B};return{kind:"file",filename:A,mediaType:Q,data:w,sizeBytes:w.byteLength,source:B}}function wd(){return{namespace:"discord-chat",refKind:"discord-chat-upload",routePath:"/api/webhooks/chat/discord/uploads"}}var tJ1={name:"@brains/chat",private:!0,version:"0.2.0-alpha.136",description:"Discord Chat SDK 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:*","@chat-adapter/discord":"^4.29.0","@chat-adapter/state-memory":"^4.29.0",chat:"^4.29.0"},devDependencies:{"@brains/core":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest"}};var POQ=/https?:\/\/\S+/i,kOQ=/[\s\S]+/,OOQ="https://discord.com/api/v10",xOQ=K.object({type:K.literal("card"),children:K.array(K.object({type:K.string()}).passthrough()),imageUrl:K.string().optional(),subtitle:K.string().optional(),title:K.string().optional()}).passthrough(),ROQ=K.object({card:K.custom((A)=>xOQ.safeParse(A).success),fallbackText:K.string().optional()});class F50 extends AZ{threadRegistry=new w50;pendingApprovals;uploadContinuity;promptActions=new Map;toolStatusMessenger=new $y0(this.threadRegistry);cardBuilder=new Hy0({getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),registerPromptAction:(A,Q)=>this.registerPromptAction(A,Q)});artifactDelivery=new fy0({getContext:()=>this.context,getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),logger:this.logger});approvalCards=new Zy0({cardBuilder:this.cardBuilder,clearMessageComponents:(A,Q)=>this.clearDiscordMessageComponents(A,Q)});subscriptionRouter=new tE0({getSubscriptions:()=>this.discordSubscriptions,getPlatform:(A)=>this.getPlatform(A),isBotCreatedThread:(A,Q)=>this.isBotCreatedDiscordThread(A,Q),logger:this.logger});chatInputBuilder=new eE0({getUploadStore:()=>this.context?.uploads.scoped(wd()),getThreadIdParts:(A)=>this.getThreadIdParts(A),logger:this.logger});gatewayLoop;discordApp;discordSubscriptions;constructor(A={}){super("chat",tJ1,A,By0);this.gatewayLoop=new Ky0({getApp:()=>this.discordApp.instance,gatewayRunMs:this.config.gatewayRunMs,gatewayRestartDelayMs:this.config.gatewayRestartDelayMs,logger:this.logger}),this.discordApp=new Uy0({discord:this.config.adapters.discord,getUploadStore:()=>this.context?.uploads.scoped(wd()),buildApp:(Q)=>oJ1({userName:this.config.userName,discord:this.config.adapters.discord,gatewayLoop:this.gatewayLoop,runtimeState:Q})}),this.pendingApprovals=new xS({loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},onRestoreError:(Q,w)=>{this.logger.debug("Failed to load pending chat approvals",{error:Q,conversationId:w})}}),this.uploadContinuity=new ES({sourceKind:"discord-chat-upload",loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},restoreAttachment:async(Q)=>{let w=this.context?.uploads.scoped(wd());if(!w)throw Error("Chat upload store unavailable");let B=await w.read(Q);return sJ1(B.record.filename,B.record.mediaType,B.content,B.record.ref)},onLoadError:(Q,w)=>{this.logger.debug("Failed to load prior chat uploads",{error:Q,conversationId:w})},onRestoreError:(Q,w)=>{this.logger.debug("Failed to restore prior chat upload",{error:Q,uploadId:w})}})}async onRegister(A){await super.onRegister(A),this.discordSubscriptions=aE0(A.runtimeState),this.registerChatHandlers(this.discordApp.build(A.runtimeState))}getWebRoutes(){return this.discordApp.getWebRoutes()}createDaemon(){if(!this.config.adapters.discord)return;return{start:async()=>{await this.discordApp.initialize(),this.gatewayLoop.start()},stop:async()=>{await this.gatewayLoop.stop(),this.threadRegistry.clear(),this.uploadContinuity.clear(),this.toolStatusMessenger.clear(),await this.discordApp.shutdown()},healthCheck:async()=>({status:this.gatewayLoop.isRunning()?"healthy":"error",message:this.gatewayLoop.isRunning()?"Chat gateway loop running":"Chat gateway loop stopped",lastCheck:new Date})}}sendMessageToChannel({channelId:A,message:Q}){let w=this.threadRegistry.get(A);if(!w)return;let B=this.toDiscordCardOutput(Q);if(B){w.post(B).catch(($)=>this.logger.error("Failed to send chat message",{error:$,channelId:A}));return}if(typeof Q!=="string")return;for(let $ of pi(A,Q))w.post($).catch((Y)=>this.logger.error("Failed to send chat message",{error:Y,channelId:A}))}async sendMessageWithId({channelId:A,message:Q}){let w=this.threadRegistry.get(A);if(!w)return;let B=this.toDiscordCardOutput(Q);if(B){let Y=await w.post(B);return this.threadRegistry.trackMessage(w.id,Y),Y.id}if(typeof Q!=="string")return;let $;for(let Y of pi(A,Q))$=await w.post(Y),this.threadRegistry.trackMessage(w.id,$);return $?.id}async editMessage({channelId:A,messageId:Q,newMessage:w}){let B=this.threadRegistry.getMessage(A,Q);if(!B)return!1;try{let $=await B.edit(this.toDiscordCardOutput(w)??(typeof w==="string"?w:""));if(A)this.threadRegistry.trackMessage(A,$);return!0}catch{return!1}}supportsMessageEditing(){return!0}toDiscordCardOutput(A){let Q=ROQ.safeParse(A);if(!Q.success)return;let{card:w,fallbackText:B}=Q.data;if(B===void 0)return{card:w};return{card:w,fallbackText:B}}formatProgressOutput(A){return Xy0(A)}formatCompletionOutput(A){return Xy0(A)}async handleProgressEvent(A,Q){let w=A.metadata.interfaceType;if(w&&w!==this.id){if(!this.isEnabledPlatform(w))return;let B={...A,metadata:{...A.metadata,interfaceType:this.id}};await super.handleProgressEvent(B,B.metadata);return}await super.handleProgressEvent(A,Q)}async handleToolActivityEvent(A){if(A.interfaceType===this.id){await super.handleToolActivityEvent(A);return}if(!this.isEnabledPlatform(A.interfaceType))return;await super.handleToolActivityEvent({...A,interfaceType:this.id})}async handleToolStatusUpdate(A){if(A.interfaceType!==this.id||!A.channelId)return;await this.toolStatusMessenger.handle(A)}isEnabledPlatform(A){return vW1(A,Boolean(this.config.adapters.discord))}registerChatHandlers(A){if(A.onDirectMessage(async(Q,w,B,$)=>{await this.handleRoutedMessage(Q,w,$)}),A.onNewMention(async(Q,w,B)=>{let $=this.getPlatformConfig(Q);if($&&this.shouldRouteDiscordMessage(Q,w,$)&&!Q.isDM&&$.useThreads)await this.subscriptionRouter.subscribeOwnedThread(Q,w);await this.handleRoutedMessage(Q,w,B)}),A.onSubscribedMessage(async(Q,w,B)=>{if(!await this.subscriptionRouter.shouldRouteSubscribedMessage(Q,w))return;await this.handleRoutedMessage(Q,w,B)}),this.config.adapters.discord&&!this.config.adapters.discord.requireMention)A.onNewMessage(kOQ,async(Q,w,B)=>{await this.handleRoutedMessage(Q,w,B)});A.onNewMessage(POQ,async(Q,w)=>{await this.handlePassiveUrlCapture(Q,w)}),A.onAction([B50,Yy0],async(Q)=>{await this.handleApprovalAction(Q)}),A.onAction(Dy0,async(Q)=>{await this.handlePromptAction(Q)})}async handlePromptAction(A){if(!this.context||!A.thread||!A.value)return;let Q=A.adapter.name;if(!this.isEnabledPlatform(Q))return;let w=A.thread;if(!this.shouldHandleDiscordAction(w,Q))return;let B=this.promptActions.get(A.value);if(B?.threadId!==w.id){await w.post(this.formatNoticePayload("That suggested action is no longer available.","Action unavailable"));return}let $=this.getThreadIdParts(w.id),Y=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:$.channelId??w.channelId,isBot:Boolean(A.user.isBot)}),D=this.getConversationId(Q,w.id),X=w.id;await this.runAgentTurn({thread:w,channelId:X,logLabel:"Error handling chat prompt action",body:async()=>{if(!this.context)return;let H=await this.context.agent.chat(B.prompt,D,{userPermissionLevel:Y,interfaceType:Q,channelId:X,channelName:w.isDM?"DM":w.channelId,...this.buildActionEventMetadata(Q,w,A)});await this.renderAgentResponse({thread:w,channelId:X,conversationId:D,response:H,userPermissionLevel:Y})}})}async handleApprovalAction(A){if(!this.context||!A.thread||!A.value)return;let Q=A.adapter.name;if(!this.isEnabledPlatform(Q))return;let w=this.getConversationId(Q,A.thread.id);if(!(await this.getPendingApprovalIds(w)).has(A.value)){await A.thread.post(this.formatNoticePayload("That approval is no longer pending."));return}let $=A.thread;if(!this.shouldHandleDiscordAction($,Q))return;let Y=this.getThreadIdParts($.id),D=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:Y.channelId??$.channelId,isBot:Boolean(A.user.isBot)});await this.confirmApproval({thread:$,conversationId:w,approvalId:A.value,confirmed:A.actionId===B50,userPermissionLevel:D,metadata:this.buildActionEventMetadata(Q,$,A)})}shouldHandleDiscordAction(A,Q){if(Q!=="discord")return!0;let w=this.config.adapters.discord;if(!w)return!1;if(A.isDM&&!w.allowDMs)return!1;return this.isAllowedChannel(A,w)}isBotCreatedDiscordThread(A,Q){if(A.isDM)return!1;let w=this.getThreadIdParts(A.id);if(!w.threadId)return!1;let B=this.getRawDiscordChannelId(Q);return B!==void 0&&B!==w.threadId}getRawDiscordChannelId(A){let Q=A.raw;if(typeof Q!=="object"||Q===null)return;let w=Q.channel_id;return typeof w==="string"?w:void 0}async handleRoutedMessage(A,Q,w){if(!this.context)return;let B=this.getPlatform(A);if(B!=="discord")return;let $=this.getPlatformConfig(A);if(!$)return;if(!this.shouldRouteDiscordMessage(A,Q,$))return;await this.routeToAgent(B,A,Q,w)}shouldRouteDiscordMessage(A,Q,w){if(A.isDM&&!w.allowDMs)return!1;if(Q.author.isMe)return!1;if(Q.author.isBot&&!Q.isMention)return!1;if(!this.isAllowedChannel(A,w))return!1;return!0}async runAgentTurn(A){this.startProcessingInput(A.channelId);try{if(this.getPlatformConfig(A.thread)?.showTypingIndicator)await A.thread.startTyping().catch((Q)=>this.logger.debug("Typing indicator failed",{error:Q,channelId:A.channelId}));await A.body()}catch(Q){this.logger.error(A.logLabel,{error:Q,channelId:A.channelId}),await this.postTurnError(A.thread,A.channelId,Q)}finally{this.endProcessingInput()}}async postTurnError(A,Q,w){let B=this.formatErrorPayload(w),$=this.toDiscordCardOutput(B);if($){await A.post($);return}let Y=typeof B==="string"?B:"Message failed.";for(let D of pi(Q,Y))await A.post(D)}async routeToAgent(A,Q,w,B){if(!this.context)return;this.threadRegistry.set(Q);let $=this.getConversationId(A,Q.id),Y=Q.id,D=this.getPermissionContext(Q,w),X=this.context.permissions.getUserLevel(A,w.author.userId,D),H=await this.chatInputBuilder.build(A,Q,w,X),W=[...H.attachments];if(await this.attachPriorUploads($,H,X),await this.postUploadNotices(Q,H.notices),!H.message&&H.attachments.length===0)return;this.rememberUploadAttachments($,W),await this.runAgentTurn({thread:Q,channelId:Y,logLabel:"Error handling chat message",body:async()=>{if(!this.context)return;let f=await this.getPendingApprovalIds($);if(f.size>0){await this.handleConfirmationResponse(H.message,$,Q,f,X,this.buildUserMessageMetadata(A,Q,w));return}let Z=this.buildCoalescedAgentInput(H.message,B),G=await this.context.agent.chat(Z.message,$,{userPermissionLevel:X,interfaceType:A,channelId:Y,channelName:this.getChannelName(Q),...this.buildUserMessageMetadata(A,Q,w,Z.metadata),...H.attachments.length>0?{attachments:H.attachments}:{}});await this.renderAgentResponse({thread:Q,channelId:Y,conversationId:$,response:G,userPermissionLevel:X})}})}async renderAgentResponse(A){if(A.confirmation)this.syncPendingConfirmationsFromResponse(A.conversationId,A.response,A.confirmation.approvalId);else this.rememberPendingConfirmationsFromResponse(A.conversationId,A.response);await this.handleAgentResponseToolStatuses(A.response,A.conversationId);let Q=await this.artifactDelivery.resolve(A.response.cards,A.userPermissionLevel);if(A.confirmation)await this.approvalCards.resolve(A.conversationId,A.confirmation.approvalId,A.confirmation.confirmed);let w=A.confirmation?this.formatConfirmationResponsePayload(A.response,A.confirmation.confirmed,this.getRemainingApprovalHelp(A.conversationId,A.response),Q.deniedCardIds):this.formatAgentResponseText(A.response.text,A.response.cards,A.response.pendingConfirmations,Q.deniedCardIds),B=await this.sendAgentResponseWithFiles({thread:A.thread,channelId:A.channelId,message:w,files:Q.files}),$=await this.sendArtifactCards(A.thread,A.response.cards,Q.deniedCardIds);await this.sendSupplementalCards(A.thread,A.response.cards,A.response.pendingConfirmations),await this.approvalCards.trackPendingConfirmations(A.thread,A.conversationId,A.response.pendingConfirmations);let Y=$??B;if(Y)for(let D of D00(A.response))this.trackAgentResponseForJob(D,Y,A.channelId)}rememberPendingConfirmationsFromResponse(A,Q){this.pendingApprovals.rememberFromResponse(A,Q)}async getPendingApprovalIds(A){return this.pendingApprovals.getApprovalIds(A)}async handleConfirmationResponse(A,Q,w,B,$,Y){let D=re({message:A,approvalIds:B});if(D.kind==="not-confirmation"){this.pendingApprovals.deleteConversation(Q),await w.post(this.formatNoticePayload("No pending approval to resolve."));return}if(D.kind==="notice"){await w.post(this.formatNoticePayload(D.message));return}await this.confirmApproval({thread:w,conversationId:Q,approvalId:D.approvalId,confirmed:D.confirmed,userPermissionLevel:$,...Y?{metadata:Y}:{}})}async confirmApproval(A){let Q=await this.context?.agent.confirmPendingAction(A.conversationId,A.confirmed,A.approvalId,{userPermissionLevel:A.userPermissionLevel,interfaceType:"discord",channelId:A.thread.id,channelName:A.thread.isDM?"DM":A.thread.channelId,...A.metadata});if(this.removePendingApproval(A.conversationId,A.approvalId),!Q)return;await this.renderAgentResponse({thread:A.thread,channelId:A.thread.id,conversationId:A.conversationId,response:Q,userPermissionLevel:A.userPermissionLevel,confirmation:{approvalId:A.approvalId,confirmed:A.confirmed}})}formatNoticePayload(A,Q="Approval notice"){return{card:{type:"card",title:Q,children:[{type:"text",content:A}]},fallbackText:A}}formatErrorPayload(A){let Q=A instanceof Error?A.message:"Unknown error";return{card:{type:"card",title:"Message failed",children:[{type:"text",content:Q}]},fallbackText:`Message failed: ${Q}`}}formatAgentResponseText(A,Q,w,B){return w00({text:A,cards:Q,pendingConfirmations:w,deniedCardIds:B,formatCard:($)=>this.cardBuilder.formatStructuredCard($,B)}).join(`
2347
2347
 
2348
2348
  `)}formatConfirmationResponsePayload(A,Q,w,B){let $=B00({response:A,confirmed:Q,remainingApprovalHelp:w,deniedCardIds:B,formatCard:(Y)=>this.cardBuilder.formatStructuredCard(Y,B),formatPendingConfirmationHelp:Yx});return{card:{type:"card",title:Q00($.variant),children:$.parts.map((Y)=>({type:"text",content:Y}))},fallbackText:$.parts.join(`
2349
2349
 
@@ -2415,7 +2415,7 @@ ${UE0(A)}
2415
2415
  <p>Once built, this page will be replaced with your actual website.</p>
2416
2416
  </div>
2417
2417
  </body>
2418
- </html>`;var RI1={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.135",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@brains/plugins":"workspace:*","@hono/bun-compress":"^0.1.0",hono:"^4.7.10"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/messaging-service":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class iI extends GU{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",RI1,A,Gg0)}async onRegister(A){if(this.siteUrl=A.siteUrl,this.previewUrl=A.previewUrl,this.siteUrl)A.endpoints.register({label:"Site",url:this.siteUrl,priority:10}),A.interactions.register({id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:this.siteUrl,kind:"human",priority:10});if(this.config.enablePreview&&this.previewUrl)A.endpoints.register({label:"Preview",url:this.previewUrl,priority:20,visibility:"anchor"}),A.interactions.register({id:"preview",label:"Preview site",description:"Open the private preview build.",href:this.previewUrl,kind:"admin",priority:20,visibility:"anchor"});this.serverManager=new O50({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,w=this.siteUrl??A?.productionUrl??`http://localhost:${this.config.productionPort}`,B=this.previewUrl??A?.previewUrl??`http://localhost:${this.config.previewPort}`,$=[];if(Q){if($.push(`Production: ${w}`),A?.previewUrl)$.push(`Preview: ${B}`)}return{status:Q?"healthy":"error",message:Q?$.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!A?.previewUrl,production:Q,previewUrl:A?.previewUrl?B:void 0,productionUrl:Q?w:void 0}}}}}async handleProgressEvent(A,Q){}async ensureDistDirectories(){let{mkdir:A,writeFile:Q}=await import("fs/promises");if(this.config.enablePreview&&this.config.previewDistDir&&!hI1(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(vI1(this.config.previewDistDir,"index.html"),zg0),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!hI1(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(vI1(this.config.productionDistDir,"index.html"),zg0),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}CB();c0();Z0();var Hb1="vercel.ai.error",IxQ=Symbol.for(Hb1),CI1,yI1,mw=class A extends(yI1=Error,CI1=IxQ,yI1){constructor({name:Q,message:w,cause:B}){super(w);this[CI1]=!0,this.name=Q,this.cause=B}static isInstance(Q){return A.hasMarker(Q,Hb1)}static hasMarker(Q,w){let B=Symbol.for(w);return Q!=null&&typeof Q==="object"&&B in Q&&typeof Q[B]==="boolean"&&Q[B]===!0}},Wb1="AI_APICallError",fb1=`vercel.ai.error.${Wb1}`,bxQ=Symbol.for(fb1),EI1,gI1,lG8=class extends(gI1=mw,EI1=bxQ,gI1){constructor({message:A,url:Q,requestBodyValues:w,statusCode:B,responseHeaders:$,responseBody:Y,cause:D,isRetryable:X=B!=null&&(B===408||B===409||B===429||B>=500),data:H}){super({name:Wb1,message:A,cause:D});this[EI1]=!0,this.url=Q,this.requestBodyValues=w,this.statusCode=B,this.responseHeaders=$,this.responseBody=Y,this.isRetryable=X,this.data=H}static isInstance(A){return mw.hasMarker(A,fb1)}},Zb1="AI_EmptyResponseBodyError",Kb1=`vercel.ai.error.${Zb1}`,LxQ=Symbol.for(Kb1),TI1,SI1,pG8=class extends(SI1=mw,TI1=LxQ,SI1){constructor({message:A="Empty response body"}={}){super({name:Zb1,message:A});this[TI1]=!0}static isInstance(A){return mw.hasMarker(A,Kb1)}};function Ub1(A){if(A==null)return"unknown error";if(typeof A==="string")return A;if(A instanceof Error)return A.message;return JSON.stringify(A)}var Gb1="AI_InvalidArgumentError",zb1=`vercel.ai.error.${Gb1}`,NxQ=Symbol.for(zb1),mI1,uI1,qb1=class extends(uI1=mw,mI1=NxQ,uI1){constructor({message:A,cause:Q,argument:w}){super({name:Gb1,message:A,cause:Q});this[mI1]=!0,this.argument=w}static isInstance(A){return mw.hasMarker(A,zb1)}},Fb1="AI_InvalidPromptError",Vb1=`vercel.ai.error.${Fb1}`,jxQ=Symbol.for(Vb1),cI1,lI1,iG8=class extends(lI1=mw,cI1=jxQ,lI1){constructor({prompt:A,message:Q,cause:w}){super({name:Fb1,message:`Invalid prompt: ${Q}`,cause:w});this[cI1]=!0,this.prompt=A}static isInstance(A){return mw.hasMarker(A,Vb1)}},Jb1="AI_InvalidResponseDataError",Ib1=`vercel.ai.error.${Jb1}`,MxQ=Symbol.for(Ib1),pI1,iI1,dG8=class extends(iI1=mw,pI1=MxQ,iI1){constructor({data:A,message:Q=`Invalid response data: ${JSON.stringify(A)}.`}){super({name:Jb1,message:Q});this[pI1]=!0,this.data=A}static isInstance(A){return mw.hasMarker(A,Ib1)}},bb1="AI_JSONParseError",Lb1=`vercel.ai.error.${bb1}`,_xQ=Symbol.for(Lb1),dI1,nI1,qg0=class extends(nI1=mw,dI1=_xQ,nI1){constructor({text:A,cause:Q}){super({name:bb1,message:`JSON parsing failed: Text: ${A}.
2418
+ </html>`;var RI1={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.136",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@brains/plugins":"workspace:*","@hono/bun-compress":"^0.1.0",hono:"^4.7.10"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/messaging-service":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};class iI extends GU{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",RI1,A,Gg0)}async onRegister(A){if(this.siteUrl=A.siteUrl,this.previewUrl=A.previewUrl,this.siteUrl)A.endpoints.register({label:"Site",url:this.siteUrl,priority:10}),A.interactions.register({id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:this.siteUrl,kind:"human",priority:10});if(this.config.enablePreview&&this.previewUrl)A.endpoints.register({label:"Preview",url:this.previewUrl,priority:20,visibility:"anchor"}),A.interactions.register({id:"preview",label:"Preview site",description:"Open the private preview build.",href:this.previewUrl,kind:"admin",priority:20,visibility:"anchor"});this.serverManager=new O50({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,w=this.siteUrl??A?.productionUrl??`http://localhost:${this.config.productionPort}`,B=this.previewUrl??A?.previewUrl??`http://localhost:${this.config.previewPort}`,$=[];if(Q){if($.push(`Production: ${w}`),A?.previewUrl)$.push(`Preview: ${B}`)}return{status:Q?"healthy":"error",message:Q?$.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!A?.previewUrl,production:Q,previewUrl:A?.previewUrl?B:void 0,productionUrl:Q?w:void 0}}}}}async handleProgressEvent(A,Q){}async ensureDistDirectories(){let{mkdir:A,writeFile:Q}=await import("fs/promises");if(this.config.enablePreview&&this.config.previewDistDir&&!hI1(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(vI1(this.config.previewDistDir,"index.html"),zg0),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!hI1(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(vI1(this.config.productionDistDir,"index.html"),zg0),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}CB();c0();Z0();var Hb1="vercel.ai.error",IxQ=Symbol.for(Hb1),CI1,yI1,mw=class A extends(yI1=Error,CI1=IxQ,yI1){constructor({name:Q,message:w,cause:B}){super(w);this[CI1]=!0,this.name=Q,this.cause=B}static isInstance(Q){return A.hasMarker(Q,Hb1)}static hasMarker(Q,w){let B=Symbol.for(w);return Q!=null&&typeof Q==="object"&&B in Q&&typeof Q[B]==="boolean"&&Q[B]===!0}},Wb1="AI_APICallError",fb1=`vercel.ai.error.${Wb1}`,bxQ=Symbol.for(fb1),EI1,gI1,lG8=class extends(gI1=mw,EI1=bxQ,gI1){constructor({message:A,url:Q,requestBodyValues:w,statusCode:B,responseHeaders:$,responseBody:Y,cause:D,isRetryable:X=B!=null&&(B===408||B===409||B===429||B>=500),data:H}){super({name:Wb1,message:A,cause:D});this[EI1]=!0,this.url=Q,this.requestBodyValues=w,this.statusCode=B,this.responseHeaders=$,this.responseBody=Y,this.isRetryable=X,this.data=H}static isInstance(A){return mw.hasMarker(A,fb1)}},Zb1="AI_EmptyResponseBodyError",Kb1=`vercel.ai.error.${Zb1}`,LxQ=Symbol.for(Kb1),TI1,SI1,pG8=class extends(SI1=mw,TI1=LxQ,SI1){constructor({message:A="Empty response body"}={}){super({name:Zb1,message:A});this[TI1]=!0}static isInstance(A){return mw.hasMarker(A,Kb1)}};function Ub1(A){if(A==null)return"unknown error";if(typeof A==="string")return A;if(A instanceof Error)return A.message;return JSON.stringify(A)}var Gb1="AI_InvalidArgumentError",zb1=`vercel.ai.error.${Gb1}`,NxQ=Symbol.for(zb1),mI1,uI1,qb1=class extends(uI1=mw,mI1=NxQ,uI1){constructor({message:A,cause:Q,argument:w}){super({name:Gb1,message:A,cause:Q});this[mI1]=!0,this.argument=w}static isInstance(A){return mw.hasMarker(A,zb1)}},Fb1="AI_InvalidPromptError",Vb1=`vercel.ai.error.${Fb1}`,jxQ=Symbol.for(Vb1),cI1,lI1,iG8=class extends(lI1=mw,cI1=jxQ,lI1){constructor({prompt:A,message:Q,cause:w}){super({name:Fb1,message:`Invalid prompt: ${Q}`,cause:w});this[cI1]=!0,this.prompt=A}static isInstance(A){return mw.hasMarker(A,Vb1)}},Jb1="AI_InvalidResponseDataError",Ib1=`vercel.ai.error.${Jb1}`,MxQ=Symbol.for(Ib1),pI1,iI1,dG8=class extends(iI1=mw,pI1=MxQ,iI1){constructor({data:A,message:Q=`Invalid response data: ${JSON.stringify(A)}.`}){super({name:Jb1,message:Q});this[pI1]=!0,this.data=A}static isInstance(A){return mw.hasMarker(A,Ib1)}},bb1="AI_JSONParseError",Lb1=`vercel.ai.error.${bb1}`,_xQ=Symbol.for(Lb1),dI1,nI1,qg0=class extends(nI1=mw,dI1=_xQ,nI1){constructor({text:A,cause:Q}){super({name:bb1,message:`JSON parsing failed: Text: ${A}.
2419
2419
  Error message: ${Ub1(Q)}`,cause:Q});this[dI1]=!0,this.text=A}static isInstance(A){return mw.hasMarker(A,Lb1)}},Nb1="AI_LoadAPIKeyError",jb1=`vercel.ai.error.${Nb1}`,PxQ=Symbol.for(jb1),rI1,oI1,nG8=class extends(oI1=mw,rI1=PxQ,oI1){constructor({message:A}){super({name:Nb1,message:A});this[rI1]=!0}static isInstance(A){return mw.hasMarker(A,jb1)}},Mb1="AI_LoadSettingError",_b1=`vercel.ai.error.${Mb1}`,kxQ=Symbol.for(_b1),sI1,aI1,rG8=class extends(aI1=mw,sI1=kxQ,aI1){constructor({message:A}){super({name:Mb1,message:A});this[sI1]=!0}static isInstance(A){return mw.hasMarker(A,_b1)}},Pb1="AI_NoContentGeneratedError",kb1=`vercel.ai.error.${Pb1}`,OxQ=Symbol.for(kb1),tI1,eI1,oG8=class extends(eI1=mw,tI1=OxQ,eI1){constructor({message:A="No content generated."}={}){super({name:Pb1,message:A});this[tI1]=!0}static isInstance(A){return mw.hasMarker(A,kb1)}},Ob1="AI_NoSuchModelError",xb1=`vercel.ai.error.${Ob1}`,xxQ=Symbol.for(xb1),Ab1,Qb1,sG8=class extends(Qb1=mw,Ab1=xxQ,Qb1){constructor({errorName:A=Ob1,modelId:Q,modelType:w,message:B=`No such ${w}: ${Q}`}){super({name:A,message:B});this[Ab1]=!0,this.modelId=Q,this.modelType=w}static isInstance(A){return mw.hasMarker(A,xb1)}},Rb1="AI_TooManyEmbeddingValuesForCallError",hb1=`vercel.ai.error.${Rb1}`,RxQ=Symbol.for(hb1),wb1,Bb1,aG8=class extends(Bb1=mw,wb1=RxQ,Bb1){constructor(A){super({name:Rb1,message:`Too many values for a single embedding call. The ${A.provider} model "${A.modelId}" can only embed up to ${A.maxEmbeddingsPerCall} values per call, but ${A.values.length} values were provided.`});this[wb1]=!0,this.provider=A.provider,this.modelId=A.modelId,this.maxEmbeddingsPerCall=A.maxEmbeddingsPerCall,this.values=A.values}static isInstance(A){return mw.hasMarker(A,hb1)}},vb1="AI_TypeValidationError",Cb1=`vercel.ai.error.${vb1}`,hxQ=Symbol.for(Cb1),$b1,Yb1,FG=class A extends(Yb1=mw,$b1=hxQ,Yb1){constructor({value:Q,cause:w,context:B}){let $="Type validation failed";if(B==null?void 0:B.field)$+=` for ${B.field}`;if((B==null?void 0:B.entityName)||(B==null?void 0:B.entityId)){$+=" (";let Y=[];if(B.entityName)Y.push(B.entityName);if(B.entityId)Y.push(`id: "${B.entityId}"`);$+=Y.join(", "),$+=")"}super({name:vb1,message:`${$}: Value: ${JSON.stringify(Q)}.
2420
2420
  Error message: ${Ub1(w)}`,cause:w});this[$b1]=!0,this.value=Q,this.context=B}static isInstance(Q){return mw.hasMarker(Q,Cb1)}static wrap({value:Q,cause:w,context:B}){var $,Y,D;if(A.isInstance(w)&&w.value===Q&&(($=w.context)==null?void 0:$.field)===(B==null?void 0:B.field)&&((Y=w.context)==null?void 0:Y.entityName)===(B==null?void 0:B.entityName)&&((D=w.context)==null?void 0:D.entityId)===(B==null?void 0:B.entityId))return w;return new A({value:Q,cause:w,context:B})}},yb1="AI_UnsupportedFunctionalityError",Eb1=`vercel.ai.error.${yb1}`,vxQ=Symbol.for(Eb1),Db1,Xb1,tG8=class extends(Xb1=mw,Db1=vxQ,Xb1){constructor({functionality:A,message:Q=`'${A}' functionality not supported.`}){super({name:yb1,message:Q});this[Db1]=!0,this.functionality=A}static isInstance(A){return mw.hasMarker(A,Eb1)}};F1();IU();IU();IU();var cb1="AI_DownloadError",lb1=`vercel.ai.error.${cb1}`,CxQ=Symbol.for(lb1),gb1,Tb1,rW=class extends(Tb1=mw,gb1=CxQ,Tb1){constructor({url:A,statusCode:Q,statusText:w,cause:B,message:$=B==null?`Failed to download ${A}: ${Q} ${w}`:`Failed to download ${A}: ${B}`}){super({name:cb1,message:$,cause:B});this[gb1]=!0,this.url=A,this.statusCode=Q,this.statusText=w}static isInstance(A){return mw.hasMarker(A,lb1)}},Lg0=2147483648;async function pb1({response:A,url:Q,maxBytes:w=Lg0}){let B=A.headers.get("content-length");if(B!=null){let f=parseInt(B,10);if(!isNaN(f)&&f>w)throw new rW({url:Q,message:`Download of ${Q} exceeded maximum size of ${w} bytes (Content-Length: ${f}).`})}let $=A.body;if($==null)return new Uint8Array(0);let Y=$.getReader(),D=[],X=0;try{while(!0){let{done:f,value:Z}=await Y.read();if(f)break;if(X+=Z.length,X>w)throw new rW({url:Q,message:`Download of ${Q} exceeded maximum size of ${w} bytes.`});D.push(Z)}}finally{try{await Y.cancel()}finally{Y.releaseLock()}}let H=new Uint8Array(X),W=0;for(let f of D)H.set(f,W),W+=f.length;return H}function Ng0(A){let Q;try{Q=new URL(A)}catch(B){throw new rW({url:A,message:`Invalid URL: ${A}`})}if(Q.protocol==="data:")return;if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw new rW({url:A,message:`URL scheme must be http, https, or data, got ${Q.protocol}`});let w=Q.hostname;if(!w)throw new rW({url:A,message:"URL must have a hostname"});if(w==="localhost"||w.endsWith(".local")||w.endsWith(".localhost"))throw new rW({url:A,message:`URL with hostname ${w} is not allowed`});if(w.startsWith("[")&&w.endsWith("]")){let B=w.slice(1,-1);if(yxQ(B))throw new rW({url:A,message:`URL with IPv6 address ${w} is not allowed`});return}if(ib1(w)){if(Jg0(w))throw new rW({url:A,message:`URL with IP address ${w} is not allowed`});return}}function ib1(A){let Q=A.split(".");if(Q.length!==4)return!1;return Q.every((w)=>{let B=Number(w);return Number.isInteger(B)&&B>=0&&B<=255&&String(B)===w})}function Jg0(A){let Q=A.split(".").map(Number),[w,B]=Q;if(w===0)return!0;if(w===10)return!0;if(w===127)return!0;if(w===169&&B===254)return!0;if(w===172&&B>=16&&B<=31)return!0;if(w===192&&B===168)return!0;return!1}function yxQ(A){let Q=A.toLowerCase();if(Q==="::1")return!0;if(Q==="::")return!0;if(Q.startsWith("::ffff:")){let w=Q.slice(7);if(ib1(w))return Jg0(w);let B=w.split(":");if(B.length===2){let $=parseInt(B[0],16),Y=parseInt(B[1],16);if(!isNaN($)&&!isNaN(Y)){let D=$>>8&255,X=$&255,H=Y>>8&255,W=Y&255;return Jg0(`${D}.${X}.${H}.${W}`)}}}if(Q.startsWith("fc")||Q.startsWith("fd"))return!0;if(Q.startsWith("fe80"))return!0;return!1}var h3=({prefix:A,size:Q=16,alphabet:w="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:B="-"}={})=>{let $=()=>{let Y=w.length,D=Array(Q);for(let X=0;X<Q;X++)D[X]=w[Math.random()*Y|0];return D.join("")};if(A==null)return $;if(w.includes(B))throw new qb1({argument:"separator",message:`The separator "${B}" must not be part of the alphabet "${w}".`});return()=>`${A}${B}${$()}`},db1=h3();function jg0(A){if(A==null)return"unknown error";if(typeof A==="string")return A;if(A instanceof Error)return A.message;return JSON.stringify(A)}function nb1(A=globalThis){var Q,w,B;if(A.window)return"runtime/browser";if((Q=A.navigator)==null?void 0:Q.userAgent)return`runtime/${A.navigator.userAgent.toLowerCase()}`;if((B=(w=A.process)==null?void 0:w.versions)==null?void 0:B.node)return`runtime/node.js/${A.process.version.substring(0)}`;if(A.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function ExQ(A){if(A==null)return{};let Q={};if(A instanceof Headers)A.forEach((w,B)=>{Q[B.toLowerCase()]=w});else{if(!Array.isArray(A))A=Object.entries(A);for(let[w,B]of A)if(B!=null)Q[w.toLowerCase()]=B}return Q}function x50(A,...Q){let w=new Headers(ExQ(A)),B=w.get("user-agent")||"";return w.set("user-agent",[B,...Q].filter(Boolean).join(" ")),Object.fromEntries(w.entries())}var gxQ=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,TxQ=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Sb1(A){let Q=JSON.parse(A);if(Q===null||typeof Q!=="object")return Q;if(gxQ.test(A)===!1&&TxQ.test(A)===!1)return Q;return SxQ(Q)}function SxQ(A){let Q=[A];while(Q.length){let w=Q;Q=[];for(let B of w){if(Object.prototype.hasOwnProperty.call(B,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(B,"constructor")&&B.constructor!==null&&typeof B.constructor==="object"&&Object.prototype.hasOwnProperty.call(B.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let $ in B){let Y=B[$];if(Y&&typeof Y==="object")Q.push(Y)}}}return A}function mxQ(A){let{stackTraceLimit:Q}=Error;try{Error.stackTraceLimit=0}catch(w){return Sb1(A)}try{return Sb1(A)}finally{Error.stackTraceLimit=Q}}function Mg0(A){if(A.type==="object"||Array.isArray(A.type)&&A.type.includes("object")){A.additionalProperties=!1;let{properties:w}=A;if(w!=null)for(let B of Object.keys(w))w[B]=z_(w[B])}if(A.items!=null)A.items=Array.isArray(A.items)?A.items.map(z_):z_(A.items);if(A.anyOf!=null)A.anyOf=A.anyOf.map(z_);if(A.allOf!=null)A.allOf=A.allOf.map(z_);if(A.oneOf!=null)A.oneOf=A.oneOf.map(z_);let{definitions:Q}=A;if(Q!=null)for(let w of Object.keys(Q))Q[w]=z_(Q[w]);return A}function z_(A){if(typeof A==="boolean")return A;return Mg0(A)}var uxQ=Symbol("Let zodToJsonSchema decide on which parser to use"),mb1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},cxQ=(A)=>typeof A==="string"?{...mb1,name:A}:{...mb1,...A};function XH(){return{}}function lxQ(A,Q){var w,B,$;let Y={type:"array"};if(((w=A.type)==null?void 0:w._def)&&(($=(B=A.type)==null?void 0:B._def)==null?void 0:$.typeName)!==KA.ZodAny)Y.items=lB(A.type._def,{...Q,currentPath:[...Q.currentPath,"items"]});if(A.minLength)Y.minItems=A.minLength.value;if(A.maxLength)Y.maxItems=A.maxLength.value;if(A.exactLength)Y.minItems=A.exactLength.value,Y.maxItems=A.exactLength.value;return Y}function pxQ(A){let Q={type:"integer",format:"int64"};if(!A.checks)return Q;for(let w of A.checks)switch(w.kind){case"min":if(w.inclusive)Q.minimum=w.value;else Q.exclusiveMinimum=w.value;break;case"max":if(w.inclusive)Q.maximum=w.value;else Q.exclusiveMaximum=w.value;break;case"multipleOf":Q.multipleOf=w.value;break}return Q}function ixQ(){return{type:"boolean"}}function rb1(A,Q){return lB(A.type._def,Q)}var dxQ=(A,Q)=>{return lB(A.innerType._def,Q)};function ob1(A,Q,w){let B=w!=null?w:Q.dateStrategy;if(Array.isArray(B))return{anyOf:B.map(($,Y)=>ob1(A,Q,$))};switch(B){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return nxQ(A)}}var nxQ=(A)=>{let Q={type:"integer",format:"unix-time"};for(let w of A.checks)switch(w.kind){case"min":Q.minimum=w.value;break;case"max":Q.maximum=w.value;break}return Q};function rxQ(A,Q){return{...lB(A.innerType._def,Q),default:A.defaultValue()}}function oxQ(A,Q){return Q.effectStrategy==="input"?lB(A.schema._def,Q):XH()}function sxQ(A){return{type:"string",enum:Array.from(A.values)}}var axQ=(A)=>{if("type"in A&&A.type==="string")return!1;return"allOf"in A};function txQ(A,Q){let w=[lB(A.left._def,{...Q,currentPath:[...Q.currentPath,"allOf","0"]}),lB(A.right._def,{...Q,currentPath:[...Q.currentPath,"allOf","1"]})].filter(($)=>!!$),B=[];return w.forEach(($)=>{if(axQ($))B.push(...$.allOf);else{let Y=$;if("additionalProperties"in $&&$.additionalProperties===!1){let{additionalProperties:D,...X}=$;Y=X}B.push(Y)}}),B.length?{allOf:B}:void 0}function exQ(A){let Q=typeof A.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray(A.value)?"array":"object"};return{type:Q==="bigint"?"integer":Q,const:A.value}}var Fg0=void 0,sZ={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Fg0===void 0)Fg0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Fg0},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function sb1(A,Q){let w={type:"string"};if(A.checks)for(let B of A.checks)switch(B.kind){case"min":w.minLength=typeof w.minLength==="number"?Math.max(w.minLength,B.value):B.value;break;case"max":w.maxLength=typeof w.maxLength==="number"?Math.min(w.maxLength,B.value):B.value;break;case"email":switch(Q.emailStrategy){case"format:email":aZ(w,"email",B.message,Q);break;case"format:idn-email":aZ(w,"idn-email",B.message,Q);break;case"pattern:zod":MY(w,sZ.email,B.message,Q);break}break;case"url":aZ(w,"uri",B.message,Q);break;case"uuid":aZ(w,"uuid",B.message,Q);break;case"regex":MY(w,B.regex,B.message,Q);break;case"cuid":MY(w,sZ.cuid,B.message,Q);break;case"cuid2":MY(w,sZ.cuid2,B.message,Q);break;case"startsWith":MY(w,RegExp(`^${Vg0(B.value,Q)}`),B.message,Q);break;case"endsWith":MY(w,RegExp(`${Vg0(B.value,Q)}$`),B.message,Q);break;case"datetime":aZ(w,"date-time",B.message,Q);break;case"date":aZ(w,"date",B.message,Q);break;case"time":aZ(w,"time",B.message,Q);break;case"duration":aZ(w,"duration",B.message,Q);break;case"length":w.minLength=typeof w.minLength==="number"?Math.max(w.minLength,B.value):B.value,w.maxLength=typeof w.maxLength==="number"?Math.min(w.maxLength,B.value):B.value;break;case"includes":{MY(w,RegExp(Vg0(B.value,Q)),B.message,Q);break}case"ip":{if(B.version!=="v6")aZ(w,"ipv4",B.message,Q);if(B.version!=="v4")aZ(w,"ipv6",B.message,Q);break}case"base64url":MY(w,sZ.base64url,B.message,Q);break;case"jwt":MY(w,sZ.jwt,B.message,Q);break;case"cidr":{if(B.version!=="v6")MY(w,sZ.ipv4Cidr,B.message,Q);if(B.version!=="v4")MY(w,sZ.ipv6Cidr,B.message,Q);break}case"emoji":MY(w,sZ.emoji(),B.message,Q);break;case"ulid":{MY(w,sZ.ulid,B.message,Q);break}case"base64":{switch(Q.base64Strategy){case"format:binary":{aZ(w,"binary",B.message,Q);break}case"contentEncoding:base64":{w.contentEncoding="base64";break}case"pattern:zod":{MY(w,sZ.base64,B.message,Q);break}}break}case"nanoid":MY(w,sZ.nanoid,B.message,Q);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return w}function Vg0(A,Q){return Q.patternStrategy==="escape"?QRQ(A):A}var ARQ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function QRQ(A){let Q="";for(let w=0;w<A.length;w++){if(!ARQ.has(A[w]))Q+="\\";Q+=A[w]}return Q}function aZ(A,Q,w,B){var $;if(A.format||(($=A.anyOf)==null?void 0:$.some((Y)=>Y.format))){if(!A.anyOf)A.anyOf=[];if(A.format)A.anyOf.push({format:A.format}),delete A.format;A.anyOf.push({format:Q,...w&&B.errorMessages&&{errorMessage:{format:w}}})}else A.format=Q}function MY(A,Q,w,B){var $;if(A.pattern||(($=A.allOf)==null?void 0:$.some((Y)=>Y.pattern))){if(!A.allOf)A.allOf=[];if(A.pattern)A.allOf.push({pattern:A.pattern}),delete A.pattern;A.allOf.push({pattern:ub1(Q,B),...w&&B.errorMessages&&{errorMessage:{pattern:w}}})}else A.pattern=ub1(Q,B)}function ub1(A,Q){var w;if(!Q.applyRegexFlags||!A.flags)return A.source;let B={i:A.flags.includes("i"),m:A.flags.includes("m"),s:A.flags.includes("s")},$=B.i?A.source.toLowerCase():A.source,Y="",D=!1,X=!1,H=!1;for(let W=0;W<$.length;W++){if(D){Y+=$[W],D=!1;continue}if(B.i){if(X){if($[W].match(/[a-z]/)){if(H)Y+=$[W],Y+=`${$[W-2]}-${$[W]}`.toUpperCase(),H=!1;else if($[W+1]==="-"&&((w=$[W+2])==null?void 0:w.match(/[a-z]/)))Y+=$[W],H=!0;else Y+=`${$[W]}${$[W].toUpperCase()}`;continue}}else if($[W].match(/[a-z]/)){Y+=`[${$[W]}${$[W].toUpperCase()}]`;continue}}if(B.m){if($[W]==="^"){Y+=`(^|(?<=[\r
2421
2421
  ]))`;continue}else if($[W]==="$"){Y+=`($|(?=[\r
@@ -2425,7 +2425,7 @@ Error message: ${Ub1(w)}`,cause:w});this[$b1]=!0,this.value=Q,this.context=B}sta
2425
2425
 
2426
2426
  `)},flush(A){A.enqueue(`data: [DONE]
2427
2427
 
2428
- `)}})}},VvQ={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function ZL1({status:A,statusText:Q,headers:w,stream:B,consumeSseStream:$}){let Y=B.pipeThrough(new FvQ);if($){let[D,X]=Y.tee();Y=D,$({stream:X})}return new Response(Y.pipeThrough(new TextEncoderStream),{status:A,statusText:Q,headers:qvQ(w,VvQ)})}var Wd=z.record(z.string(),q_.optional()),uz8=R50(()=>Hd(z.union([z.strictObject({type:z.literal("text-start"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("text-end"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("error"),errorText:z.string()}),z.strictObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.strictObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.strictObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.strictObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.strictObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),z.strictObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.strictObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional()}),z.strictObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.strictObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.custom((A)=>typeof A==="string"&&A.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.strictObject({type:z.literal("start-step")}),z.strictObject({type:z.literal("finish-step")}),z.strictObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.strictObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.strictObject({type:z.literal("abort"),reason:z.string().optional()}),z.strictObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));function JvQ(A){return A.type.startsWith("data-")}function Pg0(A){return A.type.startsWith("tool-")}function IvQ(A){return A.type==="dynamic-tool"}function tb1(A){return Pg0(A)||IvQ(A)}function eb1(A){return A.type.split("-").slice(1).join("-")}function bvQ({lastMessage:A,messageId:Q}){return{message:(A==null?void 0:A.role)==="assistant"?A:{id:Q,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function LvQ({stream:A,messageMetadataSchema:Q,dataPartSchemas:w,runUpdateMessageJob:B,onError:$,onToolCall:Y,onData:D}){return A.pipeThrough(new TransformStream({async transform(X,H){await B(async({state:W,write:f})=>{var Z,G,F,V;function b(j){let E=W.message.parts.filter(tb1).find((y)=>y.toolCallId===j);if(E==null)throw new TC({chunkType:"tool-invocation",chunkId:j,message:`No tool invocation found for tool call ID "${j}".`});return E}function L(j){var g;let E=W.message.parts.find((T)=>Pg0(T)&&T.toolCallId===j.toolCallId),y=j,h=E;if(E!=null){if(E.state=j.state,h.input=y.input,h.output=y.output,h.errorText=y.errorText,h.rawInput=y.rawInput,h.preliminary=y.preliminary,j.title!==void 0)h.title=j.title;if(j.toolMetadata!==void 0)h.toolMetadata=j.toolMetadata;h.providerExecuted=(g=y.providerExecuted)!=null?g:E.providerExecuted;let T=y.providerMetadata;if(T!=null)if(j.state==="output-available"||j.state==="output-error"){let S=E;S.resultProviderMetadata=T}else E.callProviderMetadata=T}else W.message.parts.push({type:`tool-${j.toolName}`,toolCallId:j.toolCallId,state:j.state,title:j.title,...j.toolMetadata!==void 0?{toolMetadata:j.toolMetadata}:{},input:y.input,output:y.output,rawInput:y.rawInput,errorText:y.errorText,providerExecuted:y.providerExecuted,preliminary:y.preliminary,...y.providerMetadata!=null&&(j.state==="output-available"||j.state==="output-error")?{resultProviderMetadata:y.providerMetadata}:{},...y.providerMetadata!=null&&!(j.state==="output-available"||j.state==="output-error")?{callProviderMetadata:y.providerMetadata}:{}})}function N(j){var g,E;let y=W.message.parts.find((S)=>S.type==="dynamic-tool"&&S.toolCallId===j.toolCallId),h=j,T=y;if(y!=null){if(y.state=j.state,T.toolName=j.toolName,T.input=h.input,T.output=h.output,T.errorText=h.errorText,T.rawInput=(g=h.rawInput)!=null?g:T.rawInput,T.preliminary=h.preliminary,j.title!==void 0)T.title=j.title;if(j.toolMetadata!==void 0)T.toolMetadata=j.toolMetadata;T.providerExecuted=(E=h.providerExecuted)!=null?E:y.providerExecuted;let S=h.providerMetadata;if(S!=null)if(j.state==="output-available"||j.state==="output-error"){let c=y;c.resultProviderMetadata=S}else y.callProviderMetadata=S}else W.message.parts.push({type:"dynamic-tool",toolName:j.toolName,toolCallId:j.toolCallId,state:j.state,input:h.input,output:h.output,errorText:h.errorText,preliminary:h.preliminary,providerExecuted:h.providerExecuted,title:j.title,...j.toolMetadata!==void 0?{toolMetadata:j.toolMetadata}:{},...h.providerMetadata!=null&&(j.state==="output-available"||j.state==="output-error")?{resultProviderMetadata:h.providerMetadata}:{},...h.providerMetadata!=null&&!(j.state==="output-available"||j.state==="output-error")?{callProviderMetadata:h.providerMetadata}:{}})}async function _(j){if(j!=null){let g=W.message.metadata!=null?fL1(W.message.metadata,j):j;if(Q!=null)await C50({value:g,schema:Q,context:{field:"message.metadata",entityId:W.message.id}});W.message.metadata=g}}switch(X.type){case"text-start":{let j={type:"text",text:"",providerMetadata:X.providerMetadata,state:"streaming"};W.activeTextParts[X.id]=j,W.message.parts.push(j),f();break}case"text-delta":{let j=W.activeTextParts[X.id];if(j==null)throw new TC({chunkType:"text-delta",chunkId:X.id,message:`Received text-delta for missing text part with ID "${X.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});j.text+=X.delta,j.providerMetadata=(Z=X.providerMetadata)!=null?Z:j.providerMetadata,f();break}case"text-end":{let j=W.activeTextParts[X.id];if(j==null)throw new TC({chunkType:"text-end",chunkId:X.id,message:`Received text-end for missing text part with ID "${X.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});j.state="done",j.providerMetadata=(G=X.providerMetadata)!=null?G:j.providerMetadata,delete W.activeTextParts[X.id],f();break}case"reasoning-start":{let j={type:"reasoning",text:"",providerMetadata:X.providerMetadata,state:"streaming"};W.activeReasoningParts[X.id]=j,W.message.parts.push(j),f();break}case"reasoning-delta":{let j=W.activeReasoningParts[X.id];if(j==null)throw new TC({chunkType:"reasoning-delta",chunkId:X.id,message:`Received reasoning-delta for missing reasoning part with ID "${X.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});j.text+=X.delta,j.providerMetadata=(F=X.providerMetadata)!=null?F:j.providerMetadata,f();break}case"reasoning-end":{let j=W.activeReasoningParts[X.id];if(j==null)throw new TC({chunkType:"reasoning-end",chunkId:X.id,message:`Received reasoning-end for missing reasoning part with ID "${X.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});j.providerMetadata=(V=X.providerMetadata)!=null?V:j.providerMetadata,j.state="done",delete W.activeReasoningParts[X.id],f();break}case"file":{W.message.parts.push({type:"file",mediaType:X.mediaType,url:X.url,...X.providerMetadata!=null?{providerMetadata:X.providerMetadata}:{}}),f();break}case"source-url":{W.message.parts.push({type:"source-url",sourceId:X.sourceId,url:X.url,title:X.title,providerMetadata:X.providerMetadata}),f();break}case"source-document":{W.message.parts.push({type:"source-document",sourceId:X.sourceId,mediaType:X.mediaType,title:X.title,filename:X.filename,providerMetadata:X.providerMetadata}),f();break}case"tool-input-start":{let j=W.message.parts.filter(Pg0);if(W.partialToolCalls[X.toolCallId]={text:"",toolName:X.toolName,index:j.length,dynamic:X.dynamic,title:X.title,toolMetadata:X.toolMetadata},X.dynamic)N({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-streaming",input:void 0,providerExecuted:X.providerExecuted,title:X.title,toolMetadata:X.toolMetadata,providerMetadata:X.providerMetadata});else L({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-streaming",input:void 0,providerExecuted:X.providerExecuted,title:X.title,toolMetadata:X.toolMetadata,providerMetadata:X.providerMetadata});f();break}case"tool-input-delta":{let j=W.partialToolCalls[X.toolCallId];if(j==null)throw new TC({chunkType:"tool-input-delta",chunkId:X.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${X.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});j.text+=X.inputTextDelta;let{value:g}=await fd(j.text);if(j.dynamic)N({toolCallId:X.toolCallId,toolName:j.toolName,state:"input-streaming",input:g,title:j.title,toolMetadata:j.toolMetadata});else L({toolCallId:X.toolCallId,toolName:j.toolName,state:"input-streaming",input:g,title:j.title,toolMetadata:j.toolMetadata});f();break}case"tool-input-available":{if(X.dynamic)N({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-available",input:X.input,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:X.title,toolMetadata:X.toolMetadata});else L({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-available",input:X.input,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:X.title,toolMetadata:X.toolMetadata});if(f(),Y&&!X.providerExecuted)await Y({toolCall:X});break}case"tool-input-error":{let j=W.message.parts.filter(tb1).find((E)=>E.toolCallId===X.toolCallId);if(j!=null?j.type==="dynamic-tool":!!X.dynamic)N({toolCallId:X.toolCallId,toolName:X.toolName,state:"output-error",input:X.input,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,toolMetadata:X.toolMetadata});else L({toolCallId:X.toolCallId,toolName:X.toolName,state:"output-error",input:void 0,rawInput:X.input,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,toolMetadata:X.toolMetadata});f();break}case"tool-approval-request":{let j=b(X.toolCallId);j.state="approval-requested",j.approval={id:X.approvalId},f();break}case"tool-output-denied":{let j=b(X.toolCallId);j.state="output-denied",f();break}case"tool-output-available":{let j=b(X.toolCallId);if(j.type==="dynamic-tool")N({toolCallId:X.toolCallId,toolName:j.toolName,state:"output-available",input:j.input,output:X.output,preliminary:X.preliminary,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});else L({toolCallId:X.toolCallId,toolName:eb1(j),state:"output-available",input:j.input,output:X.output,providerExecuted:X.providerExecuted,preliminary:X.preliminary,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});f();break}case"tool-output-error":{let j=b(X.toolCallId);if(j.type==="dynamic-tool")N({toolCallId:X.toolCallId,toolName:j.toolName,state:"output-error",input:j.input,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});else L({toolCallId:X.toolCallId,toolName:eb1(j),state:"output-error",input:j.input,rawInput:j.rawInput,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});f();break}case"start-step":{W.message.parts.push({type:"step-start"});break}case"finish-step":{W.activeTextParts={},W.activeReasoningParts={};break}case"start":{if(X.messageId!=null)W.message.id=X.messageId;if(await _(X.messageMetadata),X.messageId!=null||X.messageMetadata!=null)f();break}case"finish":{if(X.finishReason!=null)W.finishReason=X.finishReason;if(await _(X.messageMetadata),X.messageMetadata!=null)f();break}case"message-metadata":{if(await _(X.messageMetadata),X.messageMetadata!=null)f();break}case"error":{$==null||$(Error(X.errorText));break}default:if(JvQ(X)){if((w==null?void 0:w[X.type])!=null){let E=W.message.parts.findIndex((h)=>("id"in h)&&("data"in h)&&h.id===X.id&&h.type===X.type),y=E>=0?E:W.message.parts.length;await C50({value:X.data,schema:w[X.type],context:{field:`message.parts[${y}].data`,entityName:X.type,entityId:X.id}})}let j=X;if(j.transient){D==null||D(j);break}let g=j.id!=null?W.message.parts.find((E)=>j.type===E.type&&j.id===E.id):void 0;if(g!=null)g.data=j.data;else W.message.parts.push(j);D==null||D(j),f()}}H.enqueue(X)})}}))}function NvQ({messageId:A,originalMessages:Q=[],onStepFinish:w,onFinish:B,onError:$,stream:Y}){let D=Q==null?void 0:Q[Q.length-1];if((D==null?void 0:D.role)!=="assistant")D=void 0;else A=D.id;let X=!1,H=Y.pipeThrough(new TransformStream({transform(V,b){if(V.type==="start"){let L=V;if(L.messageId==null&&A!=null)L.messageId=A}if(V.type==="abort")X=!0;b.enqueue(V)}}));if(B==null&&w==null)return H;let W=bvQ({lastMessage:D?structuredClone(D):void 0,messageId:A!=null?A:""}),f=async(V)=>{await V({state:W,write:()=>{}})},Z=!1,G=async()=>{if(Z||!B)return;Z=!0;let V=W.message.id===(D==null?void 0:D.id);await B({isAborted:X,isContinuation:V,responseMessage:W.message,messages:[...V?Q.slice(0,-1):Q,W.message],finishReason:W.finishReason})},F=async()=>{if(!w)return;let V=W.message.id===(D==null?void 0:D.id);try{await w({isContinuation:V,responseMessage:structuredClone(W.message),messages:[...V?Q.slice(0,-1):Q,structuredClone(W.message)]})}catch(b){$(b)}};return LvQ({stream:H,runUpdateMessageJob:f,onError:$}).pipeThrough(new TransformStream({async transform(V,b){if(V.type==="finish-step")await F();b.enqueue(V)},async cancel(){await G()},async flush(){await G()}}))}var cz8=h3({prefix:"aitxt",size:24});function KL1({execute:A,onError:Q=jg0,originalMessages:w,onStepFinish:B,onFinish:$,generateId:Y=db1}){let D,X=[],H=new ReadableStream({start(Z){D=Z}});function W(Z){try{D.enqueue(Z)}catch(G){}}try{let Z=A({writer:{write(G){W(G)},merge(G){X.push((async()=>{let F=G.getReader();while(!0){let{done:V,value:b}=await F.read();if(V)break;W(b)}})().catch((F)=>{W({type:"error",errorText:Q(F)})}))},onError:Q}});if(Z)X.push(Z.catch((G)=>{W({type:"error",errorText:Q(G)})}))}catch(Z){W({type:"error",errorText:Q(Z)})}return new Promise(async(Z)=>{while(X.length>0)await X.shift();Z()}).finally(()=>{try{D.close()}catch(Z){}}),NvQ({stream:H,messageId:Y(),originalMessages:w,onStepFinish:B,onFinish:$,onError:Q})}var PD=z.record(z.string(),q_.optional()),dz8=R50(()=>Hd(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerMetadata:b2.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:b2.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:b2.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var rz8=h3({prefix:"aiobj",size:24});function UL1(A){return({url:Q,abortSignal:w})=>thQ({url:Q,maxBytes:A==null?void 0:A.maxBytes,abortSignal:w})}var sz8=h3({prefix:"aiobj",size:24});var az8=UL1();var jvQ="AI_NoSuchProviderError",MvQ=`vercel.ai.error.${jvQ}`,_vQ=Symbol.for(MvQ),PvQ;PvQ=_vQ;var tz8=UL1();var GL1={name:"@brains/web-chat",private:!0,version:"0.2.0-alpha.135",description:"Web chat interface for Brains",type:"module",exports:{".":"./src/index.ts"},files:["src","dist","package.json"],scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",test:"bun test"},dependencies:{"@ai-sdk/react":"^3.0.116","@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@streamdown/cjk":"^1.0.3","@streamdown/code":"^1.1.1","@streamdown/math":"^1.0.2","@streamdown/mermaid":"^1.0.2",ai:"^6.0.86","class-variance-authority":"^0.7.0",cmdk:"^1.1.1","lucide-react":"^1.16.0",nanoid:"^5.0.4","radix-ui":"^1.4.3",react:"^19.2.6","react-dom":"^19.2.6",shiki:"^4.1.0",streamdown:"^2.5.0","use-stick-to-bottom":"^1.1.4"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/react":"^19.0.3","@types/react-dom":"^19.0.3",typescript:"^5.3.3",vite:"^7.2.4"}};c0();async function zL1(A,Q){let w=await Q.resolvePermissionLevel(A);if(w==="public")return Q.createOperatorLoginRequiredResponse(A);let B=new URL(A.url),$=B.searchParams.get("id")?.trim();if(!$)return new Response("Missing document id",{status:400});let Y=await FL1({entityType:"document",id:$,permissionLevel:w,entityService:Q.entityService});if(!Y)return new Response("Document not found",{status:404});if(typeof Y.content!=="string")return new Response("Document content is not a PDF",{status:415});let D=Wq("document",Y.content);if(!D)return new Response("Document content is not a PDF",{status:415});let X=fq(Y.metadata,$,"document",D.mimeType);return VL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function qL1(A,Q){let w=await Q.resolvePermissionLevel(A);if(w==="public")return Q.createOperatorLoginRequiredResponse(A);let B=new URL(A.url),$=B.searchParams.get("id")?.trim();if(!$)return new Response("Missing image id",{status:400});let Y=await FL1({entityType:"image",id:$,permissionLevel:w,entityService:Q.entityService});if(!Y)return new Response("Image not found",{status:404});if(typeof Y.content!=="string")return new Response("Image content is not an image",{status:415});let D=Wq("image",Y.content);if(!D)return new Response("Image content is not an image",{status:415});let X=fq(Y.metadata,$,"image",D.mimeType);return VL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function FL1(A){let Q={entityType:A.entityType,id:A.id},w=await Zq({entityRef:Q,userLevel:A.permissionLevel,getEntity:(B)=>A.entityService.getEntity(B),getVisibleEntity:(B,$)=>A.entityService.getEntity({...B,visibilityScope:$})});return w.status==="visible"?w.entity:void 0}function VL1(A){let Q=new Headers({"Content-Type":A.mediaType,"Content-Length":String(A.data.byteLength),"Content-Disposition":rV({disposition:A.requestUrl.searchParams.has("download")?"attachment":"inline",filename:A.filename})});return new Response(A.data,{headers:Q})}Z0();c0();var Zd="upload",JL1=tO;var OvQ={namespace:"upload",refKind:Zd,routePath:"/api/chat/uploads"};function y50(){return OvQ}c0();zG0();var IL1=H00;var bL1=W00;var xvQ="file",RvQ=16384;async function LL1(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let w=Number(A.headers.get("content-length"));if(Number.isFinite(w)&&w>bL1+RvQ)return new Response("File upload too large",{status:400});let B;try{B=await A.formData()}catch{return new Response("Invalid multipart upload",{status:400})}let $=B.get(xvQ);if(!($ instanceof File))return new Response("Missing upload file",{status:400});let Y=Buffer.from(await $.arrayBuffer()),D=zq({filename:$.name,mediaType:$.type,content:Y});if(!D.ok)return new Response(D.message,{status:400});let X=Q.getUploadStore(),H=await X.save({filename:D.filename,mediaType:D.mediaType,content:Y});return Response.json(X.toResponseBody(H),{status:201})}async function NL1(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let w=new URL(A.url).searchParams.get("id")?.trim();if(!w)return new Response("Missing upload id",{status:400});let B=await _L1(w,Q.getUploadStore());if(B instanceof Response)return B;let{record:$,content:Y}=B,D=PL1($,Y);if(D instanceof Response)return D;let X=new URL(A.url).searchParams.has("download")?"attachment":"inline",H=new Uint8Array(Y).buffer;return new Response(H,{headers:{"Content-Type":$.mediaType,"Content-Length":String(Y.byteLength),"Content-Disposition":rV({disposition:X,filename:$.filename})}})}function jL1(A){let Q=Gq(A.filename??IL1),w=vvQ(A.url);if(!w)return new Response(`Unsupported file upload URL: ${Q}`,{status:400});let B=zq({filename:Q,mediaType:A.mediaType,content:w.buffer});if(!B.ok)return new Response(B.message,{status:400});return kL1(B,w.buffer)}async function ML1(A,Q){let w=await _L1(A,Q);if(w instanceof Response)return w;let{record:B,content:$}=w,Y=PL1(B,$);if(Y instanceof Response)return Y;return kL1(Y,$,{kind:Zd,id:A})}async function _L1(A,Q){try{return await Q.read(A)}catch(w){if(w instanceof zU)return hvQ(w);throw w}}function PL1(A,Q){let w=zq({filename:A.filename,mediaType:A.mediaType,content:Q});if(!w.ok)return new Response(w.message,{status:400});return w}function kL1(A,Q,w){if(A.kind==="text")return{kind:"text",filename:A.filename,mediaType:A.mediaType,content:A.text,sizeBytes:A.sizeBytes,...w!==void 0?{source:w}:{}};return{kind:"file",filename:A.filename,mediaType:A.mediaType,data:new Uint8Array(Q),sizeBytes:A.sizeBytes,...w!==void 0?{source:w}:{}}}function hvQ(A){switch(A.code){case"invalid_ref":return new Response("Invalid upload ref",{status:400});case"invalid_metadata":return new Response("Invalid upload metadata",{status:500});case"not_found":return new Response("Upload not found",{status:404})}}function vvQ(A){let Q=/^data:[^,]*,(.*)$/s.exec(A);if(!Q)return null;let B=A.slice(5,A.indexOf(",")).split(";").some(($)=>$.toLowerCase()==="base64");try{let $=B?Buffer.from(Q[1]??"","base64"):Buffer.from(decodeURIComponent(Q[1]??""),"utf8");return{buffer:$,byteLength:$.byteLength}}catch{return null}}var CvQ=K.object({type:K.literal("text"),text:K.string()}),yvQ=K.object({type:K.literal("file"),mediaType:K.string().optional(),filename:K.string().optional(),url:K.string()}),EvQ=K.object({state:K.literal("approval-responded"),approval:K.object({id:K.string(),approved:K.boolean()})}).passthrough(),gvQ=K.object({id:K.string().optional(),role:K.string(),parts:K.array(K.unknown()).optional(),content:K.string().optional()}),OL1=K.object({id:K.string().optional(),messages:K.array(gvQ).min(1),trigger:K.string().optional()}),TvQ=K.object({kind:K.literal(Zd),id:K.string().regex(JL1)}),SvQ=K.object({type:K.literal("data-upload"),data:K.object({ref:TvQ})});async function xL1(A,Q){let w=mvQ(A);if(!w)return{message:"",attachments:[]};let B=[],$=[];for(let D of w.parts??[]){let X=CvQ.safeParse(D);if(X.success){if(X.data.text.length>0)B.push(X.data.text);continue}let H=yvQ.safeParse(D);if(H.success){let f=jL1(H.data);if(f instanceof Response)return f;$.push(f);continue}let W=SvQ.safeParse(D);if(W.success){let f=await ML1(W.data.data.ref.id,Q.uploadStore);if(f instanceof Response)return f;$.push(f);continue}if(uvQ(D)==="data-upload")return new Response("Invalid upload ref",{status:400})}return{message:B.length>0?B.join(`
2428
+ `)}})}},VvQ={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function ZL1({status:A,statusText:Q,headers:w,stream:B,consumeSseStream:$}){let Y=B.pipeThrough(new FvQ);if($){let[D,X]=Y.tee();Y=D,$({stream:X})}return new Response(Y.pipeThrough(new TextEncoderStream),{status:A,statusText:Q,headers:qvQ(w,VvQ)})}var Wd=z.record(z.string(),q_.optional()),uz8=R50(()=>Hd(z.union([z.strictObject({type:z.literal("text-start"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("text-delta"),id:z.string(),delta:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("text-end"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("error"),errorText:z.string()}),z.strictObject({type:z.literal("tool-input-start"),toolCallId:z.string(),toolName:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.strictObject({type:z.literal("tool-input-delta"),toolCallId:z.string(),inputTextDelta:z.string()}),z.strictObject({type:z.literal("tool-input-available"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),title:z.string().optional()}),z.strictObject({type:z.literal("tool-input-error"),toolCallId:z.string(),toolName:z.string(),input:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),errorText:z.string(),title:z.string().optional()}),z.strictObject({type:z.literal("tool-approval-request"),approvalId:z.string(),toolCallId:z.string()}),z.strictObject({type:z.literal("tool-output-available"),toolCallId:z.string(),output:z.unknown(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional(),preliminary:z.boolean().optional()}),z.strictObject({type:z.literal("tool-output-error"),toolCallId:z.string(),errorText:z.string(),providerExecuted:z.boolean().optional(),providerMetadata:b2.optional(),toolMetadata:Wd.optional(),dynamic:z.boolean().optional()}),z.strictObject({type:z.literal("tool-output-denied"),toolCallId:z.string()}),z.strictObject({type:z.literal("reasoning-start"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("reasoning-delta"),id:z.string(),delta:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("reasoning-end"),id:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:b2.optional()}),z.strictObject({type:z.literal("file"),url:z.string(),mediaType:z.string(),providerMetadata:b2.optional()}),z.strictObject({type:z.custom((A)=>typeof A==="string"&&A.startsWith("data-"),{message:'Type must start with "data-"'}),id:z.string().optional(),data:z.unknown(),transient:z.boolean().optional()}),z.strictObject({type:z.literal("start-step")}),z.strictObject({type:z.literal("finish-step")}),z.strictObject({type:z.literal("start"),messageId:z.string().optional(),messageMetadata:z.unknown().optional()}),z.strictObject({type:z.literal("finish"),finishReason:z.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:z.unknown().optional()}),z.strictObject({type:z.literal("abort"),reason:z.string().optional()}),z.strictObject({type:z.literal("message-metadata"),messageMetadata:z.unknown()})])));function JvQ(A){return A.type.startsWith("data-")}function Pg0(A){return A.type.startsWith("tool-")}function IvQ(A){return A.type==="dynamic-tool"}function tb1(A){return Pg0(A)||IvQ(A)}function eb1(A){return A.type.split("-").slice(1).join("-")}function bvQ({lastMessage:A,messageId:Q}){return{message:(A==null?void 0:A.role)==="assistant"?A:{id:Q,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function LvQ({stream:A,messageMetadataSchema:Q,dataPartSchemas:w,runUpdateMessageJob:B,onError:$,onToolCall:Y,onData:D}){return A.pipeThrough(new TransformStream({async transform(X,H){await B(async({state:W,write:f})=>{var Z,G,F,V;function b(j){let E=W.message.parts.filter(tb1).find((y)=>y.toolCallId===j);if(E==null)throw new TC({chunkType:"tool-invocation",chunkId:j,message:`No tool invocation found for tool call ID "${j}".`});return E}function L(j){var g;let E=W.message.parts.find((T)=>Pg0(T)&&T.toolCallId===j.toolCallId),y=j,h=E;if(E!=null){if(E.state=j.state,h.input=y.input,h.output=y.output,h.errorText=y.errorText,h.rawInput=y.rawInput,h.preliminary=y.preliminary,j.title!==void 0)h.title=j.title;if(j.toolMetadata!==void 0)h.toolMetadata=j.toolMetadata;h.providerExecuted=(g=y.providerExecuted)!=null?g:E.providerExecuted;let T=y.providerMetadata;if(T!=null)if(j.state==="output-available"||j.state==="output-error"){let S=E;S.resultProviderMetadata=T}else E.callProviderMetadata=T}else W.message.parts.push({type:`tool-${j.toolName}`,toolCallId:j.toolCallId,state:j.state,title:j.title,...j.toolMetadata!==void 0?{toolMetadata:j.toolMetadata}:{},input:y.input,output:y.output,rawInput:y.rawInput,errorText:y.errorText,providerExecuted:y.providerExecuted,preliminary:y.preliminary,...y.providerMetadata!=null&&(j.state==="output-available"||j.state==="output-error")?{resultProviderMetadata:y.providerMetadata}:{},...y.providerMetadata!=null&&!(j.state==="output-available"||j.state==="output-error")?{callProviderMetadata:y.providerMetadata}:{}})}function N(j){var g,E;let y=W.message.parts.find((S)=>S.type==="dynamic-tool"&&S.toolCallId===j.toolCallId),h=j,T=y;if(y!=null){if(y.state=j.state,T.toolName=j.toolName,T.input=h.input,T.output=h.output,T.errorText=h.errorText,T.rawInput=(g=h.rawInput)!=null?g:T.rawInput,T.preliminary=h.preliminary,j.title!==void 0)T.title=j.title;if(j.toolMetadata!==void 0)T.toolMetadata=j.toolMetadata;T.providerExecuted=(E=h.providerExecuted)!=null?E:y.providerExecuted;let S=h.providerMetadata;if(S!=null)if(j.state==="output-available"||j.state==="output-error"){let c=y;c.resultProviderMetadata=S}else y.callProviderMetadata=S}else W.message.parts.push({type:"dynamic-tool",toolName:j.toolName,toolCallId:j.toolCallId,state:j.state,input:h.input,output:h.output,errorText:h.errorText,preliminary:h.preliminary,providerExecuted:h.providerExecuted,title:j.title,...j.toolMetadata!==void 0?{toolMetadata:j.toolMetadata}:{},...h.providerMetadata!=null&&(j.state==="output-available"||j.state==="output-error")?{resultProviderMetadata:h.providerMetadata}:{},...h.providerMetadata!=null&&!(j.state==="output-available"||j.state==="output-error")?{callProviderMetadata:h.providerMetadata}:{}})}async function _(j){if(j!=null){let g=W.message.metadata!=null?fL1(W.message.metadata,j):j;if(Q!=null)await C50({value:g,schema:Q,context:{field:"message.metadata",entityId:W.message.id}});W.message.metadata=g}}switch(X.type){case"text-start":{let j={type:"text",text:"",providerMetadata:X.providerMetadata,state:"streaming"};W.activeTextParts[X.id]=j,W.message.parts.push(j),f();break}case"text-delta":{let j=W.activeTextParts[X.id];if(j==null)throw new TC({chunkType:"text-delta",chunkId:X.id,message:`Received text-delta for missing text part with ID "${X.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});j.text+=X.delta,j.providerMetadata=(Z=X.providerMetadata)!=null?Z:j.providerMetadata,f();break}case"text-end":{let j=W.activeTextParts[X.id];if(j==null)throw new TC({chunkType:"text-end",chunkId:X.id,message:`Received text-end for missing text part with ID "${X.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});j.state="done",j.providerMetadata=(G=X.providerMetadata)!=null?G:j.providerMetadata,delete W.activeTextParts[X.id],f();break}case"reasoning-start":{let j={type:"reasoning",text:"",providerMetadata:X.providerMetadata,state:"streaming"};W.activeReasoningParts[X.id]=j,W.message.parts.push(j),f();break}case"reasoning-delta":{let j=W.activeReasoningParts[X.id];if(j==null)throw new TC({chunkType:"reasoning-delta",chunkId:X.id,message:`Received reasoning-delta for missing reasoning part with ID "${X.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});j.text+=X.delta,j.providerMetadata=(F=X.providerMetadata)!=null?F:j.providerMetadata,f();break}case"reasoning-end":{let j=W.activeReasoningParts[X.id];if(j==null)throw new TC({chunkType:"reasoning-end",chunkId:X.id,message:`Received reasoning-end for missing reasoning part with ID "${X.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});j.providerMetadata=(V=X.providerMetadata)!=null?V:j.providerMetadata,j.state="done",delete W.activeReasoningParts[X.id],f();break}case"file":{W.message.parts.push({type:"file",mediaType:X.mediaType,url:X.url,...X.providerMetadata!=null?{providerMetadata:X.providerMetadata}:{}}),f();break}case"source-url":{W.message.parts.push({type:"source-url",sourceId:X.sourceId,url:X.url,title:X.title,providerMetadata:X.providerMetadata}),f();break}case"source-document":{W.message.parts.push({type:"source-document",sourceId:X.sourceId,mediaType:X.mediaType,title:X.title,filename:X.filename,providerMetadata:X.providerMetadata}),f();break}case"tool-input-start":{let j=W.message.parts.filter(Pg0);if(W.partialToolCalls[X.toolCallId]={text:"",toolName:X.toolName,index:j.length,dynamic:X.dynamic,title:X.title,toolMetadata:X.toolMetadata},X.dynamic)N({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-streaming",input:void 0,providerExecuted:X.providerExecuted,title:X.title,toolMetadata:X.toolMetadata,providerMetadata:X.providerMetadata});else L({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-streaming",input:void 0,providerExecuted:X.providerExecuted,title:X.title,toolMetadata:X.toolMetadata,providerMetadata:X.providerMetadata});f();break}case"tool-input-delta":{let j=W.partialToolCalls[X.toolCallId];if(j==null)throw new TC({chunkType:"tool-input-delta",chunkId:X.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${X.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});j.text+=X.inputTextDelta;let{value:g}=await fd(j.text);if(j.dynamic)N({toolCallId:X.toolCallId,toolName:j.toolName,state:"input-streaming",input:g,title:j.title,toolMetadata:j.toolMetadata});else L({toolCallId:X.toolCallId,toolName:j.toolName,state:"input-streaming",input:g,title:j.title,toolMetadata:j.toolMetadata});f();break}case"tool-input-available":{if(X.dynamic)N({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-available",input:X.input,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:X.title,toolMetadata:X.toolMetadata});else L({toolCallId:X.toolCallId,toolName:X.toolName,state:"input-available",input:X.input,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:X.title,toolMetadata:X.toolMetadata});if(f(),Y&&!X.providerExecuted)await Y({toolCall:X});break}case"tool-input-error":{let j=W.message.parts.filter(tb1).find((E)=>E.toolCallId===X.toolCallId);if(j!=null?j.type==="dynamic-tool":!!X.dynamic)N({toolCallId:X.toolCallId,toolName:X.toolName,state:"output-error",input:X.input,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,toolMetadata:X.toolMetadata});else L({toolCallId:X.toolCallId,toolName:X.toolName,state:"output-error",input:void 0,rawInput:X.input,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,toolMetadata:X.toolMetadata});f();break}case"tool-approval-request":{let j=b(X.toolCallId);j.state="approval-requested",j.approval={id:X.approvalId},f();break}case"tool-output-denied":{let j=b(X.toolCallId);j.state="output-denied",f();break}case"tool-output-available":{let j=b(X.toolCallId);if(j.type==="dynamic-tool")N({toolCallId:X.toolCallId,toolName:j.toolName,state:"output-available",input:j.input,output:X.output,preliminary:X.preliminary,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});else L({toolCallId:X.toolCallId,toolName:eb1(j),state:"output-available",input:j.input,output:X.output,providerExecuted:X.providerExecuted,preliminary:X.preliminary,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});f();break}case"tool-output-error":{let j=b(X.toolCallId);if(j.type==="dynamic-tool")N({toolCallId:X.toolCallId,toolName:j.toolName,state:"output-error",input:j.input,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});else L({toolCallId:X.toolCallId,toolName:eb1(j),state:"output-error",input:j.input,rawInput:j.rawInput,errorText:X.errorText,providerExecuted:X.providerExecuted,providerMetadata:X.providerMetadata,title:j.title,toolMetadata:j.toolMetadata});f();break}case"start-step":{W.message.parts.push({type:"step-start"});break}case"finish-step":{W.activeTextParts={},W.activeReasoningParts={};break}case"start":{if(X.messageId!=null)W.message.id=X.messageId;if(await _(X.messageMetadata),X.messageId!=null||X.messageMetadata!=null)f();break}case"finish":{if(X.finishReason!=null)W.finishReason=X.finishReason;if(await _(X.messageMetadata),X.messageMetadata!=null)f();break}case"message-metadata":{if(await _(X.messageMetadata),X.messageMetadata!=null)f();break}case"error":{$==null||$(Error(X.errorText));break}default:if(JvQ(X)){if((w==null?void 0:w[X.type])!=null){let E=W.message.parts.findIndex((h)=>("id"in h)&&("data"in h)&&h.id===X.id&&h.type===X.type),y=E>=0?E:W.message.parts.length;await C50({value:X.data,schema:w[X.type],context:{field:`message.parts[${y}].data`,entityName:X.type,entityId:X.id}})}let j=X;if(j.transient){D==null||D(j);break}let g=j.id!=null?W.message.parts.find((E)=>j.type===E.type&&j.id===E.id):void 0;if(g!=null)g.data=j.data;else W.message.parts.push(j);D==null||D(j),f()}}H.enqueue(X)})}}))}function NvQ({messageId:A,originalMessages:Q=[],onStepFinish:w,onFinish:B,onError:$,stream:Y}){let D=Q==null?void 0:Q[Q.length-1];if((D==null?void 0:D.role)!=="assistant")D=void 0;else A=D.id;let X=!1,H=Y.pipeThrough(new TransformStream({transform(V,b){if(V.type==="start"){let L=V;if(L.messageId==null&&A!=null)L.messageId=A}if(V.type==="abort")X=!0;b.enqueue(V)}}));if(B==null&&w==null)return H;let W=bvQ({lastMessage:D?structuredClone(D):void 0,messageId:A!=null?A:""}),f=async(V)=>{await V({state:W,write:()=>{}})},Z=!1,G=async()=>{if(Z||!B)return;Z=!0;let V=W.message.id===(D==null?void 0:D.id);await B({isAborted:X,isContinuation:V,responseMessage:W.message,messages:[...V?Q.slice(0,-1):Q,W.message],finishReason:W.finishReason})},F=async()=>{if(!w)return;let V=W.message.id===(D==null?void 0:D.id);try{await w({isContinuation:V,responseMessage:structuredClone(W.message),messages:[...V?Q.slice(0,-1):Q,structuredClone(W.message)]})}catch(b){$(b)}};return LvQ({stream:H,runUpdateMessageJob:f,onError:$}).pipeThrough(new TransformStream({async transform(V,b){if(V.type==="finish-step")await F();b.enqueue(V)},async cancel(){await G()},async flush(){await G()}}))}var cz8=h3({prefix:"aitxt",size:24});function KL1({execute:A,onError:Q=jg0,originalMessages:w,onStepFinish:B,onFinish:$,generateId:Y=db1}){let D,X=[],H=new ReadableStream({start(Z){D=Z}});function W(Z){try{D.enqueue(Z)}catch(G){}}try{let Z=A({writer:{write(G){W(G)},merge(G){X.push((async()=>{let F=G.getReader();while(!0){let{done:V,value:b}=await F.read();if(V)break;W(b)}})().catch((F)=>{W({type:"error",errorText:Q(F)})}))},onError:Q}});if(Z)X.push(Z.catch((G)=>{W({type:"error",errorText:Q(G)})}))}catch(Z){W({type:"error",errorText:Q(Z)})}return new Promise(async(Z)=>{while(X.length>0)await X.shift();Z()}).finally(()=>{try{D.close()}catch(Z){}}),NvQ({stream:H,messageId:Y(),originalMessages:w,onStepFinish:B,onFinish:$,onError:Q})}var PD=z.record(z.string(),q_.optional()),dz8=R50(()=>Hd(z.array(z.object({id:z.string(),role:z.enum(["system","user","assistant"]),metadata:z.unknown().optional(),parts:z.array(z.union([z.object({type:z.literal("text"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("reasoning"),text:z.string(),state:z.enum(["streaming","done"]).optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("source-url"),sourceId:z.string(),url:z.string(),title:z.string().optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("source-document"),sourceId:z.string(),mediaType:z.string(),title:z.string(),filename:z.string().optional(),providerMetadata:b2.optional()}),z.object({type:z.literal("file"),mediaType:z.string(),filename:z.string().optional(),url:z.string(),providerMetadata:b2.optional()}),z.object({type:z.literal("step-start")}),z.object({type:z.string().startsWith("data-"),id:z.string().optional(),data:z.unknown()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-streaming"),input:z.unknown().optional(),providerExecuted:z.boolean().optional(),callProviderMetadata:b2.optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.never().optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional()})}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-available"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-error"),input:z.unknown().optional(),rawInput:z.unknown().optional(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.literal("dynamic-tool"),toolName:z.string(),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-denied"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-streaming"),providerExecuted:z.boolean().optional(),callProviderMetadata:b2.optional(),input:z.unknown().optional(),output:z.never().optional(),errorText:z.never().optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("input-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.never().optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-requested"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.never().optional(),reason:z.never().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("approval-responded"),input:z.unknown(),providerExecuted:z.boolean().optional(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.boolean(),reason:z.string().optional()})}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-available"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.unknown(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),preliminary:z.boolean().optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-error"),providerExecuted:z.boolean().optional(),input:z.unknown().optional(),rawInput:z.unknown().optional(),output:z.never().optional(),errorText:z.string(),callProviderMetadata:b2.optional(),resultProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!0),reason:z.string().optional()}).optional()}),z.object({type:z.string().startsWith("tool-"),toolCallId:z.string(),toolMetadata:PD.optional(),state:z.literal("output-denied"),providerExecuted:z.boolean().optional(),input:z.unknown(),output:z.never().optional(),errorText:z.never().optional(),callProviderMetadata:b2.optional(),approval:z.object({id:z.string(),approved:z.literal(!1),reason:z.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));var rz8=h3({prefix:"aiobj",size:24});function UL1(A){return({url:Q,abortSignal:w})=>thQ({url:Q,maxBytes:A==null?void 0:A.maxBytes,abortSignal:w})}var sz8=h3({prefix:"aiobj",size:24});var az8=UL1();var jvQ="AI_NoSuchProviderError",MvQ=`vercel.ai.error.${jvQ}`,_vQ=Symbol.for(MvQ),PvQ;PvQ=_vQ;var tz8=UL1();var GL1={name:"@brains/web-chat",private:!0,version:"0.2.0-alpha.136",description:"Web chat interface for Brains",type:"module",exports:{".":"./src/index.ts"},files:["src","dist","package.json"],scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",test:"bun test"},dependencies:{"@ai-sdk/react":"^3.0.116","@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@streamdown/cjk":"^1.0.3","@streamdown/code":"^1.1.1","@streamdown/math":"^1.0.2","@streamdown/mermaid":"^1.0.2",ai:"^6.0.86","class-variance-authority":"^0.7.0",cmdk:"^1.1.1","lucide-react":"^1.16.0",nanoid:"^5.0.4","radix-ui":"^1.4.3",react:"^19.2.6","react-dom":"^19.2.6",shiki:"^4.1.0",streamdown:"^2.5.0","use-stick-to-bottom":"^1.1.4"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/react":"^19.0.3","@types/react-dom":"^19.0.3",typescript:"^5.3.3",vite:"^7.2.4"}};c0();async function zL1(A,Q){let w=await Q.resolvePermissionLevel(A);if(w==="public")return Q.createOperatorLoginRequiredResponse(A);let B=new URL(A.url),$=B.searchParams.get("id")?.trim();if(!$)return new Response("Missing document id",{status:400});let Y=await FL1({entityType:"document",id:$,permissionLevel:w,entityService:Q.entityService});if(!Y)return new Response("Document not found",{status:404});if(typeof Y.content!=="string")return new Response("Document content is not a PDF",{status:415});let D=Wq("document",Y.content);if(!D)return new Response("Document content is not a PDF",{status:415});let X=fq(Y.metadata,$,"document",D.mimeType);return VL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function qL1(A,Q){let w=await Q.resolvePermissionLevel(A);if(w==="public")return Q.createOperatorLoginRequiredResponse(A);let B=new URL(A.url),$=B.searchParams.get("id")?.trim();if(!$)return new Response("Missing image id",{status:400});let Y=await FL1({entityType:"image",id:$,permissionLevel:w,entityService:Q.entityService});if(!Y)return new Response("Image not found",{status:404});if(typeof Y.content!=="string")return new Response("Image content is not an image",{status:415});let D=Wq("image",Y.content);if(!D)return new Response("Image content is not an image",{status:415});let X=fq(Y.metadata,$,"image",D.mimeType);return VL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function FL1(A){let Q={entityType:A.entityType,id:A.id},w=await Zq({entityRef:Q,userLevel:A.permissionLevel,getEntity:(B)=>A.entityService.getEntity(B),getVisibleEntity:(B,$)=>A.entityService.getEntity({...B,visibilityScope:$})});return w.status==="visible"?w.entity:void 0}function VL1(A){let Q=new Headers({"Content-Type":A.mediaType,"Content-Length":String(A.data.byteLength),"Content-Disposition":rV({disposition:A.requestUrl.searchParams.has("download")?"attachment":"inline",filename:A.filename})});return new Response(A.data,{headers:Q})}Z0();c0();var Zd="upload",JL1=tO;var OvQ={namespace:"upload",refKind:Zd,routePath:"/api/chat/uploads"};function y50(){return OvQ}c0();zG0();var IL1=H00;var bL1=W00;var xvQ="file",RvQ=16384;async function LL1(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let w=Number(A.headers.get("content-length"));if(Number.isFinite(w)&&w>bL1+RvQ)return new Response("File upload too large",{status:400});let B;try{B=await A.formData()}catch{return new Response("Invalid multipart upload",{status:400})}let $=B.get(xvQ);if(!($ instanceof File))return new Response("Missing upload file",{status:400});let Y=Buffer.from(await $.arrayBuffer()),D=zq({filename:$.name,mediaType:$.type,content:Y});if(!D.ok)return new Response(D.message,{status:400});let X=Q.getUploadStore(),H=await X.save({filename:D.filename,mediaType:D.mediaType,content:Y});return Response.json(X.toResponseBody(H),{status:201})}async function NL1(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let w=new URL(A.url).searchParams.get("id")?.trim();if(!w)return new Response("Missing upload id",{status:400});let B=await _L1(w,Q.getUploadStore());if(B instanceof Response)return B;let{record:$,content:Y}=B,D=PL1($,Y);if(D instanceof Response)return D;let X=new URL(A.url).searchParams.has("download")?"attachment":"inline",H=new Uint8Array(Y).buffer;return new Response(H,{headers:{"Content-Type":$.mediaType,"Content-Length":String(Y.byteLength),"Content-Disposition":rV({disposition:X,filename:$.filename})}})}function jL1(A){let Q=Gq(A.filename??IL1),w=vvQ(A.url);if(!w)return new Response(`Unsupported file upload URL: ${Q}`,{status:400});let B=zq({filename:Q,mediaType:A.mediaType,content:w.buffer});if(!B.ok)return new Response(B.message,{status:400});return kL1(B,w.buffer)}async function ML1(A,Q){let w=await _L1(A,Q);if(w instanceof Response)return w;let{record:B,content:$}=w,Y=PL1(B,$);if(Y instanceof Response)return Y;return kL1(Y,$,{kind:Zd,id:A})}async function _L1(A,Q){try{return await Q.read(A)}catch(w){if(w instanceof zU)return hvQ(w);throw w}}function PL1(A,Q){let w=zq({filename:A.filename,mediaType:A.mediaType,content:Q});if(!w.ok)return new Response(w.message,{status:400});return w}function kL1(A,Q,w){if(A.kind==="text")return{kind:"text",filename:A.filename,mediaType:A.mediaType,content:A.text,sizeBytes:A.sizeBytes,...w!==void 0?{source:w}:{}};return{kind:"file",filename:A.filename,mediaType:A.mediaType,data:new Uint8Array(Q),sizeBytes:A.sizeBytes,...w!==void 0?{source:w}:{}}}function hvQ(A){switch(A.code){case"invalid_ref":return new Response("Invalid upload ref",{status:400});case"invalid_metadata":return new Response("Invalid upload metadata",{status:500});case"not_found":return new Response("Upload not found",{status:404})}}function vvQ(A){let Q=/^data:[^,]*,(.*)$/s.exec(A);if(!Q)return null;let B=A.slice(5,A.indexOf(",")).split(";").some(($)=>$.toLowerCase()==="base64");try{let $=B?Buffer.from(Q[1]??"","base64"):Buffer.from(decodeURIComponent(Q[1]??""),"utf8");return{buffer:$,byteLength:$.byteLength}}catch{return null}}var CvQ=K.object({type:K.literal("text"),text:K.string()}),yvQ=K.object({type:K.literal("file"),mediaType:K.string().optional(),filename:K.string().optional(),url:K.string()}),EvQ=K.object({state:K.literal("approval-responded"),approval:K.object({id:K.string(),approved:K.boolean()})}).passthrough(),gvQ=K.object({id:K.string().optional(),role:K.string(),parts:K.array(K.unknown()).optional(),content:K.string().optional()}),OL1=K.object({id:K.string().optional(),messages:K.array(gvQ).min(1),trigger:K.string().optional()}),TvQ=K.object({kind:K.literal(Zd),id:K.string().regex(JL1)}),SvQ=K.object({type:K.literal("data-upload"),data:K.object({ref:TvQ})});async function xL1(A,Q){let w=mvQ(A);if(!w)return{message:"",attachments:[]};let B=[],$=[];for(let D of w.parts??[]){let X=CvQ.safeParse(D);if(X.success){if(X.data.text.length>0)B.push(X.data.text);continue}let H=yvQ.safeParse(D);if(H.success){let f=jL1(H.data);if(f instanceof Response)return f;$.push(f);continue}let W=SvQ.safeParse(D);if(W.success){let f=await ML1(W.data.data.ref.id,Q.uploadStore);if(f instanceof Response)return f;$.push(f);continue}if(uvQ(D)==="data-upload")return new Response("Invalid upload ref",{status:400})}return{message:B.length>0?B.join(`
2429
2429
 
2430
2430
  `):w.content??"",attachments:$,...w.id?{messageId:w.id}:{}}}function RL1(A){let Q=A.messages.at(-1);if(!Q||Q.role==="user")return[];return(Q.parts??[]).map((w)=>EvQ.safeParse(w)).filter((w)=>w.success).map((w)=>w.data.approval)}function mvQ(A){for(let Q=A.messages.length-1;Q>=0;Q-=1){let w=A.messages[Q];if(w?.role==="user")return w}return}function uvQ(A){if(typeof A!=="object"||A===null||!("type"in A))return;let Q=A.type;return typeof Q==="string"?Q:void 0}c0();var cvQ=/\n{0,2}\[Entities affected this turn: [\s\S]*? Reference these IDs directly in follow-ups instead of searching for them\.\]\s*$/;function E50(A){return A.replace(cvQ,"").trimEnd()}c0();function hL1(A,Q,w){A.write({type:"text-start",id:Q}),A.write({type:"text-delta",id:Q,delta:w}),A.write({type:"text-end",id:Q})}function kg0(A,Q,w=new Set){for(let B of Q){if(B.kind==="attachment"&&w.has(B.id))continue;let $=z00(B);if($.kind==="attachment"){A.write({type:"data-attachment",id:$.id,data:$});continue}if($.kind==="sources"){A.write({type:"data-sources",id:$.id,data:$});continue}if($.kind==="actions"){A.write({type:"data-actions",id:$.id,data:$});continue}let Y=$.toolCallId??$.id,D=$.input??{};switch(A.write({type:"tool-input-available",toolCallId:Y,toolName:$.toolName,input:D,dynamic:!0,title:$.preview?`${$.summary}
2431
2431
 
@@ -4726,7 +4726,7 @@ details.web-chat-data-part[open] > summary > .web-chat-data-part-chevron {
4726
4726
 
4727
4727
  `);$=D.pop()??"";for(let X of D){let H=X.split(`
4728
4728
  `).find((L)=>L.startsWith("data: "));if(!H)continue;let W;try{W=JSON.parse(H.slice(6))}catch{return w.cancel().catch(()=>{}),{success:!1,error:"Malformed SSE event from remote agent"}}let f=W.result;if(!f)continue;if(f.final!==!0)continue;w.cancel().catch(()=>{});let G=f.status,F=G?.state??"unknown",b=(G?.message?.parts??[]).filter((L)=>L.kind==="text"&&typeof L.text==="string").map((L)=>L.text).join(`
4729
- `)||"No response text";return{success:!0,data:{state:F,response:b}}}Y=await XN1(w,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class Kd extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A;this.name="A2ARequestTimeoutError"}}class Ud extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A;this.name="A2AStreamIdleTimeoutError"}}async function zCQ(A,Q,w,B){let $=new AbortController,Y;try{return await Promise.race([A(Q,{...w,signal:$.signal}),new Promise((D,X)=>{Y=setTimeout(()=>{$.abort(),X(new Kd(B))},B)})])}catch(D){if(D instanceof Kd)throw D;if($.signal.aborted)throw new Kd(B);throw D}finally{if(Y)clearTimeout(Y)}}async function XN1(A,Q){let w;try{return await Promise.race([A.read(),new Promise((B,$)=>{w=setTimeout(()=>$(new Ud(Q)),Q)})])}catch(B){if(B instanceof Ud)A.cancel().catch(()=>{});throw B}finally{if(w)clearTimeout(w)}}function qCQ(A){if(A instanceof Kd||A instanceof Ud)return!0;return A instanceof Error}function FCQ(A,Q){let w=Q>1?` after ${Q} attempts`:"";if(A instanceof Ud)return`${A.message}${w}`;let B=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${w}: ${B}`}function WN1(A={}){let Q=A.fetch??globalThis.fetch,w={requestTimeoutMs:A.requestTimeoutMs??WCQ,streamIdleTimeoutMs:A.streamIdleTimeoutMs??fCQ,maxNetworkAttempts:A.maxNetworkAttempts??ZCQ};return{name:"agent_call",description:"Call a remote A2A agent by exact domain-like target or saved local agent id. Use this when the user asks what an exact domain-like agent id has to say, asks to talk/message/contact that id, or asks that agent for its skills/capabilities. For saved agents, the tool enforces approved/not-archived status before network contact. For unsaved exact domains, the tool verifies the A2A Agent Card over HTTPS and may perform a one-shot call without saving; it returns a typed save/connect candidate after success. Use bare ids such as yeehaa.io, docs.rizom.ai, or save-it-regression.example; .example test domains are exact domain-like ids. If the user provides an HTTPS URL such as https://docs.rizom.ai/a2a, pass only the hostname docs.rizom.ai. For follow-ups to a prior exact-id call, call again with the same id so the tool revalidates current state. Never pass a full URL, a display name like Brain, or a non-HTTPS URL. If the user gives an ambiguous name, ask them to connect/save or clarify the agent first.",inputSchema:$N1,visibility:"trusted",sideEffects:"external",handler:async(B)=>{let $=K.object($N1).safeParse(B);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};let{agent:Y,message:D}=$.data,X=KCQ(Y);if(!X.ok)return{success:!1,error:X.error};let{agentId:H}=X;if(!A.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let W=await A.entityService.getEntity({entityType:"agent",id:H,visibilityScope:R9("agent_call tool is anchor-only and resolves saved remote agents at any visibility")});if(!W){if(!UCQ(H))return{success:!1,error:`Agent ${Y} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let V=`https://${H}`,b=await YN1(V,Q);if(!b)return{success:!1,error:`Could not verify an A2A Agent Card for ${H}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"};let L=await DN1(b.url,D,Q,void 0,w);if("success"in L&&L.success===!0){let N=typeof L.data==="object"&&L.data!==null?L.data:{};return{...L,data:{...N,agentCall:{mode:"one-shot",agent:H},agentContactCandidate:{source:{kind:"url",url:X.sourceUrl??H}}}}}return L}if(W.metadata.status==="archived")return{success:!1,error:`Agent ${H} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(W.metadata.status!=="approved")return{success:!1,error:`Agent ${H} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let f=`https://${H}`,Z=await YN1(f,Q);if(!Z)return{success:!1,error:`Could not fetch Agent Card from ${f}`};let G=Z.url,F;if(A.outboundTokens)try{let V=new URL(G).hostname;F=A.outboundTokens[V]}catch{}return DN1(G,D,Q,F,w)}}}var Eg0={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.135",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 JCQ={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff"};class mC extends GU{agentCard;taskManager=new Cg0;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",Eg0,A,sL1)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agent,this.permissionContext=A.permissions,this.hasWebserver)A.endpoints.register({label:"A2A",url:"/a2a",priority:25}),A.interactions.register({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),this.logger.info("A2A interface registered",{domain:A.domain});else this.logger.info("A2A interface registered in tool-only mode",{domain:A.domain})}async onReady(A){await this.rebuildAgentCard(A)}async rebuildAgentCard(A){let Q=A.identity.get(),w=A.identity.getProfile(),B=A.tools.listForPermissionLevel("public"),$=this.config.trustedTokens&&Object.keys(this.config.trustedTokens).length>0,Y;if(A.entityService.hasEntityType("skill"))try{let D=await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}});if(D.length>0)Y=D.map((X)=>NX.safeParse(X.metadata)).filter((X)=>X.success).map((X)=>X.data)}catch{}this.agentCard=aL1({character:Q,profile:w,version:Eg0.version,domain:A.domain,organization:this.config.organization,tools:B,skills:Y,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),w=this.config.trustedTokens[Q];if(!w||!this.permissionContext)return"public";return this.permissionContext.getUserLevel("a2a",w)}withCors(A){let Q=new Headers(A.headers);for(let[w,B]of Object.entries(JCQ))Q.set(w,B);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}getOrCreateApp(){if(this.app)return this.app;let A=new CC;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 w;try{w=await Q.req.json()}catch{return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let B=AN1.safeParse(w);if(!B.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(B.data.method==="message/stream"){let D=wN1.safeParse(B.data.params??{});if(!D.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${D.error.message}`},id:B.data.id}));let{stream:X}=BN1(B.data.id,D.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(new Response(X,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let Y=await QN1(B.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(Q.json(Y))}),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[WN1({outboundTokens:this.config.outboundTokens,requestTimeoutMs:this.config.requestTimeoutMs,streamIdleTimeoutMs:this.config.streamIdleTimeoutMs,maxNetworkAttempts:this.config.maxNetworkAttempts,entityService:this.getContext().entityService})]}async getInstructions(){return"## Agent-to-agent calls\n- Use `agent_call` for exact domain-like agent ids (for example `yeehaa.io`, `docs.rizom.ai`, or `save-it-regression.example`). A domain-like id is bare text with a dot and no slash/protocol; `.example` test domains are still exact domain-like ids. For saved agents, the tool validates approval before network contact. For unsaved exact domains, it verifies the Agent Card over HTTPS and may perform a one-shot call without saving.\n- Pass only an exact domain-like agent id to `agent_call`. If the user provides an HTTPS URL, pass only its hostname as the agent id (for `https://docs.rizom.ai/a2a`, pass `docs.rizom.ai`). Never pass a full URL, a non-HTTPS URL, or a display name like `Brain`.\n- If the user names an exact domain-like agent id such as `yeehaa.io`, `docs.rizom.ai`, or `refusal-followup.example`, call `agent_call` directly with that id. Do not preflight with `system_list` or `system_get`; the tool reports structured errors such as invalid Agent Card, not approved, or archived.\n- If the user asks you to ask, message, contact, hear what an exact domain-like agent id has to say, or ask that agent for its own skills/capabilities, treat that as an agent call request first and call `agent_call` in the same turn. Do not stop after listing the agent, drafting the question, searching general content locally, or reading saved agent entity metadata.\n- After `agent_call` returns within a turn, answer that turn from its response. Do **not** supplement with `system_get` (or any other read tool) on the agent entity, unless the user explicitly asks for directory/profile details about the agent itself.\n- Do not create, capture, or generate a note containing the user's question in the same turn as an agent contact request. The user asked to ask the agent, not to persist the question.\n- If `agent_call` succeeds for an unsaved one-shot domain, you may offer to save/connect that agent for future calls, but do not auto-save it.\n- If `agent_call` fails because auth, re-authentication, network, invalid Agent Card, or the remote agent is unavailable, report that failure directly. Do not say the agent was saved, connected, or may need to be saved/connected first. If useful, offer to add the agent contact using the word \"add\". Do not answer from memory, local docs, onboarding docs, or general knowledge; the requested agent was the source.\n- Each new turn that asks the same exact domain-like agent id something \u2014 including short follow-ups like \"what skills does it have\", \"and what about X\", \"tell me more\" \u2014 is a **new** contact request and needs its **own** fresh `agent_call`. Do not assume the previous turn's agent response already covers a new question, and do not substitute `system_list`/`system_get` or a no-tool answer for the fresh call. If the previous turn targeted an exact domain-like id such as `yeehaa.io`, use that same id again for the follow-up even if the previous response was a refusal or error; let `agent_call` validate the current directory state again.\n- When the user provides an HTTPS URL for an agent, use its hostname as the exact domain-like id for `agent_call`; the runtime verifies/contact over HTTPS. If the user provides a non-HTTPS URL, ask for the HTTPS agent URL or exact domain-like id instead.\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 `agent_call` later in the same turn.\n- If `agent_call` reports that an exact domain-like agent id cannot be verified, tell the user the agent could not be verified/contacted. Do not create a wish, reminder, todo, note, fallback task, or any new entity.\n- For non-HTTPS URLs and ambiguous display names, do not call `agent_call`; ask the user for the HTTPS agent URL, exact domain-like id, or a clarification first.\n- Use `agent_connect`, not generic entity creation, when the user explicitly asks you to add, save, or connect an agent contact.\n- If the target agent is discovered but not approved yet, do not call it and do not create a wish. Tell the user it must be approved first."}createDaemon(){return{start:async()=>{if(this.hasWebserver)this.logger.info("A2A mounted on shared webserver host");else this.logger.info("A2A running without webserver routes")},stop:async()=>{this.logger.info("A2A server stopped")}}}}c0();class gg0{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,w,B,$=!0){if(this.logger=A,this.fileOperations=B,this.deleteOnFileRemoval=$,w)this.handleImport=async(Y)=>{let D=await w({type:"directory-import",data:{paths:[Y]}});this.logger.debug("Queued import job for file change",{jobId:D,path:Y})},this.handleDelete=async(Y)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:Y});return}try{let{entityType:D,id:X}=this.fileOperations.parseEntityFromPath(Y),H=await w({type:"directory-delete",data:{entityId:X,entityType:D,filePath:Y}});this.logger.info("Queued delete job for removed file",{jobId:H,path:Y,entityId:X,entityType:D})}catch(D){this.logger.warn("Could not extract entity info from deleted file",{path:Y,error:D})}};else this.handleImport=async(Y)=>{await Q([Y])},this.handleDelete=async(Y)=>{this.logger.warn("File deleted but no job queue available",{path:Y})}}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(w){this.logger.error("Failed to handle file change",{event:A,path:Q,error:w})}}}var PM1=X1(jM1(),1);import{extname as FSQ}from"path";var B$0=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function I_(A){let Q=FSQ(A).toLowerCase();return B$0.includes(Q)}function MM1(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 ET0(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as VSQ,relative as JSQ,sep as _M1,join as ISQ}from"path";function oW(A,Q){return VSQ(Q)?Q:ISQ(A,Q)}function nC(A,Q){let w=oW(A,Q),B=JSQ(A,w);return _M1==="/"?B:B.split(_M1).join("/")}function bSQ(A,Q){if(!nC(Q,A).startsWith("image/"))return!1;return I_(A)}function LSQ(A,Q){if(nC(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return bSQ(A,Q)}class gT0{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=PM1.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(!LSQ(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let w=nC(this.syncPath,Q);if(this.pendingChanges.set(w,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,w]of A){let B=oW(this.syncPath,Q);try{if(this.onFileChange)await this.onFileChange(w,B)}catch($){this.logger.error("Error processing file change",{path:Q,event:w,error:$})}}}isWatching(){return!!this.watcher}getPendingChangesCount(){return this.pendingChanges.size}}async function kM1(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return NSQ(Q)}function OM1(A){if(A)A.stop();return}function xM1(A,Q){if(A)A.setCallback(Q)}async function NSQ(A){let{logger:Q,syncPath:w,watchInterval:B,importEntities:$,jobQueueCallback:Y,fileOperations:D,deleteOnFileRemoval:X}=A,H=new gg0(Q,$,Y,D,X),W=new gT0({syncPath:w,watchInterval:B,logger:Q,onFileChange:async(f,Z)=>{await H.handleFileChange(f,Z)}});return await W.start(),W}async function RM1(A){let Q=Date.now();A.logger.debug("Starting sync (import only)");let w=await A.importEntities(),B=await A.removeOrphanedEntities(),$=Date.now()-Q;return A.markSynced(new Date),A.logger.debug("Sync completed",{duration:$,imported:w.imported,orphansDeleted:B.deleted}),{export:{exported:0,failed:0,errors:[]},import:w,duration:$}}c0();class TT0{logger;syncPath;deleteOnFileRemoval;constructor(A){this.logger=A.logger,this.syncPath=A.syncPath,this.deleteOnFileRemoval=A.deleteOnFileRemoval}prepareBatchOperations(A){let Q=[],w=this.createImportOperations(A);Q.push(...w);let B=w.length;if(this.deleteOnFileRemoval)Q.push({type:"directory-cleanup",data:{}});let $=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:B,totalFiles:$}),{operations:Q,exportOperationsCount:0,importOperationsCount:B,totalFiles:$}}async queueSyncBatch(A,Q,w,B){let $=this.prepareBatchOperations(w);if($.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch($.operations,{source:Q,rootJobId:B?.rootJobId??S$(),metadata:{progressToken:B?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:B?.pluginId??"directory-sync",interfaceType:B?.interfaceType,channelId:B?.channelId}}),operationCount:$.operations.length,exportOperationsCount:$.exportOperationsCount,importOperationsCount:$.importOperationsCount,totalFiles:$.totalFiles}}createImportOperations(A){if(A.length===0)return[];let Q=50,w=[];for(let B=0;B<A.length;B+=Q){let $=A.slice(B,B+Q);w.push({type:"directory-import",data:{batchIndex:Math.floor(B/Q),paths:$,batchSize:$.length}})}return w}}class ST0{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new TT0({logger:A.logger,syncPath:A.syncPath,deleteOnFileRemoval:A.deleteOnFileRemoval})}async queueSyncBatch(A,Q,w){if(this.syncInProgress)return this.logger.debug("Sync already in progress, skipping",{source:Q}),null;this.syncInProgress=!0;try{let B=await this.fileOperations.getAllSyncFiles();return await this.batchOperationsManager.queueSyncBatch(A,Q,B,w)}finally{this.syncInProgress=!1}}}class mT0{options;constructor(A){this.options=A}createExportDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImportDeps(A){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,quarantine:this.options.quarantine,imageJobQueue:this.createImageJobQueueDeps(),entityTypes:A}}createCleanupDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImageJobQueueDeps(){return{logger:this.options.logger,syncPath:this.options.syncPath,jobQueueCallback:this.options.getJobQueueCallback(),coverImageConverter:this.options.coverImageConverter,inlineImageConverter:this.options.inlineImageConverter}}}import{basename as OSQ,dirname as xSQ,extname as RSQ}from"path";import{extname as jSQ}from"path";var $$0=[".pdf"],hM1=".meta.json";function b_(A){let Q=jSQ(A).toLowerCase();return $$0.includes(Q)}function vM1(A){return A.toLowerCase().endsWith(hM1)}function uT0(A){return`${A}${hM1}`}function CM1(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as MSQ,join as Y$0}from"path";function D$0(A,Q){let B=nC(A,Q).split("/"),$,Y;if(B.length===1)$="note",Y=B;else if(B.length>1&&B[0])$=B[0],Y=B.slice(1);else $="note",Y=B;let D;if(Y.length>1){let X=Y[Y.length-1];if(X)Y[Y.length-1]=yM1(X);D=Y.join(":")}else D=yM1(Y[0]??"");return{entityType:$,id:D}}function EM1(A,Q,w,B=".md"){let $=Q.split(":").filter((W)=>W.length>0),Y=w==="note";if($.length===1)return Y?Y$0(A,`${$[0]}${B}`):Y$0(A,w,`${$[0]}${B}`);let D=$;if($[0]===w)D=$.slice(1);let X=D[D.length-1],H=D.slice(0,-1);if(Y)return Y$0(A,...H,`${X}${B}`);return Y$0(A,w,...H,`${X}${B}`)}function gM1(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return ET0(Q);let w=A.content.match(/^data:image\/([a-z+]+);base64,/i);return w?.[1]?ET0(w[1]):".md"}function yM1(A){let Q=MSQ(A).toLowerCase();return Q===".md"||B$0.includes(Q)||$$0.includes(Q)?A.slice(0,-Q.length):A}IX();import{mkdir as hSQ,readFile as rC,writeFile as lT0,stat as vSQ,utimes as CSQ}from"fs/promises";import{join as X$0}from"path";import{mkdir as TM1,readdir as PSQ,stat as kSQ}from"fs/promises";import{access as _SQ}from"fs/promises";async function y5(A){try{return await _SQ(A),!0}catch{return!1}}async function cT0(A,Q){return cM1(A,Q,{includeDocuments:!1,includeImages:!1})}async function SM1(A,Q){return cM1(A,Q,{includeDocuments:!0,includeImages:!0})}async function mM1(A,Q){if(!await y5(A))await TM1(A,{recursive:!0});for(let w of Q)if(w!=="note")await TM1(X$0(A,w),{recursive:!0})}async function uM1(A,Q){let w=[],B={totalFiles:0,byEntityType:{}};if(!await y5(A))return{files:w,stats:B};let $=await cT0(A,Q);for(let Y of $)try{let D=X$0(A,Y),X=await kSQ(D),{entityType:H}=D$0(A,Y);w.push({path:Y,entityType:H,modified:X.mtime}),B.totalFiles++,B.byEntityType[H]=(B.byEntityType[H]??0)+1}catch{continue}return{files:w,stats:B}}async function cM1(A,Q,w){let B=[];if(!await y5(A))return B;let $=async(Y,D="",X=!1,H=!1)=>{let W=await PSQ(Y,{withFileTypes:!0});for(let f of W){let Z=D?X$0(D,f.name):f.name;if(f.isFile()&&!f.name.endsWith(".invalid")&&!vM1(f.name)){if(f.name.endsWith(".md"))B.push(Z);else if(w.includeImages&&X&&I_(f.name))B.push(Z);else if(w.includeDocuments&&H&&b_(f.name))B.push(Z)}else if(f.isDirectory()&&!f.name.startsWith(".")){if(D===""&&!Q.hasEntityType(f.name))continue;let G=X$0(Y,f.name),F=f.name==="image"&&D==="",V=f.name==="document"&&D==="";await $(G,Z,X||F,H||V)}}};return await $(A),B}function ySQ(A){return typeof A==="object"&&A!==null}class pT0{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return D$0(this.syncPath,A)}async readEntity(A){let Q=oW(this.syncPath,A),w=await vSQ(Q),{entityType:B,id:$}=this.parseEntityFromPath(A),Y=w.birthtime.getTime()>0?w.birthtime:w.mtime,D=w.mtime,X,H;if(I_(A)||b_(A)){let Z=(await rC(Q)).toString("base64"),G=RSQ(A);if(X=`data:${b_(A)?CM1(G):MM1(G)};base64,${Z}`,b_(A))H=await this.readDocumentSidecar(Q,A)}else X=await rC(Q,"utf-8");let W={entityType:B,id:$,content:X,created:Y,updated:D};if(H)W.metadata=H;return W}async readDocumentSidecar(A,Q){let w={mimeType:"application/pdf",filename:OSQ(Q)},B=uT0(A);if(!await y5(B))return w;try{let $=await rC(B,"utf-8"),Y=JSON.parse($),D=ySQ(Y)?Y:{};return{...w,...D}}catch{return w}}async writeEntity(A){let Q=this.getEntityFilePath(A),w=A.entityType==="image",B=A.entityType==="document";if(w||B){let Y=w?/^data:image\/[a-z+]+;base64,(.+)$/i:/^data:application\/pdf;base64,(.+)$/i,D=A.content.match(Y),X=D?.[1]?Buffer.from(D[1],"base64"):Buffer.from(A.content,"base64"),H=!1;if(await y5(Q)){let W=await rC(Q),f=xw(W.toString("base64")),Z=xw(X.toString("base64"));if(f===Z)H=!0}if(!H)await this.ensureEntityDirectory(A,Q),await lT0(Q,X);if(B)await this.writeDocumentSidecar(A,Q);if(H)return}else{let Y=this.entityService.serializeEntity(A);if(await y5(Q)){let D=await rC(Q,"utf-8"),X=xw(D),H=xw(Y);if(X===H)return}await this.ensureEntityDirectory(A,Q),await lT0(Q,Y,"utf-8")}let $=new Date(A.updated);await CSQ(Q,$,$)}async ensureEntityDirectory(A,Q){if(A.entityType!=="note")await hSQ(xSQ(Q),{recursive:!0})}async writeDocumentSidecar(A,Q){let w=A.metadata,B={};for(let[D,X]of Object.entries(w)){if(D==="mimeType")continue;if(X===void 0)continue;B[D]=X}let $=uT0(Q),Y=`${JSON.stringify(B,null,2)}
4729
+ `)||"No response text";return{success:!0,data:{state:F,response:b}}}Y=await XN1(w,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class Kd extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A;this.name="A2ARequestTimeoutError"}}class Ud extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A;this.name="A2AStreamIdleTimeoutError"}}async function zCQ(A,Q,w,B){let $=new AbortController,Y;try{return await Promise.race([A(Q,{...w,signal:$.signal}),new Promise((D,X)=>{Y=setTimeout(()=>{$.abort(),X(new Kd(B))},B)})])}catch(D){if(D instanceof Kd)throw D;if($.signal.aborted)throw new Kd(B);throw D}finally{if(Y)clearTimeout(Y)}}async function XN1(A,Q){let w;try{return await Promise.race([A.read(),new Promise((B,$)=>{w=setTimeout(()=>$(new Ud(Q)),Q)})])}catch(B){if(B instanceof Ud)A.cancel().catch(()=>{});throw B}finally{if(w)clearTimeout(w)}}function qCQ(A){if(A instanceof Kd||A instanceof Ud)return!0;return A instanceof Error}function FCQ(A,Q){let w=Q>1?` after ${Q} attempts`:"";if(A instanceof Ud)return`${A.message}${w}`;let B=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${w}: ${B}`}function WN1(A={}){let Q=A.fetch??globalThis.fetch,w={requestTimeoutMs:A.requestTimeoutMs??WCQ,streamIdleTimeoutMs:A.streamIdleTimeoutMs??fCQ,maxNetworkAttempts:A.maxNetworkAttempts??ZCQ};return{name:"agent_call",description:"Call a remote A2A agent by exact domain-like target or saved local agent id. Use this when the user asks what an exact domain-like agent id has to say, asks to talk/message/contact that id, or asks that agent for its skills/capabilities. For saved agents, the tool enforces approved/not-archived status before network contact. For unsaved exact domains, the tool verifies the A2A Agent Card over HTTPS and may perform a one-shot call without saving; it returns a typed save/connect candidate after success. Use bare ids such as yeehaa.io, docs.rizom.ai, or save-it-regression.example; .example test domains are exact domain-like ids. If the user provides an HTTPS URL such as https://docs.rizom.ai/a2a, pass only the hostname docs.rizom.ai. For follow-ups to a prior exact-id call, call again with the same id so the tool revalidates current state. Never pass a full URL, a display name like Brain, or a non-HTTPS URL. If the user gives an ambiguous name, ask them to connect/save or clarify the agent first.",inputSchema:$N1,visibility:"trusted",sideEffects:"external",handler:async(B)=>{let $=K.object($N1).safeParse(B);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};let{agent:Y,message:D}=$.data,X=KCQ(Y);if(!X.ok)return{success:!1,error:X.error};let{agentId:H}=X;if(!A.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let W=await A.entityService.getEntity({entityType:"agent",id:H,visibilityScope:R9("agent_call tool is anchor-only and resolves saved remote agents at any visibility")});if(!W){if(!UCQ(H))return{success:!1,error:`Agent ${Y} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let V=`https://${H}`,b=await YN1(V,Q);if(!b)return{success:!1,error:`Could not verify an A2A Agent Card for ${H}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"};let L=await DN1(b.url,D,Q,void 0,w);if("success"in L&&L.success===!0){let N=typeof L.data==="object"&&L.data!==null?L.data:{};return{...L,data:{...N,agentCall:{mode:"one-shot",agent:H},agentContactCandidate:{source:{kind:"url",url:X.sourceUrl??H}}}}}return L}if(W.metadata.status==="archived")return{success:!1,error:`Agent ${H} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(W.metadata.status!=="approved")return{success:!1,error:`Agent ${H} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let f=`https://${H}`,Z=await YN1(f,Q);if(!Z)return{success:!1,error:`Could not fetch Agent Card from ${f}`};let G=Z.url,F;if(A.outboundTokens)try{let V=new URL(G).hostname;F=A.outboundTokens[V]}catch{}return DN1(G,D,Q,F,w)}}}var Eg0={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.136",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 JCQ={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","X-Content-Type-Options":"nosniff"};class mC extends GU{agentCard;taskManager=new Cg0;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",Eg0,A,sL1)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agent,this.permissionContext=A.permissions,this.hasWebserver)A.endpoints.register({label:"A2A",url:"/a2a",priority:25}),A.interactions.register({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),this.logger.info("A2A interface registered",{domain:A.domain});else this.logger.info("A2A interface registered in tool-only mode",{domain:A.domain})}async onReady(A){await this.rebuildAgentCard(A)}async rebuildAgentCard(A){let Q=A.identity.get(),w=A.identity.getProfile(),B=A.tools.listForPermissionLevel("public"),$=this.config.trustedTokens&&Object.keys(this.config.trustedTokens).length>0,Y;if(A.entityService.hasEntityType("skill"))try{let D=await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}});if(D.length>0)Y=D.map((X)=>NX.safeParse(X.metadata)).filter((X)=>X.success).map((X)=>X.data)}catch{}this.agentCard=aL1({character:Q,profile:w,version:Eg0.version,domain:A.domain,organization:this.config.organization,tools:B,skills:Y,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),w=this.config.trustedTokens[Q];if(!w||!this.permissionContext)return"public";return this.permissionContext.getUserLevel("a2a",w)}withCors(A){let Q=new Headers(A.headers);for(let[w,B]of Object.entries(JCQ))Q.set(w,B);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}getOrCreateApp(){if(this.app)return this.app;let A=new CC;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 w;try{w=await Q.req.json()}catch{return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let B=AN1.safeParse(w);if(!B.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(B.data.method==="message/stream"){let D=wN1.safeParse(B.data.params??{});if(!D.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${D.error.message}`},id:B.data.id}));let{stream:X}=BN1(B.data.id,D.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(new Response(X,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let Y=await QN1(B.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:$});return this.withCors(Q.json(Y))}),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[WN1({outboundTokens:this.config.outboundTokens,requestTimeoutMs:this.config.requestTimeoutMs,streamIdleTimeoutMs:this.config.streamIdleTimeoutMs,maxNetworkAttempts:this.config.maxNetworkAttempts,entityService:this.getContext().entityService})]}async getInstructions(){return"## Agent-to-agent calls\n- Use `agent_call` for exact domain-like agent ids (for example `yeehaa.io`, `docs.rizom.ai`, or `save-it-regression.example`). A domain-like id is bare text with a dot and no slash/protocol; `.example` test domains are still exact domain-like ids. For saved agents, the tool validates approval before network contact. For unsaved exact domains, it verifies the Agent Card over HTTPS and may perform a one-shot call without saving.\n- Pass only an exact domain-like agent id to `agent_call`. If the user provides an HTTPS URL, pass only its hostname as the agent id (for `https://docs.rizom.ai/a2a`, pass `docs.rizom.ai`). Never pass a full URL, a non-HTTPS URL, or a display name like `Brain`.\n- If the user names an exact domain-like agent id such as `yeehaa.io`, `docs.rizom.ai`, or `refusal-followup.example`, call `agent_call` directly with that id. Do not preflight with `system_list` or `system_get`; the tool reports structured errors such as invalid Agent Card, not approved, or archived.\n- If the user asks you to ask, message, contact, hear what an exact domain-like agent id has to say, or ask that agent for its own skills/capabilities, treat that as an agent call request first and call `agent_call` in the same turn. Do not stop after listing the agent, drafting the question, searching general content locally, or reading saved agent entity metadata.\n- After `agent_call` returns within a turn, answer that turn from its response. Do **not** supplement with `system_get` (or any other read tool) on the agent entity, unless the user explicitly asks for directory/profile details about the agent itself.\n- Do not create, capture, or generate a note containing the user's question in the same turn as an agent contact request. The user asked to ask the agent, not to persist the question.\n- If `agent_call` succeeds for an unsaved one-shot domain, you may offer to save/connect that agent for future calls, but do not auto-save it.\n- If `agent_call` fails because auth, re-authentication, network, invalid Agent Card, or the remote agent is unavailable, report that failure directly. Do not say the agent was saved, connected, or may need to be saved/connected first. If useful, offer to add the agent contact using the word \"add\". Do not answer from memory, local docs, onboarding docs, or general knowledge; the requested agent was the source.\n- Each new turn that asks the same exact domain-like agent id something \u2014 including short follow-ups like \"what skills does it have\", \"and what about X\", \"tell me more\" \u2014 is a **new** contact request and needs its **own** fresh `agent_call`. Do not assume the previous turn's agent response already covers a new question, and do not substitute `system_list`/`system_get` or a no-tool answer for the fresh call. If the previous turn targeted an exact domain-like id such as `yeehaa.io`, use that same id again for the follow-up even if the previous response was a refusal or error; let `agent_call` validate the current directory state again.\n- When the user provides an HTTPS URL for an agent, use its hostname as the exact domain-like id for `agent_call`; the runtime verifies/contact over HTTPS. If the user provides a non-HTTPS URL, ask for the HTTPS agent URL or exact domain-like id instead.\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 `agent_call` later in the same turn.\n- If `agent_call` reports that an exact domain-like agent id cannot be verified, tell the user the agent could not be verified/contacted. Do not create a wish, reminder, todo, note, fallback task, or any new entity.\n- For non-HTTPS URLs and ambiguous display names, do not call `agent_call`; ask the user for the HTTPS agent URL, exact domain-like id, or a clarification first.\n- Use `agent_connect`, not generic entity creation, when the user explicitly asks you to add, save, or connect an agent contact.\n- If the target agent is discovered but not approved yet, do not call it and do not create a wish. Tell the user it must be approved first."}createDaemon(){return{start:async()=>{if(this.hasWebserver)this.logger.info("A2A mounted on shared webserver host");else this.logger.info("A2A running without webserver routes")},stop:async()=>{this.logger.info("A2A server stopped")}}}}c0();class gg0{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,w,B,$=!0){if(this.logger=A,this.fileOperations=B,this.deleteOnFileRemoval=$,w)this.handleImport=async(Y)=>{let D=await w({type:"directory-import",data:{paths:[Y]}});this.logger.debug("Queued import job for file change",{jobId:D,path:Y})},this.handleDelete=async(Y)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:Y});return}try{let{entityType:D,id:X}=this.fileOperations.parseEntityFromPath(Y),H=await w({type:"directory-delete",data:{entityId:X,entityType:D,filePath:Y}});this.logger.info("Queued delete job for removed file",{jobId:H,path:Y,entityId:X,entityType:D})}catch(D){this.logger.warn("Could not extract entity info from deleted file",{path:Y,error:D})}};else this.handleImport=async(Y)=>{await Q([Y])},this.handleDelete=async(Y)=>{this.logger.warn("File deleted but no job queue available",{path:Y})}}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(w){this.logger.error("Failed to handle file change",{event:A,path:Q,error:w})}}}var PM1=X1(jM1(),1);import{extname as FSQ}from"path";var B$0=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function I_(A){let Q=FSQ(A).toLowerCase();return B$0.includes(Q)}function MM1(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 ET0(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as VSQ,relative as JSQ,sep as _M1,join as ISQ}from"path";function oW(A,Q){return VSQ(Q)?Q:ISQ(A,Q)}function nC(A,Q){let w=oW(A,Q),B=JSQ(A,w);return _M1==="/"?B:B.split(_M1).join("/")}function bSQ(A,Q){if(!nC(Q,A).startsWith("image/"))return!1;return I_(A)}function LSQ(A,Q){if(nC(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return bSQ(A,Q)}class gT0{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=PM1.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(!LSQ(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let w=nC(this.syncPath,Q);if(this.pendingChanges.set(w,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,w]of A){let B=oW(this.syncPath,Q);try{if(this.onFileChange)await this.onFileChange(w,B)}catch($){this.logger.error("Error processing file change",{path:Q,event:w,error:$})}}}isWatching(){return!!this.watcher}getPendingChangesCount(){return this.pendingChanges.size}}async function kM1(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return NSQ(Q)}function OM1(A){if(A)A.stop();return}function xM1(A,Q){if(A)A.setCallback(Q)}async function NSQ(A){let{logger:Q,syncPath:w,watchInterval:B,importEntities:$,jobQueueCallback:Y,fileOperations:D,deleteOnFileRemoval:X}=A,H=new gg0(Q,$,Y,D,X),W=new gT0({syncPath:w,watchInterval:B,logger:Q,onFileChange:async(f,Z)=>{await H.handleFileChange(f,Z)}});return await W.start(),W}async function RM1(A){let Q=Date.now();A.logger.debug("Starting sync (import only)");let w=await A.importEntities(),B=await A.removeOrphanedEntities(),$=Date.now()-Q;return A.markSynced(new Date),A.logger.debug("Sync completed",{duration:$,imported:w.imported,orphansDeleted:B.deleted}),{export:{exported:0,failed:0,errors:[]},import:w,duration:$}}c0();class TT0{logger;syncPath;deleteOnFileRemoval;constructor(A){this.logger=A.logger,this.syncPath=A.syncPath,this.deleteOnFileRemoval=A.deleteOnFileRemoval}prepareBatchOperations(A){let Q=[],w=this.createImportOperations(A);Q.push(...w);let B=w.length;if(this.deleteOnFileRemoval)Q.push({type:"directory-cleanup",data:{}});let $=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:B,totalFiles:$}),{operations:Q,exportOperationsCount:0,importOperationsCount:B,totalFiles:$}}async queueSyncBatch(A,Q,w,B){let $=this.prepareBatchOperations(w);if($.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch($.operations,{source:Q,rootJobId:B?.rootJobId??S$(),metadata:{progressToken:B?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:B?.pluginId??"directory-sync",interfaceType:B?.interfaceType,channelId:B?.channelId}}),operationCount:$.operations.length,exportOperationsCount:$.exportOperationsCount,importOperationsCount:$.importOperationsCount,totalFiles:$.totalFiles}}createImportOperations(A){if(A.length===0)return[];let Q=50,w=[];for(let B=0;B<A.length;B+=Q){let $=A.slice(B,B+Q);w.push({type:"directory-import",data:{batchIndex:Math.floor(B/Q),paths:$,batchSize:$.length}})}return w}}class ST0{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new TT0({logger:A.logger,syncPath:A.syncPath,deleteOnFileRemoval:A.deleteOnFileRemoval})}async queueSyncBatch(A,Q,w){if(this.syncInProgress)return this.logger.debug("Sync already in progress, skipping",{source:Q}),null;this.syncInProgress=!0;try{let B=await this.fileOperations.getAllSyncFiles();return await this.batchOperationsManager.queueSyncBatch(A,Q,B,w)}finally{this.syncInProgress=!1}}}class mT0{options;constructor(A){this.options=A}createExportDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImportDeps(A){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,quarantine:this.options.quarantine,imageJobQueue:this.createImageJobQueueDeps(),entityTypes:A}}createCleanupDeps(A,Q){return{entityService:this.options.entityService,logger:this.options.logger,fileOperations:this.options.fileOperations,deleteOnFileRemoval:A,entityTypes:Q}}createImageJobQueueDeps(){return{logger:this.options.logger,syncPath:this.options.syncPath,jobQueueCallback:this.options.getJobQueueCallback(),coverImageConverter:this.options.coverImageConverter,inlineImageConverter:this.options.inlineImageConverter}}}import{basename as OSQ,dirname as xSQ,extname as RSQ}from"path";import{extname as jSQ}from"path";var $$0=[".pdf"],hM1=".meta.json";function b_(A){let Q=jSQ(A).toLowerCase();return $$0.includes(Q)}function vM1(A){return A.toLowerCase().endsWith(hM1)}function uT0(A){return`${A}${hM1}`}function CM1(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as MSQ,join as Y$0}from"path";function D$0(A,Q){let B=nC(A,Q).split("/"),$,Y;if(B.length===1)$="note",Y=B;else if(B.length>1&&B[0])$=B[0],Y=B.slice(1);else $="note",Y=B;let D;if(Y.length>1){let X=Y[Y.length-1];if(X)Y[Y.length-1]=yM1(X);D=Y.join(":")}else D=yM1(Y[0]??"");return{entityType:$,id:D}}function EM1(A,Q,w,B=".md"){let $=Q.split(":").filter((W)=>W.length>0),Y=w==="note";if($.length===1)return Y?Y$0(A,`${$[0]}${B}`):Y$0(A,w,`${$[0]}${B}`);let D=$;if($[0]===w)D=$.slice(1);let X=D[D.length-1],H=D.slice(0,-1);if(Y)return Y$0(A,...H,`${X}${B}`);return Y$0(A,w,...H,`${X}${B}`)}function gM1(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return ET0(Q);let w=A.content.match(/^data:image\/([a-z+]+);base64,/i);return w?.[1]?ET0(w[1]):".md"}function yM1(A){let Q=MSQ(A).toLowerCase();return Q===".md"||B$0.includes(Q)||$$0.includes(Q)?A.slice(0,-Q.length):A}IX();import{mkdir as hSQ,readFile as rC,writeFile as lT0,stat as vSQ,utimes as CSQ}from"fs/promises";import{join as X$0}from"path";import{mkdir as TM1,readdir as PSQ,stat as kSQ}from"fs/promises";import{access as _SQ}from"fs/promises";async function y5(A){try{return await _SQ(A),!0}catch{return!1}}async function cT0(A,Q){return cM1(A,Q,{includeDocuments:!1,includeImages:!1})}async function SM1(A,Q){return cM1(A,Q,{includeDocuments:!0,includeImages:!0})}async function mM1(A,Q){if(!await y5(A))await TM1(A,{recursive:!0});for(let w of Q)if(w!=="note")await TM1(X$0(A,w),{recursive:!0})}async function uM1(A,Q){let w=[],B={totalFiles:0,byEntityType:{}};if(!await y5(A))return{files:w,stats:B};let $=await cT0(A,Q);for(let Y of $)try{let D=X$0(A,Y),X=await kSQ(D),{entityType:H}=D$0(A,Y);w.push({path:Y,entityType:H,modified:X.mtime}),B.totalFiles++,B.byEntityType[H]=(B.byEntityType[H]??0)+1}catch{continue}return{files:w,stats:B}}async function cM1(A,Q,w){let B=[];if(!await y5(A))return B;let $=async(Y,D="",X=!1,H=!1)=>{let W=await PSQ(Y,{withFileTypes:!0});for(let f of W){let Z=D?X$0(D,f.name):f.name;if(f.isFile()&&!f.name.endsWith(".invalid")&&!vM1(f.name)){if(f.name.endsWith(".md"))B.push(Z);else if(w.includeImages&&X&&I_(f.name))B.push(Z);else if(w.includeDocuments&&H&&b_(f.name))B.push(Z)}else if(f.isDirectory()&&!f.name.startsWith(".")){if(D===""&&!Q.hasEntityType(f.name))continue;let G=X$0(Y,f.name),F=f.name==="image"&&D==="",V=f.name==="document"&&D==="";await $(G,Z,X||F,H||V)}}};return await $(A),B}function ySQ(A){return typeof A==="object"&&A!==null}class pT0{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return D$0(this.syncPath,A)}async readEntity(A){let Q=oW(this.syncPath,A),w=await vSQ(Q),{entityType:B,id:$}=this.parseEntityFromPath(A),Y=w.birthtime.getTime()>0?w.birthtime:w.mtime,D=w.mtime,X,H;if(I_(A)||b_(A)){let Z=(await rC(Q)).toString("base64"),G=RSQ(A);if(X=`data:${b_(A)?CM1(G):MM1(G)};base64,${Z}`,b_(A))H=await this.readDocumentSidecar(Q,A)}else X=await rC(Q,"utf-8");let W={entityType:B,id:$,content:X,created:Y,updated:D};if(H)W.metadata=H;return W}async readDocumentSidecar(A,Q){let w={mimeType:"application/pdf",filename:OSQ(Q)},B=uT0(A);if(!await y5(B))return w;try{let $=await rC(B,"utf-8"),Y=JSON.parse($),D=ySQ(Y)?Y:{};return{...w,...D}}catch{return w}}async writeEntity(A){let Q=this.getEntityFilePath(A),w=A.entityType==="image",B=A.entityType==="document";if(w||B){let Y=w?/^data:image\/[a-z+]+;base64,(.+)$/i:/^data:application\/pdf;base64,(.+)$/i,D=A.content.match(Y),X=D?.[1]?Buffer.from(D[1],"base64"):Buffer.from(A.content,"base64"),H=!1;if(await y5(Q)){let W=await rC(Q),f=xw(W.toString("base64")),Z=xw(X.toString("base64"));if(f===Z)H=!0}if(!H)await this.ensureEntityDirectory(A,Q),await lT0(Q,X);if(B)await this.writeDocumentSidecar(A,Q);if(H)return}else{let Y=this.entityService.serializeEntity(A);if(await y5(Q)){let D=await rC(Q,"utf-8"),X=xw(D),H=xw(Y);if(X===H)return}await this.ensureEntityDirectory(A,Q),await lT0(Q,Y,"utf-8")}let $=new Date(A.updated);await CSQ(Q,$,$)}async ensureEntityDirectory(A,Q){if(A.entityType!=="note")await hSQ(xSQ(Q),{recursive:!0})}async writeDocumentSidecar(A,Q){let w=A.metadata,B={};for(let[D,X]of Object.entries(w)){if(D==="mimeType")continue;if(X===void 0)continue;B[D]=X}let $=uT0(Q),Y=`${JSON.stringify(B,null,2)}
4730
4730
  `;if(await y5($)){if(await rC($,"utf-8")===Y)return}await this.ensureEntityDirectory(A,$),await lT0($,Y,"utf-8")}getFilePath(A,Q,w=".md"){return EM1(this.syncPath,A,Q,w)}getEntityFilePath(A){return this.getFilePath(A.id,A.entityType,gM1(A))}async getAllMarkdownFiles(){return cT0(this.syncPath,this.entityService)}async getAllSyncFiles(){return SM1(this.syncPath,this.entityService)}async ensureDirectoryStructure(A){await mM1(this.syncPath,A)}shouldUpdateEntity(A,Q){let w=xw(Q.content);return A.contentHash!==w}async gatherFileStatus(){return uM1(this.syncPath,this.entityService)}async syncDirectoryExists(){return y5(this.syncPath)}async fileExists(A){return y5(A)}}D4();Z0();D4();async function H$0(A,Q,w,B){let{sourceUrl:$}=A,Y=await Q.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:$}},limit:1}});if(Y[0])return B.debug("Reusing existing image entity",{sourceUrl:$,imageId:Y[0].id}),Y[0].id;let D=await w($),{base64:X}=WJ(D),H=Hj(X),W=fJ(X);if(!H||!W)throw Error("Could not detect image format or dimensions");let f=await Q.createEntity({entity:{id:A.id,entityType:"image",content:D,metadata:{title:A.title,alt:A.alt,format:H,width:W.width,height:W.height,sourceUrl:$}}});return B.debug("Created image entity from URL",{sourceUrl:$,imageId:f.entityId}),f.entityId}var lM1=K.object({title:K.string(),slug:K.string().optional(),coverImageUrl:K.string().url(),coverImageId:K.string().optional(),coverImageAlt:K.string().optional()});class iT0{entityService;fetcher;logger;constructor(A,Q,w=LW){this.entityService=A;this.fetcher=w;this.logger=Q.child("FrontmatterImageConverter")}detectCoverImageUrl(A){let Q;try{Q=lw(A)}catch{return null}let{frontmatter:w}=Q,B=lM1.safeParse(w);if(!B.success)return null;if(B.data.coverImageId)return null;let{title:$,slug:Y,coverImageUrl:D,coverImageAlt:X}=B.data;if(!rz(D))return null;return{sourceUrl:D,postTitle:$,postSlug:Y??w1($),customAlt:X}}async convert(A){let Q;try{Q=lw(A)}catch(W){return this.logger.debug("Parse failed",{error:W}),{content:A,converted:!1}}let{frontmatter:w}=Q,B=lM1.safeParse(w);if(!B.success)return{content:A,converted:!1};if(B.data.coverImageId)return{content:A,converted:!1};let{title:$,slug:Y,coverImageUrl:D,coverImageAlt:X}=B.data;if(!rz(D))return{content:A,converted:!1};let H={postTitle:$,postSlug:Y??w1($),sourceUrl:D,customAlt:X};try{let W=await this.createImageEntity(H),f={...w};return delete f.coverImageUrl,delete f.coverImageAlt,f.coverImageId=W,{content:iz(f,Q.content),converted:!0,imageId:W}}catch(W){return this.logger.warn("Failed to convert coverImageUrl",{url:D,error:vA(W)}),{content:A,converted:!1}}}async createImageEntity(A){let{postTitle:Q,postSlug:w,sourceUrl:B,customAlt:$}=A,Y=`Cover image for ${Q}`;return H$0({id:`${w}-cover`,title:Y,alt:$??Y,sourceUrl:B},this.entityService,this.fetcher,this.logger)}}D4();Z0();class Pd{entityService;fetcher;logger;constructor(A,Q,w=LW){this.entityService=A;this.fetcher=w;this.logger=Q.child("MarkdownImageConverter")}detectInlineImages(A,Q){let w=[],B=ub0(A);for(let $ of B){if(!rz($.url))continue;if($.url.startsWith("entity://"))continue;let Y=this.reconstructMarkdown($);w.push({sourceUrl:$.url,alt:$.alt,originalMarkdown:Y,postSlug:Q})}return w}reconstructMarkdown(A){if(A.title)return`![${A.alt}](${A.url} "${A.title}")`;return`![${A.alt}](${A.url})`}async convert(A,Q){let w=this.detectInlineImages(A,Q);if(w.length===0)return{content:A,converted:!1,convertedCount:0};let B=A,$=0,Y=0;for(let D of w)try{let X=await this.createImageEntity(D,Y++),H=`![${D.alt}](entity://image/${X})`;B=B.replace(D.originalMarkdown,H),$++,this.logger.debug("Converted inline image",{sourceUrl:D.sourceUrl,imageId:X})}catch(X){this.logger.warn("Failed to convert inline image",{sourceUrl:D.sourceUrl,error:vA(X)})}return{content:B,converted:$>0,convertedCount:$}}async createImageEntity(A,Q){let{sourceUrl:w,alt:B,postSlug:$}=A;return H$0({id:`${$}-inline-${Q}`,title:B||`Inline image ${Q+1} for ${$}`,alt:B||"",sourceUrl:w},this.entityService,this.fetcher,this.logger)}}class dT0{logger;entityService;fileOperations;constructor(A,Q,w){this.logger=A,this.entityService=Q,this.fileOperations=w}async importEntitiesWithProgress(A,Q,w,B){this.logger.debug("Importing entities with progress reporting");let $={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},Y=A??await this.fileOperations.getAllSyncFiles(),D=Y.length;await Q.report({progress:0,message:`Starting import of ${D} files`});for(let X=0;X<D;X+=w){let H=Y.slice(X,X+w),W=await B(H);$.imported+=W.imported,$.skipped+=W.skipped,$.failed+=W.failed,$.quarantined+=W.quarantined,$.errors.push(...W.errors),$.quarantinedFiles.push(...W.quarantinedFiles),$.jobIds.push(...W.jobIds);let f=Math.min(X+w,D),Z=Math.round(f/D*40);await Q.report({progress:Z,message:`Imported ${f}/${D} files`})}return $}async exportEntitiesWithProgress(A,Q,w,B){this.logger.debug("Exporting entities with progress reporting");let $=A??this.entityService.getEntityTypes();await Q.report({progress:50,message:`Starting export of ${$.length} entity types`});let Y=await B(A);return await Q.report({progress:100,message:`Exported ${Y.exported} entities`}),this.logger.debug("Export completed",Y),Y}}Z0();import{rename as ESQ,appendFile as gSQ,readFile as TSQ,writeFile as SSQ,access as mSQ}from"fs/promises";import{join as pM1}from"path";class nT0{logger;syncPath;constructor(A,Q){this.logger=A;this.syncPath=Q}isValidationError(A){if(A instanceof K.ZodError)return!0;let Q=vA(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,w,B){let $=B(A),Y=`${$}.invalid`;try{await ESQ($,Y),w.quarantined++,w.quarantinedFiles.push(A);let D=pM1(this.syncPath,".import-errors.log"),X=new Date().toISOString(),H=vA(Q),W=`${X} - ${A}: ${H}
4731
4731
  \u2192 ${A}.invalid
4732
4732
 
@@ -4754,7 +4754,7 @@ details.web-chat-data-part[open] > summary > .web-chat-data-part-chevron {
4754
4754
  *...and ${A.files.length-10} more files*`)}if(A.exists&&A.stats.totalFiles===0)Q.push(`
4755
4755
  ## Getting Started
4756
4756
  `),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(`
4757
- `)}}c0();class y$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:nS0,jobTypeName:"directory-export"});this.directorySync=w}async process(A,Q,w){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let B=Date.now();try{let $=await this.directorySync.exportEntitiesWithProgress(A.entityTypes,w,A.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:Q,exported:$.exported,failed:$.failed,duration:Date.now()-B}),$}catch($){throw this.logger.error("Directory export job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}c0();class E$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:dS0,jobTypeName:"directory-import"});this.directorySync=w}async process(A,Q,w){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let B=Date.now();try{let $=await this.directorySync.importEntitiesWithProgress(A.paths,w,A.batchSize??100);return this.logger.debug("Directory import job completed",{jobId:Q,imported:$.imported,skipped:$.skipped,failed:$.failed,quarantined:$.quarantined,duration:Date.now()-B}),$}catch($){throw this.logger.error("Directory import job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}c0();class g$0 extends _w{directorySync;context;constructor(A,Q,w){super(A,{schema:pS0,jobTypeName:"directory-sync"});this.context=Q,this.directorySync=w}async process(A,Q,w){let B=Date.now(),$=A.syncDirection??"both";this.logger.info("Starting directory sync job",{jobId:Q,operation:A.operation,syncDirection:$});let Y={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},D={exported:0,failed:0,errors:[]};if($!=="export")if(await w.report({progress:10,message:"Scanning directory for changes"}),Y=await this.importWithProgress(A.paths,w),$==="import")await this.waitForImportJobs(Y.jobIds,w),await w.report({progress:100,message:`Import complete: ${Y.imported} imported`});else await w.report({progress:50,message:`Imported ${Y.imported} entities`}),await this.waitForImportJobs(Y.jobIds,w),await w.report({progress:56,message:"Processing complete, starting export"});if($!=="import"){let H=$==="export"?10:60;await w.report({progress:H,message:"Exporting entities to directory"}),D=await this.exportWithProgress(A.entityTypes,w),await w.report({progress:100,message:$==="export"?`Export complete: ${D.exported} exported`:`Sync complete: ${Y.imported} imported, ${D.exported} exported`})}let X=Date.now()-B;return this.logger.info("Directory sync job completed",{jobId:Q,duration:X,imported:Y.imported,exported:D.exported}),{import:Y,export:D,duration:X}}async importWithProgress(A,Q){try{return await this.directorySync.importEntitiesWithProgress(A,Q,10)}catch(w){throw this.logger.error("Import phase failed",{error:w}),w}}async exportWithProgress(A,Q){try{return await this.directorySync.exportEntitiesWithProgress(A,Q,10)}catch(w){throw this.logger.error("Export phase failed",{error:w}),w}}async waitForImportJobs(A,Q){if(A.length===0)return;this.logger.debug(`Waiting for ${A.length} import jobs to complete`);let{entityService:w}=this.context,B=300000,$=500,Y=Date.now(),D=async()=>{let H=(await Promise.all(A.map((f)=>w.getAsyncJobStatus(f)))).filter((f)=>f&&(f.status==="completed"||f.status==="failed")).length;if(H===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-Y>B){this.logger.warn(`Timeout waiting for import jobs (${H}/${A.length} completed)`);return}let W=Math.round(H/A.length*100);return await Q.report({progress:50+Math.round(W*0.05),message:`Processing ${H}/${A.length} entities`}),await new Promise((f)=>setTimeout(f,$)),D()};return D()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}c0();class T$0 extends _w{context;directorySync;gitSync;constructor(A,Q,w,B){super(A,{schema:iS0,jobTypeName:"sync-request"});this.context=Q;this.directorySync=w;this.gitSync=B}async process(A,Q,w){await w.report({progress:5,message:"Pulling latest content from git"});let B=await this.gitSync.withLock(async()=>{return await this.gitSync.pull(),await w.report({progress:35,message:"Scanning pulled content for sync changes"}),this.directorySync.queueSyncBatch(this.context,A.source,{rootJobId:Q,interfaceType:A.interfaceType,channelId:A.channelId})});if(!B)return await w.report({progress:100,message:"Sync complete: no files to import"}),{gitPulled:!0,batchQueued:!1};return await w.report({progress:100,message:`Sync queued: ${B.importOperationsCount} import jobs for ${B.totalFiles} files`}),ylQ(B)}summarizeDataForLog(A){return{source:A.source,interfaceType:A.interfaceType,channelId:A.channelId}}}function ylQ(A){return{gitPulled:!0,batchQueued:!0,batchId:A.batchId,importOperations:A.importOperationsCount,totalFiles:A.totalFiles}}c0();class S$0 extends _w{context;constructor(A,Q,w){super(A,{schema:v$0,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,w){let B=v$0.parse(A);this.logger.info("Processing entity deletion for removed file",{entityId:B.entityId,entityType:B.entityType,filePath:B.filePath}),await w.report({progress:0,total:1,message:`Deleting ${B.entityType}:${B.entityId}`});try{let $=await this.context.entityService.deleteEntity({entityType:B.entityType,id:B.entityId});if($)this.logger.info("Successfully deleted entity for removed file",{entityId:B.entityId,entityType:B.entityType});else this.logger.warn("Entity not found in database",{entityId:B.entityId,entityType:B.entityType});return await w.report({progress:1,total:1,message:`Deleted ${B.entityType}:${B.entityId}`}),{deleted:$,entityId:B.entityId,entityType:B.entityType,filePath:B.filePath}}catch($){throw this.logger.error("Failed to delete entity",{entityId:B.entityId,entityType:B.entityType,error:$}),$}}summarizeDataForLog(A){return{entityId:A.entityId,entityType:A.entityType,filePath:A.filePath}}}c0();Z0();var ElQ=K.object({});class m$0 extends _w{directorySync;constructor(A,Q){super(A,{schema:ElQ,jobTypeName:"directory-cleanup"});this.directorySync=Q}async process(A,Q,w){await w.report({progress:0,message:"Removing orphaned entities"});let B=await this.directorySync.removeOrphanedEntities();return await w.report({progress:100,message:`Cleanup complete: ${B.deleted} orphans removed`}),B}}c0();D4();Z0();CB();D4();import{readFile as glQ,writeFile as TlQ}from"fs/promises";var SlQ=rS0;class u$0 extends _w{context;fetcher;constructor(A,Q,w=LW){super(Q,{schema:SlQ,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=w}async process(A,Q,w){let{filePath:B,sourceUrl:$,postTitle:Y,postSlug:D,customAlt:X}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:B,sourceUrl:$,postSlug:D});try{await this.reportProgress(w,{progress:PQ.INIT,message:`Reading file: ${B}`});let H;try{H=await glQ(B,"utf-8")}catch(b){return this.logger.error("Failed to read file",{filePath:B,error:vA(b)}),x6.failure(b)}let W;try{W=lw(H)}catch(b){return this.logger.warn("Failed to parse markdown",{filePath:B,error:vA(b)}),x6.failure(b)}let f=W.frontmatter;if(f.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:B}),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress(w,{progress:PQ.FETCH,message:"Checking for existing image"});let Z=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:$}},limit:1}}),G;if(Z[0])G=Z[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:$,imageId:G}),await this.reportProgress(w,{progress:PQ.EXTRACT,message:`Reusing existing image: ${G}`});else{await this.reportProgress(w,{progress:PQ.PROCESS,message:`Fetching image from ${$}`});let b;try{b=await this.fetcher($)}catch(E){return this.logger.error("Failed to fetch image",{sourceUrl:$,error:vA(E)}),x6.failure(E)}await this.reportProgress(w,{progress:PQ.GENERATE,message:"Creating image entity"});let{base64:L}=WJ(b),N=Hj(L),_=fJ(L);if(!N||!_)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:$}),x6.failure(Error("Could not detect image format or dimensions"));G=`${D}-cover`;let j=`Cover image for ${Y}`,g=X??j;await this.context.entityService.createEntity({entity:{id:G,entityType:"image",content:b,metadata:{title:j,alt:g,format:N,width:_.width,height:_.height,sourceUrl:$}}}),this.logger.debug("Created image entity",{imageId:G,sourceUrl:$}),await this.reportProgress(w,{progress:PQ.EXTRACT,message:`Created image: ${G}`})}await this.reportProgress(w,{progress:PQ.SAVE,message:"Updating file"});let F={...f};delete F.coverImageUrl,delete F.coverImageAlt,F.coverImageId=G;let V=iz(F,W.content);try{await TlQ(B,V,"utf-8")}catch(b){return this.logger.error("Failed to write file",{filePath:B,error:vA(b)}),x6.failure(b)}return await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:B,imageId:G,sourceUrl:$}),{success:!0,imageId:G}}catch(H){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:B,error:vA(H)}),x6.failure(H)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}c0();D4();Z0();CB();import{readFile as mlQ,writeFile as ulQ}from"fs/promises";class c$0 extends _w{converter;constructor(A,Q,w=LW){super(Q,{schema:oS0,jobTypeName:"inline-image-convert"});this.converter=new Pd(A.entityService,Q,w)}async process(A,Q,w){let{filePath:B,postSlug:$}=A;this.logger.debug("Starting inline image conversion job",{jobId:Q,filePath:B,postSlug:$});try{await this.reportProgress(w,{progress:PQ.INIT,message:`Reading file: ${B}`});let Y;try{Y=await mlQ(B,"utf-8")}catch(H){let W=vA(H);return this.logger.error("Failed to read file",{filePath:B,error:W}),{success:!1,error:W}}await this.reportProgress(w,{progress:PQ.FETCH,message:"Detecting inline images"});let D=this.converter.detectInlineImages(Y,$);if(D.length===0)return this.logger.debug("No inline images to convert",{filePath:B}),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:B,count:D.length}),await this.reportProgress(w,{progress:PQ.PROCESS,message:`Converting ${D.length} images`});let X=await this.converter.convert(Y,$);if(!X.converted)return this.logger.debug("No images were converted",{filePath:B}),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress(w,{progress:PQ.SAVE,message:"Writing updated file"});try{await ulQ(B,X.content,"utf-8")}catch(H){let W=vA(H);return this.logger.error("Failed to write file",{filePath:B,error:W}),{success:!1,error:W}}return await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:B,convertedCount:X.convertedCount}),{success:!0,convertedCount:X.convertedCount}}catch(Y){let D=vA(Y);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:B,error:D}),{success:!1,error:D}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function LO1(A,Q,w){let B=($)=>w.child($);A.jobs.registerHandler("directory-sync",new g$0(B("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new y$0(B("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new E$0(B("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new S$0(B("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new m$0(B("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new u$0(A,B("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new c$0(A,B("InlineImageConversionJobHandler"))),w.debug("Registered async job handlers")}c0();import{unlink as clQ,access as llQ}from"fs/promises";function NO1(A,Q,w,B){let{subscribe:$}=A.messaging,{entityService:Y}=A;$("entity:created",async(D)=>{let{entity:X}=D.payload;try{await Q.fileOps.writeEntity(X),w.debug("Auto-exported created entity",{id:X.id,entityType:X.entityType})}catch(H){w.error("Auto-export FAILED for created entity",{id:X.id,entityType:X.entityType,error:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0})}return{success:!0}}),$("entity:updated",async(D)=>{let{entityType:X,entityId:H}=D.payload;try{let W=await Y.getEntity({entityType:X,id:H});if(!W)return w.debug("Entity not found in DB, skipping export",{entityType:X,entityId:H}),{success:!1};await Q.fileOps.writeEntity(W),w.debug("Auto-exported updated entity",{id:W.id,entityType:W.entityType})}catch(W){w.error("Auto-export FAILED for updated entity",{entityType:X,entityId:H,error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0})}return{success:!0}}),$("entity:deleted",async(D)=>{let{entityId:X,entityType:H}=D.payload,W=Q.fileOps.getFilePath(X,H);if(await llQ(W).then(()=>!0,()=>!1))await clQ(W),w.debug("Auto-deleted entity file",{id:X,entityType:H,path:W});return{success:!0}}),w.debug("Setup auto-sync for entity events",{entityTypes:B})}function jO1(A,Q,w){Q.setJobQueueCallback(async(B)=>{let $=[{type:B.type,data:B.data}];return A.jobs.enqueueBatch($,{priority:5,source:"directory-sync-watcher",rootJobId:S$(),metadata:{operationType:"file_operations",operationTarget:w,pluginId:"directory-sync"}})})}Z0();c0();import{readdir as PO1,mkdir as ilQ,copyFile as dlQ}from"fs/promises";import{join as _O1,resolve as sS0}from"path";import{join as plQ}from"path";async function MO1(A){if(!await y5(plQ(A,".git")))return!1;try{return await AK(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function nlQ(A,Q){if(!await y5(A))return!0;if((await PO1(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await MO1(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function kO1(A,Q){let w=await PO1(A,{withFileTypes:!0});for(let B of w){let $=_O1(A,B.name),Y=_O1(Q,B.name);if(B.isDirectory()){if(!await y5(Y))await ilQ(Y,{recursive:!0});await kO1($,Y)}else await dlQ($,Y)}}async function OO1(A,Q,w){let B=sS0(process.cwd(),A);w=w?sS0(w):sS0(process.cwd(),"seed-content");let $=await nlQ(B,Q);if($&&await y5(w))Q.debug("Copying seed content to brain-data directory"),await kO1(w,B),Q.debug("Seed content copied successfully");else if($)Q.debug("No seed content directory found, starting with empty brain-data");else Q.debug("brain-data directory not empty, skipping seed content")}function xO1(A,Q,w,B,$){let Y=!1,D=async()=>{if(Y)return;Y=!0;let X=Q();if(w.seedContent){let H=w.syncPath??A.dataDir;await OO1(H,B,w.seedContentPath)}try{if($){B.debug("Git enabled \u2014 pulling before import");let W=await $.pull();if(W.files.length>0)B.info("Pulled changes from remote",{filesChanged:W.files.length})}B.debug("Starting initial sync");let H=await X.sync();B.debug("Initial sync completed",{imported:H.import.imported,failed:H.import.failed,duration:H.duration}),await A.messaging.send({type:LN.initialSyncCompleted,payload:{success:!0},...{broadcast:!0}})}catch(H){B.error("Initial sync failed",H),await A.messaging.send({type:LN.initialSyncCompleted,payload:{success:!1,error:vA(H)},...{broadcast:!0}})}};A.messaging.subscribe(LN.pluginsRegistered,async()=>{return B.debug("Plugins registered, starting initial sync"),await D(),{success:!0}})}Z0();function RO1(A,Q,w,B){let $=new DN(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(X){B.error("Git auto-commit failed",{error:X})}})},w),Y=["entity:created","entity:updated","entity:deleted"],D=[];for(let X of Y){let H=A.subscribe(X,async()=>{return $.trigger(),{success:!0}});D.push(H)}return()=>{$.dispose();for(let X of D)X()}}function hO1(A,Q,w,B,$){if(B<=0)return()=>{};let Y=B*60*1000,D=!1,X=async()=>{if(D)return;D=!0;try{let{files:W,result:f}=await A.withLock(async()=>{let Z=await A.pull();if(Z.files.length===0)return{files:[],result:null};let G=await Q.queueSyncBatch(w,"periodic-sync");return{files:Z.files,result:G}});if(W.length>0)$.info("Periodic sync: pulled changes",{filesChanged:W.length});if(f)$.debug("Periodic sync: queued imports",{importOperations:f.importOperationsCount,totalFiles:f.totalFiles})}catch(W){$.error("Periodic git sync failed",{error:W})}finally{D=!1}},H=setInterval(()=>{X()},Y);return $.info("Started periodic git sync",{intervalMinutes:B}),()=>{clearInterval(H)}}import{spawnSync as CO1}from"child_process";import{cpSync as rlQ,existsSync as vO1,mkdirSync as olQ,mkdtempSync as slQ,rmSync as alQ}from"fs";import{tmpdir as tlQ}from"os";import{fileURLToPath as elQ}from"url";import{join as ApQ,resolve as QpQ}from"path";function sI(A,Q){let w=CO1("git",Q,{cwd:A,stdio:"pipe"});if(w.status!==0){let B=w.stderr.toString().trim(),$=w.stdout.toString().trim();throw Error(B||$||`git ${Q.join(" ")} failed`)}}function wpQ(A){return A.startsWith("file://")}function BpQ(A){return elQ(A)}function $pQ(A,Q){return CO1("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function yO1(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!wpQ(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",w=BpQ(A.gitUrl),B=QpQ(A.seedContentPath);if(!vO1(B))throw Error(`Seed content path not found: ${B}`);if(!vO1(w))A.logger.debug("Creating local bare content remote",{remotePath:w,branch:Q}),olQ(w,{recursive:!0}),sI(process.cwd(),["init","--bare",`--initial-branch=${Q}`,w]);if($pQ(w,Q)){A.logger.debug("Content remote already initialized",{remotePath:w,branch:Q});return}A.logger.debug("Seeding local content remote",{remotePath:w,seedPath:B,branch:Q});let $=slQ(ApQ(tlQ(),"directory-sync-seed-"));try{sI($,["init",`--initial-branch=${Q}`]),sI($,["config","user.name",A.authorName??"Brain"]),sI($,["config","user.email",A.authorEmail??"brain@localhost"]),rlQ(B,$,{recursive:!0}),sI($,["add","."]),sI($,["commit","-m","seed content remote"]),sI($,["remote","add","origin",A.gitUrl]),sI($,["push","-u","origin",Q])}finally{alQ($,{recursive:!0,force:!0})}}function EO1(A,Q,w,B,$){let{subscribe:Y}=A.messaging;Y("entity:export:request",async(D)=>{try{return{success:!0,data:await Q().exportEntities(D.payload.entityTypes)}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Export failed"}}}),Y("entity:import:request",async(D)=>{try{let X=Q(),H=D.payload.paths,W=await X.importEntities(H);if(H&&H.length>0)await X.removeOrphanedEntities();return{success:!0,data:W}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Import failed"}}}),Y("sync:status:request",async()=>{try{let X=await Q().getStatus();return{success:!0,data:{syncPath:X.syncPath,isInitialized:X.exists,watchEnabled:X.watching}}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Status check failed"}}}),Y("sync:configure:request",async(D)=>{try{return await w({syncPath:D.payload.syncPath}),{success:!0,data:{syncPath:D.payload.syncPath,configured:!0}}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Configuration failed"}}}),Y("git-sync:get-repo-info",async()=>{if(!$?.repo)return{success:!1,error:"Git not configured"};return{success:!0,data:{repo:$.repo,branch:$.branch??"main"}}}),B.debug("Registered message handlers")}c0();Z0();c0();Z0();function gO1(A,Q){return Sw(A,"history","Get version history for an entity from git. Without sha: returns commit list. With sha: returns entity content at that version.",K.object({entityType:K.string().describe("Entity type (e.g. post, note, link)"),id:K.string().describe("Entity ID"),sha:K.string().optional().describe("Commit SHA to retrieve content at. Omit to list commit history."),limit:K.number().int().positive().optional().default(10).describe("Max commits to return (list mode only)")}),async(w)=>{let B=`${w.entityType}/${w.id}.md`;try{if(w.sha){let Y=await Q.show(w.sha,B);return l8({sha:w.sha,entityType:w.entityType,id:w.id,content:Y},`Content at ${w.sha.slice(0,7)}`)}let $=await Q.log(B,w.limit);if($.length===0)return l8({commits:[]},`No history found for ${w.entityType}/${w.id}`);return l8({commits:$,entityType:w.entityType,id:w.id},`${$.length} version${$.length===1?"":"s"} found`)}catch($){return P9($ instanceof Error?$.message:"History lookup failed")}},{visibility:"anchor",sideEffects:"none"})}function TO1(A,Q,w,B){let $=[Sw(w,"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.",K.object({}),async(Y,D)=>{try{let X=D.channelId?`${D.interfaceType}:${D.channelId}`:`plugin:${w}`,H={interfaceType:D.interfaceType,channelId:D.channelId};if(B){let f=await Q.jobs.enqueue({type:"sync-request",data:{source:X,interfaceType:H.interfaceType,channelId:H.channelId},toolContext:D});return l8({jobId:f,status:"queued",gitPulled:!0},"Sync queued: git pull and filesystem scan will run in the background")}let W=await A.queueSyncBatch(Q,X,H);if(!W)return l8({gitPulled:!1},"No files to sync");return l8({batchId:W.batchId,importOperations:W.importOperationsCount,totalFiles:W.totalFiles,gitPulled:!1},`Sync started: ${W.importOperationsCount} import jobs queued for ${W.totalFiles} files`)}catch(X){return P9(X instanceof Error?X.message:"Sync failed")}},{visibility:"anchor",sideEffects:"external",cli:{name:"sync"}}),Sw(w,"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.",K.object({}),async()=>{try{let Y=await A.getStatus(),D={syncPath:Y.syncPath,lastSync:Y.lastSync?.toISOString(),watching:Y.watching};if(B){let X=await B.getStatus();D.git={isRepo:X.isRepo,branch:X.branch,hasChanges:X.hasChanges,ahead:X.ahead,behind:X.behind,remote:X.remote}}return l8(D)}catch(Y){return P9(Y instanceof Error?Y.message:"Status check failed")}},{visibility:"anchor",sideEffects:"none"})];if(B)$.push(gO1(w,B));return $}var SO1={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.135",description:"Directory-based entity synchronization plugin for Brains",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":{types:"./src/index.ts",import:"./src/index.ts"}},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",clean:"rm -rf .turbo"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chokidar:"^3.5.3","simple-git":"^3.21.0"},devDependencies:{"@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},peerDependencies:{}};class aS0 extends IQ{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",SO1,A,md)}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:w}=A;A.templates.register({status:{name:"status",description:"Directory synchronization status",schema:ud,basePrompt:"",formatter:new C$0,requiredPermission:"anchor"}});let B=this.config.syncPath??A.dataDir;this.directorySync=new kd({syncPath:B,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,entityService:w,logger:Q});try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:B})}catch(D){throw this.logger.error("Failed to initialize directory",D),D}await this.registerJobHandlers(A);let $=this.requireDirectorySync();if(NO1(A,$,this.logger,this.config.entityTypes),this.config.autoSync)jO1(A,$,this.config.syncPath??A.dataDir);let Y=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!Y)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(Y&&this.config.git){await yO1({gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,seedContentPath:this.config.seedContentPath,bootstrapFromSeed:this.config.git.bootstrapFromSeed,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail,logger:this.logger.child("ContentRemoteBootstrap")});let D=this.config.syncPath??A.dataDir;if(this.gitSync=new lS0({logger:this.logger.child("GitSync"),dataDir:D,repo:this.config.git.repo,gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,authToken:this.config.git.authToken,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail}),await this.gitSync.initialize(),this.logger.info("Git integration enabled",{repo:this.config.git.repo}),A.jobs.registerHandler("sync-request",new T$0(this.logger.child("DirectorySyncRequestJobHandler"),A,this.requireDirectorySync(),this.gitSync)),this.gitCleanups.push(RO1(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(hO1(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)xO1(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);EO1(A,()=>this.requireDirectorySync(),(D)=>this.configure(D),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return TO1(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 kd({...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){LO1(A,this.requireDirectorySync(),this.logger)}}function M_(A={}){return new aS0(A)}c0();Z0();var mO1={name:"@brains/email-resend",private:!0,version:"0.2.0-alpha.135",description:"Generic email delivery adapter for Resend",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var XpQ=K.object({apiKey:K.string().min(1).optional(),from:K.string().min(1).optional()});class uO1 extends IQ{fetchImpl;constructor(A={},Q={}){super("email-resend",mO1,A,XpQ);this.fetchImpl=Q.fetchImpl??fetch}async onRegister(A){if(!this.config.apiKey||!this.config.from){this.logger.warn("Email Resend adapter is disabled because apiKey or from is missing");return}let Q=this.logger;A.messaging.subscribe(ow0,async(w)=>{let B=NxA.parse(w.payload);try{return{success:!0,data:await this.sendWithResend(B)}}catch($){if(B.sensitivity==="secret")Q.warn("Email delivery failed for a secret message");else Q.warn("Email delivery failed",{to:B.to,subject:B.subject,error:$ instanceof Error?$.message:String($)});return{success:!1,error:"Email delivery failed"}}})}async sendWithResend(A){let Q=this.config.apiKey,w=this.config.from;if(!Q||!w)return{status:"failed"};let B=await this.fetchImpl("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({from:w,to:A.to,subject:A.subject,text:A.text,...A.html?{html:A.html}:{}})});if(!B.ok)throw Error("Resend email request failed");let $=await B.json();return $.id?{status:"sent",id:$.id}:{status:"sent"}}}function l$0(A={}){return new uO1(A)}c0();import{render as Ap1}from"preact-render-to-string";import{h as HP}from"preact";function cO1(A){var Q,w,B="";if(typeof A=="string"||typeof A=="number")B+=A;else if(typeof A=="object")if(Array.isArray(A)){var $=A.length;for(Q=0;Q<$;Q++)A[Q]&&(w=cO1(A[Q]))&&(B&&(B+=" "),B+=w)}else for(w in A)A[w]&&(B&&(B+=" "),B+=w);return B}function Qy(){for(var A,Q,w=0,B="",$=arguments.length;w<$;w++)(A=arguments[w])&&(Q=cO1(A))&&(B&&(B+=" "),B+=Q);return B}var HpQ=(A)=>{let Q=fpQ(A),{conflictingClassGroups:w,conflictingClassGroupModifiers:B}=A;return{getClassGroupId:(D)=>{let X=D.split("-");if(X[0]===""&&X.length!==1)X.shift();return nO1(X,Q)||WpQ(D)},getConflictingClassGroupIds:(D,X)=>{let H=w[D]||[];if(X&&B[D])return[...H,...B[D]];return H}}},nO1=(A,Q)=>{if(A.length===0)return Q.classGroupId;let w=A[0],B=Q.nextPart.get(w),$=B?nO1(A.slice(1),B):void 0;if($)return $;if(Q.validators.length===0)return;let Y=A.join("-");return Q.validators.find(({validator:D})=>D(Y))?.classGroupId},lO1=/^\[(.+)\]$/,WpQ=(A)=>{if(lO1.test(A)){let Q=lO1.exec(A)[1],w=Q?.substring(0,Q.indexOf(":"));if(w)return"arbitrary.."+w}},fpQ=(A)=>{let{theme:Q,prefix:w}=A,B={nextPart:new Map,validators:[]};return KpQ(Object.entries(A.classGroups),w).forEach(([Y,D])=>{eS0(D,B,Y,Q)}),B},eS0=(A,Q,w,B)=>{A.forEach(($)=>{if(typeof $==="string"){let Y=$===""?Q:pO1(Q,$);Y.classGroupId=w;return}if(typeof $==="function"){if(ZpQ($)){eS0($(B),Q,w,B);return}Q.validators.push({validator:$,classGroupId:w});return}Object.entries($).forEach(([Y,D])=>{eS0(D,pO1(Q,Y),w,B)})})},pO1=(A,Q)=>{let w=A;return Q.split("-").forEach((B)=>{if(!w.nextPart.has(B))w.nextPart.set(B,{nextPart:new Map,validators:[]});w=w.nextPart.get(B)}),w},ZpQ=(A)=>A.isThemeGetter,KpQ=(A,Q)=>{if(!Q)return A;return A.map(([w,B])=>{let $=B.map((Y)=>{if(typeof Y==="string")return Q+Y;if(typeof Y==="object")return Object.fromEntries(Object.entries(Y).map(([D,X])=>[Q+D,X]));return Y});return[w,$]})},UpQ=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,w=new Map,B=new Map,$=(Y,D)=>{if(w.set(Y,D),Q++,Q>A)Q=0,B=w,w=new Map};return{get(Y){let D=w.get(Y);if(D!==void 0)return D;if((D=B.get(Y))!==void 0)return $(Y,D),D},set(Y,D){if(w.has(Y))w.set(Y,D);else $(Y,D)}}};var GpQ=(A)=>{let{separator:Q,experimentalParseClassName:w}=A,B=Q.length===1,$=Q[0],Y=Q.length,D=(X)=>{let H=[],W=0,f=0,Z;for(let L=0;L<X.length;L++){let N=X[L];if(W===0){if(N===$&&(B||X.slice(L,L+Y)===Q)){H.push(X.slice(f,L)),f=L+Y;continue}if(N==="/"){Z=L;continue}}if(N==="[")W++;else if(N==="]")W--}let G=H.length===0?X:X.substring(f),F=G.startsWith("!"),V=F?G.substring(1):G,b=Z&&Z>f?Z-f:void 0;return{modifiers:H,hasImportantModifier:F,baseClassName:V,maybePostfixModifierPosition:b}};if(w)return(X)=>w({className:X,parseClassName:D});return D},zpQ=(A)=>{if(A.length<=1)return A;let Q=[],w=[];return A.forEach((B)=>{if(B[0]==="[")Q.push(...w.sort(),B),w=[];else w.push(B)}),Q.push(...w.sort()),Q},qpQ=(A)=>({cache:UpQ(A.cacheSize),parseClassName:GpQ(A),...HpQ(A)}),FpQ=/\s+/,VpQ=(A,Q)=>{let{parseClassName:w,getClassGroupId:B,getConflictingClassGroupIds:$}=Q,Y=[],D=A.trim().split(FpQ),X="";for(let H=D.length-1;H>=0;H-=1){let W=D[H],{modifiers:f,hasImportantModifier:Z,baseClassName:G,maybePostfixModifierPosition:F}=w(W),V=Boolean(F),b=B(V?G.substring(0,F):G);if(!b){if(!V){X=W+(X.length>0?" "+X:X);continue}if(b=B(G),!b){X=W+(X.length>0?" "+X:X);continue}V=!1}let L=zpQ(f).join(":"),N=Z?L+"!":L,_=N+b;if(Y.includes(_))continue;Y.push(_);let j=$(b,V);for(let g=0;g<j.length;++g){let E=j[g];Y.push(N+E)}X=W+(X.length>0?" "+X:X)}return X};function JpQ(){let A=0,Q,w,B="";while(A<arguments.length)if(Q=arguments[A++]){if(w=rO1(Q))B&&(B+=" "),B+=w}return B}var rO1=(A)=>{if(typeof A==="string")return A;let Q,w="";for(let B=0;B<A.length;B++)if(A[B]){if(Q=rO1(A[B]))w&&(w+=" "),w+=Q}return w};function iO1(A,...Q){let w,B,$,Y=D;function D(H){let W=Q.reduce((f,Z)=>Z(f),A());return w=qpQ(W),B=w.cache.get,$=w.cache.set,Y=X,X(H)}function X(H){let W=B(H);if(W)return W;let f=VpQ(H,w);return $(H,f),f}return function(){return Y(JpQ.apply(null,arguments))}}var a8=(A)=>{let Q=(w)=>w[A]||[];return Q.isThemeGetter=!0,Q},oO1=/^\[(?:([a-z-]+):)?(.+)\]$/i,IpQ=/^\d+\/\d+$/,bpQ=new Set(["px","full","screen"]),LpQ=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,NpQ=/\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$/,jpQ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,MpQ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,_pQ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,E3=(A)=>wy(A)||bpQ.has(A)||IpQ.test(A),aI=(A)=>By(A,"length",CpQ),wy=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),tS0=(A)=>By(A,"number",wy),cd=(A)=>Boolean(A)&&Number.isInteger(Number(A)),PpQ=(A)=>A.endsWith("%")&&wy(A.slice(0,-1)),tQ=(A)=>oO1.test(A),tI=(A)=>LpQ.test(A),kpQ=new Set(["length","size","percentage"]),OpQ=(A)=>By(A,kpQ,sO1),xpQ=(A)=>By(A,"position",sO1),RpQ=new Set(["image","url"]),hpQ=(A)=>By(A,RpQ,EpQ),vpQ=(A)=>By(A,"",ypQ),ld=()=>!0,By=(A,Q,w)=>{let B=oO1.exec(A);if(B){if(B[1])return typeof Q==="string"?B[1]===Q:Q.has(B[1]);return w(B[2])}return!1},CpQ=(A)=>NpQ.test(A)&&!jpQ.test(A),sO1=()=>!1,ypQ=(A)=>MpQ.test(A),EpQ=(A)=>_pQ.test(A);var dO1=()=>{let A=a8("colors"),Q=a8("spacing"),w=a8("blur"),B=a8("brightness"),$=a8("borderColor"),Y=a8("borderRadius"),D=a8("borderSpacing"),X=a8("borderWidth"),H=a8("contrast"),W=a8("grayscale"),f=a8("hueRotate"),Z=a8("invert"),G=a8("gap"),F=a8("gradientColorStops"),V=a8("gradientColorStopPositions"),b=a8("inset"),L=a8("margin"),N=a8("opacity"),_=a8("padding"),j=a8("saturate"),g=a8("scale"),E=a8("sepia"),y=a8("skew"),h=a8("space"),T=a8("translate"),S=()=>["auto","contain","none"],c=()=>["auto","hidden","clip","visible","scroll"],m=()=>["auto",tQ,Q],B0=()=>[tQ,Q],a=()=>["",E3,aI],v=()=>["auto",wy,tQ],P=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],x=()=>["solid","dashed","dotted","double","none"],l=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],p=()=>["start","end","center","between","around","evenly","stretch"],A0=()=>["","0",tQ],o=()=>["auto","avoid","all","avoid-page","page","left","right","column"],K0=()=>[wy,tQ];return{cacheSize:500,separator:":",theme:{colors:[ld],spacing:[E3,aI],blur:["none","",tI,tQ],brightness:K0(),borderColor:[A],borderRadius:["none","","full",tI,tQ],borderSpacing:B0(),borderWidth:a(),contrast:K0(),grayscale:A0(),hueRotate:K0(),invert:A0(),gap:B0(),gradientColorStops:[A],gradientColorStopPositions:[PpQ,aI],inset:m(),margin:m(),opacity:K0(),padding:B0(),saturate:K0(),scale:K0(),sepia:A0(),skew:K0(),space:B0(),translate:B0()},classGroups:{aspect:[{aspect:["auto","square","video",tQ]}],container:["container"],columns:[{columns:[tI]}],"break-after":[{"break-after":o()}],"break-before":[{"break-before":o()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...P(),tQ]}],overflow:[{overflow:c()}],"overflow-x":[{"overflow-x":c()}],"overflow-y":[{"overflow-y":c()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",cd,tQ]}],basis:[{basis:m()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",tQ]}],grow:[{grow:A0()}],shrink:[{shrink:A0()}],order:[{order:["first","last","none",cd,tQ]}],"grid-cols":[{"grid-cols":[ld]}],"col-start-end":[{col:["auto",{span:["full",cd,tQ]},tQ]}],"col-start":[{"col-start":v()}],"col-end":[{"col-end":v()}],"grid-rows":[{"grid-rows":[ld]}],"row-start-end":[{row:["auto",{span:[cd,tQ]},tQ]}],"row-start":[{"row-start":v()}],"row-end":[{"row-end":v()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",tQ]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",tQ]}],gap:[{gap:[G]}],"gap-x":[{"gap-x":[G]}],"gap-y":[{"gap-y":[G]}],"justify-content":[{justify:["normal",...p()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...p(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...p(),"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":[h]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[h]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",tQ,Q]}],"min-w":[{"min-w":[tQ,Q,"min","max","fit"]}],"max-w":[{"max-w":[tQ,Q,"none","full","min","max","fit","prose",{screen:[tI]},tI]}],h:[{h:[tQ,Q,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[tQ,Q,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[tQ,Q,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[tQ,Q,"auto","min","max","fit"]}],"font-size":[{text:["base",tI,aI]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",tS0]}],"font-family":[{font:[ld]}],"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",tQ]}],"line-clamp":[{"line-clamp":["none",wy,tS0]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",E3,tQ]}],"list-image":[{"list-image":["none",tQ]}],"list-style-type":[{list:["none","disc","decimal",tQ]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[A]}],"placeholder-opacity":[{"placeholder-opacity":[N]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[A]}],"text-opacity":[{"text-opacity":[N]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...x(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",E3,aI]}],"underline-offset":[{"underline-offset":["auto",E3,tQ]}],"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:B0()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",tQ]}],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",tQ]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[N]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...P(),xpQ]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",OpQ]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},hpQ]}],"bg-color":[{bg:[A]}],"gradient-from-pos":[{from:[V]}],"gradient-via-pos":[{via:[V]}],"gradient-to-pos":[{to:[V]}],"gradient-from":[{from:[F]}],"gradient-via":[{via:[F]}],"gradient-to":[{to:[F]}],rounded:[{rounded:[Y]}],"rounded-s":[{"rounded-s":[Y]}],"rounded-e":[{"rounded-e":[Y]}],"rounded-t":[{"rounded-t":[Y]}],"rounded-r":[{"rounded-r":[Y]}],"rounded-b":[{"rounded-b":[Y]}],"rounded-l":[{"rounded-l":[Y]}],"rounded-ss":[{"rounded-ss":[Y]}],"rounded-se":[{"rounded-se":[Y]}],"rounded-ee":[{"rounded-ee":[Y]}],"rounded-es":[{"rounded-es":[Y]}],"rounded-tl":[{"rounded-tl":[Y]}],"rounded-tr":[{"rounded-tr":[Y]}],"rounded-br":[{"rounded-br":[Y]}],"rounded-bl":[{"rounded-bl":[Y]}],"border-w":[{border:[X]}],"border-w-x":[{"border-x":[X]}],"border-w-y":[{"border-y":[X]}],"border-w-s":[{"border-s":[X]}],"border-w-e":[{"border-e":[X]}],"border-w-t":[{"border-t":[X]}],"border-w-r":[{"border-r":[X]}],"border-w-b":[{"border-b":[X]}],"border-w-l":[{"border-l":[X]}],"border-opacity":[{"border-opacity":[N]}],"border-style":[{border:[...x(),"hidden"]}],"divide-x":[{"divide-x":[X]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[X]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[N]}],"divide-style":[{divide:x()}],"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:["",...x()]}],"outline-offset":[{"outline-offset":[E3,tQ]}],"outline-w":[{outline:[E3,aI]}],"outline-color":[{outline:[A]}],"ring-w":[{ring:a()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[A]}],"ring-opacity":[{"ring-opacity":[N]}],"ring-offset-w":[{"ring-offset":[E3,aI]}],"ring-offset-color":[{"ring-offset":[A]}],shadow:[{shadow:["","inner","none",tI,vpQ]}],"shadow-color":[{shadow:[ld]}],opacity:[{opacity:[N]}],"mix-blend":[{"mix-blend":[...l(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":l()}],filter:[{filter:["","none"]}],blur:[{blur:[w]}],brightness:[{brightness:[B]}],contrast:[{contrast:[H]}],"drop-shadow":[{"drop-shadow":["","none",tI,tQ]}],grayscale:[{grayscale:[W]}],"hue-rotate":[{"hue-rotate":[f]}],invert:[{invert:[Z]}],saturate:[{saturate:[j]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[w]}],"backdrop-brightness":[{"backdrop-brightness":[B]}],"backdrop-contrast":[{"backdrop-contrast":[H]}],"backdrop-grayscale":[{"backdrop-grayscale":[W]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[f]}],"backdrop-invert":[{"backdrop-invert":[Z]}],"backdrop-opacity":[{"backdrop-opacity":[N]}],"backdrop-saturate":[{"backdrop-saturate":[j]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[D]}],"border-spacing-x":[{"border-spacing-x":[D]}],"border-spacing-y":[{"border-spacing-y":[D]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",tQ]}],duration:[{duration:K0()}],ease:[{ease:["linear","in","out","in-out",tQ]}],delay:[{delay:K0()}],animate:[{animate:["none","spin","ping","pulse","bounce",tQ]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[g]}],"scale-x":[{"scale-x":[g]}],"scale-y":[{"scale-y":[g]}],rotate:[{rotate:[cd,tQ]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[y]}],"skew-y":[{"skew-y":[y]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",tQ]}],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",tQ]}],"caret-color":[{caret:[A]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":B0()}],"scroll-mx":[{"scroll-mx":B0()}],"scroll-my":[{"scroll-my":B0()}],"scroll-ms":[{"scroll-ms":B0()}],"scroll-me":[{"scroll-me":B0()}],"scroll-mt":[{"scroll-mt":B0()}],"scroll-mr":[{"scroll-mr":B0()}],"scroll-mb":[{"scroll-mb":B0()}],"scroll-ml":[{"scroll-ml":B0()}],"scroll-p":[{"scroll-p":B0()}],"scroll-px":[{"scroll-px":B0()}],"scroll-py":[{"scroll-py":B0()}],"scroll-ps":[{"scroll-ps":B0()}],"scroll-pe":[{"scroll-pe":B0()}],"scroll-pt":[{"scroll-pt":B0()}],"scroll-pr":[{"scroll-pr":B0()}],"scroll-pb":[{"scroll-pb":B0()}],"scroll-pl":[{"scroll-pl":B0()}],"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",tQ]}],fill:[{fill:[A,"none"]}],"stroke-w":[{stroke:[E3,aI,tS0]}],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"]}}},gpQ=(A,{cacheSize:Q,prefix:w,separator:B,experimentalParseClassName:$,extend:Y={},override:D={}})=>{pd(A,"cacheSize",Q),pd(A,"prefix",w),pd(A,"separator",B),pd(A,"experimentalParseClassName",$);for(let X in D)TpQ(A[X],D[X]);for(let X in Y)SpQ(A[X],Y[X]);return A},pd=(A,Q,w)=>{if(w!==void 0)A[Q]=w},TpQ=(A,Q)=>{if(Q)for(let w in Q)pd(A,w,Q[w])},SpQ=(A,Q)=>{if(Q)for(let w in Q){let B=Q[w];if(B!==void 0)A[w]=(A[w]||[]).concat(B)}},p$0=(A,...Q)=>typeof A==="function"?iO1(dO1,A,...Q):iO1(()=>gpQ(dO1(),A),...Q);var mpQ=p$0({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 $2(...A){return mpQ(Qy(A))}var aO1=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,tO1=Qy,D8=(A,Q)=>(w)=>{var B;if((Q===null||Q===void 0?void 0:Q.variants)==null)return tO1(A,w===null||w===void 0?void 0:w.class,w===null||w===void 0?void 0:w.className);let{variants:$,defaultVariants:Y}=Q,D=Object.keys($).map((W)=>{let f=w===null||w===void 0?void 0:w[W],Z=Y===null||Y===void 0?void 0:Y[W];if(f===null)return null;let G=aO1(f)||aO1(Z);return $[W][G]}),X=w&&Object.entries(w).reduce((W,f)=>{let[Z,G]=f;if(G===void 0)return W;return W[Z]=G,W},{}),H=Q===null||Q===void 0?void 0:(B=Q.compoundVariants)===null||B===void 0?void 0:B.reduce((W,f)=>{let{class:Z,className:G,...F}=f;return Object.entries(F).every((V)=>{let[b,L]=V;return Array.isArray(L)?L.includes({...Y,...X}[b]):{...Y,...X}[b]===L})?[...W,Z,G]:W},[]);return tO1(A,D,H,w===null||w===void 0?void 0:w.class,w===null||w===void 0?void 0:w.className)};import{jsxDEV as Am0}from"preact/jsx-dev-runtime";var eO1=D8("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 Qm0({variant:A,title:Q,children:w,className:B}){return Am0("div",{className:$2(eO1({variant:A}),B),role:"alert",children:[Q&&Am0("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),Am0("div",{className:$2(Q&&"mt-1","text-sm text-current opacity-75"),children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as upQ}from"preact/jsx-dev-runtime";var Ax1=D8("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 __({variant:A,size:Q,className:w,children:B,ssrOnClick:$,type:Y="button",...D}){return upQ("button",{type:Y,className:$2(Ax1({variant:A,size:Q}),w),...D,...$&&{onclick:$},children:B},void 0,!1,void 0,this)}import{jsxDEV as cpQ}from"preact/jsx-dev-runtime";var Qx1=D8("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 B9({href:A,children:Q,variant:w,size:B,external:$=!1,className:Y,"aria-label":D}){let X=$?{target:"_blank",rel:"noopener noreferrer"}:{};return cpQ("a",{href:A,className:$2(Qx1({variant:w,size:B}),Y),"aria-label":D,...X,children:Q},void 0,!1,void 0,this)}import{jsxDEV as i$0}from"preact/jsx-dev-runtime";var wx1=D8("transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2",{variants:{variant:{default:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent hover:border-brand/40",light:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent",dark:"rounded-[10px] bg-theme-dark hover:bg-theme-muted text-theme-inverse",footer:"rounded-full bg-theme-toggle hover:bg-theme-toggle-hover text-theme-toggle-icon"},size:{sm:"p-1.5",md:"p-2",lg:"p-3"}},defaultVariants:{variant:"default",size:"md"}}),lpQ={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function $y({variant:A,size:Q,className:w}){let B=lpQ[Q??"md"];return i$0("button",{onclick:"toggleTheme()",type:"button",className:$2(wx1({variant:A,size:Q}),w),"aria-label":"Toggle dark mode",children:i$0("svg",{className:$2(B,"transition-colors"),fill:"none",stroke:"currentColor",strokeWidth:1.6,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[i$0("path",{className:"sun-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},void 0,!1,void 0,this),i$0("path",{className:"moon-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M20.354 15.354A9 9 0 018.646 3.646 9 9 0 1020.354 15.354z"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as wm0}from"preact/jsx-dev-runtime";var Bx1=D8("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function d$0({items:A,className:Q,linkClassName:w="hover:text-accent transition-colors",orientation:B,children:$}){if(A.length===0&&!$)return null;let Y=[...A].sort((D,X)=>D.priority-X.priority);return wm0("ul",{className:$2(Bx1({orientation:B}),Q),children:[Y.map((D)=>wm0("li",{children:wm0("a",{href:D.href,className:w,children:D.label},void 0,!1,void 0,this)},D.href,!1,void 0,this)),$]},void 0,!0,void 0,this)}import{jsxDEV as uN8}from"preact/jsx-dev-runtime";import{jsxDEV as pN8}from"preact/jsx-dev-runtime";import{createContext as ppQ,h as ipQ}from"preact";import{useContext as dpQ}from"preact/hooks";var Bm0=ppQ(null);function Yy({headCollector:A,children:Q}){return ipQ(Bm0.Provider,{value:A},Q)}function $x1(){return dpQ(Bm0)}function jQ(A){let Q=$x1();if(Q)Q.setHeadProps(A);return null}import{createContext as baQ,h as LaQ}from"preact";import{useContext as NaQ}from"preact/hooks";mN0();var GC1=X1(UC1(),1),JaQ=new Hc({gfm:!0,breaks:!0}),IaQ={allowedTags:["h1","h2","h3","h4","h5","h6","p","br","hr","ul","ol","li","blockquote","cite","code","pre","em","strong","del","ins","sub","sup","a","img","span","table","thead","tbody","tr","th","td","div"],allowedAttributes:{a:["href","title","name"],img:["src","srcset","sizes","alt","title","width","height","class","loading","decoding"],code:["class"],pre:["class"],span:["class"],cite:["class"],div:["class"],th:["align","colspan","rowspan","scope"],td:["align","colspan","rowspan"]},allowedSchemes:["http","https","mailto","tel"],allowedSchemesByTag:{img:["http","https","entity"]},allowProtocolRelative:!1,disallowedTagsMode:"discard"};function _u0(A,Q){let{imageRenderer:w}=Q??{},$=(w?new Hc({gfm:!0,breaks:!0}).use({renderer:{image(Y,D,X){return w(Y,D,X)??!1}}}):JaQ).parse(A);return $=$.replace(/<\/blockquote>\s*<p>(\u2014|--|\u2013)([\s\S]*?)<\/p>/g,`</blockquote>
4757
+ `)}}c0();class y$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:nS0,jobTypeName:"directory-export"});this.directorySync=w}async process(A,Q,w){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let B=Date.now();try{let $=await this.directorySync.exportEntitiesWithProgress(A.entityTypes,w,A.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:Q,exported:$.exported,failed:$.failed,duration:Date.now()-B}),$}catch($){throw this.logger.error("Directory export job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}c0();class E$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:dS0,jobTypeName:"directory-import"});this.directorySync=w}async process(A,Q,w){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let B=Date.now();try{let $=await this.directorySync.importEntitiesWithProgress(A.paths,w,A.batchSize??100);return this.logger.debug("Directory import job completed",{jobId:Q,imported:$.imported,skipped:$.skipped,failed:$.failed,quarantined:$.quarantined,duration:Date.now()-B}),$}catch($){throw this.logger.error("Directory import job failed",{jobId:Q,error:$}),$}}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}c0();class g$0 extends _w{directorySync;context;constructor(A,Q,w){super(A,{schema:pS0,jobTypeName:"directory-sync"});this.context=Q,this.directorySync=w}async process(A,Q,w){let B=Date.now(),$=A.syncDirection??"both";this.logger.info("Starting directory sync job",{jobId:Q,operation:A.operation,syncDirection:$});let Y={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},D={exported:0,failed:0,errors:[]};if($!=="export")if(await w.report({progress:10,message:"Scanning directory for changes"}),Y=await this.importWithProgress(A.paths,w),$==="import")await this.waitForImportJobs(Y.jobIds,w),await w.report({progress:100,message:`Import complete: ${Y.imported} imported`});else await w.report({progress:50,message:`Imported ${Y.imported} entities`}),await this.waitForImportJobs(Y.jobIds,w),await w.report({progress:56,message:"Processing complete, starting export"});if($!=="import"){let H=$==="export"?10:60;await w.report({progress:H,message:"Exporting entities to directory"}),D=await this.exportWithProgress(A.entityTypes,w),await w.report({progress:100,message:$==="export"?`Export complete: ${D.exported} exported`:`Sync complete: ${Y.imported} imported, ${D.exported} exported`})}let X=Date.now()-B;return this.logger.info("Directory sync job completed",{jobId:Q,duration:X,imported:Y.imported,exported:D.exported}),{import:Y,export:D,duration:X}}async importWithProgress(A,Q){try{return await this.directorySync.importEntitiesWithProgress(A,Q,10)}catch(w){throw this.logger.error("Import phase failed",{error:w}),w}}async exportWithProgress(A,Q){try{return await this.directorySync.exportEntitiesWithProgress(A,Q,10)}catch(w){throw this.logger.error("Export phase failed",{error:w}),w}}async waitForImportJobs(A,Q){if(A.length===0)return;this.logger.debug(`Waiting for ${A.length} import jobs to complete`);let{entityService:w}=this.context,B=300000,$=500,Y=Date.now(),D=async()=>{let H=(await Promise.all(A.map((f)=>w.getAsyncJobStatus(f)))).filter((f)=>f&&(f.status==="completed"||f.status==="failed")).length;if(H===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-Y>B){this.logger.warn(`Timeout waiting for import jobs (${H}/${A.length} completed)`);return}let W=Math.round(H/A.length*100);return await Q.report({progress:50+Math.round(W*0.05),message:`Processing ${H}/${A.length} entities`}),await new Promise((f)=>setTimeout(f,$)),D()};return D()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}c0();class T$0 extends _w{context;directorySync;gitSync;constructor(A,Q,w,B){super(A,{schema:iS0,jobTypeName:"sync-request"});this.context=Q;this.directorySync=w;this.gitSync=B}async process(A,Q,w){await w.report({progress:5,message:"Pulling latest content from git"});let B=await this.gitSync.withLock(async()=>{return await this.gitSync.pull(),await w.report({progress:35,message:"Scanning pulled content for sync changes"}),this.directorySync.queueSyncBatch(this.context,A.source,{rootJobId:Q,interfaceType:A.interfaceType,channelId:A.channelId})});if(!B)return await w.report({progress:100,message:"Sync complete: no files to import"}),{gitPulled:!0,batchQueued:!1};return await w.report({progress:100,message:`Sync queued: ${B.importOperationsCount} import jobs for ${B.totalFiles} files`}),ylQ(B)}summarizeDataForLog(A){return{source:A.source,interfaceType:A.interfaceType,channelId:A.channelId}}}function ylQ(A){return{gitPulled:!0,batchQueued:!0,batchId:A.batchId,importOperations:A.importOperationsCount,totalFiles:A.totalFiles}}c0();class S$0 extends _w{context;constructor(A,Q,w){super(A,{schema:v$0,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,w){let B=v$0.parse(A);this.logger.info("Processing entity deletion for removed file",{entityId:B.entityId,entityType:B.entityType,filePath:B.filePath}),await w.report({progress:0,total:1,message:`Deleting ${B.entityType}:${B.entityId}`});try{let $=await this.context.entityService.deleteEntity({entityType:B.entityType,id:B.entityId});if($)this.logger.info("Successfully deleted entity for removed file",{entityId:B.entityId,entityType:B.entityType});else this.logger.warn("Entity not found in database",{entityId:B.entityId,entityType:B.entityType});return await w.report({progress:1,total:1,message:`Deleted ${B.entityType}:${B.entityId}`}),{deleted:$,entityId:B.entityId,entityType:B.entityType,filePath:B.filePath}}catch($){throw this.logger.error("Failed to delete entity",{entityId:B.entityId,entityType:B.entityType,error:$}),$}}summarizeDataForLog(A){return{entityId:A.entityId,entityType:A.entityType,filePath:A.filePath}}}c0();Z0();var ElQ=K.object({});class m$0 extends _w{directorySync;constructor(A,Q){super(A,{schema:ElQ,jobTypeName:"directory-cleanup"});this.directorySync=Q}async process(A,Q,w){await w.report({progress:0,message:"Removing orphaned entities"});let B=await this.directorySync.removeOrphanedEntities();return await w.report({progress:100,message:`Cleanup complete: ${B.deleted} orphans removed`}),B}}c0();D4();Z0();CB();D4();import{readFile as glQ,writeFile as TlQ}from"fs/promises";var SlQ=rS0;class u$0 extends _w{context;fetcher;constructor(A,Q,w=LW){super(Q,{schema:SlQ,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=w}async process(A,Q,w){let{filePath:B,sourceUrl:$,postTitle:Y,postSlug:D,customAlt:X}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:B,sourceUrl:$,postSlug:D});try{await this.reportProgress(w,{progress:PQ.INIT,message:`Reading file: ${B}`});let H;try{H=await glQ(B,"utf-8")}catch(b){return this.logger.error("Failed to read file",{filePath:B,error:vA(b)}),x6.failure(b)}let W;try{W=lw(H)}catch(b){return this.logger.warn("Failed to parse markdown",{filePath:B,error:vA(b)}),x6.failure(b)}let f=W.frontmatter;if(f.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:B}),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress(w,{progress:PQ.FETCH,message:"Checking for existing image"});let Z=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:$}},limit:1}}),G;if(Z[0])G=Z[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:$,imageId:G}),await this.reportProgress(w,{progress:PQ.EXTRACT,message:`Reusing existing image: ${G}`});else{await this.reportProgress(w,{progress:PQ.PROCESS,message:`Fetching image from ${$}`});let b;try{b=await this.fetcher($)}catch(E){return this.logger.error("Failed to fetch image",{sourceUrl:$,error:vA(E)}),x6.failure(E)}await this.reportProgress(w,{progress:PQ.GENERATE,message:"Creating image entity"});let{base64:L}=WJ(b),N=Hj(L),_=fJ(L);if(!N||!_)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:$}),x6.failure(Error("Could not detect image format or dimensions"));G=`${D}-cover`;let j=`Cover image for ${Y}`,g=X??j;await this.context.entityService.createEntity({entity:{id:G,entityType:"image",content:b,metadata:{title:j,alt:g,format:N,width:_.width,height:_.height,sourceUrl:$}}}),this.logger.debug("Created image entity",{imageId:G,sourceUrl:$}),await this.reportProgress(w,{progress:PQ.EXTRACT,message:`Created image: ${G}`})}await this.reportProgress(w,{progress:PQ.SAVE,message:"Updating file"});let F={...f};delete F.coverImageUrl,delete F.coverImageAlt,F.coverImageId=G;let V=iz(F,W.content);try{await TlQ(B,V,"utf-8")}catch(b){return this.logger.error("Failed to write file",{filePath:B,error:vA(b)}),x6.failure(b)}return await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:B,imageId:G,sourceUrl:$}),{success:!0,imageId:G}}catch(H){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:B,error:vA(H)}),x6.failure(H)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}c0();D4();Z0();CB();import{readFile as mlQ,writeFile as ulQ}from"fs/promises";class c$0 extends _w{converter;constructor(A,Q,w=LW){super(Q,{schema:oS0,jobTypeName:"inline-image-convert"});this.converter=new Pd(A.entityService,Q,w)}async process(A,Q,w){let{filePath:B,postSlug:$}=A;this.logger.debug("Starting inline image conversion job",{jobId:Q,filePath:B,postSlug:$});try{await this.reportProgress(w,{progress:PQ.INIT,message:`Reading file: ${B}`});let Y;try{Y=await mlQ(B,"utf-8")}catch(H){let W=vA(H);return this.logger.error("Failed to read file",{filePath:B,error:W}),{success:!1,error:W}}await this.reportProgress(w,{progress:PQ.FETCH,message:"Detecting inline images"});let D=this.converter.detectInlineImages(Y,$);if(D.length===0)return this.logger.debug("No inline images to convert",{filePath:B}),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:B,count:D.length}),await this.reportProgress(w,{progress:PQ.PROCESS,message:`Converting ${D.length} images`});let X=await this.converter.convert(Y,$);if(!X.converted)return this.logger.debug("No images were converted",{filePath:B}),await this.reportProgress(w,{progress:PQ.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress(w,{progress:PQ.SAVE,message:"Writing updated file"});try{await ulQ(B,X.content,"utf-8")}catch(H){let W=vA(H);return this.logger.error("Failed to write file",{filePath:B,error:W}),{success:!1,error:W}}return await this.reportProgress(w,{progress:PQ.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:B,convertedCount:X.convertedCount}),{success:!0,convertedCount:X.convertedCount}}catch(Y){let D=vA(Y);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:B,error:D}),{success:!1,error:D}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function LO1(A,Q,w){let B=($)=>w.child($);A.jobs.registerHandler("directory-sync",new g$0(B("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new y$0(B("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new E$0(B("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new S$0(B("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new m$0(B("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new u$0(A,B("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new c$0(A,B("InlineImageConversionJobHandler"))),w.debug("Registered async job handlers")}c0();import{unlink as clQ,access as llQ}from"fs/promises";function NO1(A,Q,w,B){let{subscribe:$}=A.messaging,{entityService:Y}=A;$("entity:created",async(D)=>{let{entity:X}=D.payload;try{await Q.fileOps.writeEntity(X),w.debug("Auto-exported created entity",{id:X.id,entityType:X.entityType})}catch(H){w.error("Auto-export FAILED for created entity",{id:X.id,entityType:X.entityType,error:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0})}return{success:!0}}),$("entity:updated",async(D)=>{let{entityType:X,entityId:H}=D.payload;try{let W=await Y.getEntity({entityType:X,id:H});if(!W)return w.debug("Entity not found in DB, skipping export",{entityType:X,entityId:H}),{success:!1};await Q.fileOps.writeEntity(W),w.debug("Auto-exported updated entity",{id:W.id,entityType:W.entityType})}catch(W){w.error("Auto-export FAILED for updated entity",{entityType:X,entityId:H,error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0})}return{success:!0}}),$("entity:deleted",async(D)=>{let{entityId:X,entityType:H}=D.payload,W=Q.fileOps.getFilePath(X,H);if(await llQ(W).then(()=>!0,()=>!1))await clQ(W),w.debug("Auto-deleted entity file",{id:X,entityType:H,path:W});return{success:!0}}),w.debug("Setup auto-sync for entity events",{entityTypes:B})}function jO1(A,Q,w){Q.setJobQueueCallback(async(B)=>{let $=[{type:B.type,data:B.data}];return A.jobs.enqueueBatch($,{priority:5,source:"directory-sync-watcher",rootJobId:S$(),metadata:{operationType:"file_operations",operationTarget:w,pluginId:"directory-sync"}})})}Z0();c0();import{readdir as PO1,mkdir as ilQ,copyFile as dlQ}from"fs/promises";import{join as _O1,resolve as sS0}from"path";import{join as plQ}from"path";async function MO1(A){if(!await y5(plQ(A,".git")))return!1;try{return await AK(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function nlQ(A,Q){if(!await y5(A))return!0;if((await PO1(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await MO1(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function kO1(A,Q){let w=await PO1(A,{withFileTypes:!0});for(let B of w){let $=_O1(A,B.name),Y=_O1(Q,B.name);if(B.isDirectory()){if(!await y5(Y))await ilQ(Y,{recursive:!0});await kO1($,Y)}else await dlQ($,Y)}}async function OO1(A,Q,w){let B=sS0(process.cwd(),A);w=w?sS0(w):sS0(process.cwd(),"seed-content");let $=await nlQ(B,Q);if($&&await y5(w))Q.debug("Copying seed content to brain-data directory"),await kO1(w,B),Q.debug("Seed content copied successfully");else if($)Q.debug("No seed content directory found, starting with empty brain-data");else Q.debug("brain-data directory not empty, skipping seed content")}function xO1(A,Q,w,B,$){let Y=!1,D=async()=>{if(Y)return;Y=!0;let X=Q();if(w.seedContent){let H=w.syncPath??A.dataDir;await OO1(H,B,w.seedContentPath)}try{if($){B.debug("Git enabled \u2014 pulling before import");let W=await $.pull();if(W.files.length>0)B.info("Pulled changes from remote",{filesChanged:W.files.length})}B.debug("Starting initial sync");let H=await X.sync();B.debug("Initial sync completed",{imported:H.import.imported,failed:H.import.failed,duration:H.duration}),await A.messaging.send({type:LN.initialSyncCompleted,payload:{success:!0},...{broadcast:!0}})}catch(H){B.error("Initial sync failed",H),await A.messaging.send({type:LN.initialSyncCompleted,payload:{success:!1,error:vA(H)},...{broadcast:!0}})}};A.messaging.subscribe(LN.pluginsRegistered,async()=>{return B.debug("Plugins registered, starting initial sync"),await D(),{success:!0}})}Z0();function RO1(A,Q,w,B){let $=new DN(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(X){B.error("Git auto-commit failed",{error:X})}})},w),Y=["entity:created","entity:updated","entity:deleted"],D=[];for(let X of Y){let H=A.subscribe(X,async()=>{return $.trigger(),{success:!0}});D.push(H)}return()=>{$.dispose();for(let X of D)X()}}function hO1(A,Q,w,B,$){if(B<=0)return()=>{};let Y=B*60*1000,D=!1,X=async()=>{if(D)return;D=!0;try{let{files:W,result:f}=await A.withLock(async()=>{let Z=await A.pull();if(Z.files.length===0)return{files:[],result:null};let G=await Q.queueSyncBatch(w,"periodic-sync");return{files:Z.files,result:G}});if(W.length>0)$.info("Periodic sync: pulled changes",{filesChanged:W.length});if(f)$.debug("Periodic sync: queued imports",{importOperations:f.importOperationsCount,totalFiles:f.totalFiles})}catch(W){$.error("Periodic git sync failed",{error:W})}finally{D=!1}},H=setInterval(()=>{X()},Y);return $.info("Started periodic git sync",{intervalMinutes:B}),()=>{clearInterval(H)}}import{spawnSync as CO1}from"child_process";import{cpSync as rlQ,existsSync as vO1,mkdirSync as olQ,mkdtempSync as slQ,rmSync as alQ}from"fs";import{tmpdir as tlQ}from"os";import{fileURLToPath as elQ}from"url";import{join as ApQ,resolve as QpQ}from"path";function sI(A,Q){let w=CO1("git",Q,{cwd:A,stdio:"pipe"});if(w.status!==0){let B=w.stderr.toString().trim(),$=w.stdout.toString().trim();throw Error(B||$||`git ${Q.join(" ")} failed`)}}function wpQ(A){return A.startsWith("file://")}function BpQ(A){return elQ(A)}function $pQ(A,Q){return CO1("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function yO1(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!wpQ(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",w=BpQ(A.gitUrl),B=QpQ(A.seedContentPath);if(!vO1(B))throw Error(`Seed content path not found: ${B}`);if(!vO1(w))A.logger.debug("Creating local bare content remote",{remotePath:w,branch:Q}),olQ(w,{recursive:!0}),sI(process.cwd(),["init","--bare",`--initial-branch=${Q}`,w]);if($pQ(w,Q)){A.logger.debug("Content remote already initialized",{remotePath:w,branch:Q});return}A.logger.debug("Seeding local content remote",{remotePath:w,seedPath:B,branch:Q});let $=slQ(ApQ(tlQ(),"directory-sync-seed-"));try{sI($,["init",`--initial-branch=${Q}`]),sI($,["config","user.name",A.authorName??"Brain"]),sI($,["config","user.email",A.authorEmail??"brain@localhost"]),rlQ(B,$,{recursive:!0}),sI($,["add","."]),sI($,["commit","-m","seed content remote"]),sI($,["remote","add","origin",A.gitUrl]),sI($,["push","-u","origin",Q])}finally{alQ($,{recursive:!0,force:!0})}}function EO1(A,Q,w,B,$){let{subscribe:Y}=A.messaging;Y("entity:export:request",async(D)=>{try{return{success:!0,data:await Q().exportEntities(D.payload.entityTypes)}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Export failed"}}}),Y("entity:import:request",async(D)=>{try{let X=Q(),H=D.payload.paths,W=await X.importEntities(H);if(H&&H.length>0)await X.removeOrphanedEntities();return{success:!0,data:W}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Import failed"}}}),Y("sync:status:request",async()=>{try{let X=await Q().getStatus();return{success:!0,data:{syncPath:X.syncPath,isInitialized:X.exists,watchEnabled:X.watching}}}catch(D){return{success:!1,error:D instanceof Error?D.message:"Status check failed"}}}),Y("sync:configure:request",async(D)=>{try{return await w({syncPath:D.payload.syncPath}),{success:!0,data:{syncPath:D.payload.syncPath,configured:!0}}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Configuration failed"}}}),Y("git-sync:get-repo-info",async()=>{if(!$?.repo)return{success:!1,error:"Git not configured"};return{success:!0,data:{repo:$.repo,branch:$.branch??"main"}}}),B.debug("Registered message handlers")}c0();Z0();c0();Z0();function gO1(A,Q){return Sw(A,"history","Get version history for an entity from git. Without sha: returns commit list. With sha: returns entity content at that version.",K.object({entityType:K.string().describe("Entity type (e.g. post, note, link)"),id:K.string().describe("Entity ID"),sha:K.string().optional().describe("Commit SHA to retrieve content at. Omit to list commit history."),limit:K.number().int().positive().optional().default(10).describe("Max commits to return (list mode only)")}),async(w)=>{let B=`${w.entityType}/${w.id}.md`;try{if(w.sha){let Y=await Q.show(w.sha,B);return l8({sha:w.sha,entityType:w.entityType,id:w.id,content:Y},`Content at ${w.sha.slice(0,7)}`)}let $=await Q.log(B,w.limit);if($.length===0)return l8({commits:[]},`No history found for ${w.entityType}/${w.id}`);return l8({commits:$,entityType:w.entityType,id:w.id},`${$.length} version${$.length===1?"":"s"} found`)}catch($){return P9($ instanceof Error?$.message:"History lookup failed")}},{visibility:"anchor",sideEffects:"none"})}function TO1(A,Q,w,B){let $=[Sw(w,"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.",K.object({}),async(Y,D)=>{try{let X=D.channelId?`${D.interfaceType}:${D.channelId}`:`plugin:${w}`,H={interfaceType:D.interfaceType,channelId:D.channelId};if(B){let f=await Q.jobs.enqueue({type:"sync-request",data:{source:X,interfaceType:H.interfaceType,channelId:H.channelId},toolContext:D});return l8({jobId:f,status:"queued",gitPulled:!0},"Sync queued: git pull and filesystem scan will run in the background")}let W=await A.queueSyncBatch(Q,X,H);if(!W)return l8({gitPulled:!1},"No files to sync");return l8({batchId:W.batchId,importOperations:W.importOperationsCount,totalFiles:W.totalFiles,gitPulled:!1},`Sync started: ${W.importOperationsCount} import jobs queued for ${W.totalFiles} files`)}catch(X){return P9(X instanceof Error?X.message:"Sync failed")}},{visibility:"anchor",sideEffects:"external",cli:{name:"sync"}}),Sw(w,"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.",K.object({}),async()=>{try{let Y=await A.getStatus(),D={syncPath:Y.syncPath,lastSync:Y.lastSync?.toISOString(),watching:Y.watching};if(B){let X=await B.getStatus();D.git={isRepo:X.isRepo,branch:X.branch,hasChanges:X.hasChanges,ahead:X.ahead,behind:X.behind,remote:X.remote}}return l8(D)}catch(Y){return P9(Y instanceof Error?Y.message:"Status check failed")}},{visibility:"anchor",sideEffects:"none"})];if(B)$.push(gO1(w,B));return $}var SO1={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.136",description:"Directory-based entity synchronization plugin for Brains",type:"module",main:"./src/index.ts",types:"./src/index.ts",exports:{".":{types:"./src/index.ts",import:"./src/index.ts"}},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix",clean:"rm -rf .turbo"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chokidar:"^3.5.3","simple-git":"^3.21.0"},devDependencies:{"@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"},peerDependencies:{}};class aS0 extends IQ{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",SO1,A,md)}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:w}=A;A.templates.register({status:{name:"status",description:"Directory synchronization status",schema:ud,basePrompt:"",formatter:new C$0,requiredPermission:"anchor"}});let B=this.config.syncPath??A.dataDir;this.directorySync=new kd({syncPath:B,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,entityService:w,logger:Q});try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:B})}catch(D){throw this.logger.error("Failed to initialize directory",D),D}await this.registerJobHandlers(A);let $=this.requireDirectorySync();if(NO1(A,$,this.logger,this.config.entityTypes),this.config.autoSync)jO1(A,$,this.config.syncPath??A.dataDir);let Y=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!Y)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(Y&&this.config.git){await yO1({gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,seedContentPath:this.config.seedContentPath,bootstrapFromSeed:this.config.git.bootstrapFromSeed,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail,logger:this.logger.child("ContentRemoteBootstrap")});let D=this.config.syncPath??A.dataDir;if(this.gitSync=new lS0({logger:this.logger.child("GitSync"),dataDir:D,repo:this.config.git.repo,gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,authToken:this.config.git.authToken,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail}),await this.gitSync.initialize(),this.logger.info("Git integration enabled",{repo:this.config.git.repo}),A.jobs.registerHandler("sync-request",new T$0(this.logger.child("DirectorySyncRequestJobHandler"),A,this.requireDirectorySync(),this.gitSync)),this.gitCleanups.push(RO1(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(hO1(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)xO1(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);EO1(A,()=>this.requireDirectorySync(),(D)=>this.configure(D),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return TO1(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 kd({...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){LO1(A,this.requireDirectorySync(),this.logger)}}function M_(A={}){return new aS0(A)}c0();Z0();var mO1={name:"@brains/email-resend",private:!0,version:"0.2.0-alpha.136",description:"Generic email delivery adapter for Resend",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/email-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var XpQ=K.object({apiKey:K.string().min(1).optional(),from:K.string().min(1).optional()});class uO1 extends IQ{fetchImpl;constructor(A={},Q={}){super("email-resend",mO1,A,XpQ);this.fetchImpl=Q.fetchImpl??fetch}async onRegister(A){if(!this.config.apiKey||!this.config.from){this.logger.warn("Email Resend adapter is disabled because apiKey or from is missing");return}let Q=this.logger;A.messaging.subscribe(ow0,async(w)=>{let B=NxA.parse(w.payload);try{return{success:!0,data:await this.sendWithResend(B)}}catch($){if(B.sensitivity==="secret")Q.warn("Email delivery failed for a secret message");else Q.warn("Email delivery failed",{to:B.to,subject:B.subject,error:$ instanceof Error?$.message:String($)});return{success:!1,error:"Email delivery failed"}}})}async sendWithResend(A){let Q=this.config.apiKey,w=this.config.from;if(!Q||!w)return{status:"failed"};let B=await this.fetchImpl("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({from:w,to:A.to,subject:A.subject,text:A.text,...A.html?{html:A.html}:{}})});if(!B.ok)throw Error("Resend email request failed");let $=await B.json();return $.id?{status:"sent",id:$.id}:{status:"sent"}}}function l$0(A={}){return new uO1(A)}c0();import{render as Ap1}from"preact-render-to-string";import{h as HP}from"preact";function cO1(A){var Q,w,B="";if(typeof A=="string"||typeof A=="number")B+=A;else if(typeof A=="object")if(Array.isArray(A)){var $=A.length;for(Q=0;Q<$;Q++)A[Q]&&(w=cO1(A[Q]))&&(B&&(B+=" "),B+=w)}else for(w in A)A[w]&&(B&&(B+=" "),B+=w);return B}function Qy(){for(var A,Q,w=0,B="",$=arguments.length;w<$;w++)(A=arguments[w])&&(Q=cO1(A))&&(B&&(B+=" "),B+=Q);return B}var HpQ=(A)=>{let Q=fpQ(A),{conflictingClassGroups:w,conflictingClassGroupModifiers:B}=A;return{getClassGroupId:(D)=>{let X=D.split("-");if(X[0]===""&&X.length!==1)X.shift();return nO1(X,Q)||WpQ(D)},getConflictingClassGroupIds:(D,X)=>{let H=w[D]||[];if(X&&B[D])return[...H,...B[D]];return H}}},nO1=(A,Q)=>{if(A.length===0)return Q.classGroupId;let w=A[0],B=Q.nextPart.get(w),$=B?nO1(A.slice(1),B):void 0;if($)return $;if(Q.validators.length===0)return;let Y=A.join("-");return Q.validators.find(({validator:D})=>D(Y))?.classGroupId},lO1=/^\[(.+)\]$/,WpQ=(A)=>{if(lO1.test(A)){let Q=lO1.exec(A)[1],w=Q?.substring(0,Q.indexOf(":"));if(w)return"arbitrary.."+w}},fpQ=(A)=>{let{theme:Q,prefix:w}=A,B={nextPart:new Map,validators:[]};return KpQ(Object.entries(A.classGroups),w).forEach(([Y,D])=>{eS0(D,B,Y,Q)}),B},eS0=(A,Q,w,B)=>{A.forEach(($)=>{if(typeof $==="string"){let Y=$===""?Q:pO1(Q,$);Y.classGroupId=w;return}if(typeof $==="function"){if(ZpQ($)){eS0($(B),Q,w,B);return}Q.validators.push({validator:$,classGroupId:w});return}Object.entries($).forEach(([Y,D])=>{eS0(D,pO1(Q,Y),w,B)})})},pO1=(A,Q)=>{let w=A;return Q.split("-").forEach((B)=>{if(!w.nextPart.has(B))w.nextPart.set(B,{nextPart:new Map,validators:[]});w=w.nextPart.get(B)}),w},ZpQ=(A)=>A.isThemeGetter,KpQ=(A,Q)=>{if(!Q)return A;return A.map(([w,B])=>{let $=B.map((Y)=>{if(typeof Y==="string")return Q+Y;if(typeof Y==="object")return Object.fromEntries(Object.entries(Y).map(([D,X])=>[Q+D,X]));return Y});return[w,$]})},UpQ=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,w=new Map,B=new Map,$=(Y,D)=>{if(w.set(Y,D),Q++,Q>A)Q=0,B=w,w=new Map};return{get(Y){let D=w.get(Y);if(D!==void 0)return D;if((D=B.get(Y))!==void 0)return $(Y,D),D},set(Y,D){if(w.has(Y))w.set(Y,D);else $(Y,D)}}};var GpQ=(A)=>{let{separator:Q,experimentalParseClassName:w}=A,B=Q.length===1,$=Q[0],Y=Q.length,D=(X)=>{let H=[],W=0,f=0,Z;for(let L=0;L<X.length;L++){let N=X[L];if(W===0){if(N===$&&(B||X.slice(L,L+Y)===Q)){H.push(X.slice(f,L)),f=L+Y;continue}if(N==="/"){Z=L;continue}}if(N==="[")W++;else if(N==="]")W--}let G=H.length===0?X:X.substring(f),F=G.startsWith("!"),V=F?G.substring(1):G,b=Z&&Z>f?Z-f:void 0;return{modifiers:H,hasImportantModifier:F,baseClassName:V,maybePostfixModifierPosition:b}};if(w)return(X)=>w({className:X,parseClassName:D});return D},zpQ=(A)=>{if(A.length<=1)return A;let Q=[],w=[];return A.forEach((B)=>{if(B[0]==="[")Q.push(...w.sort(),B),w=[];else w.push(B)}),Q.push(...w.sort()),Q},qpQ=(A)=>({cache:UpQ(A.cacheSize),parseClassName:GpQ(A),...HpQ(A)}),FpQ=/\s+/,VpQ=(A,Q)=>{let{parseClassName:w,getClassGroupId:B,getConflictingClassGroupIds:$}=Q,Y=[],D=A.trim().split(FpQ),X="";for(let H=D.length-1;H>=0;H-=1){let W=D[H],{modifiers:f,hasImportantModifier:Z,baseClassName:G,maybePostfixModifierPosition:F}=w(W),V=Boolean(F),b=B(V?G.substring(0,F):G);if(!b){if(!V){X=W+(X.length>0?" "+X:X);continue}if(b=B(G),!b){X=W+(X.length>0?" "+X:X);continue}V=!1}let L=zpQ(f).join(":"),N=Z?L+"!":L,_=N+b;if(Y.includes(_))continue;Y.push(_);let j=$(b,V);for(let g=0;g<j.length;++g){let E=j[g];Y.push(N+E)}X=W+(X.length>0?" "+X:X)}return X};function JpQ(){let A=0,Q,w,B="";while(A<arguments.length)if(Q=arguments[A++]){if(w=rO1(Q))B&&(B+=" "),B+=w}return B}var rO1=(A)=>{if(typeof A==="string")return A;let Q,w="";for(let B=0;B<A.length;B++)if(A[B]){if(Q=rO1(A[B]))w&&(w+=" "),w+=Q}return w};function iO1(A,...Q){let w,B,$,Y=D;function D(H){let W=Q.reduce((f,Z)=>Z(f),A());return w=qpQ(W),B=w.cache.get,$=w.cache.set,Y=X,X(H)}function X(H){let W=B(H);if(W)return W;let f=VpQ(H,w);return $(H,f),f}return function(){return Y(JpQ.apply(null,arguments))}}var a8=(A)=>{let Q=(w)=>w[A]||[];return Q.isThemeGetter=!0,Q},oO1=/^\[(?:([a-z-]+):)?(.+)\]$/i,IpQ=/^\d+\/\d+$/,bpQ=new Set(["px","full","screen"]),LpQ=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,NpQ=/\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$/,jpQ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,MpQ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,_pQ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,E3=(A)=>wy(A)||bpQ.has(A)||IpQ.test(A),aI=(A)=>By(A,"length",CpQ),wy=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),tS0=(A)=>By(A,"number",wy),cd=(A)=>Boolean(A)&&Number.isInteger(Number(A)),PpQ=(A)=>A.endsWith("%")&&wy(A.slice(0,-1)),tQ=(A)=>oO1.test(A),tI=(A)=>LpQ.test(A),kpQ=new Set(["length","size","percentage"]),OpQ=(A)=>By(A,kpQ,sO1),xpQ=(A)=>By(A,"position",sO1),RpQ=new Set(["image","url"]),hpQ=(A)=>By(A,RpQ,EpQ),vpQ=(A)=>By(A,"",ypQ),ld=()=>!0,By=(A,Q,w)=>{let B=oO1.exec(A);if(B){if(B[1])return typeof Q==="string"?B[1]===Q:Q.has(B[1]);return w(B[2])}return!1},CpQ=(A)=>NpQ.test(A)&&!jpQ.test(A),sO1=()=>!1,ypQ=(A)=>MpQ.test(A),EpQ=(A)=>_pQ.test(A);var dO1=()=>{let A=a8("colors"),Q=a8("spacing"),w=a8("blur"),B=a8("brightness"),$=a8("borderColor"),Y=a8("borderRadius"),D=a8("borderSpacing"),X=a8("borderWidth"),H=a8("contrast"),W=a8("grayscale"),f=a8("hueRotate"),Z=a8("invert"),G=a8("gap"),F=a8("gradientColorStops"),V=a8("gradientColorStopPositions"),b=a8("inset"),L=a8("margin"),N=a8("opacity"),_=a8("padding"),j=a8("saturate"),g=a8("scale"),E=a8("sepia"),y=a8("skew"),h=a8("space"),T=a8("translate"),S=()=>["auto","contain","none"],c=()=>["auto","hidden","clip","visible","scroll"],m=()=>["auto",tQ,Q],B0=()=>[tQ,Q],a=()=>["",E3,aI],v=()=>["auto",wy,tQ],P=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],x=()=>["solid","dashed","dotted","double","none"],l=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],p=()=>["start","end","center","between","around","evenly","stretch"],A0=()=>["","0",tQ],o=()=>["auto","avoid","all","avoid-page","page","left","right","column"],K0=()=>[wy,tQ];return{cacheSize:500,separator:":",theme:{colors:[ld],spacing:[E3,aI],blur:["none","",tI,tQ],brightness:K0(),borderColor:[A],borderRadius:["none","","full",tI,tQ],borderSpacing:B0(),borderWidth:a(),contrast:K0(),grayscale:A0(),hueRotate:K0(),invert:A0(),gap:B0(),gradientColorStops:[A],gradientColorStopPositions:[PpQ,aI],inset:m(),margin:m(),opacity:K0(),padding:B0(),saturate:K0(),scale:K0(),sepia:A0(),skew:K0(),space:B0(),translate:B0()},classGroups:{aspect:[{aspect:["auto","square","video",tQ]}],container:["container"],columns:[{columns:[tI]}],"break-after":[{"break-after":o()}],"break-before":[{"break-before":o()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...P(),tQ]}],overflow:[{overflow:c()}],"overflow-x":[{"overflow-x":c()}],"overflow-y":[{"overflow-y":c()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[b]}],"inset-x":[{"inset-x":[b]}],"inset-y":[{"inset-y":[b]}],start:[{start:[b]}],end:[{end:[b]}],top:[{top:[b]}],right:[{right:[b]}],bottom:[{bottom:[b]}],left:[{left:[b]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",cd,tQ]}],basis:[{basis:m()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",tQ]}],grow:[{grow:A0()}],shrink:[{shrink:A0()}],order:[{order:["first","last","none",cd,tQ]}],"grid-cols":[{"grid-cols":[ld]}],"col-start-end":[{col:["auto",{span:["full",cd,tQ]},tQ]}],"col-start":[{"col-start":v()}],"col-end":[{"col-end":v()}],"grid-rows":[{"grid-rows":[ld]}],"row-start-end":[{row:["auto",{span:[cd,tQ]},tQ]}],"row-start":[{"row-start":v()}],"row-end":[{"row-end":v()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",tQ]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",tQ]}],gap:[{gap:[G]}],"gap-x":[{"gap-x":[G]}],"gap-y":[{"gap-y":[G]}],"justify-content":[{justify:["normal",...p()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...p(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...p(),"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":[h]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[h]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",tQ,Q]}],"min-w":[{"min-w":[tQ,Q,"min","max","fit"]}],"max-w":[{"max-w":[tQ,Q,"none","full","min","max","fit","prose",{screen:[tI]},tI]}],h:[{h:[tQ,Q,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[tQ,Q,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[tQ,Q,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[tQ,Q,"auto","min","max","fit"]}],"font-size":[{text:["base",tI,aI]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",tS0]}],"font-family":[{font:[ld]}],"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",tQ]}],"line-clamp":[{"line-clamp":["none",wy,tS0]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",E3,tQ]}],"list-image":[{"list-image":["none",tQ]}],"list-style-type":[{list:["none","disc","decimal",tQ]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[A]}],"placeholder-opacity":[{"placeholder-opacity":[N]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[A]}],"text-opacity":[{"text-opacity":[N]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...x(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",E3,aI]}],"underline-offset":[{"underline-offset":["auto",E3,tQ]}],"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:B0()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",tQ]}],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",tQ]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[N]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...P(),xpQ]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",OpQ]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},hpQ]}],"bg-color":[{bg:[A]}],"gradient-from-pos":[{from:[V]}],"gradient-via-pos":[{via:[V]}],"gradient-to-pos":[{to:[V]}],"gradient-from":[{from:[F]}],"gradient-via":[{via:[F]}],"gradient-to":[{to:[F]}],rounded:[{rounded:[Y]}],"rounded-s":[{"rounded-s":[Y]}],"rounded-e":[{"rounded-e":[Y]}],"rounded-t":[{"rounded-t":[Y]}],"rounded-r":[{"rounded-r":[Y]}],"rounded-b":[{"rounded-b":[Y]}],"rounded-l":[{"rounded-l":[Y]}],"rounded-ss":[{"rounded-ss":[Y]}],"rounded-se":[{"rounded-se":[Y]}],"rounded-ee":[{"rounded-ee":[Y]}],"rounded-es":[{"rounded-es":[Y]}],"rounded-tl":[{"rounded-tl":[Y]}],"rounded-tr":[{"rounded-tr":[Y]}],"rounded-br":[{"rounded-br":[Y]}],"rounded-bl":[{"rounded-bl":[Y]}],"border-w":[{border:[X]}],"border-w-x":[{"border-x":[X]}],"border-w-y":[{"border-y":[X]}],"border-w-s":[{"border-s":[X]}],"border-w-e":[{"border-e":[X]}],"border-w-t":[{"border-t":[X]}],"border-w-r":[{"border-r":[X]}],"border-w-b":[{"border-b":[X]}],"border-w-l":[{"border-l":[X]}],"border-opacity":[{"border-opacity":[N]}],"border-style":[{border:[...x(),"hidden"]}],"divide-x":[{"divide-x":[X]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[X]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[N]}],"divide-style":[{divide:x()}],"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:["",...x()]}],"outline-offset":[{"outline-offset":[E3,tQ]}],"outline-w":[{outline:[E3,aI]}],"outline-color":[{outline:[A]}],"ring-w":[{ring:a()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[A]}],"ring-opacity":[{"ring-opacity":[N]}],"ring-offset-w":[{"ring-offset":[E3,aI]}],"ring-offset-color":[{"ring-offset":[A]}],shadow:[{shadow:["","inner","none",tI,vpQ]}],"shadow-color":[{shadow:[ld]}],opacity:[{opacity:[N]}],"mix-blend":[{"mix-blend":[...l(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":l()}],filter:[{filter:["","none"]}],blur:[{blur:[w]}],brightness:[{brightness:[B]}],contrast:[{contrast:[H]}],"drop-shadow":[{"drop-shadow":["","none",tI,tQ]}],grayscale:[{grayscale:[W]}],"hue-rotate":[{"hue-rotate":[f]}],invert:[{invert:[Z]}],saturate:[{saturate:[j]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[w]}],"backdrop-brightness":[{"backdrop-brightness":[B]}],"backdrop-contrast":[{"backdrop-contrast":[H]}],"backdrop-grayscale":[{"backdrop-grayscale":[W]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[f]}],"backdrop-invert":[{"backdrop-invert":[Z]}],"backdrop-opacity":[{"backdrop-opacity":[N]}],"backdrop-saturate":[{"backdrop-saturate":[j]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[D]}],"border-spacing-x":[{"border-spacing-x":[D]}],"border-spacing-y":[{"border-spacing-y":[D]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",tQ]}],duration:[{duration:K0()}],ease:[{ease:["linear","in","out","in-out",tQ]}],delay:[{delay:K0()}],animate:[{animate:["none","spin","ping","pulse","bounce",tQ]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[g]}],"scale-x":[{"scale-x":[g]}],"scale-y":[{"scale-y":[g]}],rotate:[{rotate:[cd,tQ]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[y]}],"skew-y":[{"skew-y":[y]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",tQ]}],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",tQ]}],"caret-color":[{caret:[A]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":B0()}],"scroll-mx":[{"scroll-mx":B0()}],"scroll-my":[{"scroll-my":B0()}],"scroll-ms":[{"scroll-ms":B0()}],"scroll-me":[{"scroll-me":B0()}],"scroll-mt":[{"scroll-mt":B0()}],"scroll-mr":[{"scroll-mr":B0()}],"scroll-mb":[{"scroll-mb":B0()}],"scroll-ml":[{"scroll-ml":B0()}],"scroll-p":[{"scroll-p":B0()}],"scroll-px":[{"scroll-px":B0()}],"scroll-py":[{"scroll-py":B0()}],"scroll-ps":[{"scroll-ps":B0()}],"scroll-pe":[{"scroll-pe":B0()}],"scroll-pt":[{"scroll-pt":B0()}],"scroll-pr":[{"scroll-pr":B0()}],"scroll-pb":[{"scroll-pb":B0()}],"scroll-pl":[{"scroll-pl":B0()}],"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",tQ]}],fill:[{fill:[A,"none"]}],"stroke-w":[{stroke:[E3,aI,tS0]}],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"]}}},gpQ=(A,{cacheSize:Q,prefix:w,separator:B,experimentalParseClassName:$,extend:Y={},override:D={}})=>{pd(A,"cacheSize",Q),pd(A,"prefix",w),pd(A,"separator",B),pd(A,"experimentalParseClassName",$);for(let X in D)TpQ(A[X],D[X]);for(let X in Y)SpQ(A[X],Y[X]);return A},pd=(A,Q,w)=>{if(w!==void 0)A[Q]=w},TpQ=(A,Q)=>{if(Q)for(let w in Q)pd(A,w,Q[w])},SpQ=(A,Q)=>{if(Q)for(let w in Q){let B=Q[w];if(B!==void 0)A[w]=(A[w]||[]).concat(B)}},p$0=(A,...Q)=>typeof A==="function"?iO1(dO1,A,...Q):iO1(()=>gpQ(dO1(),A),...Q);var mpQ=p$0({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 $2(...A){return mpQ(Qy(A))}var aO1=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,tO1=Qy,D8=(A,Q)=>(w)=>{var B;if((Q===null||Q===void 0?void 0:Q.variants)==null)return tO1(A,w===null||w===void 0?void 0:w.class,w===null||w===void 0?void 0:w.className);let{variants:$,defaultVariants:Y}=Q,D=Object.keys($).map((W)=>{let f=w===null||w===void 0?void 0:w[W],Z=Y===null||Y===void 0?void 0:Y[W];if(f===null)return null;let G=aO1(f)||aO1(Z);return $[W][G]}),X=w&&Object.entries(w).reduce((W,f)=>{let[Z,G]=f;if(G===void 0)return W;return W[Z]=G,W},{}),H=Q===null||Q===void 0?void 0:(B=Q.compoundVariants)===null||B===void 0?void 0:B.reduce((W,f)=>{let{class:Z,className:G,...F}=f;return Object.entries(F).every((V)=>{let[b,L]=V;return Array.isArray(L)?L.includes({...Y,...X}[b]):{...Y,...X}[b]===L})?[...W,Z,G]:W},[]);return tO1(A,D,H,w===null||w===void 0?void 0:w.class,w===null||w===void 0?void 0:w.className)};import{jsxDEV as Am0}from"preact/jsx-dev-runtime";var eO1=D8("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 Qm0({variant:A,title:Q,children:w,className:B}){return Am0("div",{className:$2(eO1({variant:A}),B),role:"alert",children:[Q&&Am0("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),Am0("div",{className:$2(Q&&"mt-1","text-sm text-current opacity-75"),children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as upQ}from"preact/jsx-dev-runtime";var Ax1=D8("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 __({variant:A,size:Q,className:w,children:B,ssrOnClick:$,type:Y="button",...D}){return upQ("button",{type:Y,className:$2(Ax1({variant:A,size:Q}),w),...D,...$&&{onclick:$},children:B},void 0,!1,void 0,this)}import{jsxDEV as cpQ}from"preact/jsx-dev-runtime";var Qx1=D8("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 B9({href:A,children:Q,variant:w,size:B,external:$=!1,className:Y,"aria-label":D}){let X=$?{target:"_blank",rel:"noopener noreferrer"}:{};return cpQ("a",{href:A,className:$2(Qx1({variant:w,size:B}),Y),"aria-label":D,...X,children:Q},void 0,!1,void 0,this)}import{jsxDEV as i$0}from"preact/jsx-dev-runtime";var wx1=D8("transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2",{variants:{variant:{default:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent hover:border-brand/40",light:"rounded-[10px] bg-theme-subtle border border-theme text-theme-muted hover:text-accent",dark:"rounded-[10px] bg-theme-dark hover:bg-theme-muted text-theme-inverse",footer:"rounded-full bg-theme-toggle hover:bg-theme-toggle-hover text-theme-toggle-icon"},size:{sm:"p-1.5",md:"p-2",lg:"p-3"}},defaultVariants:{variant:"default",size:"md"}}),lpQ={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function $y({variant:A,size:Q,className:w}){let B=lpQ[Q??"md"];return i$0("button",{onclick:"toggleTheme()",type:"button",className:$2(wx1({variant:A,size:Q}),w),"aria-label":"Toggle dark mode",children:i$0("svg",{className:$2(B,"transition-colors"),fill:"none",stroke:"currentColor",strokeWidth:1.6,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[i$0("path",{className:"sun-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"},void 0,!1,void 0,this),i$0("path",{className:"moon-icon",strokeLinecap:"round",strokeLinejoin:"round",d:"M20.354 15.354A9 9 0 018.646 3.646 9 9 0 1020.354 15.354z"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}import{jsxDEV as wm0}from"preact/jsx-dev-runtime";var Bx1=D8("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function d$0({items:A,className:Q,linkClassName:w="hover:text-accent transition-colors",orientation:B,children:$}){if(A.length===0&&!$)return null;let Y=[...A].sort((D,X)=>D.priority-X.priority);return wm0("ul",{className:$2(Bx1({orientation:B}),Q),children:[Y.map((D)=>wm0("li",{children:wm0("a",{href:D.href,className:w,children:D.label},void 0,!1,void 0,this)},D.href,!1,void 0,this)),$]},void 0,!0,void 0,this)}import{jsxDEV as uN8}from"preact/jsx-dev-runtime";import{jsxDEV as pN8}from"preact/jsx-dev-runtime";import{createContext as ppQ,h as ipQ}from"preact";import{useContext as dpQ}from"preact/hooks";var Bm0=ppQ(null);function Yy({headCollector:A,children:Q}){return ipQ(Bm0.Provider,{value:A},Q)}function $x1(){return dpQ(Bm0)}function jQ(A){let Q=$x1();if(Q)Q.setHeadProps(A);return null}import{createContext as baQ,h as LaQ}from"preact";import{useContext as NaQ}from"preact/hooks";mN0();var GC1=X1(UC1(),1),JaQ=new Hc({gfm:!0,breaks:!0}),IaQ={allowedTags:["h1","h2","h3","h4","h5","h6","p","br","hr","ul","ol","li","blockquote","cite","code","pre","em","strong","del","ins","sub","sup","a","img","span","table","thead","tbody","tr","th","td","div"],allowedAttributes:{a:["href","title","name"],img:["src","srcset","sizes","alt","title","width","height","class","loading","decoding"],code:["class"],pre:["class"],span:["class"],cite:["class"],div:["class"],th:["align","colspan","rowspan","scope"],td:["align","colspan","rowspan"]},allowedSchemes:["http","https","mailto","tel"],allowedSchemesByTag:{img:["http","https","entity"]},allowProtocolRelative:!1,disallowedTagsMode:"discard"};function _u0(A,Q){let{imageRenderer:w}=Q??{},$=(w?new Hc({gfm:!0,breaks:!0}).use({renderer:{image(Y,D,X){return w(Y,D,X)??!1}}}):JaQ).parse(A);return $=$.replace(/<\/blockquote>\s*<p>(\u2014|--|\u2013)([\s\S]*?)<\/p>/g,`</blockquote>
4758
4758
  <cite class="block-attribution"><span class="emdash">$1</span>$2</cite>`),GC1.default($,IaQ)}var zC1=baQ(null);function Ly({imageRenderer:A,children:Q}){return LaQ(zC1.Provider,{value:A??null},Q)}function qC1(){return NaQ(zC1)}function i3(){let A=qC1();return(Q)=>_u0(Q,A?{imageRenderer:A}:void 0)}var jaQ=/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,MaQ={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},_aQ=/&(?:amp|lt|gt|quot|#39);/g;function PaQ(A){return A.replace(_aQ,(Q)=>MaQ[Q]??Q)}function Pu0(A){return A.replace(jaQ,(Q,w)=>{return`<div class="mermaid">${PaQ(w)}</div>`})}var FC1=/<!--\s*\.slide:\s*(.*?)\s*-->/g;function VC1(A){let Q={};for(let B of A.matchAll(FC1)){let $=B[1]??"";for(let D of $.matchAll(/([\w-]+)=["']([^"']*?)["']/g)){let X=D[1],H=D[2];if(X&&H!==void 0)Q[X]=H}let Y=$.replace(/([\w-]+)=["']([^"']*?)["']/g,"").trim();if(Y)for(let D of Y.matchAll(/(?:^|\s)([\w-]+)(?=\s|$)/g)){let X=D[1];if(X)Q[X]="true"}}let w=A.replace(FC1,"").replace(/^\n+/,"").replace(/\n{3,}/g,`
4759
4759
 
4760
4760
  `).trim();return{attributes:Q,markdown:w}}var kaQ=/<!--\s*\.break\s*-->/;function JC1(A){let Q=A.split(kaQ);return Q.length>1?Q:null}import{jsxDEV as MG}from"preact/jsx-dev-runtime";var ku0=({markdown:A,deck:Q})=>{let w=i3(),$=A.split(/^---$/gm).map((f)=>f.trim()).map((f)=>{let{attributes:Z,markdown:G}=VC1(f),F=JC1(G),V;if(F)V=`<div class="slide-columns">${F.map((L)=>`<div class="slide-column">${Pu0(w(L.trim()))}</div>`).join("")}</div>`;else V=Pu0(w(G));return{attributes:Z,htmlContent:V}}),Y=$.some((f)=>f.htmlContent.includes('class="mermaid"')),D=Q?.frontmatter?.title??Q?.metadata?.title,X=Q?.frontmatter?.description??Q?.metadata?.description,H=Q?.ogImageUrl??Q?.coverImageUrl,W=$.map(({attributes:f,htmlContent:Z},G)=>MG("section",{...f,dangerouslySetInnerHTML:{__html:Z}},G,!1,void 0,this));return MG("section",{className:"presentation-section",children:[D&&MG(jQ,{title:D,...X?{description:X}:{},...H?{ogImage:H}:{},ogType:"article"},void 0,!1,void 0,this),MG("link",{rel:"stylesheet",href:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.css"},void 0,!1,void 0,this),MG("div",{className:"reveal",children:MG("div",{className:"slides",children:W},void 0,!1,void 0,this)},void 0,!1,void 0,this),MG("script",{src:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.js",defer:!0},void 0,!1,void 0,this),Y&&MG("script",{src:"https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js",defer:!0},void 0,!1,void 0,this),MG("script",{dangerouslySetInnerHTML:{__html:`
@@ -5741,13 +5741,13 @@ ${A.map((Y)=>({url:`${Q}${Y.path}`,lastmod:w,changefreq:Y.path==="/"?"daily":"we
5741
5741
  `+$:w,D=gG(this.outputDir,"styles","main.css");await this.cssProcessor.process(Y,D,this.workingDir,this.outputDir,this.logger);let X=await O7.readFile(D,"utf-8"),H=B.length>0?B:Q;if(H.length>0){let W=H.join(`
5742
5742
  `)+`
5743
5743
 
5744
- `+X;await O7.writeFile(D,W,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=gG(process.cwd(),"public");try{await O7.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await O7.readdir(A,{withFileTypes:!0});for(let w of Q){let B=gG(A,w.name),$=gG(this.outputDir,w.name);if(w.isDirectory())await this.copyDirectory(B,$);else await O7.copyFile(B,$),this.logger.debug(`Copied static asset: ${w.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([w,B])=>{let $=w.startsWith("/")?w.slice(1):w,Y=gG(this.outputDir,$);await O7.mkdir(h7w(Y),{recursive:!0}),await O7.writeFile(Y,B,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await O7.mkdir(Q,{recursive:!0});let w=await O7.readdir(A,{withFileTypes:!0});for(let B of w){let $=gG(A,B.name),Y=gG(Q,B.name);if(B.isDirectory())await this.copyDirectory($,Y);else await O7.copyFile($,Y)}}}function Xp0(A){return new Qp1(A)}_5();Z0();Z0();_5();var wp1=K.object({environment:K.enum(["preview","production"]),outputDir:K.string(),workingDir:K.string().optional(),sharedImagesDir:K.string().default("./dist/images"),enableContentGeneration:K.boolean().default(!1),cleanBeforeBuild:K.boolean().default(!0),siteConfig:GX,layouts:K.record(K.any()),themeCSS:K.string().optional()}),py8=K.object({success:K.boolean(),outputDir:K.string(),filesGenerated:K.number(),routesBuilt:K.number(),errors:K.array(K.string()).optional(),warnings:K.array(K.string()).optional()});function Bp1(A){let Q=A.list(),w=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:w}}function $p1(A,Q,w){let B=Q.getProfile(),$=w.getNavigationItems("primary"),Y=w.getNavigationItems("secondary");return{...A,...B.socialLinks!==void 0&&{socialLinks:B.socialLinks},navigation:{primary:$,secondary:Y},copyright:A.copyright??"Powered by Rizom"}}_5();D4();_5();Z0();var v7w=K.object({id:K.string(),entityType:K.string(),content:K.string(),metadata:K.object({slug:K.string()}).passthrough()}).passthrough(),C7w=K.object({content:K.string(),metadata:K.object({width:K.number().optional(),height:K.number().optional()}).passthrough()});async function L40(A,Q){let w=Q.urlGenerator??s7.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((g)=>L40(g,{...Q,urlGenerator:w})));if(typeof A!=="object")return A;let B={},$=Object.entries(A),Y=await Promise.all($.map(([,g])=>L40(g,{...Q,urlGenerator:w})));for(let g=0;g<$.length;g++){let E=$[g];if(E)B[E[0]]=Y[g]}let D=v7w.safeParse(A);if(!D.success)return B;let X=D.data,H=X.entityType,W=X.metadata.slug,f=Q.pipelineContext.entityDisplay?.[H],Z=f?f.label:H.charAt(0).toUpperCase()+H.slice(1),G=f?f.pluralName??f.label.toLowerCase()+"s":KX(H),F=`/${G}`,V=G.charAt(0).toUpperCase()+G.slice(1),b=zu(X),L=await y7w(b,Q),N=h10(X)??b,_=await E7w(N,Q);return{...B,...X,url:w.generateUrl(H,W),typeLabel:Z,listUrl:F,listLabel:V,...L,..._&&{ogImageUrl:_}}}async function y7w(A,Q){let w=A?Q.imageBuildService?.get(A):void 0;if(w)return{coverImageUrl:w.src,coverImageWidth:w.width,coverImageHeight:w.height,...w.srcset&&{coverImageSrcset:w.srcset,coverImageSizes:w.sizes}};let B=await Dp1(A,Q.pipelineContext.services.entityService);if(!B)return{};return{coverImageUrl:B.url,...B.width&&{coverImageWidth:B.width},...B.height&&{coverImageHeight:B.height}}}async function E7w(A,Q){if(!A)return;let w=Q.imageBuildService?.get(A);if(w)return Yp1(w.src,Q.siteUrl);let B=await Dp1(A,Q.pipelineContext.services.entityService);if(!B)return;if(B.url.startsWith("data:"))return;return Yp1(B.url,Q.siteUrl)}function Yp1(A,Q){if(/^https?:\/\//i.test(A)||A.startsWith("data:"))return A;if(!Q)return A;return`${Q.replace(/\/$/,"")}/${A.replace(/^\//,"")}`}async function Dp1(A,Q){if(!A)return;let w=await Q.getEntity({entityType:"image",id:A}),B=C7w.safeParse(w);if(!B.success)return;return{url:B.data.content,...B.data.metadata.width&&{width:B.data.metadata.width},...B.data.metadata.height&&{height:B.data.metadata.height}}}async function Xp1(A,Q){let w=new Set;try{let B=A.getEntityTypes();for(let $ of B){if($==="image")continue;let Y=await A.listEntities({entityType:$});for(let D of Y){let X=zu(D);if(X)w.add(X);let H=h10(D);if(H)w.add(H)}}}catch(B){Q.warn("Failed to collect image IDs for pre-resolution",{error:vA(B)})}return[...w]}async function Hp1(A,Q,w,B,$){if(!A.template)return A.content??null;let Y=A.template,D=A.dataQuery?{dataParams:A.dataQuery,fallback:A.content,publishedOnly:w,visibilityScope:B}:{savedContent:{entityType:"site-content",entityId:`${Q.id}:${A.id}`},fallback:A.content,visibilityScope:B},X=await $.pipelineContext.services.resolveTemplateContent(Y,D);if(!X)return null;return L40(X,{pipelineContext:$.pipelineContext,imageBuildService:$.imageBuildService,siteUrl:$.siteUrl,urlGenerator:s7.getInstance()})}function Wp1(A){return{routes:A.routes,siteConfig:{title:A.siteMetadata.title,description:A.siteMetadata.description,...A.siteMetadata.url&&{url:A.siteMetadata.url},...A.siteMetadata.copyright&&{copyright:A.siteMetadata.copyright},...A.siteMetadata.themeMode&&{themeMode:A.siteMetadata.themeMode},...A.siteMetadata.analyticsScript&&{analyticsScript:A.siteMetadata.analyticsScript}},headScripts:A.buildOptions.headScripts,...A.buildOptions.staticAssets&&{staticAssets:A.buildOptions.staticAssets},getContent:async(Q,w)=>{let B=A.parsedOptions.environment==="production";return Hp1(w,Q,B,"public",{pipelineContext:A.pipelineContext,imageBuildService:A.imageBuildService,siteUrl:A.siteMetadata.url})},getViewTemplate:(Q)=>{return A.pipelineContext.services.getViewTemplate(Q)},layouts:A.parsedOptions.layouts,getSiteLayoutInfo:async()=>{return $p1(A.siteMetadata,A.pipelineContext.profileService,A.pipelineContext.routeRegistry)},...A.parsedOptions.themeCSS!==void 0&&{themeCSS:A.parsedOptions.themeCSS},...A.buildOptions.slots&&{slots:A.buildOptions.slots},imageBuildService:A.imageBuildService}}import{join as g7w}from"path";async function fp1(A){let Q=A.parsedOptions.workingDir??g7w(A.parsedOptions.outputDir,".preact-work"),w=A.staticSiteBuilderFactory({logger:A.logger.child("StaticSiteBuilder"),workingDir:Q,outputDir:A.parsedOptions.outputDir});if(A.parsedOptions.cleanBeforeBuild)await w.clean();return w}async function Zp1(A){await new I40({logger:A.pipelineContext.logger.child("DynamicRouteGenerator"),entityService:A.pipelineContext.services.entityService,listViewTemplateNames:()=>A.pipelineContext.services.listViewTemplateNames()},A.pipelineContext.routeRegistry,A.pipelineContext.entityDisplay,{visibilityScope:"public",...A.publishedOnly!==void 0&&{publishedOnly:A.publishedOnly}}).generateEntityRoutes()}async function Kp1(A){let Q=new J40(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),w=await Xp1(A.pipelineContext.services.entityService,A.pipelineContext.logger);if(w.length>0)await Q.resolveAll(w);return Q}async function Up1(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,(w)=>{Q?.report(w).catch(()=>{})})}function Gp1(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function zp1(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function qp1(A){let Q=wp1.parse(A.buildOptions),w=D7.from(A.progress),B=[];try{await w?.report({message:"Starting site build",progress:0,total:100}),await w?.report({message:"Generating dynamic routes",progress:10,total:100}),await Zp1({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let $=await fp1({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),Y=Bp1(A.pipelineContext.routeRegistry);B.push(...Y.warnings);let{routes:D}=Y;await w?.report({message:`Building ${D.length} routes`,progress:20,total:100}),await w?.report({message:"Resolving images",progress:25,total:100});let X=await Kp1({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),H=Wp1({routes:D,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:X,siteMetadata:Q.siteConfig});return await Up1({staticSiteBuilder:$,buildContext:H,reporter:w}),await w?.report({message:"Site build complete",progress:100,total:100}),Gp1({outputDir:Q.outputDir,routesBuilt:D.length,warnings:B})}catch($){let Y=Error("Site build process failed");return A.pipelineContext.logger.error("Site build failed",{error:Y,originalError:$}),zp1({outputDir:Q.outputDir,errorMessage:Y.message})}}class bH{static instance=null;static defaultStaticSiteBuilderFactory=Xp0;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){bH.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,w,B,$=void 0){return bH.instance??=new bH(A,bH.defaultStaticSiteBuilderFactory,Q,w,B,$),bH.instance}static resetInstance(){bH.instance=null}static createFresh(A,Q,w,B,$,Y=void 0){return new bH(A,$??bH.defaultStaticSiteBuilderFactory,Q,w,B,Y)}constructor(A,Q,w,B,$,Y){this.pipelineContext={logger:A,services:w,routeRegistry:B,profileService:$,entityDisplay:Y},this.staticSiteBuilderFactory=Q,s7.getInstance().configure(Y)}async build(A,Q){return qp1({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}Z0();class Hp0{config;context;pluginId;logger;debounces=new Map;unsubscribeFunctions=[];constructor(A,Q,w,B){this.config=A;this.context=Q;this.pluginId=w;this.logger=B}requestBuild(A){let Q=A??(this.config.previewOutputDir?"preview":"production"),w=this.debounces.get(Q);if(!w)w=new DN(()=>{this.enqueueBuild(Q)},this.config.rebuildDebounce),this.debounces.set(Q,w);w.trigger()}setupAutoRebuild(){let A=new Set(["note"]),Q=async(B)=>{let{entityType:$}=B.payload;if(!A.has($))this.logger.debug(`Entity type ${$} will trigger rebuild`),this.requestBuild();return{success:!0}},w=["entity:created","entity:updated","entity:deleted"];for(let B of w)this.unsubscribeFunctions.push(this.context.messaging.subscribe(B,Q));this.logger.debug(`Auto-rebuild enabled (${this.config.rebuildDebounce}ms debounce), excluding types: ${[...A].join(", ")}`)}dispose(){for(let A of this.debounces.values())A.dispose();this.debounces.clear();for(let A of this.unsubscribeFunctions)A();this.unsubscribeFunctions=[]}async enqueueBuild(A){let Q=A==="production"?this.config.productionOutputDir:this.config.previewOutputDir;this.logger.debug(`Triggering ${A} site rebuild`);try{await this.context.jobs.enqueue({type:"site-build",data:{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:0,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip"}}),this.logger.debug("Site rebuild enqueued")}catch(w){this.logger.error("Failed to enqueue site rebuild",{error:w})}}}_5();function T7w(A,Q){return A.map((w)=>({...w,template:w.template.includes(":")?w.template:`${Q}:${w.template}`}))}function N40(A,Q,w){for(let B of A)w.register({...B,pluginId:Q,sections:B.sections?T7w(B.sections,Q):[]})}function Fp1(A,Q,w){A.messaging.subscribe("plugin:site-builder:route:register",async(B)=>{try{let $=ot.parse(B.payload),{routes:Y,pluginId:D}=$;return N40(Y,D,Q),{success:!0}}catch($){return w.error("Failed to register routes",{error:$}),{success:!1,error:"Failed to register routes"}}}),A.messaging.subscribe("plugin:site-builder:route:unregister",async(B)=>{try{let $=st.parse(B.payload),{paths:Y,pluginId:D}=$;if(Y)for(let X of Y)Q.unregister(X);else if(D)Q.unregisterByPlugin(D);return{success:!0}}catch($){return w.error("Failed to unregister routes",{error:$}),{success:!1,error:"Failed to unregister routes"}}}),A.messaging.subscribe("plugin:site-builder:route:list",async(B)=>{try{let $=at.parse(B.payload);return{success:!0,data:{routes:Q.list($.pluginId?$:void 0)}}}catch($){return w.error("Failed to list routes",{error:$}),{success:!1,error:"Failed to list routes"}}}),A.messaging.subscribe("plugin:site-builder:route:get",async(B)=>{try{let $=tt.parse(B.payload);return{success:!0,data:{route:Q.get($.path)}}}catch($){return w.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 Vp1}from"fs";import{join as Jp1}from"path";async function S7w(A,Q,w){let B=A.siteConfig.url??"https://example.com",$=Q.list(),Y=Yp0(B,A.environment);await Vp1.writeFile(Jp1(A.outputDir,"robots.txt"),Y,"utf-8"),w.info(`Generated robots.txt for ${A.environment} environment`);let D=Dp0($,B);await Vp1.writeFile(Jp1(A.outputDir,"sitemap.xml"),D,"utf-8"),w.info(`Generated sitemap.xml with ${$.length} URLs`)}function Ip1(A){let{context:Q,routeRegistry:w,logger:B}=A;Q.messaging.subscribe("site:build:completed",async($)=>{try{let Y=$.payload;return B.info(`Received site:build:completed event for ${Y.environment} environment - generating SEO files`),await S7w(Y,w,B),{success:!0}}catch(Y){return B.error("Failed to generate SEO files",Y),{success:!1}}})}c0();Z0();_5();var bp1=K.object({environment:K.enum(["preview","production"]).optional(),outputDir:K.string(),workingDir:K.string().optional(),enableContentGeneration:K.boolean().optional(),siteConfig:GX.optional()});_5();_5();async function Gr(A,Q){try{let w=await A({type:rT,payload:void 0});if("success"in w&&w.success&&w.data){let B=GX.safeParse(w.data);if(B.success)return GX.parse({...Q,...B.data})}}catch{}return Q}class Wp0 extends _w{sendMessage;cfg;constructor(A,Q,w){super(A,{schema:bp1,jobTypeName:"site-build"});this.sendMessage=Q;this.cfg=w}async process(A,Q,w){let B=A.environment??"preview",$=A.enableContentGeneration??!1;try{this.logger.debug("Starting site build job",{jobId:Q,environment:B,outputDir:A.outputDir}),await w.report({progress:0,total:100,message:`Starting site build for ${B} environment`});let Y=w.createSub({scale:{start:10,end:90}}),D=await Gr(this.sendMessage,A.siteConfig??this.cfg.defaultSiteConfig),X=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:$,environment:B,cleanBeforeBuild:!0,siteConfig:D,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},Y.toCallback());if(await w.report({progress:100,total:100,message:`Site build completed: ${X.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:Q,environment:B,routesBuilt:X.routesBuilt,success:X.success}),X.success){this.logger.info(`Emitting site:build:completed event for ${B} environment`);let H=B==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage({type:"site:build:completed",payload:{outputDir:A.outputDir,environment:B,routesBuilt:X.routesBuilt,siteConfig:{...D,url:H},generateEntityUrl:(W,f)=>s7.getInstance().generateUrl(W,f)},broadcast:!0})}return{success:X.success,routesBuilt:X.routesBuilt,outputDir:A.outputDir,environment:B,...X.errors&&{errors:X.errors},...X.warnings&&{warnings:X.warnings}}}catch(Y){throw this.logger.error("Site build job failed",Y),Y}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}Z0();_5();var m7w=K.object({slot:K.enum(UN).optional().default("primary"),limit:K.number().optional()});class fp0{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,w){let B=m7w.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:B});let $=this.routeRegistry.getNavigationItems(B.slot),Y=B.limit?$.slice(0,B.limit):$,D=Y.map((H)=>({label:H.label,href:H.href}));this.logger.debug("NavigationDataSource returning",{slot:B.slot,itemCount:Y.length,items:D});let X={navigation:D};return Q.parse(X)}}_5();c0();Z0();var u7w=K.object({environment:K.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function Lp1(A,Q){return[Sw(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'.",u7w,async(w)=>{return Q(w.environment),{success:!0,message:`Site build requested${w.environment?` for ${w.environment}`:""} (debounced)`,data:{}}},{sideEffects:"external",cli:{name:"build"}})]}Z0();_5();var Np1=K.object({previewOutputDir:K.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:K.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:K.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:K.string().optional().describe("Working directory for builds").default("./.preact-work"),siteInfo:GX.default({title:"Brain",description:"A knowledge management system"}),themeCSS:K.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:K.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),templates:K.any().optional().describe("Template definitions to register"),routes:K.array(GN).optional().describe("Routes to register"),layouts:K.record(K.any()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:K.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:K.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),entityDisplay:K.record(K.object({label:K.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:K.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')"),layout:K.string().optional().describe("Layout name for this entity type's generated routes (defaults to 'default')"),paginate:K.boolean().optional().describe("Enable pagination for list pages"),pageSize:K.number().optional().describe("Items per page (default: 10)"),navigation:K.object({show:K.boolean().optional().describe("Show in navigation"),slot:K.enum(UN).optional().describe("Navigation slot (primary or secondary)"),priority:K.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:K.record(K.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 jp1={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.135",description:"Static site generation plugin for Brain system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint .",clean:"rm -rf dist"},dependencies:{"@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*","@tailwindcss/typography":"^0.5.19",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",eslint:"^8.56.0",typescript:"^5.3.3"}};class Zp0 extends IQ{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",jp1,{...A,layouts:Q},Np1);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new b40(A.logger),this._slotRegistry=new A40,A.messaging.subscribe("plugin:site-builder:slot:register",async(w)=>{let{slotName:B,pluginId:$,render:Y,priority:D}=w.payload;return this._slotRegistry?.register(B,{pluginId:$,render:Y,...D!==void 0&&{priority:D}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async(w)=>{let{pluginId:B,script:$}=w.payload;return this.headScripts.set(B,$),{success:!0}}),A.entities.registerDataSource(new fp0(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=e4.getInstance(A.entityService,A.logger),Fp1(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)N40(this.config.routes,this.id,this.routeRegistry);let Q={entityService:A.entityService,sendMessage:A.messaging.send,resolveTemplateContent:(w,B)=>A.templates.resolve(w,B),getViewTemplate:(w)=>A.views.get(w),listViewTemplateNames:()=>A.views.list().map((w)=>w.name)};if(this.siteBuilder=bH.getInstance(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new Wp0(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 Hp0(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe(oT,async()=>{let w=await this.getInstructions();if(w)A.registerInstructions(w);return{success:!0}}),Ip1({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 Lp1(this.id,(Q)=>A.requestBuild(Q))}async getResources(){let A=this.getContext();return[{uri:"brain://site",name:"Site Metadata",description:"Site metadata \u2014 title, description, domain, URLs",mimeType:"application/json",handler:async()=>{let Q=await Gr(A.messaging.send,this.config.siteInfo);return{contents:[{uri:"brain://site",mimeType:"application/json",text:JSON.stringify({...Q,domain:A.domain,siteUrl:A.siteUrl,previewUrl:A.previewUrl},null,2)}]}}},{uri:"site://routes",name:"Site Routes",description:"All registered routes with sections and templates",mimeType:"application/json",handler:async()=>{let Q=this.routeRegistry.list();return{contents:[{uri:"site://routes",mimeType:"application/json",text:JSON.stringify(Q.map((w)=>({id:w.id,path:w.path,title:w.title,description:w.description,sections:w.sections.map((B)=>({id:B.id,template:B.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((w)=>({name:w.name,description:w.description,hasWebRenderer:!!w.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.",w=await Gr(A.messaging.send,this.config.siteInfo);return`## Your Site
5744
+ `+X;await O7.writeFile(D,W,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=gG(process.cwd(),"public");try{await O7.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await O7.readdir(A,{withFileTypes:!0});for(let w of Q){let B=gG(A,w.name),$=gG(this.outputDir,w.name);if(w.isDirectory())await this.copyDirectory(B,$);else await O7.copyFile(B,$),this.logger.debug(`Copied static asset: ${w.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([w,B])=>{let $=w.startsWith("/")?w.slice(1):w,Y=gG(this.outputDir,$);await O7.mkdir(h7w(Y),{recursive:!0}),await O7.writeFile(Y,B,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await O7.mkdir(Q,{recursive:!0});let w=await O7.readdir(A,{withFileTypes:!0});for(let B of w){let $=gG(A,B.name),Y=gG(Q,B.name);if(B.isDirectory())await this.copyDirectory($,Y);else await O7.copyFile($,Y)}}}function Xp0(A){return new Qp1(A)}_5();Z0();Z0();_5();var wp1=K.object({environment:K.enum(["preview","production"]),outputDir:K.string(),workingDir:K.string().optional(),sharedImagesDir:K.string().default("./dist/images"),enableContentGeneration:K.boolean().default(!1),cleanBeforeBuild:K.boolean().default(!0),siteConfig:GX,layouts:K.record(K.any()),themeCSS:K.string().optional()}),py8=K.object({success:K.boolean(),outputDir:K.string(),filesGenerated:K.number(),routesBuilt:K.number(),errors:K.array(K.string()).optional(),warnings:K.array(K.string()).optional()});function Bp1(A){let Q=A.list(),w=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:w}}function $p1(A,Q,w){let B=Q.getProfile(),$=w.getNavigationItems("primary"),Y=w.getNavigationItems("secondary");return{...A,...B.socialLinks!==void 0&&{socialLinks:B.socialLinks},navigation:{primary:$,secondary:Y},copyright:A.copyright??"Powered by Rizom"}}_5();D4();_5();Z0();var v7w=K.object({id:K.string(),entityType:K.string(),content:K.string(),metadata:K.object({slug:K.string()}).passthrough()}).passthrough(),C7w=K.object({content:K.string(),metadata:K.object({width:K.number().optional(),height:K.number().optional()}).passthrough()});async function L40(A,Q){let w=Q.urlGenerator??s7.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((g)=>L40(g,{...Q,urlGenerator:w})));if(typeof A!=="object")return A;let B={},$=Object.entries(A),Y=await Promise.all($.map(([,g])=>L40(g,{...Q,urlGenerator:w})));for(let g=0;g<$.length;g++){let E=$[g];if(E)B[E[0]]=Y[g]}let D=v7w.safeParse(A);if(!D.success)return B;let X=D.data,H=X.entityType,W=X.metadata.slug,f=Q.pipelineContext.entityDisplay?.[H],Z=f?f.label:H.charAt(0).toUpperCase()+H.slice(1),G=f?f.pluralName??f.label.toLowerCase()+"s":KX(H),F=`/${G}`,V=G.charAt(0).toUpperCase()+G.slice(1),b=zu(X),L=await y7w(b,Q),N=h10(X)??b,_=await E7w(N,Q);return{...B,...X,url:w.generateUrl(H,W),typeLabel:Z,listUrl:F,listLabel:V,...L,..._&&{ogImageUrl:_}}}async function y7w(A,Q){let w=A?Q.imageBuildService?.get(A):void 0;if(w)return{coverImageUrl:w.src,coverImageWidth:w.width,coverImageHeight:w.height,...w.srcset&&{coverImageSrcset:w.srcset,coverImageSizes:w.sizes}};let B=await Dp1(A,Q.pipelineContext.services.entityService);if(!B)return{};return{coverImageUrl:B.url,...B.width&&{coverImageWidth:B.width},...B.height&&{coverImageHeight:B.height}}}async function E7w(A,Q){if(!A)return;let w=Q.imageBuildService?.get(A);if(w)return Yp1(w.src,Q.siteUrl);let B=await Dp1(A,Q.pipelineContext.services.entityService);if(!B)return;if(B.url.startsWith("data:"))return;return Yp1(B.url,Q.siteUrl)}function Yp1(A,Q){if(/^https?:\/\//i.test(A)||A.startsWith("data:"))return A;if(!Q)return A;return`${Q.replace(/\/$/,"")}/${A.replace(/^\//,"")}`}async function Dp1(A,Q){if(!A)return;let w=await Q.getEntity({entityType:"image",id:A}),B=C7w.safeParse(w);if(!B.success)return;return{url:B.data.content,...B.data.metadata.width&&{width:B.data.metadata.width},...B.data.metadata.height&&{height:B.data.metadata.height}}}async function Xp1(A,Q){let w=new Set;try{let B=A.getEntityTypes();for(let $ of B){if($==="image")continue;let Y=await A.listEntities({entityType:$});for(let D of Y){let X=zu(D);if(X)w.add(X);let H=h10(D);if(H)w.add(H)}}}catch(B){Q.warn("Failed to collect image IDs for pre-resolution",{error:vA(B)})}return[...w]}async function Hp1(A,Q,w,B,$){if(!A.template)return A.content??null;let Y=A.template,D=A.dataQuery?{dataParams:A.dataQuery,fallback:A.content,publishedOnly:w,visibilityScope:B}:{savedContent:{entityType:"site-content",entityId:`${Q.id}:${A.id}`},fallback:A.content,visibilityScope:B},X=await $.pipelineContext.services.resolveTemplateContent(Y,D);if(!X)return null;return L40(X,{pipelineContext:$.pipelineContext,imageBuildService:$.imageBuildService,siteUrl:$.siteUrl,urlGenerator:s7.getInstance()})}function Wp1(A){return{routes:A.routes,siteConfig:{title:A.siteMetadata.title,description:A.siteMetadata.description,...A.siteMetadata.url&&{url:A.siteMetadata.url},...A.siteMetadata.copyright&&{copyright:A.siteMetadata.copyright},...A.siteMetadata.themeMode&&{themeMode:A.siteMetadata.themeMode},...A.siteMetadata.analyticsScript&&{analyticsScript:A.siteMetadata.analyticsScript}},headScripts:A.buildOptions.headScripts,...A.buildOptions.staticAssets&&{staticAssets:A.buildOptions.staticAssets},getContent:async(Q,w)=>{let B=A.parsedOptions.environment==="production";return Hp1(w,Q,B,"public",{pipelineContext:A.pipelineContext,imageBuildService:A.imageBuildService,siteUrl:A.siteMetadata.url})},getViewTemplate:(Q)=>{return A.pipelineContext.services.getViewTemplate(Q)},layouts:A.parsedOptions.layouts,getSiteLayoutInfo:async()=>{return $p1(A.siteMetadata,A.pipelineContext.profileService,A.pipelineContext.routeRegistry)},...A.parsedOptions.themeCSS!==void 0&&{themeCSS:A.parsedOptions.themeCSS},...A.buildOptions.slots&&{slots:A.buildOptions.slots},imageBuildService:A.imageBuildService}}import{join as g7w}from"path";async function fp1(A){let Q=A.parsedOptions.workingDir??g7w(A.parsedOptions.outputDir,".preact-work"),w=A.staticSiteBuilderFactory({logger:A.logger.child("StaticSiteBuilder"),workingDir:Q,outputDir:A.parsedOptions.outputDir});if(A.parsedOptions.cleanBeforeBuild)await w.clean();return w}async function Zp1(A){await new I40({logger:A.pipelineContext.logger.child("DynamicRouteGenerator"),entityService:A.pipelineContext.services.entityService,listViewTemplateNames:()=>A.pipelineContext.services.listViewTemplateNames()},A.pipelineContext.routeRegistry,A.pipelineContext.entityDisplay,{visibilityScope:"public",...A.publishedOnly!==void 0&&{publishedOnly:A.publishedOnly}}).generateEntityRoutes()}async function Kp1(A){let Q=new J40(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),w=await Xp1(A.pipelineContext.services.entityService,A.pipelineContext.logger);if(w.length>0)await Q.resolveAll(w);return Q}async function Up1(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,(w)=>{Q?.report(w).catch(()=>{})})}function Gp1(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function zp1(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function qp1(A){let Q=wp1.parse(A.buildOptions),w=D7.from(A.progress),B=[];try{await w?.report({message:"Starting site build",progress:0,total:100}),await w?.report({message:"Generating dynamic routes",progress:10,total:100}),await Zp1({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let $=await fp1({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),Y=Bp1(A.pipelineContext.routeRegistry);B.push(...Y.warnings);let{routes:D}=Y;await w?.report({message:`Building ${D.length} routes`,progress:20,total:100}),await w?.report({message:"Resolving images",progress:25,total:100});let X=await Kp1({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),H=Wp1({routes:D,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:X,siteMetadata:Q.siteConfig});return await Up1({staticSiteBuilder:$,buildContext:H,reporter:w}),await w?.report({message:"Site build complete",progress:100,total:100}),Gp1({outputDir:Q.outputDir,routesBuilt:D.length,warnings:B})}catch($){let Y=Error("Site build process failed");return A.pipelineContext.logger.error("Site build failed",{error:Y,originalError:$}),zp1({outputDir:Q.outputDir,errorMessage:Y.message})}}class bH{static instance=null;static defaultStaticSiteBuilderFactory=Xp0;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){bH.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,w,B,$=void 0){return bH.instance??=new bH(A,bH.defaultStaticSiteBuilderFactory,Q,w,B,$),bH.instance}static resetInstance(){bH.instance=null}static createFresh(A,Q,w,B,$,Y=void 0){return new bH(A,$??bH.defaultStaticSiteBuilderFactory,Q,w,B,Y)}constructor(A,Q,w,B,$,Y){this.pipelineContext={logger:A,services:w,routeRegistry:B,profileService:$,entityDisplay:Y},this.staticSiteBuilderFactory=Q,s7.getInstance().configure(Y)}async build(A,Q){return qp1({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}Z0();class Hp0{config;context;pluginId;logger;debounces=new Map;unsubscribeFunctions=[];constructor(A,Q,w,B){this.config=A;this.context=Q;this.pluginId=w;this.logger=B}requestBuild(A){let Q=A??(this.config.previewOutputDir?"preview":"production"),w=this.debounces.get(Q);if(!w)w=new DN(()=>{this.enqueueBuild(Q)},this.config.rebuildDebounce),this.debounces.set(Q,w);w.trigger()}setupAutoRebuild(){let A=new Set(["note"]),Q=async(B)=>{let{entityType:$}=B.payload;if(!A.has($))this.logger.debug(`Entity type ${$} will trigger rebuild`),this.requestBuild();return{success:!0}},w=["entity:created","entity:updated","entity:deleted"];for(let B of w)this.unsubscribeFunctions.push(this.context.messaging.subscribe(B,Q));this.logger.debug(`Auto-rebuild enabled (${this.config.rebuildDebounce}ms debounce), excluding types: ${[...A].join(", ")}`)}dispose(){for(let A of this.debounces.values())A.dispose();this.debounces.clear();for(let A of this.unsubscribeFunctions)A();this.unsubscribeFunctions=[]}async enqueueBuild(A){let Q=A==="production"?this.config.productionOutputDir:this.config.previewOutputDir;this.logger.debug(`Triggering ${A} site rebuild`);try{await this.context.jobs.enqueue({type:"site-build",data:{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:0,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip"}}),this.logger.debug("Site rebuild enqueued")}catch(w){this.logger.error("Failed to enqueue site rebuild",{error:w})}}}_5();function T7w(A,Q){return A.map((w)=>({...w,template:w.template.includes(":")?w.template:`${Q}:${w.template}`}))}function N40(A,Q,w){for(let B of A)w.register({...B,pluginId:Q,sections:B.sections?T7w(B.sections,Q):[]})}function Fp1(A,Q,w){A.messaging.subscribe("plugin:site-builder:route:register",async(B)=>{try{let $=ot.parse(B.payload),{routes:Y,pluginId:D}=$;return N40(Y,D,Q),{success:!0}}catch($){return w.error("Failed to register routes",{error:$}),{success:!1,error:"Failed to register routes"}}}),A.messaging.subscribe("plugin:site-builder:route:unregister",async(B)=>{try{let $=st.parse(B.payload),{paths:Y,pluginId:D}=$;if(Y)for(let X of Y)Q.unregister(X);else if(D)Q.unregisterByPlugin(D);return{success:!0}}catch($){return w.error("Failed to unregister routes",{error:$}),{success:!1,error:"Failed to unregister routes"}}}),A.messaging.subscribe("plugin:site-builder:route:list",async(B)=>{try{let $=at.parse(B.payload);return{success:!0,data:{routes:Q.list($.pluginId?$:void 0)}}}catch($){return w.error("Failed to list routes",{error:$}),{success:!1,error:"Failed to list routes"}}}),A.messaging.subscribe("plugin:site-builder:route:get",async(B)=>{try{let $=tt.parse(B.payload);return{success:!0,data:{route:Q.get($.path)}}}catch($){return w.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 Vp1}from"fs";import{join as Jp1}from"path";async function S7w(A,Q,w){let B=A.siteConfig.url??"https://example.com",$=Q.list(),Y=Yp0(B,A.environment);await Vp1.writeFile(Jp1(A.outputDir,"robots.txt"),Y,"utf-8"),w.info(`Generated robots.txt for ${A.environment} environment`);let D=Dp0($,B);await Vp1.writeFile(Jp1(A.outputDir,"sitemap.xml"),D,"utf-8"),w.info(`Generated sitemap.xml with ${$.length} URLs`)}function Ip1(A){let{context:Q,routeRegistry:w,logger:B}=A;Q.messaging.subscribe("site:build:completed",async($)=>{try{let Y=$.payload;return B.info(`Received site:build:completed event for ${Y.environment} environment - generating SEO files`),await S7w(Y,w,B),{success:!0}}catch(Y){return B.error("Failed to generate SEO files",Y),{success:!1}}})}c0();Z0();_5();var bp1=K.object({environment:K.enum(["preview","production"]).optional(),outputDir:K.string(),workingDir:K.string().optional(),enableContentGeneration:K.boolean().optional(),siteConfig:GX.optional()});_5();_5();async function Gr(A,Q){try{let w=await A({type:rT,payload:void 0});if("success"in w&&w.success&&w.data){let B=GX.safeParse(w.data);if(B.success)return GX.parse({...Q,...B.data})}}catch{}return Q}class Wp0 extends _w{sendMessage;cfg;constructor(A,Q,w){super(A,{schema:bp1,jobTypeName:"site-build"});this.sendMessage=Q;this.cfg=w}async process(A,Q,w){let B=A.environment??"preview",$=A.enableContentGeneration??!1;try{this.logger.debug("Starting site build job",{jobId:Q,environment:B,outputDir:A.outputDir}),await w.report({progress:0,total:100,message:`Starting site build for ${B} environment`});let Y=w.createSub({scale:{start:10,end:90}}),D=await Gr(this.sendMessage,A.siteConfig??this.cfg.defaultSiteConfig),X=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:$,environment:B,cleanBeforeBuild:!0,siteConfig:D,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},Y.toCallback());if(await w.report({progress:100,total:100,message:`Site build completed: ${X.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:Q,environment:B,routesBuilt:X.routesBuilt,success:X.success}),X.success){this.logger.info(`Emitting site:build:completed event for ${B} environment`);let H=B==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage({type:"site:build:completed",payload:{outputDir:A.outputDir,environment:B,routesBuilt:X.routesBuilt,siteConfig:{...D,url:H},generateEntityUrl:(W,f)=>s7.getInstance().generateUrl(W,f)},broadcast:!0})}return{success:X.success,routesBuilt:X.routesBuilt,outputDir:A.outputDir,environment:B,...X.errors&&{errors:X.errors},...X.warnings&&{warnings:X.warnings}}}catch(Y){throw this.logger.error("Site build job failed",Y),Y}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}Z0();_5();var m7w=K.object({slot:K.enum(UN).optional().default("primary"),limit:K.number().optional()});class fp0{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,w){let B=m7w.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:B});let $=this.routeRegistry.getNavigationItems(B.slot),Y=B.limit?$.slice(0,B.limit):$,D=Y.map((H)=>({label:H.label,href:H.href}));this.logger.debug("NavigationDataSource returning",{slot:B.slot,itemCount:Y.length,items:D});let X={navigation:D};return Q.parse(X)}}_5();c0();Z0();var u7w=K.object({environment:K.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function Lp1(A,Q){return[Sw(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'.",u7w,async(w)=>{return Q(w.environment),{success:!0,message:`Site build requested${w.environment?` for ${w.environment}`:""} (debounced)`,data:{}}},{sideEffects:"external",cli:{name:"build"}})]}Z0();_5();var Np1=K.object({previewOutputDir:K.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:K.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:K.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:K.string().optional().describe("Working directory for builds").default("./.preact-work"),siteInfo:GX.default({title:"Brain",description:"A knowledge management system"}),themeCSS:K.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:K.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),templates:K.any().optional().describe("Template definitions to register"),routes:K.array(GN).optional().describe("Routes to register"),layouts:K.record(K.any()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:K.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:K.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),entityDisplay:K.record(K.object({label:K.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:K.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')"),layout:K.string().optional().describe("Layout name for this entity type's generated routes (defaults to 'default')"),paginate:K.boolean().optional().describe("Enable pagination for list pages"),pageSize:K.number().optional().describe("Items per page (default: 10)"),navigation:K.object({show:K.boolean().optional().describe("Show in navigation"),slot:K.enum(UN).optional().describe("Navigation slot (primary or secondary)"),priority:K.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:K.record(K.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 jp1={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.136",description:"Static site generation plugin for Brain system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint .",clean:"rm -rf dist"},dependencies:{"@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*","@tailwindcss/typography":"^0.5.19",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",eslint:"^8.56.0",typescript:"^5.3.3"}};class Zp0 extends IQ{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",jp1,{...A,layouts:Q},Np1);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new b40(A.logger),this._slotRegistry=new A40,A.messaging.subscribe("plugin:site-builder:slot:register",async(w)=>{let{slotName:B,pluginId:$,render:Y,priority:D}=w.payload;return this._slotRegistry?.register(B,{pluginId:$,render:Y,...D!==void 0&&{priority:D}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async(w)=>{let{pluginId:B,script:$}=w.payload;return this.headScripts.set(B,$),{success:!0}}),A.entities.registerDataSource(new fp0(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=e4.getInstance(A.entityService,A.logger),Fp1(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)N40(this.config.routes,this.id,this.routeRegistry);let Q={entityService:A.entityService,sendMessage:A.messaging.send,resolveTemplateContent:(w,B)=>A.templates.resolve(w,B),getViewTemplate:(w)=>A.views.get(w),listViewTemplateNames:()=>A.views.list().map((w)=>w.name)};if(this.siteBuilder=bH.getInstance(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new Wp0(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 Hp0(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe(oT,async()=>{let w=await this.getInstructions();if(w)A.registerInstructions(w);return{success:!0}}),Ip1({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 Lp1(this.id,(Q)=>A.requestBuild(Q))}async getResources(){let A=this.getContext();return[{uri:"brain://site",name:"Site Metadata",description:"Site metadata \u2014 title, description, domain, URLs",mimeType:"application/json",handler:async()=>{let Q=await Gr(A.messaging.send,this.config.siteInfo);return{contents:[{uri:"brain://site",mimeType:"application/json",text:JSON.stringify({...Q,domain:A.domain,siteUrl:A.siteUrl,previewUrl:A.previewUrl},null,2)}]}}},{uri:"site://routes",name:"Site Routes",description:"All registered routes with sections and templates",mimeType:"application/json",handler:async()=>{let Q=this.routeRegistry.list();return{contents:[{uri:"site://routes",mimeType:"application/json",text:JSON.stringify(Q.map((w)=>({id:w.id,path:w.path,title:w.title,description:w.description,sections:w.sections.map((B)=>({id:B.id,template:B.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((w)=>({name:w.name,description:w.description,hasWebRenderer:!!w.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.",w=await Gr(A.messaging.send,this.config.siteInfo);return`## Your Site
5745
5745
  ${[`**Title:** ${w.title}`,`**Description:** ${w.description}`,A.domain&&`**Domain:** ${A.domain}`,A.siteUrl&&`**URL:** ${A.siteUrl}`].filter(Boolean).join(`
5746
5746
  `)}
5747
5747
 
5748
5748
  ## Site Builder Actions
5749
5749
  - When the user asks to build, rebuild, publish, or build the website/site again, call \`site-builder_build-site\` immediately.
5750
- - Every repeated build request requires a fresh \`site-builder_build-site\` call. Do not say a build was started, queued, or requested unless this turn invoked the tool.`}async onShutdown(){this.logger.debug("Shutting down site-builder plugin"),this.rebuildManager?.dispose(),bH.resetInstance(),this.logger.debug("Cleaned up all event subscriptions")}}function WP(A={}){return new Zp0(A)}c0();_5();Z0();c0();_5();var Mp1=K.object({}),zr=o1.extend({id:K.literal("site-info"),entityType:K.literal("site-info"),metadata:Mp1}),Kp0=Ae,ty=GX.omit({url:!0,analyticsScript:!0});c0();class TG extends J2{constructor(){super({entityType:"site-info",purpose:"Singleton configuration describing the published site.",schema:zr,frontmatterSchema:ty,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=ty.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 SG{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,w){return SG.instance??=new SG(A,Q,w),SG.instance}static resetInstance(){SG.instance=null}static createFresh(A,Q,w){return new SG(A,Q,w)}constructor(A,Q,w){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new TG;let B=SG.getDefaultSiteInfo();this.defaultSiteInfo={...B,...w}}async initialize(){try{if(!await this.entityService.getEntity({entityType:"site-info",id:"site-info"})){if(await this.entityService.getEntity({entityType:"site-info",id:"site-info"}))return;this.logger.info("No site info found, creating default site info");let w=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({entity:{id:"site-info",entityType:"site-info",content:w,metadata:{}}}),this.logger.info("Default site info created successfully")}}catch(A){this.logger.error("Failed to initialize site info",{error:A})}}async getSiteInfo(){try{let A=await this.entityService.getEntity({entityType:"site-info",id:"site-info"});if(A)return this.adapter.parseSiteInfoBody(A.content)}catch(A){this.logger.debug("Site info not found, using defaults",{error:A})}return this.defaultSiteInfo}}var l7w=new TG;class j40{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,w){let{entityService:B}=w,$;try{let X=await B.getEntity({entityType:"site-info",id:"site-info"});$=X?l7w.parseSiteInfoBody(X.content):{title:"Brain",description:"A knowledge management system"}}catch{$={title:"Brain",description:"A knowledge management system"}}let Y;try{let X=await B.getEntity({entityType:"anchor-profile",id:"anchor-profile"});if(X)Y=X.metadata.socialLinks}catch{}let D={...$,socialLinks:Y,copyright:$.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:D.title,hasSocialLinks:!!D.socialLinks}),Q.parse(D)}}var _p1={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.135",description:"Site info entity \u2014 site metadata, title, description, CTA",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/entity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var i7w=new TG;class Up0 extends kQ{entityType="site-info";schema=zr;adapter=i7w;defaultSiteInfo;constructor(A){super("site-info",_p1);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new j40(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=SG.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe(rT,async()=>{return{success:!0,data:await Q.getSiteInfo()}}),A.messaging.subscribe("entity:updated",async(w)=>{if(w.payload.entityType==="site-info"){let $=await Q.getSiteInfo();await A.messaging.send({type:oT,payload:$,broadcast:!0})}return{success:!0}}),A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function fP(A){return new Up0(A)}var d7w=new TG;async function qr(A){let w=(await A.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!w)throw Error("Site info not found \u2014 create a site-info entity");return d7w.parseSiteInfoBody(w.content)}Z0();var n7w=ty.extend({navigation:K.object({primary:K.array(K.object({label:K.string(),href:K.string(),priority:K.number()})),secondary:K.array(K.object({label:K.string(),href:K.string(),priority:K.number()}))}),copyright:K.string(),socialLinks:K.array(K.object({platform:K.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:K.string().describe("Profile or contact URL"),label:K.string().optional().describe("Optional display label")})).optional().describe("Social media links from profile entity")});c0();Z0();var Pp1={lexicon:1,id:"ai.rizom.brain.card",defs:{main:{type:"record",description:"Public discovery card for a Rizom brain. The operational A2A Agent Card is conventionally served at /.well-known/agent-card.json under siteUrl.",key:"literal:self",record:{type:"object",required:["siteUrl","brain","anchor","skills","model","version","createdAt"],properties:{siteUrl:{type:"string",format:"uri",description:"Public site URL. Consumers derive the A2A Agent Card URL from this base."},brain:{type:"object",description:"Brain identity described by this discovery card.",required:["did","name","role","purpose","values"],properties:{did:{type:"string",description:"Public DID for the brain identity."},name:{type:"string",maxLength:200,description:"Human-readable brain name."},role:{type:"string",maxLength:500,description:"Brain role or persona."},purpose:{type:"string",maxLength:2000,description:"Short public description of what this brain is for."},values:{type:"array",description:"Public values or principles for this brain.",items:{type:"string",maxLength:200},maxLength:50}}},anchor:{type:"object",description:"Minimal owner/operator snapshot for discovery grouping and display.",required:["did","name","kind"],properties:{did:{type:"string",description:"Public DID for the owner/operator anchor identity."},name:{type:"string",maxLength:200,description:"Human-readable anchor name."},kind:{type:"string",knownValues:["professional","team","collective"],description:"Anchor type."}}},skills:{type:"array",description:"User-facing skills this brain advertises for discovery.",items:{type:"object",required:["id","name","description"],properties:{id:{type:"string",maxLength:200},name:{type:"string",maxLength:200},description:{type:"string",maxLength:2000},tags:{type:"array",items:{type:"string"},maxLength:50},examples:{type:"array",items:{type:"string"},maxLength:20}}},maxLength:100},model:{type:"string",description:"Rizom brain model identifier."},version:{type:"string",description:"Brain runtime/model implementation version."},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var kp1={lexicon:1,id:"ai.rizom.brain.deck",defs:{main:{type:"record",description:"Public presentation deck from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},author:{type:"string"},event:{type:"string"},publishedAt:{type:"string",format:"datetime"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Op1={lexicon:1,id:"ai.rizom.brain.link",defs:{main:{type:"record",description:"Public curated link from a Rizom brain.",key:"any",record:{type:"object",required:["title","url","createdAt"],properties:{title:{type:"string",maxLength:500},url:{type:"string",format:"uri"},description:{type:"string",maxLength:2000},summary:{type:"string",maxLength:1e5},domain:{type:"string"},capturedAt:{type:"string",format:"datetime"},source:{type:"object",required:["ref","label"],properties:{ref:{type:"string"},label:{type:"string"}}},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var xp1={lexicon:1,id:"ai.rizom.brain.note",defs:{main:{type:"record",description:"Public knowledge note from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Rp1={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"object",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}}}};var hp1={lexicon:1,id:"ai.rizom.brain.project",defs:{main:{type:"record",description:"Public project or case study from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","year","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},year:{type:"integer"},url:{type:"string",format:"uri"},publishedAt:{type:"string",format:"datetime"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var vp1={lexicon:1,id:"ai.rizom.brain.series",defs:{main:{type:"record",description:"Public content series from a Rizom brain.",key:"any",record:{type:"object",required:["title","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:1e4},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Cp1={lexicon:1,id:"ai.rizom.brain.socialPost",defs:{main:{type:"record",description:"Semantic local social-post entity from a Rizom brain; not a Bluesky feed post.",key:"any",record:{type:"object",required:["title","platform","body","createdAt"],properties:{title:{type:"string",maxLength:300},platform:{type:"string"},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},status:{type:"string"},publishedAt:{type:"string",format:"datetime"},platformPostId:{type:"string"},sourceLocalEntityType:{type:"string"},sourceLocalEntityId:{type:"string"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var yp1={lexicon:1,id:"ai.rizom.brain.topic",defs:{main:{type:"record",description:"Public topic page from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var B4w=K.object({type:K.string()}).catchall(K.unknown()),$4w=K.object({lexicon:K.literal(1),id:K.string(),defs:K.object({main:K.object({type:K.literal("record"),key:K.string().min(1),record:K.object({type:K.literal("object"),required:K.array(K.string()).optional(),properties:K.record(B4w)})})})});function mG(A){return $4w.parse(A)}var MB={"ai.rizom.brain.card":mG(Pp1),"ai.rizom.brain.deck":mG(kp1),"ai.rizom.brain.link":mG(Op1),"ai.rizom.brain.note":mG(xp1),"ai.rizom.brain.post":mG(Rp1),"ai.rizom.brain.project":mG(hp1),"ai.rizom.brain.series":mG(vp1),"ai.rizom.brain.socialPost":mG(Cp1),"ai.rizom.brain.topic":mG(yp1)},Y4w="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function WF(A){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:A,compatibility:Y4w}}var D4w={"ai.rizom.brain.card":WF("@brains/atproto"),"ai.rizom.brain.deck":WF("@brains/decks"),"ai.rizom.brain.link":WF("@brains/link"),"ai.rizom.brain.note":WF("@brains/note"),"ai.rizom.brain.post":WF("@brains/blog"),"ai.rizom.brain.project":WF("@brains/portfolio"),"ai.rizom.brain.series":WF("@brains/series"),"ai.rizom.brain.socialPost":WF("@brains/social-media"),"ai.rizom.brain.topic":WF("@brains/topics")};function ZP(){return Object.values(MB)}function qp0(A){return MB[A]}function Fp0(){return Object.entries(D4w).map(([A,Q])=>({id:A,...Q}))}function zp0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var X4w=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function H4w(A){let Q=K.string(),w=A.maxLength!==void 0?Q.max(A.maxLength):Q;if(A.knownValues)w=w.refine((B)=>A.knownValues?.includes(B),{message:`expected one of ${A.knownValues.join(", ")}`});if(A.format==="datetime")w=w.refine((B)=>X4w.test(B)&&!Number.isNaN(Date.parse(B)),{message:"expected datetime"});if(A.format==="uri")w=w.refine((B)=>{try{return new URL(B),!0}catch{return!1}},{message:"expected uri"});return w}function Ep1(A){switch(A.type){case"string":return H4w(A);case"integer":return K.number().int();case"boolean":return K.boolean();case"array":{let Q=A.items?Ep1(A.items):K.unknown(),w=K.array(Q);if(A.maxLength!==void 0)w=w.max(A.maxLength);return w}case"object":return W4w(A);case"blob":return K.custom(zp0,{message:"expected blob"});default:return K.unknown()}}function gp1(A){let Q=new Set(A.required??[]),w={};for(let[B,$]of Object.entries(A.properties??{})){let Y=Ep1($);w[B]=Q.has(B)?Y:Y.optional()}return w}function W4w(A){return K.object(gp1(A)).passthrough()}function Gp0(A,Q,w,B=[]){let $=Object.keys(A).filter((Y)=>!Q.has(Y));if($.length===0)return;w.addIssue({code:K.ZodIssueCode.custom,path:B,message:`unrecognized field(s): ${$.join(", ")}`})}function f4w(A,Q){if(Gp0(A,new Set(["$type","siteUrl","brain","anchor","skills","model","version","createdAt","updatedAt"]),Q),zp0(A.brain))Gp0(A.brain,new Set(["did","name","role","purpose","values"]),Q,["brain"]);if(zp0(A.anchor))Gp0(A.anchor,new Set(["did","name","kind"]),Q,["anchor"])}function uG(A){let Q=K.object({...gp1(A.defs.main.record),$type:K.literal(A.id).optional()}).passthrough();return A.id==="ai.rizom.brain.card"?Q.superRefine(f4w):Q}var Z4w={"ai.rizom.brain.card":uG(MB["ai.rizom.brain.card"]),"ai.rizom.brain.deck":uG(MB["ai.rizom.brain.deck"]),"ai.rizom.brain.link":uG(MB["ai.rizom.brain.link"]),"ai.rizom.brain.note":uG(MB["ai.rizom.brain.note"]),"ai.rizom.brain.post":uG(MB["ai.rizom.brain.post"]),"ai.rizom.brain.project":uG(MB["ai.rizom.brain.project"]),"ai.rizom.brain.series":uG(MB["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":uG(MB["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":uG(MB["ai.rizom.brain.topic"])};function K4w(A,Q,w){let B=w.path.join(".");if(B==="$type")return`AT Protocol record $type must match lexicon id: ${String(Q.$type)} !== ${A.id}`;if(w.code==="invalid_type"&&w.received==="undefined")return`Missing required AT Protocol record field: ${B}`;if(w.code==="invalid_type")return`Invalid AT Protocol record field ${B}: expected ${w.expected}`;if(w.code==="too_big")return`Invalid AT Protocol record field ${B}: exceeds maxLength ${w.maximum}`;if(w.code==="custom")return`Invalid AT Protocol record field ${B}: ${w.message}`;if(w.code==="unrecognized_keys")return`Unrecognized AT Protocol record field(s): ${w.keys.join(", ")}`;return`Invalid AT Protocol record field ${B}: ${w.message}`}function Lb(A,Q){let w=uG(A).safeParse(Q);if(w.success)return;let B=w.error.issues[0];if(!B)throw w.error;throw Error(K4w(A,Q,B))}var M40="atproto:brain-card-discovered",Tp1="atproto:brain-discovered",Sp1="atproto:brain-card-refreshed",mp1=K.object({repoDid:K.string().min(1),uri:K.string().min(1),cid:K.string().min(1),record:Z4w["ai.rizom.brain.card"]}).strict(),IT8=K.object({agentId:K.string().min(1),name:K.string().min(1),url:K.string().url(),status:K.enum(["discovered","approved"]),repoDid:K.string().min(1).optional(),brainDid:K.string().min(1).optional(),anchorDid:K.string().min(1).optional(),cardUri:K.string().min(1).optional(),cardCid:K.string().min(1).optional()}).strict();class U5{static instance;projections=new Map;registrationCounts=new Map;static getInstance(){return this.instance??=new U5,this.instance}static createFresh(){return new U5}static resetInstance(){this.instance=void 0}register(A){this.validateProjection(A);let Q=this.projections.get(A.entityType);if(Q){if(!this.isEquivalentProjection(Q,A))throw Error(`AT Protocol projection already registered for entity type ${A.entityType}`);return this.registrationCounts.set(A.entityType,(this.registrationCounts.get(A.entityType)??1)+1),this.createUnregister(A.entityType)}return this.projections.set(A.entityType,A),this.registrationCounts.set(A.entityType,1),this.createUnregister(A.entityType)}get(A){return this.projections.get(A)}has(A){return this.projections.has(A)}list(){return Array.from(this.projections.values())}listLexicons(){return this.list().map((A)=>A.lexicon)}createUnregister(A){let Q=!0;return()=>{if(!Q)return;Q=!1;let w=this.registrationCounts.get(A)??0;if(w<=1){this.registrationCounts.delete(A),this.projections.delete(A);return}this.registrationCounts.set(A,w-1)}}isEquivalentProjection(A,Q){return A.entityType===Q.entityType&&A.collection===Q.collection&&A.lexicon.id===Q.lexicon.id&&A.validate===Q.validate}validateProjection(A){if(A.collection!==A.lexicon.id)throw Error(`AT Protocol projection collection must match lexicon id: ${A.collection} !== ${A.lexicon.id}`);if(!A.lexicon.defs.main.key)throw Error(`AT Protocol projection lexicon must define a record key: ${A.collection}`)}}LH();AE();Z0();var Vp0=K.object({defaultPrompt:K.string().default("Write a blog post about my recent work and insights"),paginate:K.boolean().default(!0),pageSize:K.number().default(10)});c0();Z0();CB();var z4w=K.object({prompt:K.string().optional(),title:K.string().optional(),content:K.string().optional(),excerpt:K.string().optional(),coverImageId:K.string().optional(),seriesName:K.string().optional(),seriesIndex:K.number().optional(),skipAi:K.boolean().optional()}),vT8=UX.extend({title:K.string().optional(),slug:K.string().optional()});class Jp0 extends Q4{constructor(A,Q){super(A,Q,{schema:z4w,jobTypeName:"blog-generation",entityType:"post"})}async generate(A,Q){let{prompt:w,coverImageId:B,seriesName:$,seriesIndex:Y,skipAi:D}=A,{title:X,content:H,excerpt:W}=A;if(D){if(!X)this.failEarly("Title is required when skipAi is true");H=H??`## Introduction
5750
+ - Every repeated build request requires a fresh \`site-builder_build-site\` call. Do not say a build was started, queued, or requested unless this turn invoked the tool.`}async onShutdown(){this.logger.debug("Shutting down site-builder plugin"),this.rebuildManager?.dispose(),bH.resetInstance(),this.logger.debug("Cleaned up all event subscriptions")}}function WP(A={}){return new Zp0(A)}c0();_5();Z0();c0();_5();var Mp1=K.object({}),zr=o1.extend({id:K.literal("site-info"),entityType:K.literal("site-info"),metadata:Mp1}),Kp0=Ae,ty=GX.omit({url:!0,analyticsScript:!0});c0();class TG extends J2{constructor(){super({entityType:"site-info",purpose:"Singleton configuration describing the published site.",schema:zr,frontmatterSchema:ty,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=ty.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 SG{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,w){return SG.instance??=new SG(A,Q,w),SG.instance}static resetInstance(){SG.instance=null}static createFresh(A,Q,w){return new SG(A,Q,w)}constructor(A,Q,w){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new TG;let B=SG.getDefaultSiteInfo();this.defaultSiteInfo={...B,...w}}async initialize(){try{if(!await this.entityService.getEntity({entityType:"site-info",id:"site-info"})){if(await this.entityService.getEntity({entityType:"site-info",id:"site-info"}))return;this.logger.info("No site info found, creating default site info");let w=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({entity:{id:"site-info",entityType:"site-info",content:w,metadata:{}}}),this.logger.info("Default site info created successfully")}}catch(A){this.logger.error("Failed to initialize site info",{error:A})}}async getSiteInfo(){try{let A=await this.entityService.getEntity({entityType:"site-info",id:"site-info"});if(A)return this.adapter.parseSiteInfoBody(A.content)}catch(A){this.logger.debug("Site info not found, using defaults",{error:A})}return this.defaultSiteInfo}}var l7w=new TG;class j40{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,w){let{entityService:B}=w,$;try{let X=await B.getEntity({entityType:"site-info",id:"site-info"});$=X?l7w.parseSiteInfoBody(X.content):{title:"Brain",description:"A knowledge management system"}}catch{$={title:"Brain",description:"A knowledge management system"}}let Y;try{let X=await B.getEntity({entityType:"anchor-profile",id:"anchor-profile"});if(X)Y=X.metadata.socialLinks}catch{}let D={...$,socialLinks:Y,copyright:$.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:D.title,hasSocialLinks:!!D.socialLinks}),Q.parse(D)}}var _p1={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.136",description:"Site info entity \u2014 site metadata, title, description, CTA",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts","lint:fix":"eslint src test --ext .ts --fix"},dependencies:{"@brains/entity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var i7w=new TG;class Up0 extends kQ{entityType="site-info";schema=zr;adapter=i7w;defaultSiteInfo;constructor(A){super("site-info",_p1);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new j40(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=SG.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe(rT,async()=>{return{success:!0,data:await Q.getSiteInfo()}}),A.messaging.subscribe("entity:updated",async(w)=>{if(w.payload.entityType==="site-info"){let $=await Q.getSiteInfo();await A.messaging.send({type:oT,payload:$,broadcast:!0})}return{success:!0}}),A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function fP(A){return new Up0(A)}var d7w=new TG;async function qr(A){let w=(await A.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!w)throw Error("Site info not found \u2014 create a site-info entity");return d7w.parseSiteInfoBody(w.content)}Z0();var n7w=ty.extend({navigation:K.object({primary:K.array(K.object({label:K.string(),href:K.string(),priority:K.number()})),secondary:K.array(K.object({label:K.string(),href:K.string(),priority:K.number()}))}),copyright:K.string(),socialLinks:K.array(K.object({platform:K.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:K.string().describe("Profile or contact URL"),label:K.string().optional().describe("Optional display label")})).optional().describe("Social media links from profile entity")});c0();Z0();var Pp1={lexicon:1,id:"ai.rizom.brain.card",defs:{main:{type:"record",description:"Public discovery card for a Rizom brain. The operational A2A Agent Card is conventionally served at /.well-known/agent-card.json under siteUrl.",key:"literal:self",record:{type:"object",required:["siteUrl","brain","anchor","skills","model","version","createdAt"],properties:{siteUrl:{type:"string",format:"uri",description:"Public site URL. Consumers derive the A2A Agent Card URL from this base."},brain:{type:"object",description:"Brain identity described by this discovery card.",required:["did","name","role","purpose","values"],properties:{did:{type:"string",description:"Public DID for the brain identity."},name:{type:"string",maxLength:200,description:"Human-readable brain name."},role:{type:"string",maxLength:500,description:"Brain role or persona."},purpose:{type:"string",maxLength:2000,description:"Short public description of what this brain is for."},values:{type:"array",description:"Public values or principles for this brain.",items:{type:"string",maxLength:200},maxLength:50}}},anchor:{type:"object",description:"Minimal owner/operator snapshot for discovery grouping and display.",required:["did","name","kind"],properties:{did:{type:"string",description:"Public DID for the owner/operator anchor identity."},name:{type:"string",maxLength:200,description:"Human-readable anchor name."},kind:{type:"string",knownValues:["professional","team","collective"],description:"Anchor type."}}},skills:{type:"array",description:"User-facing skills this brain advertises for discovery.",items:{type:"object",required:["id","name","description"],properties:{id:{type:"string",maxLength:200},name:{type:"string",maxLength:200},description:{type:"string",maxLength:2000},tags:{type:"array",items:{type:"string"},maxLength:50},examples:{type:"array",items:{type:"string"},maxLength:20}}},maxLength:100},model:{type:"string",description:"Rizom brain model identifier."},version:{type:"string",description:"Brain runtime/model implementation version."},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var kp1={lexicon:1,id:"ai.rizom.brain.deck",defs:{main:{type:"record",description:"Public presentation deck from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},author:{type:"string"},event:{type:"string"},publishedAt:{type:"string",format:"datetime"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Op1={lexicon:1,id:"ai.rizom.brain.link",defs:{main:{type:"record",description:"Public curated link from a Rizom brain.",key:"any",record:{type:"object",required:["title","url","createdAt"],properties:{title:{type:"string",maxLength:500},url:{type:"string",format:"uri"},description:{type:"string",maxLength:2000},summary:{type:"string",maxLength:1e5},domain:{type:"string"},capturedAt:{type:"string",format:"datetime"},source:{type:"object",required:["ref","label"],properties:{ref:{type:"string"},label:{type:"string"}}},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var xp1={lexicon:1,id:"ai.rizom.brain.note",defs:{main:{type:"record",description:"Public knowledge note from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Rp1={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"object",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}}}};var hp1={lexicon:1,id:"ai.rizom.brain.project",defs:{main:{type:"record",description:"Public project or case study from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","year","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},year:{type:"integer"},url:{type:"string",format:"uri"},publishedAt:{type:"string",format:"datetime"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var vp1={lexicon:1,id:"ai.rizom.brain.series",defs:{main:{type:"record",description:"Public content series from a Rizom brain.",key:"any",record:{type:"object",required:["title","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:1e4},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Cp1={lexicon:1,id:"ai.rizom.brain.socialPost",defs:{main:{type:"record",description:"Semantic local social-post entity from a Rizom brain; not a Bluesky feed post.",key:"any",record:{type:"object",required:["title","platform","body","createdAt"],properties:{title:{type:"string",maxLength:300},platform:{type:"string"},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},status:{type:"string"},publishedAt:{type:"string",format:"datetime"},platformPostId:{type:"string"},sourceLocalEntityType:{type:"string"},sourceLocalEntityId:{type:"string"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var yp1={lexicon:1,id:"ai.rizom.brain.topic",defs:{main:{type:"record",description:"Public topic page from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var B4w=K.object({type:K.string()}).catchall(K.unknown()),$4w=K.object({lexicon:K.literal(1),id:K.string(),defs:K.object({main:K.object({type:K.literal("record"),key:K.string().min(1),record:K.object({type:K.literal("object"),required:K.array(K.string()).optional(),properties:K.record(B4w)})})})});function mG(A){return $4w.parse(A)}var MB={"ai.rizom.brain.card":mG(Pp1),"ai.rizom.brain.deck":mG(kp1),"ai.rizom.brain.link":mG(Op1),"ai.rizom.brain.note":mG(xp1),"ai.rizom.brain.post":mG(Rp1),"ai.rizom.brain.project":mG(hp1),"ai.rizom.brain.series":mG(vp1),"ai.rizom.brain.socialPost":mG(Cp1),"ai.rizom.brain.topic":mG(yp1)},Y4w="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function WF(A){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:A,compatibility:Y4w}}var D4w={"ai.rizom.brain.card":WF("@brains/atproto"),"ai.rizom.brain.deck":WF("@brains/decks"),"ai.rizom.brain.link":WF("@brains/link"),"ai.rizom.brain.note":WF("@brains/note"),"ai.rizom.brain.post":WF("@brains/blog"),"ai.rizom.brain.project":WF("@brains/portfolio"),"ai.rizom.brain.series":WF("@brains/series"),"ai.rizom.brain.socialPost":WF("@brains/social-media"),"ai.rizom.brain.topic":WF("@brains/topics")};function ZP(){return Object.values(MB)}function qp0(A){return MB[A]}function Fp0(){return Object.entries(D4w).map(([A,Q])=>({id:A,...Q}))}function zp0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var X4w=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function H4w(A){let Q=K.string(),w=A.maxLength!==void 0?Q.max(A.maxLength):Q;if(A.knownValues)w=w.refine((B)=>A.knownValues?.includes(B),{message:`expected one of ${A.knownValues.join(", ")}`});if(A.format==="datetime")w=w.refine((B)=>X4w.test(B)&&!Number.isNaN(Date.parse(B)),{message:"expected datetime"});if(A.format==="uri")w=w.refine((B)=>{try{return new URL(B),!0}catch{return!1}},{message:"expected uri"});return w}function Ep1(A){switch(A.type){case"string":return H4w(A);case"integer":return K.number().int();case"boolean":return K.boolean();case"array":{let Q=A.items?Ep1(A.items):K.unknown(),w=K.array(Q);if(A.maxLength!==void 0)w=w.max(A.maxLength);return w}case"object":return W4w(A);case"blob":return K.custom(zp0,{message:"expected blob"});default:return K.unknown()}}function gp1(A){let Q=new Set(A.required??[]),w={};for(let[B,$]of Object.entries(A.properties??{})){let Y=Ep1($);w[B]=Q.has(B)?Y:Y.optional()}return w}function W4w(A){return K.object(gp1(A)).passthrough()}function Gp0(A,Q,w,B=[]){let $=Object.keys(A).filter((Y)=>!Q.has(Y));if($.length===0)return;w.addIssue({code:K.ZodIssueCode.custom,path:B,message:`unrecognized field(s): ${$.join(", ")}`})}function f4w(A,Q){if(Gp0(A,new Set(["$type","siteUrl","brain","anchor","skills","model","version","createdAt","updatedAt"]),Q),zp0(A.brain))Gp0(A.brain,new Set(["did","name","role","purpose","values"]),Q,["brain"]);if(zp0(A.anchor))Gp0(A.anchor,new Set(["did","name","kind"]),Q,["anchor"])}function uG(A){let Q=K.object({...gp1(A.defs.main.record),$type:K.literal(A.id).optional()}).passthrough();return A.id==="ai.rizom.brain.card"?Q.superRefine(f4w):Q}var Z4w={"ai.rizom.brain.card":uG(MB["ai.rizom.brain.card"]),"ai.rizom.brain.deck":uG(MB["ai.rizom.brain.deck"]),"ai.rizom.brain.link":uG(MB["ai.rizom.brain.link"]),"ai.rizom.brain.note":uG(MB["ai.rizom.brain.note"]),"ai.rizom.brain.post":uG(MB["ai.rizom.brain.post"]),"ai.rizom.brain.project":uG(MB["ai.rizom.brain.project"]),"ai.rizom.brain.series":uG(MB["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":uG(MB["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":uG(MB["ai.rizom.brain.topic"])};function K4w(A,Q,w){let B=w.path.join(".");if(B==="$type")return`AT Protocol record $type must match lexicon id: ${String(Q.$type)} !== ${A.id}`;if(w.code==="invalid_type"&&w.received==="undefined")return`Missing required AT Protocol record field: ${B}`;if(w.code==="invalid_type")return`Invalid AT Protocol record field ${B}: expected ${w.expected}`;if(w.code==="too_big")return`Invalid AT Protocol record field ${B}: exceeds maxLength ${w.maximum}`;if(w.code==="custom")return`Invalid AT Protocol record field ${B}: ${w.message}`;if(w.code==="unrecognized_keys")return`Unrecognized AT Protocol record field(s): ${w.keys.join(", ")}`;return`Invalid AT Protocol record field ${B}: ${w.message}`}function Lb(A,Q){let w=uG(A).safeParse(Q);if(w.success)return;let B=w.error.issues[0];if(!B)throw w.error;throw Error(K4w(A,Q,B))}var M40="atproto:brain-card-discovered",Tp1="atproto:brain-discovered",Sp1="atproto:brain-card-refreshed",mp1=K.object({repoDid:K.string().min(1),uri:K.string().min(1),cid:K.string().min(1),record:Z4w["ai.rizom.brain.card"]}).strict(),IT8=K.object({agentId:K.string().min(1),name:K.string().min(1),url:K.string().url(),status:K.enum(["discovered","approved"]),repoDid:K.string().min(1).optional(),brainDid:K.string().min(1).optional(),anchorDid:K.string().min(1).optional(),cardUri:K.string().min(1).optional(),cardCid:K.string().min(1).optional()}).strict();class U5{static instance;projections=new Map;registrationCounts=new Map;static getInstance(){return this.instance??=new U5,this.instance}static createFresh(){return new U5}static resetInstance(){this.instance=void 0}register(A){this.validateProjection(A);let Q=this.projections.get(A.entityType);if(Q){if(!this.isEquivalentProjection(Q,A))throw Error(`AT Protocol projection already registered for entity type ${A.entityType}`);return this.registrationCounts.set(A.entityType,(this.registrationCounts.get(A.entityType)??1)+1),this.createUnregister(A.entityType)}return this.projections.set(A.entityType,A),this.registrationCounts.set(A.entityType,1),this.createUnregister(A.entityType)}get(A){return this.projections.get(A)}has(A){return this.projections.has(A)}list(){return Array.from(this.projections.values())}listLexicons(){return this.list().map((A)=>A.lexicon)}createUnregister(A){let Q=!0;return()=>{if(!Q)return;Q=!1;let w=this.registrationCounts.get(A)??0;if(w<=1){this.registrationCounts.delete(A),this.projections.delete(A);return}this.registrationCounts.set(A,w-1)}}isEquivalentProjection(A,Q){return A.entityType===Q.entityType&&A.collection===Q.collection&&A.lexicon.id===Q.lexicon.id&&A.validate===Q.validate}validateProjection(A){if(A.collection!==A.lexicon.id)throw Error(`AT Protocol projection collection must match lexicon id: ${A.collection} !== ${A.lexicon.id}`);if(!A.lexicon.defs.main.key)throw Error(`AT Protocol projection lexicon must define a record key: ${A.collection}`)}}LH();AE();Z0();var Vp0=K.object({defaultPrompt:K.string().default("Write a blog post about my recent work and insights"),paginate:K.boolean().default(!0),pageSize:K.number().default(10)});c0();Z0();CB();var z4w=K.object({prompt:K.string().optional(),title:K.string().optional(),content:K.string().optional(),excerpt:K.string().optional(),coverImageId:K.string().optional(),seriesName:K.string().optional(),seriesIndex:K.number().optional(),skipAi:K.boolean().optional()}),vT8=UX.extend({title:K.string().optional(),slug:K.string().optional()});class Jp0 extends Q4{constructor(A,Q){super(A,Q,{schema:z4w,jobTypeName:"blog-generation",entityType:"post"})}async generate(A,Q){let{prompt:w,coverImageId:B,seriesName:$,seriesIndex:Y,skipAi:D}=A,{title:X,content:H,excerpt:W}=A;if(D){if(!X)this.failEarly("Title is required when skipAi is true");H=H??`## Introduction
5751
5751
 
5752
5752
  Add your introduction here.
5753
5753
 
@@ -5967,7 +5967,7 @@ ${w.content}`,templateName:"blog:excerpt"})})}c0();AE();LH();function T4w(A){let
5967
5967
  letter-spacing: 0.02em;
5968
5968
  }
5969
5969
  .printable-footer a { color: inherit; text-decoration: none; overflow-wrap: anywhere; }
5970
- `}},void 0,!1,void 0,this),x7("header",{className:"printable-hero",children:[x7("div",{className:"printable-masthead",children:Q.brandLabel&&x7("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this),x7("div",{children:[x7("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.excerpt&&x7("p",{className:"printable-excerpt",children:Q.excerpt},void 0,!1,void 0,this),x7("div",{className:"printable-meta",children:[Q.author&&x7("span",{children:["By ",Q.author]},void 0,!0,void 0,this),w&&x7("span",{children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q.coverImageUrl&&x7("figure",{className:"printable-cover-wrap",children:x7("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this)},void 0,!1,void 0,this),x7($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Q.canonicalUrl||Q.brandLabel)&&x7("footer",{className:"printable-footer",children:[x7("span",{children:Q.brandLabel??"Printable PDF"},void 0,!1,void 0,this),Q.canonicalUrl&&x7("a",{href:Q.canonicalUrl,children:Q.canonicalUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var IYw=26214400,bYw=60000;class xp0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==O40)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=LYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await qYw(JYw(VYw(),"brain-blog-printable-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/printable/post/${Q.id}`,template:Yi1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:IYw,timeoutMs:bYw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${NYw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await FYw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){let{frontmatter:Q}=lw(A.content),w=C8.parse(Q);if(!w.coverImageId)return;let B=await this.context.entityService.getEntity({entityType:"image",id:w.coverImageId});return B?.content.startsWith("data:image/")?B.content:void 0}}function LYw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=C8.parse(w);return{title:$.title,body:B,...$.excerpt?{excerpt:$.excerpt}:{},...$.author?{author:$.author}:{},...$.publishedAt?{publishedAt:$.publishedAt}:{},...$.canonicalUrl?{canonicalUrl:$.canonicalUrl}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function NYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}import{mkdtemp as kYw,rm as OYw}from"fs/promises";import{tmpdir as xYw}from"os";import{join as RYw}from"path";Z0();LH();Z0();import{jsxDEV as PYw}from"preact/jsx-dev-runtime";var Nr="og-image",jYw="blog:og-image",Di1=K.object({title:K.string().min(1),excerpt:K.string().optional(),author:K.string().optional(),publishedAt:K.string().optional(),brandLabel:K.string().optional(),coverImageUrl:K.string().optional()}),Xi1={name:jYw,pluginId:"blog",schema:Di1,renderers:{image:_Yw}};function MYw(A){if(!A)return;let Q=new Date(A);if(Number.isNaN(Q.getTime()))return;return Q.toLocaleDateString("en-GB",{year:"numeric",month:"short",day:"2-digit"})}function _Yw(A){let Q=Di1.parse(A);return PYw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Journal",title:Q.title,subtitle:Q.excerpt,meta:[Q.author],tag:MYw(Q.publishedAt)},void 0,!1,void 0,this)}var hYw={width:1200,height:630},vYw=60000;class Rp0{context;metadata={outputEntityType:"image",targetField:"ogImageId"};screenshotPng;constructor(A,Q={}){this.context=A;this.screenshotPng=Q.screenshotPng??Lr}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==Nr)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=CYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await kYw(RYw(xYw(),"brain-blog-og-image-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/og/post/${Q.id}`,template:Xi1,format:"image",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"image",data:await this.screenshotPng(Y.urlFor($.urlPath),hYw,{timeoutMs:vYw,fullPage:!1,omitBackground:!1}),mimeType:"image/png",filename:`${yYw(Q)}-og.png`}}finally{await Y.close()}}finally{await OYw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){let{frontmatter:Q}=lw(A.content),w=C8.parse(Q);if(!w.coverImageId)return;let B=await this.context.entityService.getEntity({entityType:"image",id:w.coverImageId});return B?.content.startsWith("data:image/")?B.content:void 0}}function CYw(A,Q={}){let{frontmatter:w}=lw(A.content),B=C8.parse(w);return{title:B.title,...B.excerpt?{excerpt:B.excerpt}:{},...B.author?{author:B.author}:{},...B.publishedAt?{publishedAt:B.publishedAt}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function yYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var Hi1={name:"@brains/blog",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/contracts":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class hp0 extends kQ{entityType=ZF.entityType;schema=ey;adapter=ZF;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("blog",Hi1,A,Vp0)}getEntityTypeConfig(){return{weight:2,publish:{publishStatuses:["queued","published"]}}}createGenerationHandler(A){return new Jp0(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return ip1()}getDataSources(){return[new bp0(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (Zi1(),fi1));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),dp1(A,this.logger),np1(A,this.logger),op1(A,this.logger),sp1(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("post",O40,new xp0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("post",Nr,new Rp0(A)),this.deferPublishAssetRegistration(A),this.unregisterAtprotoProjection=U5.getInstance().register(jp0()),this.logger.info("Blog plugin registered (routes auto-generated at /posts/)")}deferPublishAssetRegistration(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish-assets:register",payload:{entityType:"post",attachmentType:Nr,mediaEntityType:"image",targetEntityField:{location:"frontmatter",field:"ogImageId"},requiredWhen:{status:"published"},autoGenerate:!0,jobType:"image:image-render-source"}}),{success:!0}})}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0,this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}}function vp0(A={}){return new hp0(A)}LH();AE();c0();Z0();Z0();l$();c0();var Qf=K.object({title:K.string(),slug:K.string(),coverImageId:K.string().optional()}),Ki1=Qf.pick({title:!0,slug:!0}),Nb=o1.extend({metadata:Ki1}),x40=Nb.extend({frontmatter:Qf}),R40=x40.extend({description:K.string().optional(),postCount:K.number(),coverImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()}),Ui1=K.object({description:K.string().optional()});function GP(A){return new pw(Ui1,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}c0();class Cp0 extends J2{constructor(){super({entityType:"series",purpose:"A series grouping related posts or content under one theme.",schema:Nb,frontmatterSchema:Qf,supportsCoverImage:!0,bodyFormatter:GP("")})}toMarkdown(A){let Q,w={};try{Q=this.parseFrontMatter(A.content,Qf).coverImageId,w=GP(A.metadata.title).parse(this.extractBody(A.content))}catch{}let B={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},Y=GP(A.metadata.title).format(w);return this.buildMarkdown(Y,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Qf);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,Qf);return GP(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var jb=new Cp0;c0();Z0();IX();Z0();var TYw=K.object({seriesName:K.string().optional(),seriesIndex:K.number().optional()});function h40(A){let Q=TYw.safeParse(A);return Q.success?Q.data:{}}function zP(A){return h40(A.metadata).seriesName}function Gi1(A){return h40(A.metadata).seriesIndex}function zi1(A,Q){let w=Gi1(A)??Number.MAX_SAFE_INTEGER,B=Gi1(Q)??Number.MAX_SAFE_INTEGER;return w-B}class yp0{entityService;logger;constructor(A,Q){this.entityService=A;this.logger=Q}async syncAllSeries(){this.logger.debug("Syncing series from all entity types");let A=await this.collectSeriesNames();this.logger.debug(`Found ${A.size} unique series`);let Q=await this.entityService.listEntities({entityType:"series"}),w=new Map(Q.map(($)=>[$.id,$])),B=new Set;for(let $ of A){let Y=w1($);B.add(Y);let D=w.get(Y),X=D?.content??this.createSeriesContent($),H=xw(X);if(D?.contentHash===H)continue;let W={id:Y,entityType:"series",content:X,contentHash:H,created:D?.created??new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:$,slug:w1($)}};await this.entityService.upsertEntity({entity:W}),this.logger.debug(`Upserted series: ${$}`)}for(let $ of Q)if(!B.has($.id))await this.entityService.deleteEntity({entityType:"series",id:$.id}),this.logger.debug(`Deleted orphaned series: ${$.id}`)}async handleEntityChange(A,Q){let w=zP(A);if(w)await this.ensureSeriesExists(w);if(Q&&Q!==w)await this.cleanupOrphanedSeries(Q)}async handleEntityDeleted(){await this.syncAllSeries()}async ensureSeriesExists(A){let Q=w1(A);if(await this.entityService.getEntity({entityType:"series",id:Q}))return;let B=this.createSeriesContent(A),$={id:Q,entityType:"series",content:B,contentHash:xw(B),created:new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:A,slug:w1(A)}};await this.entityService.upsertEntity({entity:$}),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=w1(A);if(!await this.entityService.getEntity({entityType:"series",id:Q}))return;if(!await this.hasSeriesReferences(A))await this.entityService.deleteEntity({entityType:"series",id:Q}),this.logger.debug(`Deleted orphaned series: ${A}`)}async hasSeriesReferences(A){let Q=this.entityService.getEntityTypes();for(let w of Q){if(w==="series")continue;if((await this.entityService.listEntities({entityType:w,options:{filter:{metadata:{seriesName:A}},limit:1}})).length>0)return!0}return!1}async collectSeriesNames(){let A=new Set,Q=this.entityService.getEntityTypes();for(let w of Q){if(w==="series")continue;let B=await this.entityService.listEntities({entityType:w});for(let $ of B){let Y=zP($);if(Y)A.add(Y)}}return A}createSeriesContent(A){let Q={title:A,slug:w1(A)};return f7("",Q)}}c0();Z0();var SYw=K.object({entityType:K.literal("series"),query:K.object({id:K.string().optional(),limit:K.number().optional(),page:K.number().optional(),pageSize:K.number().optional()}).passthrough()}),mYw=K.object({type:K.enum(["list","detail"]),seriesName:K.string().optional()});function uYw(A){let Q=mYw.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let w=SYw.safeParse(A);if(w.success){let{query:B}=w.data;if(B.id)return{type:"detail",seriesSlug:B.id};return{type:"list"}}throw Error('Invalid series query format. Expected { type: "list"|"detail" } or { entityType: "series", query: { id?: string } }')}function qi1(A){let Q=v2(A.content,Qf);return x40.parse({...A,frontmatter:Q.metadata})}class Ep0{logger;id="series:entities";name="Series DataSource";description="Fetches series list and detail data";constructor(A){this.logger=A}async fetch(A,Q,w){let B=uYw(A),$=w.entityService;if(B.type==="list")return this.fetchSeriesList(Q,$);if(B.seriesName)return this.fetchSeriesDetail(B.seriesName,Q,$);if(B.seriesSlug)return this.fetchSeriesDetailBySlug(B.seriesSlug,Q,$);throw Error("Invalid series query: must specify seriesName or slug for detail")}async fetchSeriesList(A,Q){let w=await Q.listEntities({entityType:"series"}),B=await this.countEntitiesPerSeries(Q),$=w.map((Y)=>{let D=qi1(Y),X=jb.parseBody(Y.content);return{...D,description:X.description,postCount:B.get(Y.metadata.title)??0}});return this.logger.debug(`Found ${$.length} series entities`),A.parse({series:$})}async fetchSeriesDetail(A,Q,w,B){if(!B)B=(await w.listEntities({entityType:"series",options:{filter:{metadata:{title:A}}}}))[0];if(!B)throw Error(`Series not found: ${A}`);let $=qi1(B),Y=jb.parseBody(B.content),D=await this.getSeriesMembers(A,w);return this.logger.debug(`Found ${D.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:D,series:{...$,description:Y.description,postCount:D.length},description:Y.description})}async fetchSeriesDetailBySlug(A,Q,w){let $=(await w.listEntities({entityType:"series",options:{filter:{metadata:{slug:A}}}}))[0];if(!$)throw Error(`Series not found with slug: ${A}`);return this.fetchSeriesDetail($.metadata.title,Q,w,$)}async countEntitiesPerSeries(A){let Q=new Map,w=A.getEntityTypes();for(let B of w){if(B==="series")continue;let $=await A.listEntities({entityType:B});for(let Y of $){let D=zP(Y);if(D)Q.set(D,(Q.get(D)??0)+1)}}return Q}async getSeriesMembers(A,Q){let w=[],B=Q.getEntityTypes();for(let $ of B){if($==="series")continue;let Y=await Q.listEntities({entityType:$,options:{filter:{metadata:{seriesName:A}}}});w.push(...Y)}return w.sort(zi1),w}}c0();Z0();IX();var cYw=K.object({prompt:K.string().optional(),title:K.string().optional(),seriesId:K.string().optional()}),lYw=K.object({title:K.string().optional(),excerpt:K.string().optional()});class v40{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 w=await this.context.entityService.getEntity({entityType:"series",id:Q});if(!w)return{success:!1,error:`Series not found: ${Q}`};let B=await this.gatherMemberSummaries(w.metadata.title);if(B.length===0)return{success:!1,error:`No members found in series: ${w.metadata.title}`};let $=A.prompt??`Series name: ${w.metadata.title}
5970
+ `}},void 0,!1,void 0,this),x7("header",{className:"printable-hero",children:[x7("div",{className:"printable-masthead",children:Q.brandLabel&&x7("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this),x7("div",{children:[x7("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.excerpt&&x7("p",{className:"printable-excerpt",children:Q.excerpt},void 0,!1,void 0,this),x7("div",{className:"printable-meta",children:[Q.author&&x7("span",{children:["By ",Q.author]},void 0,!0,void 0,this),w&&x7("span",{children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q.coverImageUrl&&x7("figure",{className:"printable-cover-wrap",children:x7("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this)},void 0,!1,void 0,this),x7($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Q.canonicalUrl||Q.brandLabel)&&x7("footer",{className:"printable-footer",children:[x7("span",{children:Q.brandLabel??"Printable PDF"},void 0,!1,void 0,this),Q.canonicalUrl&&x7("a",{href:Q.canonicalUrl,children:Q.canonicalUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var IYw=26214400,bYw=60000;class xp0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==O40)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=LYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await qYw(JYw(VYw(),"brain-blog-printable-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/printable/post/${Q.id}`,template:Yi1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:IYw,timeoutMs:bYw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${NYw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await FYw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){let{frontmatter:Q}=lw(A.content),w=C8.parse(Q);if(!w.coverImageId)return;let B=await this.context.entityService.getEntity({entityType:"image",id:w.coverImageId});return B?.content.startsWith("data:image/")?B.content:void 0}}function LYw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=C8.parse(w);return{title:$.title,body:B,...$.excerpt?{excerpt:$.excerpt}:{},...$.author?{author:$.author}:{},...$.publishedAt?{publishedAt:$.publishedAt}:{},...$.canonicalUrl?{canonicalUrl:$.canonicalUrl}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function NYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}import{mkdtemp as kYw,rm as OYw}from"fs/promises";import{tmpdir as xYw}from"os";import{join as RYw}from"path";Z0();LH();Z0();import{jsxDEV as PYw}from"preact/jsx-dev-runtime";var Nr="og-image",jYw="blog:og-image",Di1=K.object({title:K.string().min(1),excerpt:K.string().optional(),author:K.string().optional(),publishedAt:K.string().optional(),brandLabel:K.string().optional(),coverImageUrl:K.string().optional()}),Xi1={name:jYw,pluginId:"blog",schema:Di1,renderers:{image:_Yw}};function MYw(A){if(!A)return;let Q=new Date(A);if(Number.isNaN(Q.getTime()))return;return Q.toLocaleDateString("en-GB",{year:"numeric",month:"short",day:"2-digit"})}function _Yw(A){let Q=Di1.parse(A);return PYw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Journal",title:Q.title,subtitle:Q.excerpt,meta:[Q.author],tag:MYw(Q.publishedAt)},void 0,!1,void 0,this)}var hYw={width:1200,height:630},vYw=60000;class Rp0{context;metadata={outputEntityType:"image",targetField:"ogImageId"};screenshotPng;constructor(A,Q={}){this.context=A;this.screenshotPng=Q.screenshotPng??Lr}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==Nr)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=CYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await kYw(RYw(xYw(),"brain-blog-og-image-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/og/post/${Q.id}`,template:Xi1,format:"image",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"image",data:await this.screenshotPng(Y.urlFor($.urlPath),hYw,{timeoutMs:vYw,fullPage:!1,omitBackground:!1}),mimeType:"image/png",filename:`${yYw(Q)}-og.png`}}finally{await Y.close()}}finally{await OYw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){let{frontmatter:Q}=lw(A.content),w=C8.parse(Q);if(!w.coverImageId)return;let B=await this.context.entityService.getEntity({entityType:"image",id:w.coverImageId});return B?.content.startsWith("data:image/")?B.content:void 0}}function CYw(A,Q={}){let{frontmatter:w}=lw(A.content),B=C8.parse(w);return{title:B.title,...B.excerpt?{excerpt:B.excerpt}:{},...B.author?{author:B.author}:{},...B.publishedAt?{publishedAt:B.publishedAt}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function yYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var Hi1={name:"@brains/blog",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/contracts":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class hp0 extends kQ{entityType=ZF.entityType;schema=ey;adapter=ZF;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("blog",Hi1,A,Vp0)}getEntityTypeConfig(){return{weight:2,publish:{publishStatuses:["queued","published"]}}}createGenerationHandler(A){return new Jp0(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return ip1()}getDataSources(){return[new bp0(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (Zi1(),fi1));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),dp1(A,this.logger),np1(A,this.logger),op1(A,this.logger),sp1(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("post",O40,new xp0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("post",Nr,new Rp0(A)),this.deferPublishAssetRegistration(A),this.unregisterAtprotoProjection=U5.getInstance().register(jp0()),this.logger.info("Blog plugin registered (routes auto-generated at /posts/)")}deferPublishAssetRegistration(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish-assets:register",payload:{entityType:"post",attachmentType:Nr,mediaEntityType:"image",targetEntityField:{location:"frontmatter",field:"ogImageId"},requiredWhen:{status:"published"},autoGenerate:!0,jobType:"image:image-render-source"}}),{success:!0}})}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0,this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}}function vp0(A={}){return new hp0(A)}LH();AE();c0();Z0();Z0();l$();c0();var Qf=K.object({title:K.string(),slug:K.string(),coverImageId:K.string().optional()}),Ki1=Qf.pick({title:!0,slug:!0}),Nb=o1.extend({metadata:Ki1}),x40=Nb.extend({frontmatter:Qf}),R40=x40.extend({description:K.string().optional(),postCount:K.number(),coverImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()}),Ui1=K.object({description:K.string().optional()});function GP(A){return new pw(Ui1,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}c0();class Cp0 extends J2{constructor(){super({entityType:"series",purpose:"A series grouping related posts or content under one theme.",schema:Nb,frontmatterSchema:Qf,supportsCoverImage:!0,bodyFormatter:GP("")})}toMarkdown(A){let Q,w={};try{Q=this.parseFrontMatter(A.content,Qf).coverImageId,w=GP(A.metadata.title).parse(this.extractBody(A.content))}catch{}let B={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},Y=GP(A.metadata.title).format(w);return this.buildMarkdown(Y,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Qf);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,Qf);return GP(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var jb=new Cp0;c0();Z0();IX();Z0();var TYw=K.object({seriesName:K.string().optional(),seriesIndex:K.number().optional()});function h40(A){let Q=TYw.safeParse(A);return Q.success?Q.data:{}}function zP(A){return h40(A.metadata).seriesName}function Gi1(A){return h40(A.metadata).seriesIndex}function zi1(A,Q){let w=Gi1(A)??Number.MAX_SAFE_INTEGER,B=Gi1(Q)??Number.MAX_SAFE_INTEGER;return w-B}class yp0{entityService;logger;constructor(A,Q){this.entityService=A;this.logger=Q}async syncAllSeries(){this.logger.debug("Syncing series from all entity types");let A=await this.collectSeriesNames();this.logger.debug(`Found ${A.size} unique series`);let Q=await this.entityService.listEntities({entityType:"series"}),w=new Map(Q.map(($)=>[$.id,$])),B=new Set;for(let $ of A){let Y=w1($);B.add(Y);let D=w.get(Y),X=D?.content??this.createSeriesContent($),H=xw(X);if(D?.contentHash===H)continue;let W={id:Y,entityType:"series",content:X,contentHash:H,created:D?.created??new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:$,slug:w1($)}};await this.entityService.upsertEntity({entity:W}),this.logger.debug(`Upserted series: ${$}`)}for(let $ of Q)if(!B.has($.id))await this.entityService.deleteEntity({entityType:"series",id:$.id}),this.logger.debug(`Deleted orphaned series: ${$.id}`)}async handleEntityChange(A,Q){let w=zP(A);if(w)await this.ensureSeriesExists(w);if(Q&&Q!==w)await this.cleanupOrphanedSeries(Q)}async handleEntityDeleted(){await this.syncAllSeries()}async ensureSeriesExists(A){let Q=w1(A);if(await this.entityService.getEntity({entityType:"series",id:Q}))return;let B=this.createSeriesContent(A),$={id:Q,entityType:"series",content:B,contentHash:xw(B),created:new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:A,slug:w1(A)}};await this.entityService.upsertEntity({entity:$}),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=w1(A);if(!await this.entityService.getEntity({entityType:"series",id:Q}))return;if(!await this.hasSeriesReferences(A))await this.entityService.deleteEntity({entityType:"series",id:Q}),this.logger.debug(`Deleted orphaned series: ${A}`)}async hasSeriesReferences(A){let Q=this.entityService.getEntityTypes();for(let w of Q){if(w==="series")continue;if((await this.entityService.listEntities({entityType:w,options:{filter:{metadata:{seriesName:A}},limit:1}})).length>0)return!0}return!1}async collectSeriesNames(){let A=new Set,Q=this.entityService.getEntityTypes();for(let w of Q){if(w==="series")continue;let B=await this.entityService.listEntities({entityType:w});for(let $ of B){let Y=zP($);if(Y)A.add(Y)}}return A}createSeriesContent(A){let Q={title:A,slug:w1(A)};return f7("",Q)}}c0();Z0();var SYw=K.object({entityType:K.literal("series"),query:K.object({id:K.string().optional(),limit:K.number().optional(),page:K.number().optional(),pageSize:K.number().optional()}).passthrough()}),mYw=K.object({type:K.enum(["list","detail"]),seriesName:K.string().optional()});function uYw(A){let Q=mYw.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let w=SYw.safeParse(A);if(w.success){let{query:B}=w.data;if(B.id)return{type:"detail",seriesSlug:B.id};return{type:"list"}}throw Error('Invalid series query format. Expected { type: "list"|"detail" } or { entityType: "series", query: { id?: string } }')}function qi1(A){let Q=v2(A.content,Qf);return x40.parse({...A,frontmatter:Q.metadata})}class Ep0{logger;id="series:entities";name="Series DataSource";description="Fetches series list and detail data";constructor(A){this.logger=A}async fetch(A,Q,w){let B=uYw(A),$=w.entityService;if(B.type==="list")return this.fetchSeriesList(Q,$);if(B.seriesName)return this.fetchSeriesDetail(B.seriesName,Q,$);if(B.seriesSlug)return this.fetchSeriesDetailBySlug(B.seriesSlug,Q,$);throw Error("Invalid series query: must specify seriesName or slug for detail")}async fetchSeriesList(A,Q){let w=await Q.listEntities({entityType:"series"}),B=await this.countEntitiesPerSeries(Q),$=w.map((Y)=>{let D=qi1(Y),X=jb.parseBody(Y.content);return{...D,description:X.description,postCount:B.get(Y.metadata.title)??0}});return this.logger.debug(`Found ${$.length} series entities`),A.parse({series:$})}async fetchSeriesDetail(A,Q,w,B){if(!B)B=(await w.listEntities({entityType:"series",options:{filter:{metadata:{title:A}}}}))[0];if(!B)throw Error(`Series not found: ${A}`);let $=qi1(B),Y=jb.parseBody(B.content),D=await this.getSeriesMembers(A,w);return this.logger.debug(`Found ${D.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:D,series:{...$,description:Y.description,postCount:D.length},description:Y.description})}async fetchSeriesDetailBySlug(A,Q,w){let $=(await w.listEntities({entityType:"series",options:{filter:{metadata:{slug:A}}}}))[0];if(!$)throw Error(`Series not found with slug: ${A}`);return this.fetchSeriesDetail($.metadata.title,Q,w,$)}async countEntitiesPerSeries(A){let Q=new Map,w=A.getEntityTypes();for(let B of w){if(B==="series")continue;let $=await A.listEntities({entityType:B});for(let Y of $){let D=zP(Y);if(D)Q.set(D,(Q.get(D)??0)+1)}}return Q}async getSeriesMembers(A,Q){let w=[],B=Q.getEntityTypes();for(let $ of B){if($==="series")continue;let Y=await Q.listEntities({entityType:$,options:{filter:{metadata:{seriesName:A}}}});w.push(...Y)}return w.sort(zi1),w}}c0();Z0();IX();var cYw=K.object({prompt:K.string().optional(),title:K.string().optional(),seriesId:K.string().optional()}),lYw=K.object({title:K.string().optional(),excerpt:K.string().optional()});class v40{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 w=await this.context.entityService.getEntity({entityType:"series",id:Q});if(!w)return{success:!1,error:`Series not found: ${Q}`};let B=await this.gatherMemberSummaries(w.metadata.title);if(B.length===0)return{success:!1,error:`No members found in series: ${w.metadata.title}`};let $=A.prompt??`Series name: ${w.metadata.title}
5971
5971
 
5972
5972
  Content in this series:
5973
5973
  ${B.join(`
@@ -5979,7 +5979,7 @@ Your task is to write a series description (2-3 sentences) that:
5979
5979
  3. Is engaging and makes readers want to explore the content
5980
5980
  4. Works well as a series overview on a website
5981
5981
 
5982
- Be concise and focus on what makes this series unique and valuable.`});async function Ni1({entity:A,config:Q}){let w=Nb.parse(A),B=jb.parseBody(w.content);return{$type:"ai.rizom.brain.series",title:w.metadata.title,slug:w.metadata.slug,...B.description&&{description:B.description},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"series",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function gp0(){return{entityType:"series",collection:"ai.rizom.brain.series",lexicon:MB["ai.rizom.brain.series"],validate:!1,buildRecord:Ni1}}var ji1={name:"@brains/series",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/entity-service":"workspace:*","@brains/job-queue":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var Mi1=K.discriminatedUnion("mode",[K.object({mode:K.literal("derive"),reason:K.string().optional()}),K.object({mode:K.literal("source"),entityId:K.string(),entityType:K.string(),seriesName:K.string().optional(),previousSeriesName:K.string().optional()})]);class Tp0 extends kQ{entityType="series";schema=Nb;adapter=jb;manager;unregisterAtprotoProjection;constructor(){super("series",ji1)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new v40(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...bi1(),description:Li1}}getDataSources(){return[new Ep0(this.logger.child("SeriesDataSource"))]}getDerivedEntityProjections(A){return[{id:"series-projection",targetType:"series",job:{type:"series:project",handler:this.createSeriesProjectionHandler(A)},initialSync:{jobData:{mode:"derive",reason:"initial-sync"},jobOptions:this.getSyncProjectionJobOptions("initial-sync")},sourceChange:{sourceTypes:["*"],events:["entity:created","entity:updated","entity:deleted"],requireInitialSync:!0,jobData:(Q)=>{if(Q.entityType==="series")return null;if(!Q.entity)return null;let w=zP(Q.entity),B=h40(Q.previousMetadata).seriesName;if(!w&&!B)return null;return{mode:"source",entityId:Q.entity.id,entityType:Q.entity.entityType,...w?{seriesName:w}:{},...B&&B!==w?{previousSeriesName:B}:{}}},jobOptions:(Q)=>{if(!Q.entity)return;return this.getSourceProjectionJobOptions(Q.entity)}}}]}async onRegister(A){this.manager=new yp0(A.entityService,this.logger.child("SeriesManager")),this.unregisterAtprotoProjection=U5.getInstance().register(gp0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}createSeriesProjectionHandler(A){return{process:async(Q)=>{let w=Mi1.parse(Q);if(w.mode==="derive")return await this.projectAll(A),{success:!0};let B=await A.entityService.getEntity({entityType:w.entityType,id:w.entityId});if(B)await this.projectSource(B,w.previousSeriesName);else{let $=this.requireManager();for(let Y of[w.seriesName,w.previousSeriesName])if(Y)await $.cleanupOrphanedSeries(Y)}return{success:!0}},validateAndParse:(Q)=>{let w=Mi1.safeParse(Q??{});return w.success?w.data:null}}}requireManager(){if(!this.manager)throw Error("SeriesPlugin not registered");return this.manager}getSyncProjectionJobOptions(A){return{source:this.id,deduplication:"coalesce",deduplicationKey:`series-sync:${A}`,metadata:{operationType:"data_processing",operationTarget:"series"}}}getSourceProjectionJobOptions(A){return{source:this.id,deduplication:"coalesce",deduplicationKey:`series-source:${A.entityType}:${A.id}`,metadata:{operationType:"data_processing",operationTarget:`series:${A.entityType}:${A.id}`}}}async projectSource(A,Q){await this.requireManager().handleEntityChange(A,Q)}async projectAll(A){await this.requireManager().syncAllSeries();let Q=new v40(this.logger.child("SeriesGenerationHandler"),A),w=await A.entityService.listEntities({entityType:"series"});for(let B of w)try{if(!this.adapter.parseBody(B.content).description)this.logger.info(`Generating description for series: ${B.metadata.title}`),await Q.process({seriesId:B.id})}catch($){this.logger.error(`Failed to generate description for series: ${B.id}`,{error:$})}}}function Sp0(){return new Tp0}c0();Z0();c0();Z0();Z0();c0();var rYw=K.enum(["generating","draft","queued","published","failed"]),_i1="publishedAt is required when deck status is published",Pi1=(A)=>A.status==="published"&&!A.publishedAt,mp0=(A)=>{if(Pi1(A))throw Error(_i1)},wf=K.object({title:K.string(),slug:K.string().optional(),description:K.string().optional(),author:K.string().optional(),status:rYw,publishedAt:K.string().datetime().optional(),event:K.string().optional(),coverImageId:K.string().optional(),ogImageId:K.string().optional()}),oYw=wf.pick({title:!0,description:!0,status:!0,publishedAt:!0,coverImageId:!0}).extend({slug:K.string(),error:K.string().optional()}).superRefine((A,Q)=>{if(!Pi1(A))return;Q.addIssue({code:K.ZodIssueCode.custom,path:["publishedAt"],message:_i1})}),wE=o1.extend({entityType:K.literal("deck"),metadata:oYw}),C40=wE.extend({frontmatter:wf,body:K.string(),ogImageUrl:K.string().optional()}),qP=C40.extend({url:K.string().optional(),typeLabel:K.string().optional(),listUrl:K.string().optional(),listLabel:K.string().optional(),coverImageUrl:K.string().optional(),ogImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()});class up0 extends J2{constructor(){super({entityType:"deck",purpose:"A slide-deck presentation.",schema:wE,frontmatterSchema:wf,supportsCoverImage:!0})}validateSlideStructure(A){if(!/^---$/gm.test(A))throw Error("Invalid deck: markdown must contain slide separators (---) to be a valid presentation")}toMarkdown(A){let Q=this.extractBody(A.content);this.validateSlideStructure(Q);let w=this.parseFrontMatter(A.content,wf);mp0(w);let B={...w,slug:w.slug??A.metadata.slug};return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontmatter(A),w=this.extractBody(A);mp0(Q),this.validateSlideStructure(w);let B=Q.slug??w1(Q.title),$=Q.status;return{entityType:"deck",content:A,metadata:{slug:B,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)}buildStub(A){let Q={title:A.title,slug:A.id,status:"generating"};return{content:this.buildMarkdown(`---
5982
+ Be concise and focus on what makes this series unique and valuable.`});async function Ni1({entity:A,config:Q}){let w=Nb.parse(A),B=jb.parseBody(w.content);return{$type:"ai.rizom.brain.series",title:w.metadata.title,slug:w.metadata.slug,...B.description&&{description:B.description},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"series",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function gp0(){return{entityType:"series",collection:"ai.rizom.brain.series",lexicon:MB["ai.rizom.brain.series"],validate:!1,buildRecord:Ni1}}var ji1={name:"@brains/series",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/entity-service":"workspace:*","@brains/job-queue":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var Mi1=K.discriminatedUnion("mode",[K.object({mode:K.literal("derive"),reason:K.string().optional()}),K.object({mode:K.literal("source"),entityId:K.string(),entityType:K.string(),seriesName:K.string().optional(),previousSeriesName:K.string().optional()})]);class Tp0 extends kQ{entityType="series";schema=Nb;adapter=jb;manager;unregisterAtprotoProjection;constructor(){super("series",ji1)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new v40(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...bi1(),description:Li1}}getDataSources(){return[new Ep0(this.logger.child("SeriesDataSource"))]}getDerivedEntityProjections(A){return[{id:"series-projection",targetType:"series",job:{type:"series:project",handler:this.createSeriesProjectionHandler(A)},initialSync:{jobData:{mode:"derive",reason:"initial-sync"},jobOptions:this.getSyncProjectionJobOptions("initial-sync")},sourceChange:{sourceTypes:["*"],events:["entity:created","entity:updated","entity:deleted"],requireInitialSync:!0,jobData:(Q)=>{if(Q.entityType==="series")return null;if(!Q.entity)return null;let w=zP(Q.entity),B=h40(Q.previousMetadata).seriesName;if(!w&&!B)return null;return{mode:"source",entityId:Q.entity.id,entityType:Q.entity.entityType,...w?{seriesName:w}:{},...B&&B!==w?{previousSeriesName:B}:{}}},jobOptions:(Q)=>{if(!Q.entity)return;return this.getSourceProjectionJobOptions(Q.entity)}}}]}async onRegister(A){this.manager=new yp0(A.entityService,this.logger.child("SeriesManager")),this.unregisterAtprotoProjection=U5.getInstance().register(gp0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}createSeriesProjectionHandler(A){return{process:async(Q)=>{let w=Mi1.parse(Q);if(w.mode==="derive")return await this.projectAll(A),{success:!0};let B=await A.entityService.getEntity({entityType:w.entityType,id:w.entityId});if(B)await this.projectSource(B,w.previousSeriesName);else{let $=this.requireManager();for(let Y of[w.seriesName,w.previousSeriesName])if(Y)await $.cleanupOrphanedSeries(Y)}return{success:!0}},validateAndParse:(Q)=>{let w=Mi1.safeParse(Q??{});return w.success?w.data:null}}}requireManager(){if(!this.manager)throw Error("SeriesPlugin not registered");return this.manager}getSyncProjectionJobOptions(A){return{source:this.id,deduplication:"coalesce",deduplicationKey:`series-sync:${A}`,metadata:{operationType:"data_processing",operationTarget:"series"}}}getSourceProjectionJobOptions(A){return{source:this.id,deduplication:"coalesce",deduplicationKey:`series-source:${A.entityType}:${A.id}`,metadata:{operationType:"data_processing",operationTarget:`series:${A.entityType}:${A.id}`}}}async projectSource(A,Q){await this.requireManager().handleEntityChange(A,Q)}async projectAll(A){await this.requireManager().syncAllSeries();let Q=new v40(this.logger.child("SeriesGenerationHandler"),A),w=await A.entityService.listEntities({entityType:"series"});for(let B of w)try{if(!this.adapter.parseBody(B.content).description)this.logger.info(`Generating description for series: ${B.metadata.title}`),await Q.process({seriesId:B.id})}catch($){this.logger.error(`Failed to generate description for series: ${B.id}`,{error:$})}}}function Sp0(){return new Tp0}c0();Z0();c0();Z0();Z0();c0();var rYw=K.enum(["generating","draft","queued","published","failed"]),_i1="publishedAt is required when deck status is published",Pi1=(A)=>A.status==="published"&&!A.publishedAt,mp0=(A)=>{if(Pi1(A))throw Error(_i1)},wf=K.object({title:K.string(),slug:K.string().optional(),description:K.string().optional(),author:K.string().optional(),status:rYw,publishedAt:K.string().datetime().optional(),event:K.string().optional(),coverImageId:K.string().optional(),ogImageId:K.string().optional()}),oYw=wf.pick({title:!0,description:!0,status:!0,publishedAt:!0,coverImageId:!0}).extend({slug:K.string(),error:K.string().optional()}).superRefine((A,Q)=>{if(!Pi1(A))return;Q.addIssue({code:K.ZodIssueCode.custom,path:["publishedAt"],message:_i1})}),wE=o1.extend({entityType:K.literal("deck"),metadata:oYw}),C40=wE.extend({frontmatter:wf,body:K.string(),ogImageUrl:K.string().optional()}),qP=C40.extend({url:K.string().optional(),typeLabel:K.string().optional(),listUrl:K.string().optional(),listLabel:K.string().optional(),coverImageUrl:K.string().optional(),ogImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()});class up0 extends J2{constructor(){super({entityType:"deck",purpose:"A slide-deck presentation.",schema:wE,frontmatterSchema:wf,supportsCoverImage:!0})}validateSlideStructure(A){if(!/^---$/gm.test(A))throw Error("Invalid deck: markdown must contain slide separators (---) to be a valid presentation")}toMarkdown(A){let Q=this.extractBody(A.content);this.validateSlideStructure(Q);let w=this.parseFrontMatter(A.content,wf);mp0(w);let B={...w,slug:w.slug??A.metadata.slug};return this.buildMarkdown(Q,B)}fromMarkdown(A){let Q=this.parseFrontmatter(A),w=this.extractBody(A);mp0(Q),this.validateSlideStructure(w);let B=Q.slug??w1(Q.title),$=Q.status;return{entityType:"deck",content:A,metadata:{slug:B,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)}buildStub(A){let Q={title:A.title,slug:A.id,status:"generating"};return{content:this.buildMarkdown(`---
5983
5983
  `,Q),metadata:{title:A.title,slug:A.id,status:"generating"}}}}var jr=new up0;Z0();IB();var sYw=K.object({markdown:K.string().describe("Markdown content with slide separators (---)"),deck:qP.optional()}),cp0=R1({name:"deck-detail",description:"Render a presentation deck as Reveal.js slides",schema:sYw,dataSourceId:"decks:entities",requiredPermission:"public",layout:{component:ku0,fullscreen:!0}});IB();Z0();var lp0=K.object({decks:K.array(C40)}),pp0=K.object({decks:K.array(qP),pageTitle:K.string().optional(),pageLabel:K.string().optional()});import{jsxDEV as ip0}from"preact/jsx-dev-runtime";var aYw="Presentations",dp0=({decks:A,pageLabel:Q})=>{let w=A.map(($)=>({id:$.id,url:$.url,title:$.frontmatter.title,date:$.frontmatter.publishedAt??$.created,description:$.frontmatter.description}));return ip0("div",{className:"deck-list bg-theme",children:ip0("div",{className:"container mx-auto max-w-[1100px] px-6 py-16 md:px-12 md:py-24",children:ip0(Vn,{label:Q&&Q!=="Decks"?Q:aYw,items:w},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)};l$();class y40 extends pw{constructor(){super(lp0,{title:"Deck List",mappings:[{key:"decks",label:"Decks",type:"array",itemType:"object"}]})}}var np0=R1({name:"deck-list",description:"List view of all presentation decks",schema:pp0,dataSourceId:"decks:entities",requiredPermission:"public",formatter:new y40,layout:{component:dp0}});Z0();c0();var tYw=K.object({title:K.string().max(80).describe("A short, punchy title (2-5 words) that's memorable and evocative"),content:K.string().describe("Full slide deck content in markdown format with slide separators (---). Each slide should have a header and focused content."),description:K.string().describe("A concise 1-2 sentence summary that captures the essence of the talk")}),ki1=R1({name:"decks:generation",description:"Template for AI to generate complete slide decks from prompts",schema:tYw,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are creating slide decks in a distinctive voice that blends philosophy, technology, and culture.
5984
5984
 
5985
5985
  Your task is to generate a complete slide deck based on the user's prompt.
@@ -6287,14 +6287,14 @@ ${X}`,templateName:"decks:description"})).description,await this.reportProgress(
6287
6287
  color: var(--carousel-accent);
6288
6288
  font-weight: 600;
6289
6289
  }
6290
- `}},void 0,!1,void 0,this),$.map((W,f)=>_4("section",{className:`deck-carousel-slide${f===0?" is-cover":""}`,children:[_4("header",{className:"deck-carousel-header",children:_4("span",{className:"deck-carousel-wordmark","aria-label":w??Q,children:[_4("span",{className:"wm-primary",children:Y.primary},void 0,!1,void 0,this),Y.secondary!==void 0&&_4($Dw,{children:[_4("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),_4("span",{className:"wm-secondary",children:Y.secondary},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_4("div",{className:"deck-carousel-body",children:_4("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:H(W.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),_4("footer",{className:"deck-carousel-footer",children:[_4("span",{className:"deck-carousel-footer-meta",children:B??Q},void 0,!1,void 0,this),_4("span",{className:"deck-carousel-counter","aria-label":`Slide ${f+1} of ${D}`,children:[_4("span",{className:"deck-carousel-counter-current",children:String(f+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",_4("span",{children:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},f,!0,void 0,this))]},void 0,!0,void 0,this)}import{mkdtemp as YDw,rm as DDw}from"fs/promises";import{tmpdir as XDw}from"os";import{join as HDw}from"path";Z0();var WDw=26214400,fDw=60000,vi1=20;class sp0{context;metadata={outputEntityType:"document"};renderPdf;getThemeMode;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK,this.getThemeMode=Q.getThemeMode??(async()=>"dark")}async resolve(A){if(A.sourceEntityType!=="deck")return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let w=ZDw(Q,{brandLabel:this.resolveBrandLabel()});if(w.slides.length>vi1)throw Error(`Refusing to render carousel with ${w.slides.length} slides; maxSlides=${vi1}`);let B=await this.getThemeMode(),$=await YDw(HDw(XDw(),"brain-deck-carousel-"));try{let Y=await jH({outputDir:$,mediaPath:`/_media/carousel/${Q.id}`,template:hi1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:B},themeCSS:this.context.themeCSS}),D=await MH({rootDir:$});try{return{type:"document",data:await this.renderPdf(D.urlFor(Y.urlPath),{maxBytes:WDw,timeoutMs:fDw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${KDw(Q)}-carousel.pdf`}}finally{await D.close()}}finally{await DDw($,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name;return Q.length>0?Q:void 0}}function ZDw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=typeof w.title==="string"?w.title:A.metadata.title,Y=typeof w.event==="string"&&w.event.length>0?w.event:void 0,D=B.split(/^---$/gm).map((X)=>X.trim()).filter((X)=>X.length>0).map((X)=>({markdown:X}));return{title:$,slides:D,...Q.brandLabel?{brandLabel:Q.brandLabel}:{},...Y?{eyebrow:Y}:{}}}function KDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();import{jsxDEV as zDw}from"preact/jsx-dev-runtime";var E40="og-image",UDw="decks:og-image",Ci1=K.object({title:K.string().min(1),description:K.string().optional(),event:K.string().optional(),brandLabel:K.string().optional(),slideCount:K.number().int().positive().optional(),coverImageUrl:K.string().optional()}),yi1={name:UDw,pluginId:"decks",schema:Ci1,renderers:{image:GDw}};function GDw(A){let Q=Ci1.parse(A),w=Q.slideCount?`${Q.slideCount} slide${Q.slideCount===1?"":"s"}`:void 0;return zDw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Deck",title:Q.title,subtitle:Q.description,meta:[Q.event],tag:w},void 0,!1,void 0,this)}Z0();class ap0{context;deps;metadata={outputEntityType:"image",targetField:"ogImageId"};constructor(A,Q={}){this.context=A;this.deps=Q}async resolve(A){if(A.sourceEntityType!=="deck"||A.attachmentType!==E40)return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w,content:B}=lw(Q.content),$=wf.parse(w),Y=qDw(B),D=this.resolveBrandLabel(),X=await this.resolveCoverImageUrl($.coverImageId),H={title:$.title,...$.description?{description:$.description}:{},...$.event?{event:$.event}:{},...Y?{slideCount:Y}:{},...X?{coverImageUrl:X}:{},...D?{brandLabel:D}:{}};return{type:"image",data:await UP({mediaPath:`/_media/og/deck/${Q.id}`,template:yi1,content:H,title:H.title,themeMode:"dark",themeCSS:this.context.themeCSS,tmpPrefix:"brain-deck-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${FDw(Q)}-og.png`}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){if(!A)return;let Q=await this.context.entityService.getEntity({entityType:"image",id:A});return Q?.content.startsWith("data:image/")?Q.content:void 0}}function qDw(A){return A.split(/^---$/gm).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).length}function FDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}c0();async function Ei1({entity:A,config:Q}){let w=wE.parse(A),B=v2(w.content,wf),$=B.metadata;return{$type:"ai.rizom.brain.deck",title:$.title,...$.slug&&{slug:$.slug},...$.description&&{description:$.description},body:B.content,format:"text/markdown",...$.author&&{author:$.author},...$.event&&{event:$.event},...$.publishedAt&&{publishedAt:$.publishedAt},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"deck",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function tp0(){return{entityType:"deck",collection:"ai.rizom.brain.deck",lexicon:MB["ai.rizom.brain.deck"],validate:!1,buildRecord:Ei1}}var gi1={name:"@brains/decks",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class ep0 extends kQ{deps;entityType=jr.entityType;schema=jr.schema;adapter=jr;unregisterCarouselAttachmentProvider;unregisterOgImageAttachmentProvider;unregisterAtprotoProjection;constructor(A={}){super("decks",gi1);this.deps=A}createGenerationHandler(A){return new op0(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":cp0,"deck-list":np0,generation:ki1,description:Oi1}}getDataSources(){return[new rp0(this.logger)]}getEntityTypeConfig(){return{weight:1.5}}async onRegister(A){this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.registerCarouselAttachmentProvider(A),this.registerOgImageAttachmentProvider(A),this.registerEvalHandlers(A),this.unregisterAtprotoProjection=U5.getInstance().register(tp0()),this.logger.info("Decks plugin registered")}async onShutdown(){this.unregisterCarouselAttachmentProvider?.(),this.unregisterCarouselAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0,this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}deferPublishRegistration(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"deck",provider:{name:"internal",publish:async()=>({id:"internal"})},config:{executionMode:"provider"}}}),{success:!0}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:w,entityId:B}=Q.payload;if(w!=="deck")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"deck",id:B});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:`Deck not found: ${B}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let Y=new Date().toISOString(),D={...$,metadata:{...$.metadata,status:"published",publishedAt:Y}};await A.entityService.updateEntity({entity:{...D,content:this.adapter.toMarkdown(D)}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:w,entityId:B,result:{id:B}}})}catch($){await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:vA($)}})}return{success:!0}})}registerCarouselAttachmentProvider(A){let Q={...this.deps,getThemeMode:this.deps.getThemeMode??(async()=>{try{return(await qr(A.entityService)).themeMode??"dark"}catch{return"dark"}})};this.unregisterCarouselAttachmentProvider=A.attachments.register("deck",xi1,new sp0(A,Q))}registerOgImageAttachmentProvider(A){this.unregisterOgImageAttachmentProvider=A.attachments.register("deck",E40,new ap0(A))}registerEvalHandlers(A){A.eval.registerHandler("generateDeck",async(Q)=>{let w=K.object({prompt:K.string(),event:K.string().optional()}).parse(Q);return A.ai.generate({prompt:`${w.prompt}${w.event?`
6290
+ `}},void 0,!1,void 0,this),$.map((W,f)=>_4("section",{className:`deck-carousel-slide${f===0?" is-cover":""}`,children:[_4("header",{className:"deck-carousel-header",children:_4("span",{className:"deck-carousel-wordmark","aria-label":w??Q,children:[_4("span",{className:"wm-primary",children:Y.primary},void 0,!1,void 0,this),Y.secondary!==void 0&&_4($Dw,{children:[_4("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),_4("span",{className:"wm-secondary",children:Y.secondary},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_4("div",{className:"deck-carousel-body",children:_4("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:H(W.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),_4("footer",{className:"deck-carousel-footer",children:[_4("span",{className:"deck-carousel-footer-meta",children:B??Q},void 0,!1,void 0,this),_4("span",{className:"deck-carousel-counter","aria-label":`Slide ${f+1} of ${D}`,children:[_4("span",{className:"deck-carousel-counter-current",children:String(f+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",_4("span",{children:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},f,!0,void 0,this))]},void 0,!0,void 0,this)}import{mkdtemp as YDw,rm as DDw}from"fs/promises";import{tmpdir as XDw}from"os";import{join as HDw}from"path";Z0();var WDw=26214400,fDw=60000,vi1=20;class sp0{context;metadata={outputEntityType:"document"};renderPdf;getThemeMode;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK,this.getThemeMode=Q.getThemeMode??(async()=>"dark")}async resolve(A){if(A.sourceEntityType!=="deck")return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let w=ZDw(Q,{brandLabel:this.resolveBrandLabel()});if(w.slides.length>vi1)throw Error(`Refusing to render carousel with ${w.slides.length} slides; maxSlides=${vi1}`);let B=await this.getThemeMode(),$=await YDw(HDw(XDw(),"brain-deck-carousel-"));try{let Y=await jH({outputDir:$,mediaPath:`/_media/carousel/${Q.id}`,template:hi1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:B},themeCSS:this.context.themeCSS}),D=await MH({rootDir:$});try{return{type:"document",data:await this.renderPdf(D.urlFor(Y.urlPath),{maxBytes:WDw,timeoutMs:fDw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${KDw(Q)}-carousel.pdf`}}finally{await D.close()}}finally{await DDw($,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name;return Q.length>0?Q:void 0}}function ZDw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=typeof w.title==="string"?w.title:A.metadata.title,Y=typeof w.event==="string"&&w.event.length>0?w.event:void 0,D=B.split(/^---$/gm).map((X)=>X.trim()).filter((X)=>X.length>0).map((X)=>({markdown:X}));return{title:$,slides:D,...Q.brandLabel?{brandLabel:Q.brandLabel}:{},...Y?{eyebrow:Y}:{}}}function KDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();import{jsxDEV as zDw}from"preact/jsx-dev-runtime";var E40="og-image",UDw="decks:og-image",Ci1=K.object({title:K.string().min(1),description:K.string().optional(),event:K.string().optional(),brandLabel:K.string().optional(),slideCount:K.number().int().positive().optional(),coverImageUrl:K.string().optional()}),yi1={name:UDw,pluginId:"decks",schema:Ci1,renderers:{image:GDw}};function GDw(A){let Q=Ci1.parse(A),w=Q.slideCount?`${Q.slideCount} slide${Q.slideCount===1?"":"s"}`:void 0;return zDw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Deck",title:Q.title,subtitle:Q.description,meta:[Q.event],tag:w},void 0,!1,void 0,this)}Z0();class ap0{context;deps;metadata={outputEntityType:"image",targetField:"ogImageId"};constructor(A,Q={}){this.context=A;this.deps=Q}async resolve(A){if(A.sourceEntityType!=="deck"||A.attachmentType!==E40)return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w,content:B}=lw(Q.content),$=wf.parse(w),Y=qDw(B),D=this.resolveBrandLabel(),X=await this.resolveCoverImageUrl($.coverImageId),H={title:$.title,...$.description?{description:$.description}:{},...$.event?{event:$.event}:{},...Y?{slideCount:Y}:{},...X?{coverImageUrl:X}:{},...D?{brandLabel:D}:{}};return{type:"image",data:await UP({mediaPath:`/_media/og/deck/${Q.id}`,template:yi1,content:H,title:H.title,themeMode:"dark",themeCSS:this.context.themeCSS,tmpPrefix:"brain-deck-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${FDw(Q)}-og.png`}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){if(!A)return;let Q=await this.context.entityService.getEntity({entityType:"image",id:A});return Q?.content.startsWith("data:image/")?Q.content:void 0}}function qDw(A){return A.split(/^---$/gm).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).length}function FDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}c0();async function Ei1({entity:A,config:Q}){let w=wE.parse(A),B=v2(w.content,wf),$=B.metadata;return{$type:"ai.rizom.brain.deck",title:$.title,...$.slug&&{slug:$.slug},...$.description&&{description:$.description},body:B.content,format:"text/markdown",...$.author&&{author:$.author},...$.event&&{event:$.event},...$.publishedAt&&{publishedAt:$.publishedAt},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"deck",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function tp0(){return{entityType:"deck",collection:"ai.rizom.brain.deck",lexicon:MB["ai.rizom.brain.deck"],validate:!1,buildRecord:Ei1}}var gi1={name:"@brains/decks",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class ep0 extends kQ{deps;entityType=jr.entityType;schema=jr.schema;adapter=jr;unregisterCarouselAttachmentProvider;unregisterOgImageAttachmentProvider;unregisterAtprotoProjection;constructor(A={}){super("decks",gi1);this.deps=A}createGenerationHandler(A){return new op0(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":cp0,"deck-list":np0,generation:ki1,description:Oi1}}getDataSources(){return[new rp0(this.logger)]}getEntityTypeConfig(){return{weight:1.5}}async onRegister(A){this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.registerCarouselAttachmentProvider(A),this.registerOgImageAttachmentProvider(A),this.registerEvalHandlers(A),this.unregisterAtprotoProjection=U5.getInstance().register(tp0()),this.logger.info("Decks plugin registered")}async onShutdown(){this.unregisterCarouselAttachmentProvider?.(),this.unregisterCarouselAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0,this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}deferPublishRegistration(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"deck",provider:{name:"internal",publish:async()=>({id:"internal"})},config:{executionMode:"provider"}}}),{success:!0}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:w,entityId:B}=Q.payload;if(w!=="deck")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"deck",id:B});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:`Deck not found: ${B}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let Y=new Date().toISOString(),D={...$,metadata:{...$.metadata,status:"published",publishedAt:Y}};await A.entityService.updateEntity({entity:{...D,content:this.adapter.toMarkdown(D)}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:w,entityId:B,result:{id:B}}})}catch($){await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:vA($)}})}return{success:!0}})}registerCarouselAttachmentProvider(A){let Q={...this.deps,getThemeMode:this.deps.getThemeMode??(async()=>{try{return(await qr(A.entityService)).themeMode??"dark"}catch{return"dark"}})};this.unregisterCarouselAttachmentProvider=A.attachments.register("deck",xi1,new sp0(A,Q))}registerOgImageAttachmentProvider(A){this.unregisterOgImageAttachmentProvider=A.attachments.register("deck",E40,new ap0(A))}registerEvalHandlers(A){A.eval.registerHandler("generateDeck",async(Q)=>{let w=K.object({prompt:K.string(),event:K.string().optional()}).parse(Q);return A.ai.generate({prompt:`${w.prompt}${w.event?`
6291
6291
 
6292
6292
  Note: This presentation is for "${w.event}".`:""}`,templateName:"decks:generation"})}),A.eval.registerHandler("generateDescription",async(Q)=>{let w=K.object({title:K.string(),content:K.string()}).parse(Q);return A.ai.generate({prompt:`Title: ${w.title}
6293
6293
 
6294
6294
  Content:
6295
6295
  ${w.content}`,templateName:"decks:description"})})}}function _r(){return new ep0}c0();Z0();Z0();aB();var Ai0=K.literal("application/pdf"),Ti1=K.enum(["pending","draft","failed"]),Qi0=K.object({title:K.string().optional(),mimeType:Ai0,filename:K.string().min(1),pageCount:K.number().int().min(0).optional(),status:Ti1.optional(),processingJobId:K.string().optional(),processingError:K.string().optional(),sourceEntityType:K.string().min(1).optional(),sourceEntityId:K.string().min(1).optional(),sourceUploadId:K.string().optional(),sourceFilename:K.string().optional(),sourceMediaType:K.string().optional(),attachmentType:K.string().min(1).optional(),dedupKey:K.string().min(1).optional()}),BE=o1.extend({entityType:K.literal("document"),content:K.string().regex(/^data:application\/pdf;base64,.+$/),metadata:Qi0});function Pr(A){let Q=A.match(/^data:(application\/pdf);base64,(.+)$/i);if(!Q?.[1]||!Q[2])throw Error("Invalid PDF document data URL");return{mimeType:"application/pdf",base64:Q[2]}}function g40(A){return`data:application/pdf;base64,${Buffer.from(A).toString("base64")}`}function wi0(A){let Q=Buffer.from(A).toString("latin1"),w=0,B=/\/Type\s*\/Pages\b[^]*?\/Count\s+(\d+)|\/Count\s+(\d+)[^]*?\/Type\s*\/Pages\b/g;for(let Y of Q.matchAll(B)){let D=parseInt(Y[1]??Y[2]??"0",10);if(D>w)w=D}if(w>0)return w;return Q.match(/\/Type\s*\/Page(?!\w)/g)?.length??0}class T40{entityType="document";purpose="A durable rendered file artifact such as a printable or carousel PDF.";schema=BE;toMarkdown(A){return A.content}fromMarkdown(A){return Pr(A),{entityType:"document",content:A}}extractMetadata(A){return A.metadata}parseFrontMatter(A,Q){return Q.parse({})}generateFrontMatter(A){return""}getBodyTemplate(){return""}createDocumentEntity(A){let{dataUrl:Q,...w}=A,{mimeType:B}=Pr(Q);return{entityType:"document",content:Q,metadata:{mimeType:B,...w}}}}var KF=new T40;async function mi0(A,Q={}){let w=Q.maxBytes??5000000;if(A.byteLength>w)throw Error(`Uploaded PDF is too large for synchronous markdown extraction (${A.byteLength} bytes; max ${w} bytes)`);let $=await(await Promise.resolve().then(() => (nn1(),dn1))).getDocument({data:new Uint8Array(A),disableFontFace:!1,useSystemFonts:!0,useWorkerFetch:!1}).promise;try{let Y=Q.maxPages??50;if($.numPages>Y)throw Error(`Uploaded PDF has ${$.numPages} pages; maximum supported for synchronous markdown extraction is ${Y}`);let D=[];for(let H=1;H<=$.numPages;H+=1){let Z=(await(await $.getPage(H)).getTextContent()).items.flatMap((G)=>("str"in G)?[G.str]:[]).join(" ").replace(/\s+/g," ").trim();if(Z.length>0)D.push(Z)}let X=D.join(`
6296
6296
 
6297
- `).trim();if(!X)throw Error("Could not extract text from the uploaded PDF");return X}finally{await $.destroy()}}c0();Z0();import{createHash as QXw}from"crypto";var wXw=26214400,BXw=20,$Xw=60000,rn1=80,YXw=10,ui0=K.object({renderUrl:K.string().url().optional(),sourceEntityType:K.string().min(1),sourceEntityId:K.string().min(1),attachmentType:K.string().min(1),documentId:K.string().min(1).optional(),title:K.string().min(1).optional(),filename:K.string().min(1).optional(),dedupKey:K.string().min(1).optional(),replace:K.boolean().optional(),pageCount:K.number().int().min(0).optional(),maxPageCount:K.number().int().positive().optional(),maxBytes:K.number().int().positive().optional(),timeoutMs:K.number().int().positive().optional(),width:K.union([K.string(),K.number()]).optional(),height:K.union([K.string(),K.number()]).optional(),format:K.string().optional(),targetEntityType:K.string().min(1).optional(),targetEntityId:K.string().min(1).optional()}),er=ui0.refine((A)=>A.targetEntityType===void 0&&A.targetEntityId===void 0||A.targetEntityType!==void 0&&A.targetEntityId!==void 0,{message:"targetEntityType and targetEntityId must be provided together",path:["targetEntityId"]});class MY0 extends _w{context;renderPdf;constructor(A,Q,w={}){super(A,{schema:er,jobTypeName:"document-generate"});this.context=Q;this.renderPdf=w.renderPdf??VK}async getDedupKey(A){if(A.dedupKey!==void 0)return A.dedupKey;if(A.renderUrl!==void 0)return`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl}`;let Q=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:resolved-attachment`,w=await this.context.entityService.getEntity({entityType:A.sourceEntityType,id:A.sourceEntityId});return w?`${Q}:${w.contentHash}`:Q}async process(A,Q,w){this.logger.debug("Starting document generation job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});let B=A.maxPageCount??BXw,$=A.maxBytes??wXw,Y=A.timeoutMs??$Xw;if(A.pageCount!==void 0&&A.pageCount>B)throw Error(`Refusing to render ${A.pageCount} page PDF; maxPageCount=${B}`);let D=await this.getDedupKey(A),X=_Y0(A,D),H=A.documentId!==void 0||A.filename!==void 0;if(A.replace!==!0){let W=await this.findDocumentByDedupKey(D,H?X:void 0);if(W&&(!H||W.id===X)){if(A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,W.id,A);return await this.reportProgress(w,{progress:100,message:"Reusing existing generated document"}),{success:!0,documentId:W.id,reused:!0}}}await this.reportProgress(w,{progress:20,message:"Rendering PDF document"});try{let W=await this.resolveDocumentAttachment(A,X,{timeoutMs:Y,maxBytes:$}),f=W.data;if(f.byteLength>$)throw Error(`Rendered PDF exceeds maxBytes=${$}: ${f.byteLength} bytes`);let Z=wi0(f);if(Z>B)throw Error(`Rendered PDF has ${Z} pages, exceeding maxPageCount=${B}`);let G=Z>0?Z:A.pageCount;await this.reportProgress(w,{progress:70,message:"Storing PDF document"});let F=A.filename??(A.renderUrl===void 0?W.filename:`${X}.pdf`),V=KF.createDocumentEntity({dataUrl:g40(f),filename:F,...A.title&&{title:A.title},...G!==void 0&&{pageCount:G},status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,dedupKey:D});if(await LX({entityService:this.context.entityService,entity:{...V,id:X}}),A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,X,A);return await this.reportProgress(w,{progress:100,message:"PDF document generation complete"}),{success:!0,documentId:X,reused:!1}}catch(W){let f=vA(W);throw this.logger.error("Document generation failed",{jobId:Q,error:f}),await UU({entityService:this.context.entityService,entityType:"document",id:X,error:f}),W}}async resolveDocumentAttachment(A,Q,w){if(A.renderUrl!==void 0)return{type:"document",data:await this.renderPdf(A.renderUrl,{timeoutMs:w.timeoutMs,maxBytes:w.maxBytes,printBackground:!0,preferCSSPageSize:!0,...A.width!==void 0&&{width:A.width},...A.height!==void 0&&{height:A.height},...A.format!==void 0&&{format:A.format}}),mimeType:"application/pdf",filename:A.filename??`${Q}.pdf`};let B=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!B)throw Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`);if(B.type!=="document")throw Error(`Attachment provider returned ${B.type}; expected document`);return B}async findDocumentByDedupKey(A,Q){let w=await this.context.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}});if(w.length>1)this.logger.warn("Multiple documents share dedupKey; using first",{dedupKey:A,count:w.length,ids:w.map(($)=>$.id),preferredDocumentId:Q});let B=w.filter(($)=>$.metadata.status!=="pending"&&$.metadata.status!=="failed");return B.find(($)=>$.id===Q)??B[0]}async attachDocumentToTarget(A,Q,w,B){let $=await this.context.entityService.getEntity({entityType:A,id:Q});if(!$)throw Error(`Target entity not found: ${A}/${Q}`);let{frontmatter:Y}=lw($.content),D=Array.isArray(Y.documents)?Y.documents.filter(XXw):[],X=B.replace?await this.removeReferencesForSameSourceAttachment(D,w,B):D,H=X.some((W)=>W.id===w)?X:[...X,{id:w}];await this.context.entityService.updateEntity({entity:{...$,content:o4($.content,"documents",H)}})}async removeReferencesForSameSourceAttachment(A,Q,w){let B=[];for(let $ of A){if($.id===Q){B.push($);continue}let Y=await this.context.entityService.getEntity({entityType:"document",id:$.id});if(!Y||!HXw(Y,w))B.push($)}return B}}function _Y0(A,Q){let w=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl??"resolved-attachment"}`,B=A.documentId??A.filename?.replace(/\.pdf$/i,"")??Q??w,$=A.replace===!0&&A.documentId===void 0?`${B}-${Date.now()}`:B;return DXw($)}function DXw(A){let Q=w1(A.replace(/[/:]+/g," "))||`document-${on1(A)}`;if(Q.length<=rn1)return Q;let w=`-${on1(A)}`;return`${Q.slice(0,rn1-w.length).replace(/-+$/g,"")}${w}`}function on1(A){return QXw("sha256").update(A).digest("hex").slice(0,YXw)}function XXw(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}function HXw(A,Q){return A.metadata.sourceEntityType===Q.sourceEntityType&&A.metadata.sourceEntityId===Q.sourceEntityId&&A.metadata.attachmentType===Q.attachmentType}var sn1={name:"@brains/document-plugin",private:!0,version:"0.2.0-alpha.135",description:"Document entity type for generated PDFs and publishable document attachments",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};var fXw=`data:application/pdf;base64,${Buffer.from(`%PDF-1.4
6297
+ `).trim();if(!X)throw Error("Could not extract text from the uploaded PDF");return X}finally{await $.destroy()}}c0();Z0();import{createHash as QXw}from"crypto";var wXw=26214400,BXw=20,$Xw=60000,rn1=80,YXw=10,ui0=K.object({renderUrl:K.string().url().optional(),sourceEntityType:K.string().min(1),sourceEntityId:K.string().min(1),attachmentType:K.string().min(1),documentId:K.string().min(1).optional(),title:K.string().min(1).optional(),filename:K.string().min(1).optional(),dedupKey:K.string().min(1).optional(),replace:K.boolean().optional(),pageCount:K.number().int().min(0).optional(),maxPageCount:K.number().int().positive().optional(),maxBytes:K.number().int().positive().optional(),timeoutMs:K.number().int().positive().optional(),width:K.union([K.string(),K.number()]).optional(),height:K.union([K.string(),K.number()]).optional(),format:K.string().optional(),targetEntityType:K.string().min(1).optional(),targetEntityId:K.string().min(1).optional()}),er=ui0.refine((A)=>A.targetEntityType===void 0&&A.targetEntityId===void 0||A.targetEntityType!==void 0&&A.targetEntityId!==void 0,{message:"targetEntityType and targetEntityId must be provided together",path:["targetEntityId"]});class MY0 extends _w{context;renderPdf;constructor(A,Q,w={}){super(A,{schema:er,jobTypeName:"document-generate"});this.context=Q;this.renderPdf=w.renderPdf??VK}async getDedupKey(A){if(A.dedupKey!==void 0)return A.dedupKey;if(A.renderUrl!==void 0)return`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl}`;let Q=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:resolved-attachment`,w=await this.context.entityService.getEntity({entityType:A.sourceEntityType,id:A.sourceEntityId});return w?`${Q}:${w.contentHash}`:Q}async process(A,Q,w){this.logger.debug("Starting document generation job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});let B=A.maxPageCount??BXw,$=A.maxBytes??wXw,Y=A.timeoutMs??$Xw;if(A.pageCount!==void 0&&A.pageCount>B)throw Error(`Refusing to render ${A.pageCount} page PDF; maxPageCount=${B}`);let D=await this.getDedupKey(A),X=_Y0(A,D),H=A.documentId!==void 0||A.filename!==void 0;if(A.replace!==!0){let W=await this.findDocumentByDedupKey(D,H?X:void 0);if(W&&(!H||W.id===X)){if(A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,W.id,A);return await this.reportProgress(w,{progress:100,message:"Reusing existing generated document"}),{success:!0,documentId:W.id,reused:!0}}}await this.reportProgress(w,{progress:20,message:"Rendering PDF document"});try{let W=await this.resolveDocumentAttachment(A,X,{timeoutMs:Y,maxBytes:$}),f=W.data;if(f.byteLength>$)throw Error(`Rendered PDF exceeds maxBytes=${$}: ${f.byteLength} bytes`);let Z=wi0(f);if(Z>B)throw Error(`Rendered PDF has ${Z} pages, exceeding maxPageCount=${B}`);let G=Z>0?Z:A.pageCount;await this.reportProgress(w,{progress:70,message:"Storing PDF document"});let F=A.filename??(A.renderUrl===void 0?W.filename:`${X}.pdf`),V=KF.createDocumentEntity({dataUrl:g40(f),filename:F,...A.title&&{title:A.title},...G!==void 0&&{pageCount:G},status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,dedupKey:D});if(await LX({entityService:this.context.entityService,entity:{...V,id:X}}),A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,X,A);return await this.reportProgress(w,{progress:100,message:"PDF document generation complete"}),{success:!0,documentId:X,reused:!1}}catch(W){let f=vA(W);throw this.logger.error("Document generation failed",{jobId:Q,error:f}),await UU({entityService:this.context.entityService,entityType:"document",id:X,error:f}),W}}async resolveDocumentAttachment(A,Q,w){if(A.renderUrl!==void 0)return{type:"document",data:await this.renderPdf(A.renderUrl,{timeoutMs:w.timeoutMs,maxBytes:w.maxBytes,printBackground:!0,preferCSSPageSize:!0,...A.width!==void 0&&{width:A.width},...A.height!==void 0&&{height:A.height},...A.format!==void 0&&{format:A.format}}),mimeType:"application/pdf",filename:A.filename??`${Q}.pdf`};let B=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!B)throw Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`);if(B.type!=="document")throw Error(`Attachment provider returned ${B.type}; expected document`);return B}async findDocumentByDedupKey(A,Q){let w=await this.context.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}});if(w.length>1)this.logger.warn("Multiple documents share dedupKey; using first",{dedupKey:A,count:w.length,ids:w.map(($)=>$.id),preferredDocumentId:Q});let B=w.filter(($)=>$.metadata.status!=="pending"&&$.metadata.status!=="failed");return B.find(($)=>$.id===Q)??B[0]}async attachDocumentToTarget(A,Q,w,B){let $=await this.context.entityService.getEntity({entityType:A,id:Q});if(!$)throw Error(`Target entity not found: ${A}/${Q}`);let{frontmatter:Y}=lw($.content),D=Array.isArray(Y.documents)?Y.documents.filter(XXw):[],X=B.replace?await this.removeReferencesForSameSourceAttachment(D,w,B):D,H=X.some((W)=>W.id===w)?X:[...X,{id:w}];await this.context.entityService.updateEntity({entity:{...$,content:o4($.content,"documents",H)}})}async removeReferencesForSameSourceAttachment(A,Q,w){let B=[];for(let $ of A){if($.id===Q){B.push($);continue}let Y=await this.context.entityService.getEntity({entityType:"document",id:$.id});if(!Y||!HXw(Y,w))B.push($)}return B}}function _Y0(A,Q){let w=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl??"resolved-attachment"}`,B=A.documentId??A.filename?.replace(/\.pdf$/i,"")??Q??w,$=A.replace===!0&&A.documentId===void 0?`${B}-${Date.now()}`:B;return DXw($)}function DXw(A){let Q=w1(A.replace(/[/:]+/g," "))||`document-${on1(A)}`;if(Q.length<=rn1)return Q;let w=`-${on1(A)}`;return`${Q.slice(0,rn1-w.length).replace(/-+$/g,"")}${w}`}function on1(A){return QXw("sha256").update(A).digest("hex").slice(0,YXw)}function XXw(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}function HXw(A,Q){return A.metadata.sourceEntityType===Q.sourceEntityType&&A.metadata.sourceEntityId===Q.sourceEntityId&&A.metadata.attachmentType===Q.attachmentType}var sn1={name:"@brains/document-plugin",private:!0,version:"0.2.0-alpha.136",description:"Document entity type for generated PDFs and publishable document attachments",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};var fXw=`data:application/pdf;base64,${Buffer.from(`%PDF-1.4
6298
6298
  % Pending document placeholder
6299
6299
  %%EOF
6300
6300
  `).toString("base64")}`,ZXw=K.object({}),ci0={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function KXw(A,Q){let w=A.title?.trim();if(w)return w;return Q.replace(/\.[^.]+$/,"").trim()||Q}function UXw(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function GXw(A){let Q=encodeURIComponent(A.entityId);return{mediaType:"application/pdf",url:`/api/chat/attachments/document?id=${Q}`,downloadUrl:`/api/chat/attachments/document?id=${Q}&download=1`,filename:A.filename,source:{entityType:"document",entityId:A.entityId,attachmentType:"uploaded"}}}class li0 extends IQ{entityType=KF.entityType;schema=BE;adapter=KF;pluginContext;constructor(){super("document",sn1,{},ZXw)}async onRegister(A){this.pluginContext=A,A.entities.register(this.entityType,this.schema,this.adapter,{embeddable:!1}),A.entities.registerCreateInterceptor(this.entityType,(Q)=>this.interceptCreate(Q)),A.entities.registerUploadSaveHandler({entityType:this.entityType,mediaTypes:["application/pdf"],handler:async(Q)=>{let w=await this.promoteUpload({entityType:this.entityType,...Q.title!==void 0?{title:Q.title}:{},from:Q.upload},A);return w.kind==="handled"?w.result:{success:!1,error:"Document upload save was not handled"}}}),A.jobs.registerHandler("generate",new MY0(this.logger.child("DocumentGenerationJobHandler"),A))}async interceptCreate(A){let Q=this.pluginContext;if(A.from?.kind===ci0.refKind){if(!Q)return{kind:"handled",result:{success:!1,error:"Plugin context not initialized"}};return this.promoteUpload(A,Q)}if(!A.from||A.from.kind!=="entity-attachment")return{kind:"continue",input:A};if(!Q)return{kind:"handled",result:{success:!1,error:"Plugin context not initialized"}};let w=er.parse({sourceEntityType:A.from.sourceEntityType,sourceEntityId:A.from.sourceEntityId,attachmentType:A.from.attachmentType,...A.title&&{title:A.title},...A.replace===!0&&{replace:!0},...A.targetEntityType&&{targetEntityType:A.targetEntityType},...A.targetEntityId&&{targetEntityId:A.targetEntityId}}),B=await this.getDedupKey(w,Q),$=w.replace===!0?void 0:await this.findExistingDocument(B,Q),Y=$?.id??_Y0(w,B);if(!$)await this.createPendingDocument(Q,{id:Y,title:w.title??Y,filename:`${Y}.pdf`,sourceEntityType:w.sourceEntityType,sourceEntityId:w.sourceEntityId,attachmentType:w.attachmentType,dedupKey:B});let D=await Q.jobs.enqueue({type:"generate",data:{...w,dedupKey:B,documentId:Y}}),X=`${Y}.pdf`;return{kind:"handled",result:{success:!0,data:{entityId:Y,jobId:D,status:"generating",attachment:{mediaType:"application/pdf",url:`/api/chat/attachments/document?id=${encodeURIComponent(Y)}`,downloadUrl:`/api/chat/attachments/document?id=${encodeURIComponent(Y)}&download=1`,filename:X,source:{entityType:"document",entityId:Y,attachmentType:w.attachmentType}}}}}}async promoteUpload(A,Q){let w=A.from;if(w?.kind!==ci0.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let B;try{B=await Q.uploads.scoped(ci0).read(w.id)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}if(B.record.mediaType!=="application/pdf")return{kind:"handled",result:{success:!1,error:"Only PDF uploads can be promoted to document entities"}};let $=KXw(A,B.record.filename),Y=w1($);if(!Y)return{kind:"handled",result:{success:!1,error:"Could not derive a document id from the uploaded filename. Provide a title."}};let D=new Date().toISOString(),X=KF.createDocumentEntity({dataUrl:UXw(B.record.mediaType,B.content),filename:B.record.filename,title:$,status:"draft",sourceUploadId:w.id,sourceFilename:B.record.filename,sourceMediaType:B.record.mediaType,attachmentType:"uploaded",dedupKey:`upload:${w.kind}:${w.id}`}),H=await Q.entityService.createEntity({entity:{id:Y,...X,created:D,updated:D},options:{deduplicateId:!0}});return{kind:"handled",result:{success:!0,data:{entityId:H.entityId,status:"created",attachment:GXw({entityId:H.entityId,filename:B.record.filename})}}}}async createPendingDocument(A,Q){let w=new Date().toISOString(),B=KF.createDocumentEntity({dataUrl:fXw,filename:Q.filename,title:Q.title,status:"pending",sourceEntityType:Q.sourceEntityType,sourceEntityId:Q.sourceEntityId,attachmentType:Q.attachmentType,dedupKey:Q.dedupKey});await bN({entityService:A.entityService,entity:{id:Q.id,...B,created:w,updated:w}})}async getDedupKey(A,Q){if(A.dedupKey!==void 0)return A.dedupKey;if(A.renderUrl!==void 0)return`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl}`;let w=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:resolved-attachment`,B=await Q.entityService.getEntity({entityType:A.sourceEntityType,id:A.sourceEntityId});return B?`${w}:${B.contentHash}`:w}async findExistingDocument(A,Q){return(await Q.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}}))[0]}async getInstructions(){return"Document entities store durable file artifacts such as PDFs. Uploaded PDFs are raw document files, not decks. Source-derived document artifacts are durable documents backed by registered attachment providers such as carousel or printable. Generate saved PDF artifacts through system_generate with source.kind attachment; preserve raw uploaded PDFs with system_create source.kind upload and transform preserve."}async getTools(){return[]}}function pi0(){return new li0}c0();c0();Z0();Z0();c0();var zXw=K.enum(["generating","failed"]),FF=K.object({title:K.string().optional(),status:zXw.optional(),error:K.string().optional()}),an1=FF.pick({title:!0,status:!0,error:!0}).extend({title:K.string()}),xb=o1.extend({entityType:K.literal("note"),metadata:an1}),qXw=xb.extend({frontmatter:FF,body:K.string()});c0();Z0();class ii0 extends J2{constructor(){super({entityType:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",schema:xb,frontmatterSchema:FF})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,FF);if(w.title)return this.buildMarkdown(Q,w)}catch{}return Q}fromMarkdown(A){let Q=this.parseMarkdownFrontmatter(A),w=Q.title??this.extractH1(A)??"Untitled";return{content:A,entityType:"note",metadata:{title:w,...Q.status&&{status:Q.status},...Q.error&&{error:Q.error}}}}parseNoteFrontmatter(A){return this.parseMarkdownFrontmatter(A.content)}parseMarkdownFrontmatter(A){try{return this.parseFrontMatter(A,FF)}catch{return{}}}buildStub(A){let Q={title:A.title,status:"generating"};return{content:this.buildMarkdown("",Q),metadata:{title:A.title,status:"generating"}}}createNoteContent(A,Q){try{let w=this.parseFrontMatter(Q,K.record(K.unknown()));if(Object.keys(w).length===0)return Q;let B={...w,title:w.title??A},$=this.extractBody(Q);return this.buildMarkdown($,B)}catch{return Q}}extractH1(A){return A.match(/^#\s+(.+)$/m)?.[1]?.trim()??null}}var Rb=new ii0;Z0();var di0=K.object({defaultPrompt:K.string().default("Create a note summarizing key concepts from my knowledge base")});Z0();c0();var tn1=K.object({title:K.string().max(80).describe("A clear, descriptive title for the note (3-8 words)"),body:K.string().describe("Note content in markdown format with clear organization and structure")}),ni0=R1({name:"note:generation",description:"Template for AI to generate notes from prompts",schema:tn1,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create personal knowledge notes for research and reference.
@@ -6312,7 +6312,7 @@ title: ${JSON.stringify(A)}
6312
6312
  ---
6313
6313
 
6314
6314
  ${Q.trim()}
6315
- `}var bXw={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},LXw=K.object({uploadId:K.string().min(1),title:K.string().optional()});class oi0 extends _w{context;constructor(A,Q){super(A,{schema:LXw,jobTypeName:"upload-import"});this.context=Q}async process(A,Q,w){await this.reportProgress(w,{progress:10,message:"Reading uploaded file"});let B=await this.context.uploads.scoped(bXw).read(A.uploadId);await this.reportProgress(w,{progress:35,message:"Extracting markdown from upload"});let $=await wr1({upload:B,...A.title!==void 0?{title:A.title}:{}});await this.reportProgress(w,{progress:80,message:"Saving imported note"});let Y=new Date().toISOString(),D=Rb.fromMarkdown($.content),X=await this.context.entityService.createEntity({entity:{id:$.id,entityType:"note",content:$.content,metadata:{title:$.title,...D.metadata},created:Y,updated:Y},options:{deduplicateId:!0}});return await this.reportProgress(w,{progress:100,message:"Upload imported as markdown note"}),{entityId:X.entityId,status:"created"}}summarizeDataForLog(A){return{uploadId:A.uploadId,hasTitle:A.title!==void 0}}}c0();async function Br1({entity:A,config:Q}){let w=xb.parse(A),B=v2(w.content,FF);return{$type:"ai.rizom.brain.note",title:w.metadata.title,body:B.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"note",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function si0(){return{entityType:"note",collection:"ai.rizom.brain.note",lexicon:MB["ai.rizom.brain.note"],validate:!1,buildRecord:Br1}}var $r1={name:"@brains/note",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var Yr1={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};class ai0 extends kQ{entityType=Rb.entityType;schema=xb;adapter=Rb;unregisterAtprotoProjection;constructor(A={}){super("note",$r1,A,di0)}async interceptCreate(A,Q,w){if(A.from?.kind!==Yr1.refKind)return{kind:"continue",input:A};if(A.transform!=="extract-markdown")return{kind:"handled",result:{success:!1,error:'Importing an upload as a note requires transform: "extract-markdown"'}};let B=A.from.id,$;try{$=await w.uploads.scoped(Yr1).readRecord(B)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}try{if(!Qr1($.mediaType))return{kind:"handled",result:{success:!1,error:"Only text, JSON, and PDF uploads can be imported as markdown notes"}};let Y=ri0({filename:$.filename,...A.title!==void 0?{title:A.title}:{}}),D=await w.jobs.enqueue({type:"upload-import",data:{uploadId:B,...A.title!==void 0?{title:A.title}:{}}});return{kind:"handled",result:{success:!0,data:{entityId:Y.id,status:"generating",jobId:D}}}}catch(Y){return{kind:"handled",result:{success:!1,error:Y instanceof Error?Y.message:"Failed to import upload as markdown"}}}}createGenerationHandler(A){return new PY0(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:ni0}}async onRegister(A){A.jobs.registerHandler("upload-import",new oi0(this.logger.child("UploadMarkdownImportJobHandler"),A)),A.eval.registerHandler("generateNote",async(Q)=>{let w=K.object({prompt:K.string()}).parse(Q);return A.ai.generate({prompt:w.prompt,templateName:"note:generation"})}),this.unregisterAtprotoProjection=U5.getInstance().register(si0())}async getInstructions(){return"Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes."}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}}function LP(A={}){return new ai0(A)}c0();Z0();Z0();c0();var Dr1=K.object({ref:K.string(),label:K.string()}),Xr1=K.enum(["pending","draft","published"]),VF=K.object({status:Xr1,title:K.string(),url:K.string().url(),description:K.string().optional(),domain:K.string(),capturedAt:K.string().datetime(),source:Dr1}),Hr1=VF.pick({title:!0,status:!0}),NP=o1.extend({entityType:K.literal("link"),metadata:Hr1}),ti0=K.object({enableSummarization:K.boolean().default(!0).describe("Generate AI summaries for captured links"),jinaApiKey:K.string().optional().describe("Jina Reader API key for higher rate limits (500 RPM vs 20 RPM without key)")});c0();class hb extends J2{constructor(){super({entityType:"link",purpose:"A saved external URL or web resource captured for later reference.",schema:NP,frontmatterSchema:VF})}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},w=A.summary??"";return this.buildMarkdown(w,Q)}parseLinkContent(A){return{frontmatter:this.parseFrontMatter(A,VF),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 FE=new hb;c0();Z0();var jXw=K.object({success:K.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:K.string().describe("If success is false, explain why content could not be extracted. Use an empty string when success is true."),title:K.string().max(80).describe("The page title - extract from the content or create a descriptive one. Leave empty string if success is false."),description:K.string().describe("A one-sentence description of what the page is about. Leave empty string if success is false."),summary:K.string().describe("A 1-2 paragraph summary of the main content. Leave empty string if success is false.")}),Wr1=R1({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:jXw,basePrompt:`You are an expert at extracting key information from webpage content.
6315
+ `}var bXw={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},LXw=K.object({uploadId:K.string().min(1),title:K.string().optional()});class oi0 extends _w{context;constructor(A,Q){super(A,{schema:LXw,jobTypeName:"upload-import"});this.context=Q}async process(A,Q,w){await this.reportProgress(w,{progress:10,message:"Reading uploaded file"});let B=await this.context.uploads.scoped(bXw).read(A.uploadId);await this.reportProgress(w,{progress:35,message:"Extracting markdown from upload"});let $=await wr1({upload:B,...A.title!==void 0?{title:A.title}:{}});await this.reportProgress(w,{progress:80,message:"Saving imported note"});let Y=new Date().toISOString(),D=Rb.fromMarkdown($.content),X=await this.context.entityService.createEntity({entity:{id:$.id,entityType:"note",content:$.content,metadata:{title:$.title,...D.metadata},created:Y,updated:Y},options:{deduplicateId:!0}});return await this.reportProgress(w,{progress:100,message:"Upload imported as markdown note"}),{entityId:X.entityId,status:"created"}}summarizeDataForLog(A){return{uploadId:A.uploadId,hasTitle:A.title!==void 0}}}c0();async function Br1({entity:A,config:Q}){let w=xb.parse(A),B=v2(w.content,FF);return{$type:"ai.rizom.brain.note",title:w.metadata.title,body:B.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"note",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function si0(){return{entityType:"note",collection:"ai.rizom.brain.note",lexicon:MB["ai.rizom.brain.note"],validate:!1,buildRecord:Br1}}var $r1={name:"@brains/note",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var Yr1={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};class ai0 extends kQ{entityType=Rb.entityType;schema=xb;adapter=Rb;unregisterAtprotoProjection;constructor(A={}){super("note",$r1,A,di0)}async interceptCreate(A,Q,w){if(A.from?.kind!==Yr1.refKind)return{kind:"continue",input:A};if(A.transform!=="extract-markdown")return{kind:"handled",result:{success:!1,error:'Importing an upload as a note requires transform: "extract-markdown"'}};let B=A.from.id,$;try{$=await w.uploads.scoped(Yr1).readRecord(B)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}try{if(!Qr1($.mediaType))return{kind:"handled",result:{success:!1,error:"Only text, JSON, and PDF uploads can be imported as markdown notes"}};let Y=ri0({filename:$.filename,...A.title!==void 0?{title:A.title}:{}}),D=await w.jobs.enqueue({type:"upload-import",data:{uploadId:B,...A.title!==void 0?{title:A.title}:{}}});return{kind:"handled",result:{success:!0,data:{entityId:Y.id,status:"generating",jobId:D}}}}catch(Y){return{kind:"handled",result:{success:!1,error:Y instanceof Error?Y.message:"Failed to import upload as markdown"}}}}createGenerationHandler(A){return new PY0(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:ni0}}async onRegister(A){A.jobs.registerHandler("upload-import",new oi0(this.logger.child("UploadMarkdownImportJobHandler"),A)),A.eval.registerHandler("generateNote",async(Q)=>{let w=K.object({prompt:K.string()}).parse(Q);return A.ai.generate({prompt:w.prompt,templateName:"note:generation"})}),this.unregisterAtprotoProjection=U5.getInstance().register(si0())}async getInstructions(){return"Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes."}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}}function LP(A={}){return new ai0(A)}c0();Z0();Z0();c0();var Dr1=K.object({ref:K.string(),label:K.string()}),Xr1=K.enum(["pending","draft","published"]),VF=K.object({status:Xr1,title:K.string(),url:K.string().url(),description:K.string().optional(),domain:K.string(),capturedAt:K.string().datetime(),source:Dr1}),Hr1=VF.pick({title:!0,status:!0}),NP=o1.extend({entityType:K.literal("link"),metadata:Hr1}),ti0=K.object({enableSummarization:K.boolean().default(!0).describe("Generate AI summaries for captured links"),jinaApiKey:K.string().optional().describe("Jina Reader API key for higher rate limits (500 RPM vs 20 RPM without key)")});c0();class hb extends J2{constructor(){super({entityType:"link",purpose:"A saved external URL or web resource captured for later reference.",schema:NP,frontmatterSchema:VF})}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},w=A.summary??"";return this.buildMarkdown(w,Q)}parseLinkContent(A){return{frontmatter:this.parseFrontMatter(A,VF),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 FE=new hb;c0();Z0();var jXw=K.object({success:K.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:K.string().describe("If success is false, explain why content could not be extracted. Use an empty string when success is true."),title:K.string().max(80).describe("The page title - extract from the content or create a descriptive one. Leave empty string if success is false."),description:K.string().describe("A one-sentence description of what the page is about. Leave empty string if success is false."),summary:K.string().describe("A 1-2 paragraph summary of the main content. Leave empty string if success is false.")}),Wr1=R1({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:jXw,basePrompt:`You are an expert at extracting key information from webpage content.
6316
6316
 
6317
6317
  You will receive webpage content in markdown format. Your job is to extract structured information from it.
6318
6318
 
@@ -6334,7 +6334,7 @@ Accuracy rules:
6334
6334
 
6335
6335
  `))return{success:!1,error:D.trim(),errorType:"fetch_failed"};return{success:!0,content:D}}catch(w){return this.handleFetchError(w,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 kXw}from"crypto";class vb{static URL_PATTERN=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi;static extractUrls(A){let Q=A.match(vb.URL_PATTERN)??[];return[...new Set(Q)]}static normalizeUrl(A){try{let Q=new URL(A),w=Q.pathname.replace(/\/$/,"")||"/";return`${Q.protocol}//${Q.host}${w}`}catch{return A}}static generateEntityId(A){let Q=this.normalizeUrl(A),w=kXw("sha256").update(Q).digest("hex");try{return`${new URL(Q).hostname.replace(/\./g,"-")}-${w.substring(0,6)}`}catch{return w.substring(0,12)}}static isValidUrl(A){try{let Q=new URL(A);return["http:","https:"].includes(Q.protocol)}catch{return!1}}}c0();Z0();CB();var OXw=K.object({url:K.string().url(),metadata:K.object({interfaceId:K.string().optional(),userId:K.string().optional(),channelId:K.string().optional(),channelName:K.string().optional(),timestamp:K.string().optional()}).optional()}),vn8=K.object({success:K.boolean(),entityId:K.string().optional(),title:K.string().optional(),url:K.string().optional(),status:K.enum(["pending","draft","published"]).optional(),error:K.string().optional()});class OY0 extends _w{context;linkAdapter;urlFetcher;constructor(A,Q,w){super(A,{schema:OXw,jobTypeName:"link-capture"});this.context=Q,this.linkAdapter=new hb,this.urlFetcher=new VE(w?.jinaApiKey?{jinaApiKey:w.jinaApiKey}:void 0)}async process(A,Q,w){let{url:B,metadata:$}=A;try{await w.report({progress:PQ.START,total:100,message:"Starting link capture"});let Y=vb.generateEntityId(B);await w.report({progress:PQ.INIT,total:100,message:"Checking for existing link"});let D=await this.context.entityService.getEntity({entityType:"link",id:Y});if(D){let{frontmatter:F}=this.linkAdapter.parseLinkContent(D.content),V=D.metadata.status;if(V!=="pending")return this.logger.info("Link already captured, returning existing",{url:B,entityId:Y}),{success:!0,entityId:D.id,title:F.title,url:B,status:V};this.logger.info("Pending link exists, completing extraction",{url:B,entityId:Y})}let X=this.resolveSource($),H=new Date().toISOString();await w.report({progress:PQ.FETCH,total:100,message:"Fetching webpage content"});let W=await this.urlFetcher.fetch(B);if(!W.success){if(W.errorType==="url_not_found"||W.errorType==="url_unreachable"){this.logger.warn("Link URL not accessible",{url:B,errorType:W.errorType,error:W.error});let F=new URL(B).hostname,V=`Could not capture link: ${W.error}`,b=this.linkAdapter.createLinkContent({status:"pending",title:F,url:B,description:V,summary:V,domain:F,capturedAt:H,source:X});return await LX({entityService:this.context.entityService,entity:{id:Y,entityType:"link",content:b,metadata:{status:"pending",title:F}}}),{success:!1,entityId:Y,title:F,url:B,status:"pending",error:V}}}await w.report({progress:PQ.PROCESS,total:100,message:"Extracting content with AI"});let f=await this.context.ai.generate({templateName:"link:extraction",prompt:W.success?`Extract structured information from this webpage content:
6336
6336
 
6337
- ${W.content}`:`The URL ${B} could not be fetched. Return success: false with error: "${W.error}"`,data:{url:B,hasContent:W.success},interfacePermissionGrant:"public"});if(this.logger.debug("AI extraction result",{result:f}),await w.report({progress:PQ.EXTRACT,total:100,message:"Processing extraction results"}),f.success===!1||!f.title||!f.description||!f.summary){let F=f.title||new URL(B).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:B}),await w.report({progress:PQ.SAVE,total:100,message:"Saving link as pending"});let V=this.linkAdapter.createLinkContent({status:"pending",title:F,url:B,description:f.description,summary:f.summary,domain:new URL(B).hostname,capturedAt:H,source:X}),b=await LX({entityService:this.context.entityService,entity:{id:Y,entityType:"link",content:V,metadata:{status:"pending",title:F}}});return await w.report({progress:PQ.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:b.entityId,title:F,url:B,status:"pending"}}await w.report({progress:PQ.SAVE,total:100,message:`Saving link: "${f.title}"`});let Z=this.linkAdapter.createLinkContent({status:"draft",title:f.title,url:B,description:f.description,summary:f.summary,domain:new URL(B).hostname,capturedAt:H,source:X}),G=await LX({entityService:this.context.entityService,entity:{id:Y,entityType:"link",content:Z,metadata:{status:"draft",title:f.title}}});return await w.report({progress:PQ.COMPLETE,total:100,message:`Link captured: "${f.title}"`}),{success:!0,entityId:G.entityId,title:f.title,url:B,status:"draft"}}catch(Y){return this.logger.error("Link capture job failed",{error:Y,jobId:Q,data:A}),x6.failure(Y)}}resolveSource(A){let Q=A?.channelId,w=A?.channelName;if(Q)return{ref:`matrix:${Q}`,label:w??Q};let B=A?.interfaceId??"cli";return{ref:`${B}:local`,label:B.toUpperCase()}}summarizeDataForLog(A){return{url:A.url,interfaceId:A.metadata?.interfaceId}}}async function Kr1({entity:A,config:Q}){let w=NP.parse(A),{frontmatter:B,summary:$}=FE.parseLinkContent(w.content);return{$type:"ai.rizom.brain.link",title:B.title,url:B.url,...B.description&&{description:B.description},...$&&{summary:$},domain:B.domain,capturedAt:B.capturedAt,source:B.source,...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"link",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function $d0(){return{entityType:"link",collection:"ai.rizom.brain.link",lexicon:MB["ai.rizom.brain.link"],validate:!1,buildRecord:Kr1}}var Ur1={name:"@brains/link",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Yd0 extends kQ{entityType=FE.entityType;schema=NP;adapter=FE;shell;unregisterAtprotoProjection;constructor(A={}){super("link",Ur1,A,ti0)}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 OY0(this.logger.child("LinkCaptureJobHandler"),this.context,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0),this.id),Q}async interceptCreate(A,Q,w){if(A.content)try{let Y=this.adapter.fromMarkdown(A.content).metadata,D=typeof Y?.title==="string"?Y.title:void 0,X=typeof Y?.status==="string"?Y.status:void 0,H=this.extractFirstUrl(A.content);if(D&&X&&H){let W=w1(H)||w1(D)||`${A.entityType}-${Date.now()}`,f=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await w.entityService.createEntity({entity:{id:W,entityType:A.entityType,content:A.content,metadata:{title:D,status:X},created:f,updated:f}})).entityId,status:"created"}}}}}catch{}let B=A.url??this.extractFirstUrl(A.content,A.prompt,A.title);if(B){if(!this.shell)throw Error("LinkPlugin shell was not initialized during register()");try{let $=await this.createPendingLink(B,A.title,Q,w),Y=await this.shell.getJobQueueService().enqueue({type:"link-capture",data:{url:B,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},options:{source:this.id,metadata:{operationType:"data_processing",pluginId:this.id,interfaceType:Q.interfaceType,...Q.channelId?{channelId:Q.channelId}:{}}}});return{kind:"handled",result:{success:!0,data:{entityId:$,status:"generating",jobId:Y}}}}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 OY0(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:Wr1,"link-list":fr1,"link-detail":Zr1}}getDataSources(){return[new Bd0(this.logger.child("LinksDataSource"))]}async onRegister(A){this.unregisterAtprotoProjection=U5.getInstance().register($d0()),A.eval.registerHandler("extractContent",async(Q)=>{let{url:w}=K.object({url:K.string().url()}).parse(Q),$=await new VE(this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0).fetch(w);if(!$.success)return{success:!1,error:$.error,errorType:$.errorType};return A.ai.generate({templateName:"link:extraction",prompt:`Extract structured information from this webpage content:
6337
+ ${W.content}`:`The URL ${B} could not be fetched. Return success: false with error: "${W.error}"`,data:{url:B,hasContent:W.success},interfacePermissionGrant:"public"});if(this.logger.debug("AI extraction result",{result:f}),await w.report({progress:PQ.EXTRACT,total:100,message:"Processing extraction results"}),f.success===!1||!f.title||!f.description||!f.summary){let F=f.title||new URL(B).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:B}),await w.report({progress:PQ.SAVE,total:100,message:"Saving link as pending"});let V=this.linkAdapter.createLinkContent({status:"pending",title:F,url:B,description:f.description,summary:f.summary,domain:new URL(B).hostname,capturedAt:H,source:X}),b=await LX({entityService:this.context.entityService,entity:{id:Y,entityType:"link",content:V,metadata:{status:"pending",title:F}}});return await w.report({progress:PQ.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:b.entityId,title:F,url:B,status:"pending"}}await w.report({progress:PQ.SAVE,total:100,message:`Saving link: "${f.title}"`});let Z=this.linkAdapter.createLinkContent({status:"draft",title:f.title,url:B,description:f.description,summary:f.summary,domain:new URL(B).hostname,capturedAt:H,source:X}),G=await LX({entityService:this.context.entityService,entity:{id:Y,entityType:"link",content:Z,metadata:{status:"draft",title:f.title}}});return await w.report({progress:PQ.COMPLETE,total:100,message:`Link captured: "${f.title}"`}),{success:!0,entityId:G.entityId,title:f.title,url:B,status:"draft"}}catch(Y){return this.logger.error("Link capture job failed",{error:Y,jobId:Q,data:A}),x6.failure(Y)}}resolveSource(A){let Q=A?.channelId,w=A?.channelName;if(Q)return{ref:`matrix:${Q}`,label:w??Q};let B=A?.interfaceId??"cli";return{ref:`${B}:local`,label:B.toUpperCase()}}summarizeDataForLog(A){return{url:A.url,interfaceId:A.metadata?.interfaceId}}}async function Kr1({entity:A,config:Q}){let w=NP.parse(A),{frontmatter:B,summary:$}=FE.parseLinkContent(w.content);return{$type:"ai.rizom.brain.link",title:B.title,url:B.url,...B.description&&{description:B.description},...$&&{summary:$},domain:B.domain,capturedAt:B.capturedAt,source:B.source,...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"link",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function $d0(){return{entityType:"link",collection:"ai.rizom.brain.link",lexicon:MB["ai.rizom.brain.link"],validate:!1,buildRecord:Kr1}}var Ur1={name:"@brains/link",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Yd0 extends kQ{entityType=FE.entityType;schema=NP;adapter=FE;shell;unregisterAtprotoProjection;constructor(A={}){super("link",Ur1,A,ti0)}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 OY0(this.logger.child("LinkCaptureJobHandler"),this.context,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0),this.id),Q}async interceptCreate(A,Q,w){if(A.content)try{let Y=this.adapter.fromMarkdown(A.content).metadata,D=typeof Y?.title==="string"?Y.title:void 0,X=typeof Y?.status==="string"?Y.status:void 0,H=this.extractFirstUrl(A.content);if(D&&X&&H){let W=w1(H)||w1(D)||`${A.entityType}-${Date.now()}`,f=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await w.entityService.createEntity({entity:{id:W,entityType:A.entityType,content:A.content,metadata:{title:D,status:X},created:f,updated:f}})).entityId,status:"created"}}}}}catch{}let B=A.url??this.extractFirstUrl(A.content,A.prompt,A.title);if(B){if(!this.shell)throw Error("LinkPlugin shell was not initialized during register()");try{let $=await this.createPendingLink(B,A.title,Q,w),Y=await this.shell.getJobQueueService().enqueue({type:"link-capture",data:{url:B,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},options:{source:this.id,metadata:{operationType:"data_processing",pluginId:this.id,interfaceType:Q.interfaceType,...Q.channelId?{channelId:Q.channelId}:{}}}});return{kind:"handled",result:{success:!0,data:{entityId:$,status:"generating",jobId:Y}}}}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 OY0(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:Wr1,"link-list":fr1,"link-detail":Zr1}}getDataSources(){return[new Bd0(this.logger.child("LinksDataSource"))]}async onRegister(A){this.unregisterAtprotoProjection=U5.getInstance().register($d0()),A.eval.registerHandler("extractContent",async(Q)=>{let{url:w}=K.object({url:K.string().url()}).parse(Q),$=await new VE(this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0).fetch(w);if(!$.success)return{success:!1,error:$.error,errorType:$.errorType};return A.ai.generate({templateName:"link:extraction",prompt:`Extract structured information from this webpage content:
6338
6338
 
6339
6339
  ${$.content}`,data:{url:w,hasContent:!0},interfacePermissionGrant:"public"})})}async createPendingLink(A,Q,w,B){let $=vb.generateEntityId(A),Y=new URL(A),D=new Date().toISOString(),X=Q?.trim()?Q.trim():Y.hostname,H=this.adapter.createLinkContent({status:"pending",title:X,url:A,description:"Link capture is in progress.",summary:`Pending link capture for ${A}.`,domain:Y.hostname,capturedAt:D,source:this.resolveSource(w)});return(await bN({entityService:B.entityService,entity:{id:$,entityType:"link",content:H,metadata:{status:"pending",title:X},created:D,updated:D}})).entityId}resolveSource(A){if(A.channelId)return{ref:`matrix:${A.channelId}`,label:A.channelName??A.channelId};return{ref:`${A.interfaceType}:local`,label:A.interfaceType.toUpperCase()}}extractFirstUrl(...A){for(let Q of A){if(!Q)continue;let[w]=vb.extractUrls(Q);if(w)return w}return}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}}function Gr1(A={}){return new Yd0(A)}var jP=Gr1;Z0();var Yr8=K.object({id:K.string().optional(),metadata:K.object({conversationId:K.string().optional(),interfaceId:K.string().optional(),userId:K.string().optional(),messageId:K.string().optional(),timestamp:K.string().optional()}).optional()});c0();Z0();IB();Z0();c0();var zr1=K.enum(["generating","draft","published","failed"]),H9=K.object({title:K.string(),slug:K.string().optional(),status:zr1,publishedAt:K.string().datetime().optional(),description:K.string(),year:K.number(),coverImageId:K.string().optional(),ogImageId:K.string().optional(),url:K.string().url().optional()}),qr1=H9.pick({title:!0,status:!0,publishedAt:!0,year:!0}).extend({slug:K.string(),error:K.string().optional()}),Cb=o1.extend({entityType:K.literal("project"),metadata:qr1}),xY0=K.object({context:K.string(),problem:K.string(),solution:K.string(),outcome:K.string()}),Qo=Cb.extend({frontmatter:H9,body:K.string(),structuredContent:xY0.optional(),coverImageUrl:K.string().optional(),ogImageUrl:K.string().optional()}),JE=Qo.extend({url:K.string().optional(),typeLabel:K.string().optional(),coverImageUrl:K.string().optional(),ogImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()}),RXw=Qo.extend({url:K.string(),typeLabel:K.string(),coverImageUrl:K.string().optional(),ogImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()});c0();Z0();l$();class Dd0 extends pw{constructor(){super(xY0,{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 Xd0=new Dd0;class Hd0 extends J2{constructor(){super({entityType:"project",purpose:"A project record in the user's portfolio.",schema:Cb,frontmatterSchema:H9,supportsCoverImage:!0,bodyFormatter:Xd0})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,H9),B={...w,slug:w.slug??A.metadata.slug};return this.buildMarkdown(Q,B)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,H9),w=Q.slug??w1(Q.title);return{content:A,entityType:"project",metadata:{title:Q.title,slug:w,status:Q.status,publishedAt:Q.publishedAt,year:Q.year}}}parseProjectFrontmatter(A){return this.parseFrontMatter(A.content,H9)}parseStructuredContent(A){return Xd0.parse(this.extractBody(A.content))}createProjectContent(A,Q){let w=Xd0.format(Q);return this.buildMarkdown(w,A)}buildStub(A){let Q=new Date().getUTCFullYear(),w={title:A.title,slug:A.id,status:"generating",description:"",year:Q};return{content:this.buildMarkdown("",w),metadata:{title:A.title,slug:A.id,status:"generating",year:Q}}}}var yb=new Hd0;Z0();var Wd0=K.object({});import{jsxDEV as RH,Fragment as vXw}from"preact/jsx-dev-runtime";var hXw=({project:A})=>{let{frontmatter:Q,url:w,coverImageUrl:B}=A;return RH(uw,{href:w,children:[B&&RH("img",{src:B,alt:Q.title,className:"w-full h-56 object-cover rounded-md mb-4"},void 0,!1,void 0,this),RH(d9,{children:Q.title},void 0,!1,void 0,this),RH("p",{className:"text-theme leading-relaxed",children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},fd0=({projects:A,pageTitle:Q,pagination:w,baseUrl:B="/projects"})=>{let $=Q??"Projects",Y=w?.totalItems??A.length,D=`Browse all ${Y} ${Y===1?"project":"projects"}`;return RH(vXw,{children:[RH(jQ,{title:$,description:D},void 0,!1,void 0,this),RH("div",{className:"project-list bg-theme",children:RH("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[RH("h1",{className:"text-4xl font-bold text-heading mb-12",children:$},void 0,!1,void 0,this),RH("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:A.map((X)=>RH(hXw,{project:X},X.id,!1,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&RH("div",{className:"mt-12",children:RH(o3,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:B},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 zB,Fragment as Fr1}from"preact/jsx-dev-runtime";var CXw=({prevProject:A,nextProject:Q})=>{if(!A&&!Q)return null;return zB("nav",{className:"pt-12 mt-12 border-t border-theme-muted",children:zB("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[A?zB(uw,{href:A.url,variant:"compact",children:[zB("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Previous"},void 0,!1,void 0,this),zB("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):zB("div",{},void 0,!1,void 0,this),Q&&zB(uw,{href:Q.url,variant:"compact",className:"md:text-right",children:[zB("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Next"},void 0,!1,void 0,this),zB("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)},RY0=({title:A,content:Q})=>{if(!Q)return null;return zB("section",{className:"mb-12",children:[zB("h2",{className:"text-2xl font-bold text-heading mb-4",children:A},void 0,!1,void 0,this),zB($9,{markdown:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Zd0=({project:A,prevProject:Q,nextProject:w})=>{let{frontmatter:B,structuredContent:$,metadata:Y,coverImageUrl:D}=A,X=A.ogImageUrl??D;return zB(Fr1,{children:[zB(jQ,{title:B.title,description:B.description,...X?{ogImage:X}:{},ogType:"article"},void 0,!1,void 0,this),zB("article",{className:"project-detail",children:zB("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:zB("div",{className:"max-w-3xl mx-auto",children:[D&&A.coverImageWidth&&A.coverImageHeight&&zB(n3,{src:D,alt:B.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8 shadow-lg"},void 0,!1,void 0,this),zB("h1",{className:"text-4xl md:text-5xl font-bold text-heading leading-tight tracking-tight mb-4",children:B.title},void 0,!1,void 0,this),zB("div",{className:"flex flex-wrap items-center gap-4 text-theme-muted mb-8",children:[zB("span",{className:"text-sm",children:Y.year},void 0,!1,void 0,this),B.url&&zB(Fr1,{children:[zB("span",{className:"text-theme-muted",children:"|"},void 0,!1,void 0,this),zB("a",{href:B.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),zB("p",{className:"text-lg text-theme mb-12 leading-relaxed",children:B.description},void 0,!1,void 0,this),$&&zB("div",{className:"case-study",children:[zB(RY0,{title:"Context",content:$.context},void 0,!1,void 0,this),zB(RY0,{title:"Problem",content:$.problem},void 0,!1,void 0,this),zB(RY0,{title:"Solution",content:$.solution},void 0,!1,void 0,this),zB(RY0,{title:"Outcome",content:$.outcome},void 0,!1,void 0,this)]},void 0,!0,void 0,this),zB(CXw,{prevProject:Q,nextProject:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};Z0();c0();var yXw=K.object({title:K.string().max(80).describe("A clear, compelling project title (3-8 words). Should capture the essence of the project."),description:K.string().describe("A 1-2 sentence summary of the project for portfolio cards. Focus on the core value delivered."),context:K.string().describe("Background information: Who was the client/user? What was the situation? What constraints existed? (2-4 paragraphs)"),problem:K.string().describe("The challenge: What specific problem needed solving? What were the pain points? (2-3 paragraphs)"),solution:K.string().describe("The approach: What was built? What technologies/methods were used? How did it work? (3-5 paragraphs)"),outcome:K.string().describe("The results: What impact did this have? What metrics improved? What was learned? (2-3 paragraphs)")}),Kd0=R1({name:"portfolio:generation",description:"Template for AI to generate portfolio project case studies",schema:yXw,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create a professional portfolio case study based on REAL project information.
6340
6340
 
@@ -6510,7 +6510,7 @@ Use the project request as the primary source of truth. If retrieved knowledge c
6510
6510
  font: 10px/1.45 var(--font-mono, "JetBrains Mono", ui-monospace, monospace);
6511
6511
  }
6512
6512
  .printable-footer a { color: inherit; text-decoration: none; overflow-wrap: anywhere; }
6513
- `}},void 0,!1,void 0,this),W9("section",{className:"project-shell",children:[W9("header",{className:"project-hero",children:[W9("div",{className:"project-index",children:[Q.brandLabel&&W9("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),Q.year&&W9("span",{className:"project-year",children:Q.year},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W9("div",{className:"project-title-panel",children:[W9("span",{className:"printable-kind",children:"Case study dossier"},void 0,!1,void 0,this),W9("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.description&&W9("p",{className:"printable-description",children:Q.description},void 0,!1,void 0,this),W9("div",{className:"printable-meta",children:[Q.year&&W9("span",{children:Q.year},void 0,!1,void 0,this),Q.url&&W9("span",{children:Q.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q.coverImageUrl&&W9("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this),W9($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Q.canonicalUrl||Q.url||Q.brandLabel)&&W9("footer",{className:"printable-footer",children:[W9("span",{children:Q.brandLabel??"Project printable"},void 0,!1,void 0,this),Q.canonicalUrl||Q.url?W9("a",{href:Q.canonicalUrl??Q.url,children:Q.canonicalUrl??Q.url},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var pXw=26214400,iXw=60000;class zd0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==CY0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let w=dXw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await mXw(lXw(cXw(),"brain-project-printable-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/printable/project/${Q.id}`,template:Ir1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:pXw,timeoutMs:iXw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${nXw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await uXw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){let{frontmatter:Q}=lw(A.content),w=H9.parse(Q);if(!w.coverImageId)return;let B=await this.context.entityService.getEntity({entityType:"image",id:w.coverImageId});return B?.content.startsWith("data:image/")?B.content:void 0}}function dXw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=H9.parse(w);return{title:$.title,body:B,...$.description?{description:$.description}:{},year:$.year,...$.publishedAt?{publishedAt:$.publishedAt}:{},...$.url?{url:$.url,canonicalUrl:$.url}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function nXw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();Z0();import{jsxDEV as sXw}from"preact/jsx-dev-runtime";var yY0="og-image",rXw="portfolio:og-image",br1=K.object({title:K.string().min(1),description:K.string().optional(),year:K.number().optional(),brandLabel:K.string().optional(),coverImageUrl:K.string().optional()}),Lr1={name:rXw,pluginId:"portfolio",schema:br1,renderers:{image:oXw}};function oXw(A){let Q=br1.parse(A);return sXw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Project",title:Q.title,subtitle:Q.description,tag:Q.year},void 0,!1,void 0,this)}class qd0{context;deps;metadata={outputEntityType:"image",targetField:"ogImageId"};constructor(A,Q={}){this.context=A;this.deps=Q}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==yY0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w}=lw(Q.content),B=H9.parse(w),$=this.resolveBrandLabel(),Y=await this.resolveCoverImageUrl(B.coverImageId),D={title:B.title,...B.description?{description:B.description}:{},year:B.year,...Y?{coverImageUrl:Y}:{},...$?{brandLabel:$}:{}};return{type:"image",data:await UP({mediaPath:`/_media/og/project/${Q.id}`,template:Lr1,content:D,title:D.title,themeMode:"light",themeCSS:this.context.themeCSS,tmpPrefix:"brain-project-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${aXw(Q)}-og.png`}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){if(!A)return;let Q=await this.context.entityService.getEntity({entityType:"image",id:A});return Q?.content.startsWith("data:image/")?Q.content:void 0}}function aXw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var Nr1={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest",typescript:"^5.3.3"}};var eXw=K.object({projects:K.array(JE),pageTitle:K.string().optional(),pagination:e7.nullable(),baseUrl:K.string().optional()});function AHw(A,Q){for(let w of[A,Q]){let B=w?.match(/\b(19\d{2}|20\d{2})\b/);if(B?.[1])return Number(B[1])}return null}class Fd0 extends kQ{entityType=yb.entityType;schema=Cb;adapter=yb;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("portfolio",Nr1,A,Wd0)}async interceptCreate(A,Q,w){if(!A.prompt||A.content)return{kind:"continue",input:A};let B=AHw(A.title,A.prompt);if(!B)return{kind:"continue",input:A};return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await w.jobs.enqueue({type:"project:generation",data:{prompt:A.prompt,...A.title?{title:A.title}:{},year:B},toolContext:Q,options:{source:this.id,metadata:{operationType:"content_operations"}}})}}}}createGenerationHandler(A){return new hY0(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":R1({name:"project-list",description:"Portfolio project list page template",schema:eXw,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:fd0}}),"project-detail":R1({name:"project-detail",description:"Individual project case study template",schema:K.object({project:JE,prevProject:JE.nullable(),nextProject:JE.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:Zd0}}),generation:Kd0}}getDataSources(){return[new vY0(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("project",CY0,new zd0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("project",yY0,new qd0(A)),this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.unregisterAtprotoProjection=U5.getInstance().register(Gd0())}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0,this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}registerEvalHandlers(A){A.eval.registerHandler("generateProject",async(Q)=>{let w=K.object({prompt:K.string(),year:K.number()}).parse(Q);return A.ai.generate({prompt:Ud0(w),templateName:"portfolio:generation"})})}deferPublishRegistration(A){let Q={name:"internal",publish:async()=>({id:"internal"})};A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"project",provider:Q,config:{executionMode:"provider"}}}),{success:!0}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:w,entityId:B}=Q.payload;if(w!=="project")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"project",id:B});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:`Project not found: ${B}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let Y=v2($.content,H9),D=new Date().toISOString(),X=f7(Y.content,{...Y.metadata,status:"published",publishedAt:D});await A.entityService.updateEntity({entity:{...$,content:X,metadata:{...$.metadata,status:"published",publishedAt:D}}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:w,entityId:B,publishedAt:D}})}catch($){await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:vA($)}})}return{success:!0}})}}function Vd0(A={}){return new Fd0(A)}c0();Z0();var QHw=K.enum(["public","shared","restricted"]),jr1=K.object({includeEntityTypes:K.array(K.string()).default([]),minRelevanceScore:K.number().min(0).max(1).default(0.5),mergeSimilarityThreshold:K.number().min(0).max(1).default(0.85),autoMerge:K.boolean().default(!0),extractableStatuses:K.array(K.string()).default(["published"]),enableAutoExtraction:K.boolean().default(!0),extractionVisibility:QHw.default("public"),sourceChangeBatchDelayMs:K.number().int().min(0).default(1000)});c0();Z0();c0();var wHw=K.object({}),IE=o1.extend({entityType:K.literal("topic"),metadata:wHw}),As8=K.object({content:K.string()}),Mr1=K.object({title:K.string().describe("Topic title")});var MP="topics",qB="topic",Jd0="topics-projection",_r1="topic:project",EY0="topics-plugin",Pr1="topics:batch-completed",kr1="topics-source-batch";class IK extends J2{constructor(){super({entityType:qB,purpose:"A recurring theme or subject derived from the user's content.",schema:IE,frontmatterSchema:Mr1})}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:qB}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseTopicBody(A.content),B=this.buildMarkdown("",this.buildFrontmatter(Q.title)).match(/^---\n[\s\S]*?\n---/);return B?B[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))}}c0();Z0();Z0();var BHw=K.object({title:K.string().max(100),content:K.string(),relevanceScore:K.number().min(0).max(1)}),Or1=K.array(BHw);var $Hw=K.object({topics:Or1}),xr1=R1({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:$Hw,basePrompt:`You are an expert at analyzing content and extracting key topics.
6513
+ `}},void 0,!1,void 0,this),W9("section",{className:"project-shell",children:[W9("header",{className:"project-hero",children:[W9("div",{className:"project-index",children:[Q.brandLabel&&W9("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),Q.year&&W9("span",{className:"project-year",children:Q.year},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W9("div",{className:"project-title-panel",children:[W9("span",{className:"printable-kind",children:"Case study dossier"},void 0,!1,void 0,this),W9("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.description&&W9("p",{className:"printable-description",children:Q.description},void 0,!1,void 0,this),W9("div",{className:"printable-meta",children:[Q.year&&W9("span",{children:Q.year},void 0,!1,void 0,this),Q.url&&W9("span",{children:Q.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Q.coverImageUrl&&W9("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this),W9($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Q.canonicalUrl||Q.url||Q.brandLabel)&&W9("footer",{className:"printable-footer",children:[W9("span",{children:Q.brandLabel??"Project printable"},void 0,!1,void 0,this),Q.canonicalUrl||Q.url?W9("a",{href:Q.canonicalUrl??Q.url,children:Q.canonicalUrl??Q.url},void 0,!1,void 0,this):null]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var pXw=26214400,iXw=60000;class zd0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==CY0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let w=dXw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await mXw(lXw(cXw(),"brain-project-printable-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/printable/project/${Q.id}`,template:Ir1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:pXw,timeoutMs:iXw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${nXw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await uXw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){let{frontmatter:Q}=lw(A.content),w=H9.parse(Q);if(!w.coverImageId)return;let B=await this.context.entityService.getEntity({entityType:"image",id:w.coverImageId});return B?.content.startsWith("data:image/")?B.content:void 0}}function dXw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=H9.parse(w);return{title:$.title,body:B,...$.description?{description:$.description}:{},year:$.year,...$.publishedAt?{publishedAt:$.publishedAt}:{},...$.url?{url:$.url,canonicalUrl:$.url}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function nXw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();Z0();import{jsxDEV as sXw}from"preact/jsx-dev-runtime";var yY0="og-image",rXw="portfolio:og-image",br1=K.object({title:K.string().min(1),description:K.string().optional(),year:K.number().optional(),brandLabel:K.string().optional(),coverImageUrl:K.string().optional()}),Lr1={name:rXw,pluginId:"portfolio",schema:br1,renderers:{image:oXw}};function oXw(A){let Q=br1.parse(A);return sXw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Project",title:Q.title,subtitle:Q.description,tag:Q.year},void 0,!1,void 0,this)}class qd0{context;deps;metadata={outputEntityType:"image",targetField:"ogImageId"};constructor(A,Q={}){this.context=A;this.deps=Q}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==yY0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w}=lw(Q.content),B=H9.parse(w),$=this.resolveBrandLabel(),Y=await this.resolveCoverImageUrl(B.coverImageId),D={title:B.title,...B.description?{description:B.description}:{},year:B.year,...Y?{coverImageUrl:Y}:{},...$?{brandLabel:$}:{}};return{type:"image",data:await UP({mediaPath:`/_media/og/project/${Q.id}`,template:Lr1,content:D,title:D.title,themeMode:"light",themeCSS:this.context.themeCSS,tmpPrefix:"brain-project-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${aXw(Q)}-og.png`}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}async resolveCoverImageUrl(A){if(!A)return;let Q=await this.context.entityService.getEntity({entityType:"image",id:A});return Q?.content.startsWith("data:image/")?Q.content:void 0}}function aXw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var Nr1={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest",typescript:"^5.3.3"}};var eXw=K.object({projects:K.array(JE),pageTitle:K.string().optional(),pagination:e7.nullable(),baseUrl:K.string().optional()});function AHw(A,Q){for(let w of[A,Q]){let B=w?.match(/\b(19\d{2}|20\d{2})\b/);if(B?.[1])return Number(B[1])}return null}class Fd0 extends kQ{entityType=yb.entityType;schema=Cb;adapter=yb;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("portfolio",Nr1,A,Wd0)}async interceptCreate(A,Q,w){if(!A.prompt||A.content)return{kind:"continue",input:A};let B=AHw(A.title,A.prompt);if(!B)return{kind:"continue",input:A};return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await w.jobs.enqueue({type:"project:generation",data:{prompt:A.prompt,...A.title?{title:A.title}:{},year:B},toolContext:Q,options:{source:this.id,metadata:{operationType:"content_operations"}}})}}}}createGenerationHandler(A){return new hY0(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":R1({name:"project-list",description:"Portfolio project list page template",schema:eXw,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:fd0}}),"project-detail":R1({name:"project-detail",description:"Individual project case study template",schema:K.object({project:JE,prevProject:JE.nullable(),nextProject:JE.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:Zd0}}),generation:Kd0}}getDataSources(){return[new vY0(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("project",CY0,new zd0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("project",yY0,new qd0(A)),this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.unregisterAtprotoProjection=U5.getInstance().register(Gd0())}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0,this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}registerEvalHandlers(A){A.eval.registerHandler("generateProject",async(Q)=>{let w=K.object({prompt:K.string(),year:K.number()}).parse(Q);return A.ai.generate({prompt:Ud0(w),templateName:"portfolio:generation"})})}deferPublishRegistration(A){let Q={name:"internal",publish:async()=>({id:"internal"})};A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"project",provider:Q,config:{executionMode:"provider"}}}),{success:!0}})}subscribeToPublishExecute(A){A.messaging.subscribe("publish:execute",async(Q)=>{let{entityType:w,entityId:B}=Q.payload;if(w!=="project")return{success:!0};try{let $=await A.entityService.getEntity({entityType:"project",id:B});if(!$)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:`Project not found: ${B}`}}),{success:!0};if($.metadata.status==="published")return{success:!0};let Y=v2($.content,H9),D=new Date().toISOString(),X=f7(Y.content,{...Y.metadata,status:"published",publishedAt:D});await A.entityService.updateEntity({entity:{...$,content:X,metadata:{...$.metadata,status:"published",publishedAt:D}}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:w,entityId:B,publishedAt:D}})}catch($){await A.messaging.send({type:"publish:report:failure",payload:{entityType:w,entityId:B,error:vA($)}})}return{success:!0}})}}function Vd0(A={}){return new Fd0(A)}c0();Z0();var QHw=K.enum(["public","shared","restricted"]),jr1=K.object({includeEntityTypes:K.array(K.string()).default([]),minRelevanceScore:K.number().min(0).max(1).default(0.5),mergeSimilarityThreshold:K.number().min(0).max(1).default(0.85),autoMerge:K.boolean().default(!0),extractableStatuses:K.array(K.string()).default(["published"]),enableAutoExtraction:K.boolean().default(!0),extractionVisibility:QHw.default("public"),sourceChangeBatchDelayMs:K.number().int().min(0).default(1000)});c0();Z0();c0();var wHw=K.object({}),IE=o1.extend({entityType:K.literal("topic"),metadata:wHw}),As8=K.object({content:K.string()}),Mr1=K.object({title:K.string().describe("Topic title")});var MP="topics",qB="topic",Jd0="topics-projection",_r1="topic:project",EY0="topics-plugin",Pr1="topics:batch-completed",kr1="topics-source-batch";class IK extends J2{constructor(){super({entityType:qB,purpose:"A recurring theme or subject derived from the user's content.",schema:IE,frontmatterSchema:Mr1})}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:qB}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseTopicBody(A.content),B=this.buildMarkdown("",this.buildFrontmatter(Q.title)).match(/^---\n[\s\S]*?\n---/);return B?B[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))}}c0();Z0();Z0();var BHw=K.object({title:K.string().max(100),content:K.string(),relevanceScore:K.number().min(0).max(1)}),Or1=K.array(BHw);var $Hw=K.object({topics:Or1}),xr1=R1({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:$Hw,basePrompt:`You are an expert at analyzing content and extracting key topics.
6514
6514
 
6515
6515
  Analyze the provided content and extract meaningful topics discussed.
6516
6516
 
@@ -6613,13 +6613,13 @@ ${A.incomingTopic.content}`})}}function zHw(A){if(A.length===0)return"";return A
6613
6613
 
6614
6614
  ${Q.content}`}).join(`
6615
6615
 
6616
- `)}async function _P(A,Q,w,B={}){if(A.length===0)return{created:0,merged:0,skipped:0,batches:0};let $=B.minRelevanceScore??0,Y=B.autoMerge??!1,D=B.mergeSimilarityThreshold??0.85,X=B.targetVisibility??"public",H=ur1(A),W=new bK(Q.entityService,w),f=B.topicMergeSynthesizer??new Md0(Q,w),Z=await uY0(Q.entityService,void 0,X),G=new Map,F=0,V=0,b=0;for(let N of H){w.info(`Processing batch of ${N.length} entities`);let _=zHw(N),j=cY0({entityTitle:`Batch of ${N.length} entities`,entityType:"batch",content:_,existingTopicTitles:Z});try{let E=(await Q.ai.generate({prompt:j,templateName:"topics:extraction"})).topics.filter((y)=>y.relevanceScore>=$);for(let y of E)try{if(Y){let S=await W.findMergeCandidate({incoming:y,threshold:D,additionalCandidates:Array.from(G.values()),targetVisibility:X});if(S){let c=await f.synthesize({existingTopic:S.topic,incomingTopic:y}),m=await W.applySynthesizedMerge({existingId:S.topic.id,synthesized:{...c,title:S.title},visibility:X});if(!m)throw Error(`Failed to merge topic: ${y.title}`);G.set(m.id,m),V++;continue}}let h=W.getTopicIdForTitle(y.title,X);if(G.has(h)){b++;continue}let T=await W.createTopicOptimistic({title:y.title,content:y.content,visibility:X});if(T.topic)G.set(T.topic.id,T.topic);if(T.created)F++;else b++}catch(h){w.error("Topic batch item failed",{title:y.title,error:vA(h)})}}catch(g){w.error("Batch topic extraction failed",{batchSize:N.length,promptChars:j.length,error:vA(g)})}}let L={created:F,merged:V,skipped:b,batches:H.length};if(F>0||V>0)await Q.messaging.send({type:Pr1,payload:L,broadcast:!0});return L}c0();Z0();var qHw=K.discriminatedUnion("mode",[K.object({mode:K.literal("derive"),reason:K.string().optional()}),K.object({mode:K.literal("rebuild"),reason:K.string().optional()}),K.object({mode:K.literal("source-batch"),minRelevanceScore:K.number().min(0).max(1).optional()})]);class _d0{refs=new Map;add(A){this.refs.set(`${A.entityType}:${A.entityId}`,A)}drain(){let A=Array.from(this.refs.values());return this.refs.clear(),A}}function nr1(A){let{context:Q,logger:w,config:B}=A;return{process:async($)=>{if($.mode==="derive")return await A.extractAllTopics(),{success:!0};if($.mode==="rebuild")return await A.rebuildAllTopics(),{success:!0};return FHw({context:Q,logger:w,config:B,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:$.minRelevanceScore??B.minRelevanceScore})},validateAndParse:($)=>{let Y=qHw.safeParse($??{});return Y.success?Y.data:null}}}async function FHw(A){let Q=A.sourceBatch.drain(),w=await Promise.all(Q.map(async(W)=>({ref:W,entity:await A.context.entityService.getEntity({entityType:W.entityType,id:W.entityId})}))),B=0,$=0,Y=0,D=0,X=[];for(let{ref:W,entity:f}of w){if(!f){$++;continue}if(f.contentHash!==W.contentHash){B++;continue}if(!A.isEntityPublished(f)){Y++;continue}if(!iV(f.visibility,A.config.extractionVisibility)){D++;continue}X.push(f)}if(X.length===0)return{success:!0,sources:Q.length,created:0,merged:0,skipped:0,batches:0,stale:B,missing:$,unpublished:Y,hidden:D};let H=await _P(X,A.context,A.logger,{minRelevanceScore:A.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});return{success:!0,sources:Q.length,...H,stale:B,missing:$,unpublished:Y,hidden:D}}function rr1(){return{priority:5,source:EY0,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:MP}}}async function or1(A){let Q=await ar1(A);if(Q.length===0){A.logger.info("No entities to extract topics from");return}A.logger.info(`Batch topic extraction: ${Q.length} entities`);let w=await _P(Q,A.context,A.logger,{minRelevanceScore:A.config.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});A.logger.info("Batch topic extraction complete",w)}async function sr1(A){let Q=await ar1(A),w=await Pd0(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",w)}async function Pd0(A,Q,w,B){let $=new bK(Q.entityService,w),Y=await $.listTopics({visibility:B.extractionVisibility});for(let X of Y)await $.deleteTopic(X.id);if(A.length===0)return{deleted:Y.length,created:0,merged:0,skipped:0,batches:0};let D=await _P(A,Q,w,{minRelevanceScore:B.minRelevanceScore,autoMerge:B.autoMerge,mergeSimilarityThreshold:B.mergeSimilarityThreshold,targetVisibility:B.extractionVisibility});return{deleted:Y.length,...D}}async function ar1(A){let Q=VHw(A),w=[];for(let B of Q){let $=await A.context.entityService.listEntities({entityType:B,options:{filter:{visibilityScope:A.config.extractionVisibility}}});for(let Y of $){if(!A.isEntityPublished(Y))continue;w.push(Y)}}return w}function VHw(A){return A.context.entityService.getEntityTypes().filter((w)=>A.shouldProcessEntityType(w))}var NE=K.object({entityType:K.string(),content:K.string(),metadata:K.record(K.unknown()).optional()}),JHw=NE.extend({minRelevanceScore:K.number().optional()}),IHw=K.object({contentA:NE,contentB:NE,minRelevanceScore:K.number().optional(),threshold:K.number().min(0).max(1).optional()}),Yo=K.object({title:K.string(),content:K.string()}),bHw=K.object({existingTopics:K.array(Yo),incomingTopic:Yo,threshold:K.number().optional()}),LHw=K.object({existingTopics:K.array(Yo).default([]),incomingTopic:Yo.extend({relevanceScore:K.number().min(0).max(1).optional()}),threshold:K.number().optional()}),NHw=K.object({entities:K.array(NE).min(1),minRelevanceScore:K.number().optional()}),jHw=K.object({existingTopics:K.array(Yo).optional(),entities:K.array(NE)}),MHw=K.object({entities:K.array(NE)});function LE(A,Q=""){return{id:`eval${Q}-${Date.now()}`,entityType:A.entityType,content:A.content,contentHash:xw(A.content),visibility:"public",metadata:A.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}}function tr1(A){return{title:A.title,relevanceScore:A.relevanceScore}}function _Hw(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function PHw(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:_Hw(Q)}]}}async function PP(A){let Q=await A.entityService.listEntities({entityType:qB});await Promise.all(Q.map((w)=>A.entityService.deleteEntity({entityType:qB,id:w.id})))}async function kHw(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise((w)=>setTimeout(w,100))}}function er1(A){let{context:Q,logger:w,config:B}=A,$=new jd0(Q,w),Y=async(D,X,H="")=>{let W=LE(D,H);return $.extractFromEntity(W,X)};Q.eval.registerHandler("extractFromEntity",async(D)=>{await PP(Q);let X=JHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=LE(X);return(await $.extractFromEntity(W,H)).map((Z)=>PHw(Z,W))}),Q.eval.registerHandler("checkMergeSimilarity",async(D)=>{await PP(Q);let X=IHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=X.threshold??B.mergeSimilarityThreshold,[f,Z]=await Promise.all([Y(X.contentA,H,"-a"),Y(X.contentB,H,"-b")]),G=new bK(Q.entityService,w),F=[];for(let L of f){let N=await G.createTopic(L);if(N)F.push(N)}let V=(await Promise.all(Z.map(async(L)=>{let N=await G.findMergeCandidate({incoming:L,threshold:W,additionalCandidates:F});if(!N)return null;return{incomingTitle:L.title,candidateTitle:N.title,candidateScore:N.score}}))).filter((L)=>L!==null),b=V.map((L)=>L.candidateTitle);return{topicsA:f.map(tr1),topicsB:Z.map(tr1),matchingTitles:b,mergeCandidates:V,wouldMerge:V.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(D)=>{await PP(Q);let X=bHw.parse(D),H=X.threshold??B.mergeSimilarityThreshold,W=new bK(Q.entityService,w),f=[];for(let G of X.existingTopics){let F=await W.createTopic(G);if(F)f.push(F)}let Z=await W.findMergeCandidate({incoming:{title:X.incomingTopic.title},threshold:H,additionalCandidates:f});return{found:Z!==null,candidateTitle:Z?.title,candidateScore:Z?.score}}),Q.eval.registerHandler("processTopicWithAutoMerge",async(D)=>{await PP(Q);let X=LHw.parse(D),H=new bK(Q.entityService,w);for(let G of X.existingTopics)await H.createTopic({title:G.title,content:G.content});await kHw(Q);let W=LE({entityType:"post",content:X.incomingTopic.content,metadata:{title:X.incomingTopic.title}},"-source"),f=await _P([W],Q,w,{minRelevanceScore:0,autoMerge:!0,mergeSimilarityThreshold:X.threshold??B.mergeSimilarityThreshold}),Z=await Q.entityService.listEntities({entityType:qB});return{...f,topicCount:Z.length,topics:Z.map(Ld0)}}),Q.eval.registerHandler("rebuildTopics",async(D)=>{await PP(Q);let X=jHw.parse(D),H=new bK(Q.entityService,w);for(let G of X.existingTopics??[])await H.createTopic(G);let W=X.entities.map((G,F)=>LE(G,`-rebuild-${F}`)),f=await Pd0(W,Q,w,B),Z=await Q.entityService.listEntities({entityType:qB});return{...f,topicCount:Z.length,topics:Z.map(Ld0)}}),Q.eval.registerHandler("extractSequentially",async(D)=>{await PP(Q);let X=NHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=new bK(Q.entityService,w),f=[];for(let[G,F]of X.entities.entries()){let V=LE(F,`-sequential-${G}`),b=await $.extractFromEntity(V,H);for(let L of b)await W.createTopic({title:L.title,content:L.content});f.push({extractedTitles:b.map((L)=>L.title)})}let Z=await Q.entityService.listEntities({entityType:qB});return{totalTopics:Z.length,perEntity:f,topics:Z.map(bE)}}),Q.eval.registerHandler("batchExtract",async(D)=>{await PP(Q);let H=MHw.parse(D).entities.map((Z,G)=>LE(Z,`-batch-${G}`)),W=await _P(H,Q,w,{minRelevanceScore:B.minRelevanceScore}),f=await Q.entityService.listEntities({entityType:qB});return{...W,topics:f.map(bE)}})}var OHw=new IK;async function Ao1({entity:A,config:Q}){let w=IE.parse(A),B=OHw.parseTopicBody(w.content);return{$type:"ai.rizom.brain.topic",title:B.title,body:B.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"topic",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function kd0(){return{entityType:"topic",collection:"ai.rizom.brain.topic",lexicon:MB["ai.rizom.brain.topic"],validate:!1,buildRecord:Ao1}}var Qo1={name:"@brains/topics",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var RHw=new IK;class wo1 extends kQ{entityType=qB;schema=IE;adapter=RHw;unregisterAtprotoProjection;sourceBatch=new _d0;constructor(A={}){super(MP,Qo1,A,jr1)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:xr1,"merge-synthesis":Rr1,"topic-list":hr1,"topic-detail":vr1}}getDataSources(){return[new Nd0(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:Jd0,targetType:qB,job:{type:_r1,handler:nr1({context:A,logger:this.logger,config:this.config,extractAllTopics:()=>this.extractAllTopics(A),rebuildAllTopics:()=>this.rebuildAllTopics(A),sourceBatch:this.sourceBatch,isEntityPublished:(Q)=>this.isEntityPublished(Q)})},initialSync:{shouldEnqueue:async()=>!await IN(A,qB,{visibility:this.config.extractionVisibility}),jobData:{mode:"derive",reason:"initial-sync"},jobOptions:rr1()},sourceChange:{sourceTypes:this.config.includeEntityTypes,requireInitialSync:!0,jobData:(Q)=>{let w=Q.entity;if(!w)return null;if(!this.shouldProcessEntityType(w.entityType,A.entityService))return null;if(!this.isEntityPublished(w))return null;if(!iV(w.visibility,this.config.extractionVisibility))return null;return this.sourceBatch.add({entityId:w.id,entityType:w.entityType,contentHash:w.contentHash}),{mode:"source-batch"}},jobOptions:()=>({priority:5,source:EY0,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:kr1,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:MP}})}}]}async onRegister(A){A.insights.register("topic-distribution",Er1()),gr1({context:A,pluginId:this.id}),er1({context:A,logger:this.logger,config:this.config}),this.unregisterAtprotoProjection=U5.getInstance().register(kd0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(Jd0)?.hasQueuedInitialSync()??!1}shouldProcessEntityType(A,Q){if(A===qB)return!1;if(!this.config.includeEntityTypes.includes(A))return!1;return Q.getEntityTypeConfig(A).projectionSource!==!1}isEntityPublished(A){let w=A.metadata.status;if(w===void 0||w===null)return!0;if(typeof w!=="string")return!1;return this.config.extractableStatuses.includes(w)}async extractAllTopics(A){await or1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await sr1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function lY0(A){return new wo1(A)}c0();Z0();c0();var Od0=K.enum(["linkedin"]),xd0=K.enum(["generating","draft","queued","published","failed"]),Bo1=K.enum(["post","deck"]),$o1=K.object({id:K.string().min(1).describe("Document entity ID")}),Df=K.object({title:K.string().describe("Short descriptive title (3-6 words) for file naming"),platform:Od0.describe("Target platform"),status:xd0,coverImageId:K.string().optional().describe("Image entity ID for post image"),documents:K.array($o1).optional().describe("Document attachments for publishing"),publishedAt:K.string().datetime().optional(),platformPostId:K.string().optional().describe("ID from platform after publishing"),sourceEntityId:K.string().optional().describe("Source entity ID if auto-generated"),sourceEntityType:Bo1.optional().describe("Source entity type (post, deck)")}),Yo1=Df.extend({platform:Od0.optional(),status:xd0.optional()}),Do1=Df.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:K.string().describe("URL-friendly identifier: {platform}-{title}"),error:K.string().optional()}),Eb=o1.extend({entityType:K.literal("social-post"),metadata:Do1}),pY0=Eb.extend({frontmatter:Df,body:K.string()}),iY0=pY0.extend({url:K.string().optional(),listUrl:K.string().optional(),listLabel:K.string().optional(),typeLabel:K.string().optional(),coverImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()});c0();Z0();class Rd0 extends J2{constructor(){super({entityType:"social-post",purpose:"A short post drafted for social media such as LinkedIn or X.",schema:Eb,frontmatterSchema:Df,supportsCoverImage:!0})}toMarkdown(A){let Q="",w={};try{w=this.parseFrontMatter(A.content,Df),Q=this.extractBody(A.content)}catch{Q=A.content}let B={...w,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,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Yo1),w=Q.platform??"linkedin",B=Q.status??"draft",$=`${w}-${w1(Q.title)}`;return{content:A,entityType:"social-post",metadata:{title:Q.title,slug:$,platform:w,status:B,publishedAt:Q.publishedAt,platformPostId:Q.platformPostId}}}parsePostFrontmatter(A){return this.parseFrontMatter(A.content,Df)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}buildStub(A){let w={title:A.title,platform:"linkedin",status:"generating"};return{content:this.buildMarkdown("",w),metadata:{title:A.title,slug:`linkedin-${w1(A.title)}`,platform:"linkedin",status:"generating"}}}}var h7=new Rd0;c0();c0();Z0();var hHw=qU.extend({platform:K.enum(["linkedin"]).optional(),status:K.enum(["generating","draft","queued","published","failed"]).optional(),sortByQueue:K.boolean().optional(),nextInQueue:K.boolean().optional()}),vHw=FU.extend({query:hHw.optional()});function Xo1(A){let Q=v2(A.content,Df);return pY0.parse({...A,frontmatter:Q.metadata,body:Q.content})}class dY0 extends f${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=vHw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return Xo1(A)}buildDetailResult(A,Q){return{post:A}}buildListResult(A,Q,w){return{posts:A,totalCount:Q?.totalItems??A.length,pagination:Q,baseUrl:w.baseUrl}}async fetch(A,Q,w){let{query:B}=this.parseQuery(A),$=w.entityService;if(B.nextInQueue)return this.fetchNextInQueue(Q,$);if(B.id){let{item:f}=await this.fetchDetail(B.id,$);return Q.parse(this.buildDetailResult(f,null))}let Y={};if(B.platform)Y.platform=B.platform;if(B.status)Y.status=B.status;let D=Object.keys(Y).length>0,X=B.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:H,pagination:W}=await this.fetchList(B,$,{...D&&{filter:{metadata:Y}},sortFields:X});return Q.parse(this.buildListResult(H,W,B))}async fetchNextInQueue(A,Q){let B=(await Q.listEntities({entityType:this.config.entityType,options:{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}}))[0],$=B?Xo1(B):null;return A.parse({post:$})}}Z0();var Ho1=K.object({accessToken:K.string().optional(),refreshToken:K.string().optional(),organizationId:K.string().optional(),apiVersion:K.string().regex(/^\d{6}$/).optional()}),hd0=K.object({linkedin:Ho1.optional(),publishInterval:K.number().default(3600000),enabled:K.boolean().default(!0),defaultPrompt:K.string().default("Create an engaging social media post that drives engagement"),maxRetries:K.number().default(3),autoGenerateOnBlogPublish:K.boolean().default(!1)});c0();Z0();CB();Cd0();import{jsxDEV as c5,Fragment as EHw}from"preact/jsx-dev-runtime";function CHw(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function yHw(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var rY0=({posts:A,pageTitle:Q,pagination:w,baseUrl:B="/social-posts"})=>{let $=Q??"Social Posts",Y=w?.totalItems??A.length,D=`Browse all ${Y} social ${Y===1?"post":"posts"}`;return c5(EHw,{children:[c5(jQ,{title:$,description:D},void 0,!1,void 0,this),c5("div",{className:"social-post-list bg-theme",children:c5("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[c5("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:$},void 0,!1,void 0,this),A.length===0?c5("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):c5("ul",{className:"space-y-6",children:A.map((X)=>c5("li",{children:c5(uw,{href:X.url,variant:"horizontal",children:c5("div",{className:"flex flex-col sm:flex-row gap-4",children:[X.coverImageUrl&&c5("img",{src:X.coverImageUrl,alt:X.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),c5("div",{className:"flex-1 min-w-0",children:[c5("div",{className:"flex items-start justify-between gap-4 mb-2",children:[c5("h2",{className:"text-lg font-semibold text-heading",children:X.frontmatter.title},void 0,!1,void 0,this),c5("time",{className:"text-sm text-theme-muted shrink-0",children:yHw(X.frontmatter.publishedAt??X.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c5("div",{className:"flex items-center gap-2 mb-3",children:[c5(vD,{status:X.frontmatter.status},void 0,!1,void 0,this),c5("span",{className:"text-xs text-theme-muted uppercase",children:X.frontmatter.platform},void 0,!1,void 0,this),c5("span",{className:"text-xs text-theme-muted font-mono",children:X.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c5("p",{className:"text-theme leading-relaxed",children:CHw(X.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)},X.id,!1,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&c5(o3,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:B},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 l5,Fragment as gHw}from"preact/jsx-dev-runtime";function Wo1(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var oY0=({post:A})=>{let Q=`Social Post - ${A.frontmatter.platform}`,w=A.body.slice(0,160),B=[{label:"Home",href:"/"},{label:A.listLabel??"Social Posts",href:A.listUrl??"/social-posts"},{label:A.frontmatter.platform}];return l5(gHw,{children:[l5(jQ,{title:Q,description:w},void 0,!1,void 0,this),l5("section",{className:"social-post-detail",children:l5("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:l5("div",{className:"max-w-3xl mx-auto",children:[l5(_G,{items:B},void 0,!1,void 0,this),l5("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),l5("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[l5(vD,{status:A.frontmatter.status},void 0,!1,void 0,this),l5("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),l5("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&&l5(n3,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),l5(uw,{className:"p-8 mb-8",children:l5("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),l5("div",{className:"space-y-4 text-sm text-theme-muted",children:[l5("div",{children:[l5("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",Wo1(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&l5("div",{children:[l5("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",Wo1(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&l5("div",{children:l5("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 Do(A){return`social-media:${A}`}var THw=K.union([K.boolean(),K.object({generate:K.boolean().optional(),prompt:K.string().optional()})]),yd0=K.object({prompt:K.string().optional(),platform:K.enum(["linkedin"]).optional(),sourceEntityType:K.enum(["post","deck"]).optional(),sourceEntityId:K.string().optional(),title:K.string().optional().describe("Required when content is provided directly"),content:K.string().optional(),addToQueue:K.boolean().optional(),generateImage:K.boolean().optional().describe("Auto-generate cover image for post"),coverImage:THw.optional().describe("Generic cover image generation request")}),SHw=UX.extend({slug:K.string().optional()});class kP extends Q4{constructor(A,Q){super(A,Q,{schema:yd0,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let w=A.platform??"linkedin",B=A.addToQueue??!1,{prompt:$,sourceEntityType:Y,sourceEntityId:D}=A,{content:X,title:H}=A;if(X&&H)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(X&&!H){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let L=await this.context.ai.generate({prompt:X,templateName:Do(w)});H=L.title,X=L.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(D&&Y){await this.reportProgress(Q,{progress:10,message:`Fetching source ${Y}`});let L=await this.context.entityService.getEntity({entityType:Y,id:D});if(!L)this.failEarly(`Source entity not found: ${Y}/${D}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let _=K.object({slug:K.string()}).safeParse(L.metadata),j=_.success?_.data.slug:D,g=await this.context.ai.generate({prompt:`Create an engaging ${w} post to promote this ${Y}:
6616
+ `)}async function _P(A,Q,w,B={}){if(A.length===0)return{created:0,merged:0,skipped:0,batches:0};let $=B.minRelevanceScore??0,Y=B.autoMerge??!1,D=B.mergeSimilarityThreshold??0.85,X=B.targetVisibility??"public",H=ur1(A),W=new bK(Q.entityService,w),f=B.topicMergeSynthesizer??new Md0(Q,w),Z=await uY0(Q.entityService,void 0,X),G=new Map,F=0,V=0,b=0;for(let N of H){w.info(`Processing batch of ${N.length} entities`);let _=zHw(N),j=cY0({entityTitle:`Batch of ${N.length} entities`,entityType:"batch",content:_,existingTopicTitles:Z});try{let E=(await Q.ai.generate({prompt:j,templateName:"topics:extraction"})).topics.filter((y)=>y.relevanceScore>=$);for(let y of E)try{if(Y){let S=await W.findMergeCandidate({incoming:y,threshold:D,additionalCandidates:Array.from(G.values()),targetVisibility:X});if(S){let c=await f.synthesize({existingTopic:S.topic,incomingTopic:y}),m=await W.applySynthesizedMerge({existingId:S.topic.id,synthesized:{...c,title:S.title},visibility:X});if(!m)throw Error(`Failed to merge topic: ${y.title}`);G.set(m.id,m),V++;continue}}let h=W.getTopicIdForTitle(y.title,X);if(G.has(h)){b++;continue}let T=await W.createTopicOptimistic({title:y.title,content:y.content,visibility:X});if(T.topic)G.set(T.topic.id,T.topic);if(T.created)F++;else b++}catch(h){w.error("Topic batch item failed",{title:y.title,error:vA(h)})}}catch(g){w.error("Batch topic extraction failed",{batchSize:N.length,promptChars:j.length,error:vA(g)})}}let L={created:F,merged:V,skipped:b,batches:H.length};if(F>0||V>0)await Q.messaging.send({type:Pr1,payload:L,broadcast:!0});return L}c0();Z0();var qHw=K.discriminatedUnion("mode",[K.object({mode:K.literal("derive"),reason:K.string().optional()}),K.object({mode:K.literal("rebuild"),reason:K.string().optional()}),K.object({mode:K.literal("source-batch"),minRelevanceScore:K.number().min(0).max(1).optional()})]);class _d0{refs=new Map;add(A){this.refs.set(`${A.entityType}:${A.entityId}`,A)}drain(){let A=Array.from(this.refs.values());return this.refs.clear(),A}}function nr1(A){let{context:Q,logger:w,config:B}=A;return{process:async($)=>{if($.mode==="derive")return await A.extractAllTopics(),{success:!0};if($.mode==="rebuild")return await A.rebuildAllTopics(),{success:!0};return FHw({context:Q,logger:w,config:B,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:$.minRelevanceScore??B.minRelevanceScore})},validateAndParse:($)=>{let Y=qHw.safeParse($??{});return Y.success?Y.data:null}}}async function FHw(A){let Q=A.sourceBatch.drain(),w=await Promise.all(Q.map(async(W)=>({ref:W,entity:await A.context.entityService.getEntity({entityType:W.entityType,id:W.entityId})}))),B=0,$=0,Y=0,D=0,X=[];for(let{ref:W,entity:f}of w){if(!f){$++;continue}if(f.contentHash!==W.contentHash){B++;continue}if(!A.isEntityPublished(f)){Y++;continue}if(!iV(f.visibility,A.config.extractionVisibility)){D++;continue}X.push(f)}if(X.length===0)return{success:!0,sources:Q.length,created:0,merged:0,skipped:0,batches:0,stale:B,missing:$,unpublished:Y,hidden:D};let H=await _P(X,A.context,A.logger,{minRelevanceScore:A.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});return{success:!0,sources:Q.length,...H,stale:B,missing:$,unpublished:Y,hidden:D}}function rr1(){return{priority:5,source:EY0,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:MP}}}async function or1(A){let Q=await ar1(A);if(Q.length===0){A.logger.info("No entities to extract topics from");return}A.logger.info(`Batch topic extraction: ${Q.length} entities`);let w=await _P(Q,A.context,A.logger,{minRelevanceScore:A.config.minRelevanceScore,autoMerge:A.config.autoMerge,mergeSimilarityThreshold:A.config.mergeSimilarityThreshold,targetVisibility:A.config.extractionVisibility});A.logger.info("Batch topic extraction complete",w)}async function sr1(A){let Q=await ar1(A),w=await Pd0(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",w)}async function Pd0(A,Q,w,B){let $=new bK(Q.entityService,w),Y=await $.listTopics({visibility:B.extractionVisibility});for(let X of Y)await $.deleteTopic(X.id);if(A.length===0)return{deleted:Y.length,created:0,merged:0,skipped:0,batches:0};let D=await _P(A,Q,w,{minRelevanceScore:B.minRelevanceScore,autoMerge:B.autoMerge,mergeSimilarityThreshold:B.mergeSimilarityThreshold,targetVisibility:B.extractionVisibility});return{deleted:Y.length,...D}}async function ar1(A){let Q=VHw(A),w=[];for(let B of Q){let $=await A.context.entityService.listEntities({entityType:B,options:{filter:{visibilityScope:A.config.extractionVisibility}}});for(let Y of $){if(!A.isEntityPublished(Y))continue;w.push(Y)}}return w}function VHw(A){return A.context.entityService.getEntityTypes().filter((w)=>A.shouldProcessEntityType(w))}var NE=K.object({entityType:K.string(),content:K.string(),metadata:K.record(K.unknown()).optional()}),JHw=NE.extend({minRelevanceScore:K.number().optional()}),IHw=K.object({contentA:NE,contentB:NE,minRelevanceScore:K.number().optional(),threshold:K.number().min(0).max(1).optional()}),Yo=K.object({title:K.string(),content:K.string()}),bHw=K.object({existingTopics:K.array(Yo),incomingTopic:Yo,threshold:K.number().optional()}),LHw=K.object({existingTopics:K.array(Yo).default([]),incomingTopic:Yo.extend({relevanceScore:K.number().min(0).max(1).optional()}),threshold:K.number().optional()}),NHw=K.object({entities:K.array(NE).min(1),minRelevanceScore:K.number().optional()}),jHw=K.object({existingTopics:K.array(Yo).optional(),entities:K.array(NE)}),MHw=K.object({entities:K.array(NE)});function LE(A,Q=""){return{id:`eval${Q}-${Date.now()}`,entityType:A.entityType,content:A.content,contentHash:xw(A.content),visibility:"public",metadata:A.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}}function tr1(A){return{title:A.title,relevanceScore:A.relevanceScore}}function _Hw(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function PHw(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:_Hw(Q)}]}}async function PP(A){let Q=await A.entityService.listEntities({entityType:qB});await Promise.all(Q.map((w)=>A.entityService.deleteEntity({entityType:qB,id:w.id})))}async function kHw(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise((w)=>setTimeout(w,100))}}function er1(A){let{context:Q,logger:w,config:B}=A,$=new jd0(Q,w),Y=async(D,X,H="")=>{let W=LE(D,H);return $.extractFromEntity(W,X)};Q.eval.registerHandler("extractFromEntity",async(D)=>{await PP(Q);let X=JHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=LE(X);return(await $.extractFromEntity(W,H)).map((Z)=>PHw(Z,W))}),Q.eval.registerHandler("checkMergeSimilarity",async(D)=>{await PP(Q);let X=IHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=X.threshold??B.mergeSimilarityThreshold,[f,Z]=await Promise.all([Y(X.contentA,H,"-a"),Y(X.contentB,H,"-b")]),G=new bK(Q.entityService,w),F=[];for(let L of f){let N=await G.createTopic(L);if(N)F.push(N)}let V=(await Promise.all(Z.map(async(L)=>{let N=await G.findMergeCandidate({incoming:L,threshold:W,additionalCandidates:F});if(!N)return null;return{incomingTitle:L.title,candidateTitle:N.title,candidateScore:N.score}}))).filter((L)=>L!==null),b=V.map((L)=>L.candidateTitle);return{topicsA:f.map(tr1),topicsB:Z.map(tr1),matchingTitles:b,mergeCandidates:V,wouldMerge:V.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(D)=>{await PP(Q);let X=bHw.parse(D),H=X.threshold??B.mergeSimilarityThreshold,W=new bK(Q.entityService,w),f=[];for(let G of X.existingTopics){let F=await W.createTopic(G);if(F)f.push(F)}let Z=await W.findMergeCandidate({incoming:{title:X.incomingTopic.title},threshold:H,additionalCandidates:f});return{found:Z!==null,candidateTitle:Z?.title,candidateScore:Z?.score}}),Q.eval.registerHandler("processTopicWithAutoMerge",async(D)=>{await PP(Q);let X=LHw.parse(D),H=new bK(Q.entityService,w);for(let G of X.existingTopics)await H.createTopic({title:G.title,content:G.content});await kHw(Q);let W=LE({entityType:"post",content:X.incomingTopic.content,metadata:{title:X.incomingTopic.title}},"-source"),f=await _P([W],Q,w,{minRelevanceScore:0,autoMerge:!0,mergeSimilarityThreshold:X.threshold??B.mergeSimilarityThreshold}),Z=await Q.entityService.listEntities({entityType:qB});return{...f,topicCount:Z.length,topics:Z.map(Ld0)}}),Q.eval.registerHandler("rebuildTopics",async(D)=>{await PP(Q);let X=jHw.parse(D),H=new bK(Q.entityService,w);for(let G of X.existingTopics??[])await H.createTopic(G);let W=X.entities.map((G,F)=>LE(G,`-rebuild-${F}`)),f=await Pd0(W,Q,w,B),Z=await Q.entityService.listEntities({entityType:qB});return{...f,topicCount:Z.length,topics:Z.map(Ld0)}}),Q.eval.registerHandler("extractSequentially",async(D)=>{await PP(Q);let X=NHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=new bK(Q.entityService,w),f=[];for(let[G,F]of X.entities.entries()){let V=LE(F,`-sequential-${G}`),b=await $.extractFromEntity(V,H);for(let L of b)await W.createTopic({title:L.title,content:L.content});f.push({extractedTitles:b.map((L)=>L.title)})}let Z=await Q.entityService.listEntities({entityType:qB});return{totalTopics:Z.length,perEntity:f,topics:Z.map(bE)}}),Q.eval.registerHandler("batchExtract",async(D)=>{await PP(Q);let H=MHw.parse(D).entities.map((Z,G)=>LE(Z,`-batch-${G}`)),W=await _P(H,Q,w,{minRelevanceScore:B.minRelevanceScore}),f=await Q.entityService.listEntities({entityType:qB});return{...W,topics:f.map(bE)}})}var OHw=new IK;async function Ao1({entity:A,config:Q}){let w=IE.parse(A),B=OHw.parseTopicBody(w.content);return{$type:"ai.rizom.brain.topic",title:B.title,body:B.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"topic",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function kd0(){return{entityType:"topic",collection:"ai.rizom.brain.topic",lexicon:MB["ai.rizom.brain.topic"],validate:!1,buildRecord:Ao1}}var Qo1={name:"@brains/topics",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","@types/node":"^20.0.0",typescript:"^5.3.3"}};var RHw=new IK;class wo1 extends kQ{entityType=qB;schema=IE;adapter=RHw;unregisterAtprotoProjection;sourceBatch=new _d0;constructor(A={}){super(MP,Qo1,A,jr1)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:xr1,"merge-synthesis":Rr1,"topic-list":hr1,"topic-detail":vr1}}getDataSources(){return[new Nd0(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:Jd0,targetType:qB,job:{type:_r1,handler:nr1({context:A,logger:this.logger,config:this.config,extractAllTopics:()=>this.extractAllTopics(A),rebuildAllTopics:()=>this.rebuildAllTopics(A),sourceBatch:this.sourceBatch,isEntityPublished:(Q)=>this.isEntityPublished(Q)})},initialSync:{shouldEnqueue:async()=>!await IN(A,qB,{visibility:this.config.extractionVisibility}),jobData:{mode:"derive",reason:"initial-sync"},jobOptions:rr1()},sourceChange:{sourceTypes:this.config.includeEntityTypes,requireInitialSync:!0,jobData:(Q)=>{let w=Q.entity;if(!w)return null;if(!this.shouldProcessEntityType(w.entityType,A.entityService))return null;if(!this.isEntityPublished(w))return null;if(!iV(w.visibility,this.config.extractionVisibility))return null;return this.sourceBatch.add({entityId:w.id,entityType:w.entityType,contentHash:w.contentHash}),{mode:"source-batch"}},jobOptions:()=>({priority:5,source:EY0,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:kr1,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:MP}})}}]}async onRegister(A){A.insights.register("topic-distribution",Er1()),gr1({context:A,pluginId:this.id}),er1({context:A,logger:this.logger,config:this.config}),this.unregisterAtprotoProjection=U5.getInstance().register(kd0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(Jd0)?.hasQueuedInitialSync()??!1}shouldProcessEntityType(A,Q){if(A===qB)return!1;if(!this.config.includeEntityTypes.includes(A))return!1;return Q.getEntityTypeConfig(A).projectionSource!==!1}isEntityPublished(A){let w=A.metadata.status;if(w===void 0||w===null)return!0;if(typeof w!=="string")return!1;return this.config.extractableStatuses.includes(w)}async extractAllTopics(A){await or1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await sr1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function lY0(A){return new wo1(A)}c0();Z0();c0();var Od0=K.enum(["linkedin"]),xd0=K.enum(["generating","draft","queued","published","failed"]),Bo1=K.enum(["post","deck"]),$o1=K.object({id:K.string().min(1).describe("Document entity ID")}),Df=K.object({title:K.string().describe("Short descriptive title (3-6 words) for file naming"),platform:Od0.describe("Target platform"),status:xd0,coverImageId:K.string().optional().describe("Image entity ID for post image"),documents:K.array($o1).optional().describe("Document attachments for publishing"),publishedAt:K.string().datetime().optional(),platformPostId:K.string().optional().describe("ID from platform after publishing"),sourceEntityId:K.string().optional().describe("Source entity ID if auto-generated"),sourceEntityType:Bo1.optional().describe("Source entity type (post, deck)")}),Yo1=Df.extend({platform:Od0.optional(),status:xd0.optional()}),Do1=Df.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:K.string().describe("URL-friendly identifier: {platform}-{title}"),error:K.string().optional()}),Eb=o1.extend({entityType:K.literal("social-post"),metadata:Do1}),pY0=Eb.extend({frontmatter:Df,body:K.string()}),iY0=pY0.extend({url:K.string().optional(),listUrl:K.string().optional(),listLabel:K.string().optional(),typeLabel:K.string().optional(),coverImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()});c0();Z0();class Rd0 extends J2{constructor(){super({entityType:"social-post",purpose:"A short post drafted for social media such as LinkedIn or X.",schema:Eb,frontmatterSchema:Df,supportsCoverImage:!0})}toMarkdown(A){let Q="",w={};try{w=this.parseFrontMatter(A.content,Df),Q=this.extractBody(A.content)}catch{Q=A.content}let B={...w,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,B)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Yo1),w=Q.platform??"linkedin",B=Q.status??"draft",$=`${w}-${w1(Q.title)}`;return{content:A,entityType:"social-post",metadata:{title:Q.title,slug:$,platform:w,status:B,publishedAt:Q.publishedAt,platformPostId:Q.platformPostId}}}parsePostFrontmatter(A){return this.parseFrontMatter(A.content,Df)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}buildStub(A){let w={title:A.title,platform:"linkedin",status:"generating"};return{content:this.buildMarkdown("",w),metadata:{title:A.title,slug:`linkedin-${w1(A.title)}`,platform:"linkedin",status:"generating"}}}}var h7=new Rd0;c0();c0();Z0();var hHw=qU.extend({platform:K.enum(["linkedin"]).optional(),status:K.enum(["generating","draft","queued","published","failed"]).optional(),sortByQueue:K.boolean().optional(),nextInQueue:K.boolean().optional()}),vHw=FU.extend({query:hHw.optional()});function Xo1(A){let Q=v2(A.content,Df);return pY0.parse({...A,frontmatter:Q.metadata,body:Q.content})}class dY0 extends f${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=vHw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return Xo1(A)}buildDetailResult(A,Q){return{post:A}}buildListResult(A,Q,w){return{posts:A,totalCount:Q?.totalItems??A.length,pagination:Q,baseUrl:w.baseUrl}}async fetch(A,Q,w){let{query:B}=this.parseQuery(A),$=w.entityService;if(B.nextInQueue)return this.fetchNextInQueue(Q,$);if(B.id){let{item:f}=await this.fetchDetail(B.id,$);return Q.parse(this.buildDetailResult(f,null))}let Y={};if(B.platform)Y.platform=B.platform;if(B.status)Y.status=B.status;let D=Object.keys(Y).length>0,X=B.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:H,pagination:W}=await this.fetchList(B,$,{...D&&{filter:{metadata:Y}},sortFields:X});return Q.parse(this.buildListResult(H,W,B))}async fetchNextInQueue(A,Q){let B=(await Q.listEntities({entityType:this.config.entityType,options:{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}}))[0],$=B?Xo1(B):null;return A.parse({post:$})}}Z0();var Ho1=K.object({accessToken:K.string().optional(),refreshToken:K.string().optional(),organizationId:K.string().optional(),apiVersion:K.string().regex(/^\d{6}$/).optional()}),hd0=K.object({linkedin:Ho1.optional(),publishInterval:K.number().default(3600000),enabled:K.boolean().default(!0),defaultPrompt:K.string().default("Create an engaging social media post that drives engagement"),maxRetries:K.number().default(3),autoGenerateOnBlogPublish:K.boolean().default(!1)});c0();Z0();CB();Cd0();import{jsxDEV as c5,Fragment as EHw}from"preact/jsx-dev-runtime";function CHw(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function yHw(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var rY0=({posts:A,pageTitle:Q,pagination:w,baseUrl:B="/social-posts"})=>{let $=Q??"Social Posts",Y=w?.totalItems??A.length,D=`Browse all ${Y} social ${Y===1?"post":"posts"}`;return c5(EHw,{children:[c5(jQ,{title:$,description:D},void 0,!1,void 0,this),c5("div",{className:"social-post-list bg-theme",children:c5("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[c5("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:$},void 0,!1,void 0,this),A.length===0?c5("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):c5("ul",{className:"space-y-6",children:A.map((X)=>c5("li",{children:c5(uw,{href:X.url,variant:"horizontal",children:c5("div",{className:"flex flex-col sm:flex-row gap-4",children:[X.coverImageUrl&&c5("img",{src:X.coverImageUrl,alt:X.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),c5("div",{className:"flex-1 min-w-0",children:[c5("div",{className:"flex items-start justify-between gap-4 mb-2",children:[c5("h2",{className:"text-lg font-semibold text-heading",children:X.frontmatter.title},void 0,!1,void 0,this),c5("time",{className:"text-sm text-theme-muted shrink-0",children:yHw(X.frontmatter.publishedAt??X.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c5("div",{className:"flex items-center gap-2 mb-3",children:[c5(vD,{status:X.frontmatter.status},void 0,!1,void 0,this),c5("span",{className:"text-xs text-theme-muted uppercase",children:X.frontmatter.platform},void 0,!1,void 0,this),c5("span",{className:"text-xs text-theme-muted font-mono",children:X.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),c5("p",{className:"text-theme leading-relaxed",children:CHw(X.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)},X.id,!1,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&c5(o3,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:B},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 l5,Fragment as gHw}from"preact/jsx-dev-runtime";function Wo1(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var oY0=({post:A})=>{let Q=`Social Post - ${A.frontmatter.platform}`,w=A.body.slice(0,160),B=[{label:"Home",href:"/"},{label:A.listLabel??"Social Posts",href:A.listUrl??"/social-posts"},{label:A.frontmatter.platform}];return l5(gHw,{children:[l5(jQ,{title:Q,description:w},void 0,!1,void 0,this),l5("section",{className:"social-post-detail",children:l5("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:l5("div",{className:"max-w-3xl mx-auto",children:[l5(_G,{items:B},void 0,!1,void 0,this),l5("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),l5("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[l5(vD,{status:A.frontmatter.status},void 0,!1,void 0,this),l5("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),l5("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&&l5(n3,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),l5(uw,{className:"p-8 mb-8",children:l5("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),l5("div",{className:"space-y-4 text-sm text-theme-muted",children:[l5("div",{children:[l5("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",Wo1(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&l5("div",{children:[l5("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",Wo1(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&l5("div",{children:l5("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 Do(A){return`social-media:${A}`}var THw=K.union([K.boolean(),K.object({generate:K.boolean().optional(),prompt:K.string().optional()})]),yd0=K.object({prompt:K.string().optional(),platform:K.enum(["linkedin"]).optional(),sourceEntityType:K.enum(["post","deck"]).optional(),sourceEntityId:K.string().optional(),title:K.string().optional().describe("Required when content is provided directly"),content:K.string().optional(),addToQueue:K.boolean().optional(),generateImage:K.boolean().optional().describe("Auto-generate cover image for post"),coverImage:THw.optional().describe("Generic cover image generation request")}),SHw=UX.extend({slug:K.string().optional()});class kP extends Q4{constructor(A,Q){super(A,Q,{schema:yd0,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let w=A.platform??"linkedin",B=A.addToQueue??!1,{prompt:$,sourceEntityType:Y,sourceEntityId:D}=A,{content:X,title:H}=A;if(X&&H)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(X&&!H){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let L=await this.context.ai.generate({prompt:X,templateName:Do(w)});H=L.title,X=L.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(D&&Y){await this.reportProgress(Q,{progress:10,message:`Fetching source ${Y}`});let L=await this.context.entityService.getEntity({entityType:Y,id:D});if(!L)this.failEarly(`Source entity not found: ${Y}/${D}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let _=K.object({slug:K.string()}).safeParse(L.metadata),j=_.success?_.data.slug:D,g=await this.context.ai.generate({prompt:`Create an engaging ${w} post to promote this ${Y}:
6617
6617
 
6618
6618
  Source: ${Y}/${j}
6619
6619
 
6620
6620
  ${L.content}`,templateName:Do(w)});H=g.title,X=g.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:Do(w)});H=L.title,X=L.content,await this.reportProgress(Q,{progress:50,message:"Social post generated"})}else this.failEarly("No content source provided (prompt, sourceEntityId, or content)");if(!X||!H)this.failEarly("Content or title was not generated");let f={title:H,platform:w,status:B?"queued":"draft",...D&&{sourceEntityId:D},...Y&&{sourceEntityType:Y}},Z=h7.createPostContent(f,X),F=h7.fromMarkdown(Z).metadata;if(!F)this.failEarly("Failed to parse social post metadata");let V=await qq({entityType:"social-post",title:H,deriveId:(L)=>`${w}-${w1(L)}`,regeneratePrompt:"Generate a different social media post title on the same topic.",context:this.context}),b=Z;if(V!==H){F.title=V,F.slug=`${w}-${w1(V)}`;let L={...f,title:V};b=h7.createPostContent(L,X)}return{id:F.slug,content:b,metadata:F,title:V,resultExtras:{slug:F.slug},createOptions:{deduplicateId:!0}}}async onGenerationFailure(A,Q){await this.context.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:Q}})}async afterCreate(A,Q,w,B){if(A.generateImage){await this.reportProgress(w,{progress:90,message:"Queueing image generation"});let $=B.title??"Social Post";await this.context.jobs.enqueue({type:"image:image-generate",data:{prompt:`Social media graphic for: ${$}`,title:`${$} Image`,aspectRatio:"16:9",targetEntityType:"social-post",targetEntityId:Q},toolContext:{interfaceType:"job",userId:"system"}})}await this.context.messaging.send({type:"generate:report:success",payload:{entityType:"social-post",entityId:Q}})}summarizeDataForLog(A){return{platform:A.platform??"linkedin",hasPrompt:!!A.prompt,sourceEntityType:A.sourceEntityType,addToQueue:A.addToQueue??!1,generateImage:A.generateImage??!1,coverImage:!!A.coverImage}}}function Xo(A){if(A.length<=200)return A;return`${A.slice(0,200)}\u2026 (truncated, ${A.length} bytes)`}function mHw(A){let Q={status:"READY",media:A.urn};if(A.title)Q.title={text:A.title};return Q}function uHw(A){if(!Ed0(A))return null;let Q=sY0(A,"value");if(!Q)return null;let w=sY0(Q,"uploadMechanism");if(!w)return null;let B=sY0(w,"com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest");if(!B)return null;let $=B.uploadUrl,Y=Q.asset;if(typeof $!=="string"||typeof Y!=="string")return null;return{uploadUrl:$,assetUrn:Y}}function cHw(A){if(!Ed0(A))return null;let Q=sY0(A,"value");if(!Q)return null;let{uploadUrl:w,document:B}=Q;if(typeof w!=="string"||typeof B!=="string")return null;return{uploadUrl:w,documentUrn:B}}function sY0(A,Q){let w=A[Q];return Ed0(w)?w:null}function Ed0(A){return typeof A==="object"&&A!==null}var lHw="202604";class gd0{config;logger;name="linkedin";apiBaseUrl="https://api.linkedin.com/v2";restApiBaseUrl="https://api.linkedin.com/rest";fetch;cachedUserId=null;constructor(A,Q,w={}){this.config=A;this.logger=Q;this.fetch=w.fetch??globalThis.fetch.bind(globalThis)}async publish(A,Q,w,B){if(!this.config.accessToken)throw Error("LinkedIn access token not configured");let $=await this.getAuthor(),Y=B?.[0];if(B&&B.length>1)this.logger.warn("LinkedIn document publishing supports one PDF",{count:B.length});let D=null;if(Y){let Z=await this.uploadDocument($,Y);return this.publishDocumentPost($,A,Z,Y.filename)}else if(w){let Z=await this.uploadImage($,w);if(Z)D={category:"IMAGE",urn:Z}}let X={shareCommentary:{text:A},shareMediaCategory:D?.category??"NONE",...D&&{media:[mHw(D)]}},H=await this.fetch(`${this.apiBaseUrl}/ugcPosts`,{method:"POST",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:$,lifecycleState:"PUBLISHED",specificContent:{"com.linkedin.ugc.ShareContent":X},visibility:{"com.linkedin.ugc.MemberNetworkVisibility":"PUBLIC"}})});if(!H.ok){let Z=Xo(await H.text());throw this.logger.error("LinkedIn API error",{status:H.status,error:Z}),Error(`LinkedIn API error: ${H.status} - ${Z}`)}let W=H.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn post created",{postId:W,mediaCategory:D?.category??"NONE"});let f={id:W};if(W)f.url=`https://www.linkedin.com/feed/update/${W}`;return f}getRestHeaders(){return{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","Linkedin-Version":this.config.apiVersion??lHw,"X-Restli-Protocol-Version":"2.0.0"}}async uploadImage(A,Q){try{let w=await this.fetch(`${this.apiBaseUrl}/assets?action=registerUpload`,{method:"POST",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({registerUploadRequest:{recipes:["urn:li:digitalmediaRecipe:feedshare-image"],owner:A,serviceRelationships:[{relationshipType:"OWNER",identifier:"urn:li:userGeneratedContent"}]}})});if(!w.ok){let X=Xo(await w.text());return this.logger.warn("LinkedIn image upload registration failed",{status:w.status,error:X}),null}let B=uHw(await w.json());if(!B)return this.logger.warn("LinkedIn image upload registration was malformed"),null;let{uploadUrl:$,assetUrn:Y}=B,D=await this.fetch($,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!D.ok)return this.logger.warn("LinkedIn image binary upload failed",{status:D.status}),null;return this.logger.info("LinkedIn image uploaded",{assetUrn:Y}),Y}catch(w){return this.logger.warn("LinkedIn image upload error",{error:w}),null}}async uploadDocument(A,Q){let w=await this.fetch(`${this.restApiBaseUrl}/documents?action=initializeUpload`,{method:"POST",headers:this.getRestHeaders(),body:JSON.stringify({initializeUploadRequest:{owner:A}})});if(!w.ok){let Y=Xo(await w.text());throw Error(`LinkedIn document upload initialization failed: ${w.status} - ${Y}`)}let B=cHw(await w.json());if(!B)throw Error("LinkedIn document upload initialization was malformed");let $=await this.fetch(B.uploadUrl,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!$.ok)throw Error(`LinkedIn document binary upload failed: ${$.status}`);return this.logger.info("LinkedIn document uploaded",{documentUrn:B.documentUrn,filename:Q.filename}),B.documentUrn}async publishDocumentPost(A,Q,w,B){let $=await this.fetch(`${this.restApiBaseUrl}/posts`,{method:"POST",headers:this.getRestHeaders(),body:JSON.stringify({author:A,commentary:Q,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},content:{media:{id:w,title:B}},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1})});if(!$.ok){let X=Xo(await $.text());throw this.logger.error("LinkedIn document post API error",{status:$.status,error:X}),Error(`LinkedIn document post API error: ${$.status} - ${X}`)}let Y=$.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn document post created",{postId:Y,documentUrn:w});let D={id:Y};if(Y)D.url=`https://www.linkedin.com/feed/update/${Y}`;return D}async validateCredentials(){if(!this.config.accessToken)return!1;try{if(this.config.organizationId)return(await this.fetch(`${this.apiBaseUrl}/organizations/${this.config.organizationId}`,{headers:{Authorization:`Bearer ${this.config.accessToken}`}})).ok;return await this.getUserId(),!0}catch{return!1}}async getAuthor(){if(this.config.organizationId)return`urn:li:organization:${this.config.organizationId}`;return this.getUserId()}async getUserId(){if(this.cachedUserId)return this.cachedUserId;if(!this.config.accessToken)throw Error("LinkedIn access token not configured");try{let w=await this.fetch("https://api.linkedin.com/v2/userinfo",{headers:{Authorization:`Bearer ${this.config.accessToken}`}});if(w.ok){let B=await w.json();return this.cachedUserId=`urn:li:person:${B.sub}`,this.cachedUserId}}catch{}let A=await this.fetch("https://api.linkedin.com/v2/me",{headers:{Authorization:`Bearer ${this.config.accessToken}`}});if(!A.ok){let w=Xo(await A.text());throw Error(`Failed to get LinkedIn user ID: ${A.status} - ${w}`)}let Q=await A.json();return this.cachedUserId=`urn:li:person:${Q.id}`,this.cachedUserId}}function Td0(A,Q,w={}){return new gd0(A,Q,w)}c0();Z0();IB();Cd0();var pHw=K.object({posts:K.array(iY0),totalCount:K.number().optional(),pagination:e7.nullable(),baseUrl:K.string().optional()}),iHw=K.object({post:iY0});function fo1(){return{linkedin:nY0,"social-post-list":R1({name:"social-post-list",description:"Social post list page template",schema:pHw,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:rY0}}),"social-post-detail":R1({name:"social-post-detail",description:"Individual social post template",schema:iHw,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:oY0}})}}Z0();var dHw=K.object({prompt:K.string().optional(),content:K.string().optional(),platform:K.enum(["linkedin"]).default("linkedin")}),nHw=K.object({prompt:K.string().optional(),content:K.string().optional(),title:K.string().optional(),platform:K.enum(["linkedin"]).optional()});function Zo1(A){A.eval.registerHandler("generation",async(Q)=>{let w=dHw.parse(Q),B=w.content?`Create an engaging LinkedIn post to share this content:
6621
6621
 
6622
- ${w.content}`:w.prompt??"Write an engaging LinkedIn post";return A.ai.generate({prompt:B,templateName:`social-media:${w.platform}`})}),A.eval.registerHandler("create",async(Q)=>{let w=nHw.parse(Q),B=[],$=D7.from(async(W)=>{let f={progress:W.progress};if(W.message!==void 0)f.message=W.message;B.push(f)});if(!$)throw Error("Failed to create progress reporter");let D=await new kP(A.logger,A).process(w,`eval-${Date.now()}`,$),X=!1,H;if(D.success&&D.entityId){let W=await A.entityService.getEntity({entityType:"social-post",id:D.entityId});X=!!W,H=W?.content.slice(0,300)}return{...D,entityExists:X,entityPreview:H,progressSteps:B}})}Z0();c0();class Ho{sendMessage;logger;entityService;providers;permissions;resolveAttachment;constructor(A){this.sendMessage=A.sendMessage,this.logger=A.logger,this.entityService=A.entityService,this.providers=A.providers,this.permissions=A.permissions,this.resolveAttachment=A.resolveAttachment}async handle(A){let{entityType:Q,entityId:w}=A;if(Q!=="social-post")return;this.permissions.assertEntityActionAllowed(Q,"publish",A.authContext??{userPermissionLevel:"anchor"}),this.logger.debug("Handling publish:execute",{entityId:w});try{let B=await this.entityService.getEntity({entityType:"social-post",id:w});if(!B){await this.reportFailure(Q,w,`Post not found: ${w}`);return}let $=B;if($.metadata.status==="published"){this.logger.debug("Post already published, skipping",{entityId:w});return}let Y=$.metadata.platform,D=this.providers.get(Y);if(!D){await this.reportFailure(Q,w,`No provider configured for platform: ${Y}`);return}let X=v2($.content,Df),H;if(X.metadata.coverImageId)H=await this.fetchImageData(X.metadata.coverImageId);let W=X.metadata.documents??[],f=await this.fetchDocumentData(W);try{if(W.length>0&&f.length===0)throw Error(`Refusing to publish: ${W.length} document(s) referenced but none could be fetched`);let Z=W.length===0?await this.resolveSourceAttachment(X.metadata):[],G=f.length>0?f:Z,F=G.length?await D.publish(X.content,$.metadata,H,G):await D.publish(X.content,$.metadata,H),V=new Date().toISOString(),b=F.id||void 0,L={...X.metadata,status:"published",publishedAt:V,...b&&{platformPostId:b}},N=h7.createPostContent(L,X.content);await this.entityService.updateEntity({entity:{...$,content:N,metadata:{...$.metadata,status:"published",publishedAt:V,platformPostId:b}}}),await this.reportSuccess(Q,w,F.id),this.logger.info(`Post published successfully: ${w}`,{platform:Y,platformPostId:b})}catch(Z){let G=Z instanceof Error?Z.message:String(Z),F={...X.metadata,status:"failed"},V=h7.createPostContent(F,X.content);await this.entityService.updateEntity({entity:{...$,content:V,metadata:{...$.metadata,status:"failed"}}}),await this.reportFailure(Q,w,G),this.logger.error(`Post publish failed: ${w}`,{platform:Y,error:G})}}catch(B){let $=vA(B);this.logger.error("Unexpected error in publish handler",{entityId:w,error:$}),await this.reportFailure(Q,w,$)}}async reportSuccess(A,Q,w){await this.sendMessage({type:"publish:report:success",payload:{entityType:A,entityId:Q,result:{id:w}}})}async reportFailure(A,Q,w){await this.sendMessage({type:"publish:report:failure",payload:{entityType:A,entityId:Q,error:w}})}async resolveSourceAttachment(A){if(!this.resolveAttachment||!A.sourceEntityType||!A.sourceEntityId)return[];let Q=await this.resolveAttachment({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:"carousel"});return Q?[Q]:[]}async fetchDocumentData(A){if(!A?.length)return[];let Q=[];for(let w of A){let B=await this.fetchSingleDocumentData(w.id);if(B)Q.push(B)}return Q}async fetchSingleDocumentData(A){try{let Q=await this.entityService.getEntity({entityType:"document",id:A});if(!Q){this.logger.warn("Document not found",{documentId:A});return}let w=Q.content.match(/^data:application\/pdf;base64,(.+)$/);if(!w?.[1]){this.logger.warn("Invalid document data URL format",{documentId:A});return}let B=typeof Q.metadata.filename==="string"?Q.metadata.filename:`${A}.pdf`;return{type:"document",data:Buffer.from(w[1],"base64"),mimeType:"application/pdf",filename:B}}catch(Q){this.logger.warn("Failed to fetch document",{documentId:A,error:Q});return}}async fetchImageData(A){try{let Q=await this.entityService.getEntity({entityType:"image",id:A});if(!Q){this.logger.warn("Cover image not found",{imageId:A});return}let B=Q.content.match(/^data:([^;]+);base64,(.+)$/);if(!B?.[1]||!B[2]){this.logger.warn("Invalid image data URL format",{imageId:A});return}let $=B[1],Y=B[2];return{data:Buffer.from(Y,"base64"),mimeType:$}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function Ko1(A,Q,w){if(Q.size===0){w.debug("No providers configured, skipping publish-pipeline registration");return}A.messaging.subscribe("system:plugins:ready",async()=>{let B=Q.values().next().value;return await A.messaging.send({type:"publish:register",payload:{entityType:"social-post",provider:B,config:{publishResultIdField:"platformPostId"}}}),w.info("Registered social-post with publish-pipeline"),{success:!0}})}function Uo1(A,Q,w){let B=new Ho({sendMessage:A.messaging.send,logger:w.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q,permissions:A.permissions,resolveAttachment:A.attachments.resolve});A.messaging.subscribe("publish:execute",async($)=>{return await B.handle($.payload),{success:!0}}),w.debug("Subscribed to publish:execute messages")}Z0();function Go1(A,Q){A.messaging.subscribe("entity:updated",async(w)=>{let{entityType:B,entityId:$,entity:Y}=w.payload;if(B!=="post")return{success:!0};if(Y.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:$}},limit:1}})).length>0)return Q.debug(`Social post already exists for ${$}, skipping auto-generate`),{success:!0};return await A.messaging.send({type:"social:auto-generate",payload:{sourceEntityType:B,sourceEntityId:$,platform:"linkedin"}}),Q.info(`Auto-generate social post triggered for queued post ${$}`),{success:!0}}catch(X){let H=vA(X);return Q.error(`Failed to trigger auto-generate for ${$}:`,{error:H}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function zo1(A,Q){A.messaging.subscribe("social:auto-generate",async(w)=>{let{sourceEntityType:B,sourceEntityId:$,platform:Y}=w.payload;try{let D=await A.jobs.enqueue({type:`${h7.entityType}:generation`,data:{sourceEntityType:B,sourceEntityId:$,platform:Y,addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info(`Social post generation job enqueued for ${B}/${$}`,{jobId:D}),{success:!0,jobId:D}}catch(D){let X=vA(D);return Q.error(`Failed to enqueue social post generation for ${$}:`,{error:X}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function qo1(A,Q){A.messaging.subscribe("generate:execute",async(w)=>{let{entityType:B}=w.payload;if(B!=="social-post")return{success:!0};Q.info("Received generate:execute for social-post");try{let $=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:5}});if($.length===0)return Q.info("No published posts found for social post generation"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"No published posts available for social post generation"}}),{success:!0};let Y=null;for(let X of $)if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:X.id}},limit:1}})).length===0){Y=X;break}if(!Y)return Q.info("All recent posts already have social posts"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"All recent posts already have social posts generated"}}),{success:!0};let D=await A.jobs.enqueue({type:`${h7.entityType}:generation`,data:{sourceEntityType:"post",sourceEntityId:Y.id,platform:"linkedin",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info("Social post generation job queued",{jobId:D,sourcePostId:Y.id}),{success:!0}}catch($){let Y=vA($);return Q.error("Failed to handle generate:execute:",{error:Y}),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:Y}}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}async function Fo1({entity:A,config:Q}){let w=Eb.parse(A),B=h7.parsePostFrontmatter(w),$=h7.getPostContent(w);return{$type:"ai.rizom.brain.socialPost",title:B.title,platform:B.platform,body:$,format:"text/markdown",status:B.status,...B.publishedAt&&{publishedAt:B.publishedAt},...B.platformPostId&&{platformPostId:B.platformPostId},...B.sourceEntityType&&{sourceLocalEntityType:B.sourceEntityType},...B.sourceEntityId&&{sourceLocalEntityId:B.sourceEntityId},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"social-post",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function Sd0(){return{entityType:"social-post",collection:"ai.rizom.brain.socialPost",lexicon:MB["ai.rizom.brain.socialPost"],validate:!1,buildRecord:Fo1}}var Vo1={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class md0 extends kQ{entityType=h7.entityType;schema=Eb;adapter=h7;providers=new Map;unregisterAtprotoProjection;constructor(A){super("social-media",Vo1,A,hd0)}createGenerationHandler(A){return new kP(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return fo1()}getDataSources(){return[new dY0(this.logger.child("SocialPostDataSource"))]}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}async onRegister(A){if(this.initializeProviders(),Ko1(A,this.providers,this.logger),Uo1(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)Go1(A,this.logger),zo1(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");qo1(A,this.logger),Zo1(A),this.unregisterAtprotoProjection=U5.getInstance().register(Sd0()),this.logger.info("Social media plugin registered successfully")}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}initializeProviders(){if(this.config.linkedin?.accessToken){let A=Td0(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function Wo(A){return new md0(A)}Z0();var oHw=K.enum(["draft","queued","published","failed"]),Jo1=K.object({status:oHw.default("draft"),queueOrder:K.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:K.string().datetime().optional()});class ud0{name="internal";async publish(A,Q){return{id:"internal"}}}var fo={interfaceType:"system",userId:"system",userPermissionLevel:"anchor",authorization:"system"},RY={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",QUEUED:"publish:queued",COMPLETED:"publish:completed",FAILED:"publish:failed",LIST_RESPONSE:"publish:list:response"},gb={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"},Io1={REGISTER:"publish-assets:register"};Z0();var sHw=K.enum(["provider"]),bo1=K.object({executionMode:sHw.optional(),publishResultIdField:K.string().min(1).optional(),publishTimestampField:K.string().min(1).optional(),enabled:K.boolean().optional()}).strict();var aHw=K.object({skipIfDraftExists:K.boolean().optional(),minSourceEntities:K.number().optional(),maxUnpublishedDrafts:K.number().optional(),sourceEntityType:K.string().optional()}),Lo1=K.object({entitySchedules:K.record(K.string(),K.string()).optional(),generationSchedules:K.record(K.string(),K.string()).optional(),generationConditions:K.record(K.string(),aHw).optional()});class sG{static instance=null;queues=new Map;static getInstance(){return sG.instance??=new sG,sG.instance}static resetInstance(){sG.instance=null}static createFresh(){return new sG}constructor(){}async add(A,Q,w=fo){let B=this.getOrCreateQueue(A),$=B.find((X)=>X.entityId===Q);if($)return{position:$.position};let Y=B.length+1,D={entityId:Q,entityType:A,position:Y,queuedAt:new Date().toISOString(),authContext:{...w}};return B.push(D),{position:Y}}async remove(A,Q){let w=this.queues.get(A);if(!w)return;let B=w.findIndex(($)=>$.entityId===Q);if(B===-1)return;w.splice(B,1),this.recalculatePositions(w)}async reorder(A,Q,w){let B=this.queues.get(A);if(!B)return;let $=B.findIndex((X)=>X.entityId===Q);if($===-1)return;let[Y]=B.splice($,1);if(!Y)return;let D=Math.max(0,Math.min(w-1,B.length));B.splice(D,0,Y),this.recalculatePositions(B)}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 w=Q[0];if(!w)continue;if(!A||w.queuedAt<A.queuedAt)A=w}return A}async popNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let w=Q.shift()??null;if(w)this.recalculatePositions(Q);return w}getRegisteredTypes(){return Array.from(this.queues.keys())}async getQueuedEntityTypes(){let A=[];for(let[Q,w]of this.queues.entries())if(w.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,w)=>{Q.position=w+1})}}class aG{static instance=null;providers=new Map;executionModes=new Map;publishResultIdFields=new Map;publishTimestampFields=new Map;defaultProvider=new ud0;static getInstance(){return aG.instance??=new aG,aG.instance}static resetInstance(){aG.instance=null}static createFresh(){return new aG}constructor(){}register(A,Q,w){let B=this.providers.get(A);if(B&&B.name!=="internal"&&Q.name==="internal")return;if(this.providers.set(A,Q),this.executionModes.set(A,w?.executionMode??"provider"),w?.publishResultIdField)this.publishResultIdFields.set(A,w.publishResultIdField);else this.publishResultIdFields.delete(A);if(w?.publishTimestampField)this.publishTimestampFields.set(A,w.publishTimestampField);else this.publishTimestampFields.delete(A)}get(A){return this.providers.get(A)??this.defaultProvider}getExecutionMode(A){return this.executionModes.get(A)??"provider"}getPublishResultIdField(A){return this.publishResultIdFields.get(A)}getPublishTimestampField(A){return this.publishTimestampFields.get(A)}has(A){return this.providers.has(A)}unregister(A){this.providers.delete(A),this.executionModes.delete(A),this.publishResultIdFields.delete(A),this.publishTimestampFields.delete(A)}getRegisteredTypes(){return Array.from(this.providers.keys())}}Z0();Z0();async function No1(A,Q){if(!Q.publishExecutor){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"Publish executor not configured",retryCount:0,willRetry:!1});return}await tHw(A,Q)}async function tHw(A,Q){if(!Q.publishExecutor)return;try{let w=await Q.publishExecutor.publish({entityType:A.entityType,id:A.entityId});if("error"in w){let B={entityType:A.entityType,entityId:A.entityId,error:w.error,retryCount:0,willRetry:!1};if(Q.messageBus)await Q.messageBus.send({type:RY.FAILED,payload:B,sender:"publish-service"});Q.onFailed?.(B);return}cd0(A.entityType,A.entityId,w.result,Q)}catch(w){let B=vA(w);Q.retryTracker.recordFailure(A.entityId,B);let $=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:B,retryCount:$?.retryCount??1,willRetry:!1})}}function cd0(A,Q,w,B){if(B.retryTracker.clearRetries(Q),B.messageBus)B.messageBus.send({type:RY.COMPLETED,payload:{entityType:A,entityId:Q,result:w},sender:"publish-service"});B.onPublish?.({entityType:A,entityId:Q,result:w})}function jo1(A,Q,w,B){B.retryTracker.recordFailure(Q,w);let $=B.retryTracker.getRetryInfo(Q),Y={entityType:A,entityId:Q,error:w,retryCount:$?.retryCount??1,willRetry:!1};if(B.messageBus)B.messageBus.send({type:RY.FAILED,payload:Y,sender:"publish-service"});B.onFailed?.(Y)}async function Mo1(A,Q){let w=Q.generationConditions[A];if(w&&Q.onCheckGenerationConditions){let $=await Q.onCheckGenerationConditions(A,w);if(!$.shouldGenerate){if(Q.messageBus)Q.messageBus.send({type:gb.SKIPPED,payload:{entityType:A,reason:$.reason??"Conditions not met"},sender:"content-pipeline"});return}}let B={entityType:A};if(Q.messageBus)await Q.messageBus.send({type:gb.EXECUTE,payload:B,sender:"content-pipeline"});Q.onGenerate?.(B)}function _o1(A,Q,w){if(w)w.send({type:gb.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function Po1(A,Q,w){if(w)w.send({type:gb.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var eHw=1000;class ld0{deps;publishJobs=new Map;immediateIntervalJob=null;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.entitySchedules)){let w=this.deps.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,w)}this.immediateIntervalJob=this.deps.config.backend.scheduleInterval(eHw,()=>this.processUnscheduledTypes())}stop(){if(AWw(this.publishJobs),this.immediateIntervalJob)this.immediateIntervalJob.stop(),this.immediateIntervalJob=null}async processEntityType(A){if(!this.deps.isRunning())return;try{let Q=await this.deps.config.queueManager.getNext(A);if(Q)await this.processEntry(Q)}catch(Q){this.deps.config.logger.error(`Scheduler error for ${A}:`,Q)}}async processUnscheduledTypes(){if(!this.deps.isRunning())return;try{let A=await this.deps.config.queueManager.getQueuedEntityTypes();for(let Q of A)if(!this.entitySchedules[Q]){let w=await this.deps.config.queueManager.getNext(Q);if(w){await this.processEntry(w);break}}}catch(A){this.deps.config.logger.error("Scheduler error for unscheduled types:",A)}}async processEntry(A){await this.deps.config.queueManager.remove(A.entityType,A.entityId);let Q=this.deps.getPublishDeps();await No1(A,Q)}get entitySchedules(){return this.deps.config.entitySchedules}}function AWw(A){for(let Q of A.values())Q.stop();A.clear()}class pd0{deps;generationJobs=new Map;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.generationSchedules)){let w=this.deps.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,w)}}stop(){QWw(this.generationJobs)}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await Mo1(A,this.deps.getGenerationDeps())}catch(Q){this.deps.config.logger.error(`Generation trigger error for ${A}:`,Q)}}get generationSchedules(){return this.deps.config.generationSchedules}}function QWw(A){for(let Q of A.values())Q.stop();A.clear()}class LK{static instance=null;config;publishRunner;generationRunner;running=!1;static getInstance(A){return LK.instance??=new LK(A),LK.instance}static resetInstance(){if(LK.instance)LK.instance.stop();LK.instance=null}static createFresh(A){return new LK(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new ld0({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new pd0({config:this.config,getGenerationDeps:()=>this.generationDeps,isRunning:()=>this.running})}async start(){if(this.running)return;this.running=!0,this.publishRunner.start(),this.generationRunner.start()}async stop(){this.running=!1,this.publishRunner.stop(),this.generationRunner.stop()}isRunning(){return this.running}completePublish(A,Q,w){cd0(A,Q,w,this.publishDeps)}failPublish(A,Q,w){jo1(A,Q,w,this.publishDeps)}completeGeneration(A,Q){_o1(A,Q,this.config.messageBus)}failGeneration(A,Q){Po1(A,Q,this.config.messageBus)}get entitySchedules(){return this.config.entitySchedules}get generationSchedules(){return this.config.generationSchedules}get publishDeps(){return{retryTracker:this.config.retryTracker,messageBus:this.config.messageBus,publishExecutor:this.config.publishExecutor,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,w){try{this.config.backend.validateCron(Q)}catch(B){throw Error(`Invalid ${w} cron expression for ${A}: "${Q}" - ${vA(B)}`)}}}class tG{static instance=null;retries=new Map;static getInstance(){return tG.instance??=new tG,tG.instance}static resetInstance(){tG.instance=null}static createFresh(){return new tG}constructor(){}recordFailure(A,Q){let B=(this.retries.get(A)?.retryCount??0)+1;this.retries.set(A,{entityId:A,retryCount:B,lastError:Q})}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}}}function P4(A,Q,w,B,$,Y,D,X){return P4.fromTZ(P4.tp(A,Q,w,B,$,Y,D),X)}P4.fromTZISO=(A,Q,w)=>P4.fromTZ(wWw(A,Q),w);P4.fromTZ=function(A,Q){let w=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),B=id0(A.tz,w),$=new Date(w.getTime()-B),Y=id0(A.tz,$);if(Y-B===0)return $;{let D=new Date(w.getTime()-Y),X=id0(A.tz,D);if(X-Y===0)return D;if(!Q&&X-Y>0)return D;if(Q)throw Error("Invalid date passed to fromTZ()");return $}};P4.toTZ=function(A,Q){let w=A.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),B=new Date(w);return{y:B.getFullYear(),m:B.getMonth()+1,d:B.getDate(),h:B.getHours(),i:B.getMinutes(),s:B.getSeconds(),tz:Q}};P4.tp=(A,Q,w,B,$,Y,D)=>({y:A,m:Q,d:w,h:B,i:$,s:Y,tz:D});function id0(A,Q=new Date){let w=Q.toLocaleString("en-US",{timeZone:A,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],B=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${B} GMT`)-Date.parse(`${B} ${w}`)}function wWw(A,Q){let w=new Date(Date.parse(A));if(isNaN(w))throw Error("minitz: Invalid ISO8601 passed to parser.");let B=A.substring(9);return A.includes("Z")||B.includes("-")||B.includes("+")?P4.tp(w.getUTCFullYear(),w.getUTCMonth()+1,w.getUTCDate(),w.getUTCHours(),w.getUTCMinutes(),w.getUTCSeconds(),"Etc/UTC"):P4.tp(w.getFullYear(),w.getMonth()+1,w.getDate(),w.getHours(),w.getMinutes(),w.getSeconds(),Q)}P4.minitz=P4;var dd0=32,Ko=31|dd0,Ro1=[1,2,4,8,16],ko1=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 Xf(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,Ko),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(A,Q,w,B){let $=this[A],Y=A==="day"&&this.lastDayOfMonth;if(Q===""&&!Y)throw TypeError("CronPattern: configuration entry "+A+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return $.fill(B);let D=Q.split(",");if(D.length>1)for(let X=0;X<D.length;X++)this.partToArray(A,D[X],w,B);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,A,w,B):Q.indexOf("-")!==-1?this.handleRange(Q,A,w,B):Q.indexOf("/")!==-1?this.handleStepping(Q,A,w,B):Q!==""&&this.handleNumber(Q,A,w,B)}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,w,B){let $=this.extractNth(A,Q),Y=parseInt($[0],10)+w;if(isNaN(Y))throw TypeError("CronPattern: "+Q+" is not a number: '"+A+"'");this.setPart(Q,Y,$[1]||B)}setPart(A,Q,w){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,w);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]=w}handleRangeWithStepping(A,Q,w,B){let $=this.extractNth(A,Q),Y=$[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(Y===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+A+"'");let[,D,X,H]=Y,W=parseInt(D,10)+w,f=parseInt(X,10)+w,Z=parseInt(H,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(f))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if(W>f)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let G=W;G<=f;G+=Z)this.setPart(Q,G,$[1]||B)}extractNth(A,Q){let w=A,B;if(w.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");B=w.split("#")[1],w=w.split("#")[0]}return[w,B]}handleRange(A,Q,w,B){let $=this.extractNth(A,Q),Y=$[0].split("-");if(Y.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+A+"'");let D=parseInt(Y[0],10)+w,X=parseInt(Y[1],10)+w;if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(X))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(D>X)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let H=D;H<=X;H++)this.setPart(Q,H,$[1]||B)}handleStepping(A,Q,w,B){let $=this.extractNth(A,Q),Y=$[0].split("/");if(Y.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+A+"'");Y[0]===""&&(Y[0]="*");let D=0;Y[0]!=="*"&&(D=parseInt(Y[0],10)+w);let X=parseInt(Y[1],10);if(isNaN(X))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(X===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(X>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=D;H<this[Q].length;H+=X)this.setPart(Q,H,$[1]||B)}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]|dd0;else if(Q===Ko)this.dayOfWeek[A]=Ko;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|Ro1[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Oo1=[31,28,31,30,31,30,31,31,30,31,30,31],JF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],Xf=class A{tz;ms;second;minute;hour;day;month;year;constructor(Q,w){if(this.tz=w,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,w,B,$){let Y=new Date(Date.UTC(Q,w,B)).getUTCDay(),D=0;for(let X=1;X<=B;X++)new Date(Date.UTC(Q,w,X)).getUTCDay()===Y&&D++;if($&Ko&&Ro1[D-1]&$)return!0;if($&dd0){let X=new Date(Date.UTC(Q,w+1,0)).getUTCDate();for(let H=B+1;H<=X;H++)if(new Date(Date.UTC(Q,w,H)).getUTCDay()===Y)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 w=P4.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=w.s,this.minute=w.i,this.hour=w.h,this.day=w.d,this.month=w.m-1,this.year=w.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>Oo1[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 w=P4.fromTZISO(Q);this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes(),this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),this.apply()}else return this.fromDate(P4.fromTZISO(Q,this.tz))}findNext(Q,w,B,$){let Y=this[w],D;B.lastDayOfMonth&&(this.month!==1?D=Oo1[this.month]:D=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let X=!B.starDOW&&w=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[w]+$;H<B[w].length;H++){let W=B[w][H];if(w==="day"&&B.lastDayOfMonth&&H-$==D&&(W=1),w==="day"&&!B.starDOW){let f=B.dayOfWeek[(X+(H-$-1))%7];if(f&&f&Ko)f=this.isNthWeekdayOfMonth(this.year,this.month,H-$,f)?1:0;else if(f)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${f}`);Q.legacyMode&&!B.starDOM?W=W||f:W=W&&f}if(W)return this[w]=H-$,Y!==this[w]?2:1}return 3}recurse(Q,w,B){let $=this.findNext(w,JF[B][0],Q,JF[B][2]);if($>1){let Y=B+1;for(;Y<JF.length;)this[JF[Y][0]]=-JF[Y][2],Y++;if($===3)return this[JF[B][1]]++,this[JF[B][0]]=-JF[B][2],this.apply(),this.recurse(Q,w,0);if(this.apply())return this.recurse(Q,w,B-1)}return B+=1,B>=JF.length?this:this.year>=3000?null:this.recurse(Q,w,B)}increment(Q,w,B){return this.second+=w.interval!==void 0&&w.interval>1&&B?w.interval:1,this.ms=0,this.apply(),this.recurse(Q,w,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)):P4.fromTZ(P4.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function BWw(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 Xf(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new Xf(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 Zo(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function $Ww(A){return Zo(A)}function YWw(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var xo1=30000,aY0=[],nd0=class{name;options;_states;fn;constructor(A,Q,w){let B,$;if(Zo(Q))$=Q;else if(typeof Q=="object")B=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(Zo(w))$=w;else if(typeof w=="object")B=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=B?.name,this.options=BWw(B),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:B?B.maxRuns:void 0,paused:B?B.paused:!1,pattern:new ko1("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new Xf(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new ko1(A,this.options.timezone),this.name){if(aY0.find((Y)=>Y.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");aY0.push(this)}return $!==void 0&&$Ww($)&&(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 w=[],B=Q||this._states.currentRun||void 0;for(;A--&&(B=this.nextRun(B));)w.push(B);return w}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let A=this.nextRun(this._states.currentRun),Q=!this._states.paused,w=this.fn!==void 0,B=!this._states.kill;return Q&&w&&B&&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 Xf||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new Xf(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=aY0.indexOf(this);A>=0&&aY0.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(),w=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||w===null?this:(Q>xo1&&(Q=xo1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(w),Q),this._states.currentTimeout&&this.options.unref&&YWw(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new Xf(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){Zo(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Xf(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,w=!this._states.paused&&Q.getTime()>=A.getTime(),B=this._states.blocking&&this.options.protect;w&&!B?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):w&&B&&Zo(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(A){let Q=!!(A||this._states.currentRun),w=!1;!A&&this.options.startAt&&this.options.interval&&([A,Q]=this._calculatePreviousRun(A,Q),w=!A),A=new Xf(A,this.options.timezone||this.options.utcOffset),this.options.startAt&&A&&A.getTime()<this.options.startAt.getTime()&&(A=this.options.startAt);let B=this._states.once||new Xf(A,this.options.timezone||this.options.utcOffset);return!w&&B!==this._states.once&&(B=B.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=A.getTime()||B===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&B.getTime()>=this.options.stopAt.getTime()?null:B}_calculatePreviousRun(A,Q){let w=new Xf(void 0,this.options.timezone||this.options.utcOffset),B=A;if(this.options.startAt.getTime()<=w.getTime()){B=this.options.startAt;let $=B.getTime()+this.options.interval*1000;for(;$<=w.getTime();)B=new Xf(B,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),$=B.getTime()+this.options.interval*1000;Q=!0}return B===null&&(B=void 0),[B,Q]}};class tY0{scheduleCron(A,Q){let w=new nd0(A,()=>{Q()});return{stop:()=>w.stop()}}scheduleInterval(A,Q){let w=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(w)}}validateCron(A){new nd0(A).stop()}}Z0();var ho1=K.union([K.string().min(1),K.object({location:K.enum(["metadata","frontmatter"]),field:K.string().min(1)})]),eY0=K.object({entityType:K.string().min(1),attachmentType:K.string().min(1),mediaEntityType:K.enum(["image","document"]),targetEntityField:ho1.optional(),requiredWhen:K.object({status:K.string().min(1).optional(),visibility:K.string().min(1).optional()}).optional(),autoGenerate:K.boolean().optional(),requiredForPublish:K.boolean().optional(),jobType:K.string().min(1).optional()});function rd0(A){return`${A.entityType}:${A.attachmentType}`}class eG{static instance=null;definitions=new Map;static getInstance(){return eG.instance??=new eG,eG.instance}static resetInstance(){eG.instance=null}static createFresh(){return new eG}constructor(){}register(A){let Q=eY0.parse(A),w=rd0(Q);return this.definitions.set(w,Q),()=>this.unregister(Q.entityType,Q.attachmentType)}get(A,Q){return this.definitions.get(rd0({entityType:A,attachmentType:Q}))}list(A){let Q=Array.from(this.definitions.values());return A?Q.filter((w)=>w.entityType===A):Q}has(A,Q){return this.get(A,Q)!==void 0}unregister(A,Q){this.definitions.delete(rd0({entityType:A,attachmentType:Q}))}clear(){this.definitions.clear()}}Z0();class AD0{deps;constructor(A){this.deps=A}async ensureForEntity(A,Q={}){let w=this.deps.registry.list(A.entityType).filter(($)=>$.autoGenerate===!0).filter(($)=>!Q.attachmentType||$.attachmentType===Q.attachmentType),B={checked:w.length,enqueued:0,skipped:0};for(let $ of w)if(await this.ensureDefinition(A,$))B.enqueued+=1;else B.skipped+=1;return B}async ensureDefinition(A,Q){if(!this.matchesPolicy(A,Q))return!1;if(this.hasTargetField(A,Q.targetEntityField))return!1;if(!this.deps.context.attachments.hasProvider(A.entityType,Q.attachmentType))return!1;let w=this.resolveJobType(Q);if(!w)return!1;let B=this.getPredictedMediaId(A,Q),$=this.getDeduplicationKey(A,Q);return await this.deps.context.jobs.enqueue({type:w,data:{sourceEntityType:A.entityType,sourceEntityId:A.id,attachmentType:Q.attachmentType,imageId:B,dedupKey:$,targetEntityType:A.entityType,targetEntityId:A.id,...this.getTargetImageFieldData(Q.targetEntityField)},options:{source:"content-pipeline",metadata:{operationType:"content_operations"},deduplication:"skip",deduplicationKey:$}}),this.deps.context.logger.debug("Queued publish asset generation",{entityType:A.entityType,entityId:A.id,attachmentType:Q.attachmentType,jobType:w}),!0}matchesPolicy(A,Q){let{requiredWhen:w}=Q;if(!w)return!0;if(w.status&&A.metadata.status!==w.status)return!1;if(w.visibility&&A.visibility!==w.visibility)return!1;return!0}hasTargetField(A,Q){if(!Q)return!1;if(typeof Q==="string")return od0(A.metadata[Q]);if(Q.location==="metadata")return od0(A.metadata[Q.field]);let{frontmatter:w}=lw(A.content);return od0(w[Q.field])}resolveJobType(A){if(A.jobType)return A.jobType;if(A.mediaEntityType==="image")return"image:image-render-source";return}getPredictedMediaId(A,Q){let w=Q.attachmentType==="og-image"?"og":Q.attachmentType;return w1(`${w}-${A.entityType}-${A.id}`)}getDeduplicationKey(A,Q){return`publish-asset:${Q.attachmentType}:${A.entityType}:${A.id}`}getTargetImageFieldData(A){let Q=typeof A==="string"?A:A?.field;if(Q==="coverImageId"||Q==="ogImageId")return{targetImageField:Q};return{}}}function od0(A){return typeof A==="string"?A.length>0:A!==void 0}c0();Z0();var DWw=K.object({id:K.string().min(1)});async function Co1(A,Q){let{bodyContent:w,coverImageId:B,documents:$,sourceEntityType:Y,sourceEntityId:D}=XWw(Q.content),X=B?await fWw(A,B):void 0,H;if($&&$.length>0){let f=await ZWw(A,$);if(f.length>0)H=f}H??=await WWw(A,Y,D);let W={bodyContent:w};if(X)W.imageData=X;if(H&&H.length>0)W.documentData=H;return W}function XWw(A){try{let Q=v2(A,K.record(K.unknown())),w=Q.metadata.coverImageId,B=typeof w==="string"?w:void 0,$=HWw(Q.metadata.documents),Y=vo1(Q.metadata.sourceEntityType),D=vo1(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...B&&{coverImageId:B},...$.length>0&&{documents:$},...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}}}catch{return{bodyContent:A}}}function HWw(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let w=DWw.safeParse(Q);return w.success?[w.data]:[]})}function vo1(A){return typeof A==="string"&&A.length>0?A:void 0}async function WWw(A,Q,w){if(!Q||!w)return;let B=await A.attachments.resolve({sourceEntityType:Q,sourceEntityId:w,attachmentType:"carousel"});return B?[B]:void 0}async function fWw(A,Q){let w=await A.entityService.getEntity({entityType:"image",id:Q});if(!w?.content)return;let B=yo1(w.content);if(!B?.mimeType.startsWith("image/"))return;return{data:B.data,mimeType:B.mimeType}}async function ZWw(A,Q){return(await Promise.all(Q.map((B)=>KWw(A,B)))).filter((B)=>B!==void 0)}async function KWw(A,Q){let w=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!w?.content)return;let B=yo1(w.content);if(B?.mimeType!=="application/pdf")return;return{type:"document",data:B.data,mimeType:"application/pdf",filename:UWw(w,Q.id)}}function yo1(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function UWw(A,Q){let w=A.metadata.filename;return typeof w==="string"&&w.length>0?w:`${Q}.pdf`}Z0();var GWw=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;async function sd0(A,Q,w,B={}){let $=B.publishTimestampField??"publishedAt",Y=Q.metadata[$],D=B.publishedAt??(typeof Y==="string"?Y:void 0)??new Date().toISOString(),X={...Q.metadata,status:"published",[$]:D,platformId:w.id,...zWw(w.id,B.publishResultIdField)},H={...Q,content:Eo1(Q.content,D,w.id,B.publishResultIdField,$),metadata:X};return await A.entityService.updateEntity({entity:H}),H}function Eo1(A,Q,w,B,$="publishedAt"){if(!GWw.test(A))return A;let Y=o4(o4(A,"status","published"),$,Q);if(!w||!B)return Y;return o4(Y,B,w)}function zWw(A,Q){if(!Q||Q==="platformId")return{};return{[Q]:A}}class jE{deps;constructor(A){this.deps=A}async resolveCandidate(A){let{entityType:Q,id:w,slug:B}=A;if(!w&&!B)return{error:"Either 'id' or 'slug' must be provided"};let $=await this.findPublishableEntity(Q,w,B);if(!$)return{error:`Entity not found: ${Q}:${w??B}`};if($.visibility!=="public")return{error:`Cannot publish ${Q}:${$.id} to a public provider because visibility is ${$.visibility}`};if($.metadata.status==="published")return{error:"Entity is already published"};if(!this.deps.providerRegistry.has(Q))return{error:`No publish provider registered for ${Q}. Check that the required credentials are configured.`};return{entity:$}}async publish(A){let Q=await this.resolveCandidate(A);if("error"in Q)return Q;let{entity:w}=Q,{entityType:B}=A,$=this.deps.providerRegistry.get(B),{bodyContent:Y,imageData:D,documentData:X}=await Co1(this.deps.context,w),H=await $.publish(Y,w.metadata,D,X),W=this.deps.providerRegistry.getPublishResultIdField(B),f=this.deps.providerRegistry.getPublishTimestampField(B),Z=await sd0(this.deps.context,w,H,{...W?{publishResultIdField:W}:{},...f?{publishTimestampField:f}:{}});return await this.runPublishAssetPreflight(Z),{entity:Z,result:H}}async runPublishAssetPreflight(A){if(!this.deps.publishAssetPreflight)return;try{await this.deps.publishAssetPreflight.ensureForEntity(A)}catch(Q){this.deps.context.logger.warn("Publish asset preflight failed",{entityType:A.entityType,entityId:A.id,error:Q instanceof Error?Q.message:String(Q)})}}async findPublishableEntity(A,Q,w){if(Q)return this.deps.context.entityService.getEntity({entityType:A,id:Q});if(!w)return null;return(await this.deps.context.entityService.listEntities({entityType:A,options:{filter:{metadata:{slug:w}},limit:1}}))[0]??null}}c0();Z0();var ad0=K.object({action:K.enum(["list","add","remove","reorder"]).describe("Queue action to perform"),entityType:K.string().optional().describe("Entity type (required for add/remove/reorder, optional for list)"),entityId:K.string().optional().describe("Entity ID (required for add/remove/reorder)"),position:K.number().optional().describe("New position for reorder action (1-based)")}),td0=K.object({position:K.number(),entityType:K.string(),entityId:K.string(),queuedAt:K.string()}),qWw=K.object({success:K.literal(!0),message:K.string().optional(),data:K.object({queue:K.array(td0).optional(),entityType:K.string().optional(),entityId:K.string().optional(),position:K.number().optional()}).optional()}),FWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),ed0=K.union([qWw,FWw]);function QD0(A,Q,w){return{...Sw(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",ad0,async($,Y)=>{let{action:D,entityType:X,entityId:H,position:W}=$;switch(D){case"list":return VWw(w,X);case"add":return JWw(A,w,X,H,Y);case"remove":return IWw(A,w,X,H,Y);case"reorder":return bWw(A,w,X,H,W,Y);default:return{success:!1,error:`Unknown action: ${D}`}}},{sideEffects:"writes"}),outputSchema:ed0}}async function VWw(A,Q){let w=[];if(Q)w=await A.list(Q);else{let $=A.getRegisteredTypes();for(let Y of $){let D=await A.list(Y);w.push(...D)}w.sort((Y,D)=>new Date(Y.queuedAt).getTime()-new Date(D.queuedAt).getTime())}if(w.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:w.map(($,Y)=>({position:Y+1,entityType:$.entityType,entityId:$.entityId,queuedAt:$.queuedAt}))},message:`${w.length} items in queue`}}async function JWw(A,Q,w,B,$){let Y=An0("add",w,B);if(!Y.success)return Y.error;A.permissions.assertEntityActionAllowed(Y.entityType,"publish",$??{});let D=await Q.add(Y.entityType,Y.entityId,{...$,authorization:"user"});return{success:!0,data:{entityType:Y.entityType,entityId:Y.entityId,position:D.position},message:`Added to queue at position ${D.position}`}}async function IWw(A,Q,w,B,$){let Y=An0("remove",w,B);if(!Y.success)return Y.error;return A.permissions.assertEntityActionAllowed(Y.entityType,"update",$??{}),await Q.remove(Y.entityType,Y.entityId),{success:!0,data:{entityType:Y.entityType,entityId:Y.entityId},message:"Removed from queue"}}async function bWw(A,Q,w,B,$,Y){let D=An0("reorder",w,B);if(!D.success)return D.error;let X=LWw($);if(!X.success)return X.error;return A.permissions.assertEntityActionAllowed(D.entityType,"update",Y??{}),await Q.reorder(D.entityType,D.entityId,X.position),{success:!0,data:{entityType:D.entityType,entityId:D.entityId,position:X.position},message:`Moved to position ${X.position}`}}function An0(A,Q,w){if(!Q)return{success:!1,error:{success:!1,error:`entityType is required for ${A} action`}};if(!w)return{success:!1,error:{success:!1,error:`entityId is required for ${A} action`}};return{success:!0,entityType:Q,entityId:w}}function LWw(A){if(A===void 0)return{success:!1,error:{success:!1,error:"position is required for reorder action"}};if(A<1)return{success:!1,error:{success:!1,error:"position must be a positive number"}};return{success:!0,position:A}}Z0();import{createHash as NWw}from"crypto";var wD0=K.object({entityType:K.string().describe("Entity type to publish (e.g., social-post, post, deck)"),id:K.string().optional().describe("Entity ID to publish"),slug:K.string().optional().describe("Entity slug to publish"),confirmed:K.boolean().optional(),confirmationToken:K.string().optional(),contentHash:K.string().optional(),expiresAt:K.string().datetime().optional()}),jWw=K.object({success:K.literal(!0),message:K.string().optional(),data:K.object({entityType:K.string().optional(),entityId:K.string().optional(),platformId:K.string().optional(),url:K.string().optional()}).optional()}),MWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),_Ww=K.object({success:K.literal(!1).optional(),error:K.string().optional(),needsConfirmation:K.literal(!0),toolName:K.string(),summary:K.string(),preview:K.string().optional(),args:K.unknown()}),Qn0=K.union([jWw,MWw,_Ww]),PWw=900000;function BD0(A,Q,w,B){let $=B??new jE({context:A,providerRegistry:w}),Y=`${Q}_publish`;return{name:Y,description:"Publish an entity directly to its platform. Call this when the user asks to publish; the tool will request confirmation itself. Works with any registered entity type (social-post, post, deck, etc.)",inputSchema:wD0.shape,outputSchema:Qn0,visibility:"anchor",sideEffects:"external",handler:async(D,X)=>{let H=wD0.safeParse(D);if(!H.success)return{success:!1,error:`Invalid input: ${H.error.errors.map((b)=>`${b.path.join(".")}: ${b.message}`).join(", ")}`};let W=H.data,{entityType:f,id:Z,slug:G}=W;try{A.permissions.assertEntityActionAllowed(f,"publish",X)}catch(b){return{success:!1,error:b instanceof Error?b.message:String(b)}}let F=await $.resolveCandidate({entityType:f,id:Z,slug:G});if("error"in F)return{success:!1,error:F.error};let{entity:V}=F;if(W.confirmed){let b=OWw(Y,W,V);if(b!==null)return b;let L;try{L=await $.publish({entityType:f,id:V.id})}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}if("error"in L)return{success:!1,error:L.error};let{entity:N,result:_}=L;return{success:!0,data:{entityType:f,entityId:N.id,platformId:_.id,url:_.url},message:`Published ${f}:${N.id}`}}return kWw(Y,W,V)}}}function kWw(A,Q,w){let B=new Date(Date.now()+PWw).toISOString(),$=go1(A,w,B),Y=xWw(w);return{needsConfirmation:!0,toolName:A,summary:`Publish "${Y}"?`,preview:`This will publish ${w.entityType}:${w.id} to its registered public publish provider.`,args:{...Q,id:w.id,slug:void 0,confirmed:!0,confirmationToken:$,contentHash:w.contentHash,expiresAt:B}}}function OWw(A,Q,w){let{confirmationToken:B,contentHash:$,expiresAt:Y}=Q;if(!B||!Y)return{success:!1,error:"Invalid publish confirmation token. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};let D=Date.parse(Y);if(Number.isNaN(D))return{success:!1,error:"Invalid publish confirmation expiry. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};if(D<=Date.now())return{success:!1,error:"Publish confirmation expired. Request confirmation again before publishing.",code:"EXPIRED_CONFIRMATION_TOKEN"};if($&&$!==w.contentHash)return{success:!1,error:`Cannot publish ${w.entityType}:${w.id} because it changed after confirmation. Review it and try again.`};if(B!==go1(A,w,Y))return{success:!1,error:"Invalid publish confirmation token. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};return null}function go1(A,Q,w){return NWw("sha256").update(A).update("\x00").update(Q.entityType).update("\x00").update(Q.id).update("\x00").update(Q.contentHash).update("\x00").update(w).digest("hex")}function xWw(A){let Q=A.metadata.title;if(typeof Q==="string"&&Q.length>0)return Q;let w=A.metadata.subject;if(typeof w==="string"&&w.length>0)return w;let B=A.metadata.slug;if(typeof B==="string"&&B.length>0)return B;return A.id}c0();Z0();var wn0=K.object({entityType:K.string().min(1).describe("Entity type to reconcile"),status:K.string().min(1).optional().describe("Optional metadata status filter, e.g. published"),assetType:K.string().min(1).optional().describe("Optional attachment type filter, e.g. og-image")}),Bn0=K.object({success:K.literal(!0),data:K.object({entityType:K.string(),assetType:K.string().optional(),checkedEntities:K.number(),checkedAssets:K.number(),enqueued:K.number(),skipped:K.number()}),message:K.string().optional()});function $D0(A,Q,w,B){return{...Sw(Q,"ensure-assets","Reconcile configured publish assets for existing entities, queueing missing generated assets such as OG images.",wn0,async(Y,D)=>{if(A.permissions.assertEntityActionAllowed(Y.entityType,"publish",D),w.list(Y.entityType).filter((G)=>G.autoGenerate===!0).filter((G)=>!Y.assetType||G.attachmentType===Y.assetType).length===0)return{success:!0,data:{entityType:Y.entityType,...Y.assetType&&{assetType:Y.assetType},checkedEntities:0,checkedAssets:0,enqueued:0,skipped:0},message:`No publish assets configured for ${Y.entityType}`};let H=await A.entityService.listEntities({entityType:Y.entityType,options:{...Y.status&&{filter:{metadata:{status:Y.status}}}}}),W=0,f=0,Z=0;for(let G of H){let F=await B.ensureForEntity(G,{...Y.assetType&&{attachmentType:Y.assetType}});W+=F.checked,f+=F.enqueued,Z+=F.skipped}return{success:!0,data:{entityType:Y.entityType,...Y.assetType&&{assetType:Y.assetType},checkedEntities:H.length,checkedAssets:W,enqueued:f,skipped:Z},message:`Queued ${f} publish asset job(s)`}},{sideEffects:"writes"}),outputSchema:Bn0}}c0();Z0();function To1(A,Q){RWw(A,Q),hWw(A,Q),vWw(A,Q),CWw(A,Q)}function RWw(A,Q){A.messaging.subscribe(RY.REGISTER,async(w)=>yWw(Q,w.payload)),A.messaging.subscribe(RY.QUEUE,async(w)=>SWw(A,Q,w.payload)),A.messaging.subscribe(RY.DIRECT,async(w)=>mWw(A,Q,w.payload)),A.messaging.subscribe(RY.REMOVE,async(w)=>uWw(Q,w.payload)),A.messaging.subscribe(RY.REORDER,async(w)=>cWw(Q,w.payload)),A.messaging.subscribe(RY.LIST,async(w)=>lWw(A,Q,w.payload)),A.messaging.subscribe(RY.REPORT_SUCCESS,async(w)=>pWw(Q,w.payload)),A.messaging.subscribe(RY.REPORT_FAILURE,async(w)=>iWw(Q,w.payload)),Q.logger.debug("Subscribed to publish messages")}function hWw(A,Q){A.messaging.subscribe(gb.REPORT_SUCCESS,async(w)=>dWw(Q,w.payload)),A.messaging.subscribe(gb.REPORT_FAILURE,async(w)=>nWw(Q,w.payload)),Q.logger.debug("Subscribed to generation messages")}function vWw(A,Q){A.messaging.subscribe(Io1.REGISTER,async(w)=>EWw(Q,w.payload)),Q.logger.debug("Subscribed to publish asset messages")}function CWw(A,Q){let w=async(B)=>gWw(A,Q,B.payload);A.messaging.subscribe("entity:created",w),A.messaging.subscribe("entity:updated",w),Q.logger.debug("Subscribed to entity change messages for publish assets")}async function yWw(A,Q){let{entityType:w,provider:B,config:$}=Q;try{let Y=$?bo1.safeParse($):void 0;if(Y&&!Y.success)return A.logger.warn("Invalid publish provider config",{entityType:w,error:Y.error.message}),{success:!1};if(B)A.providerRegistry.register(w,B,Y?.data),A.logger.info(`Registered provider for entity type: ${w}`,{providerName:B.name,executionMode:A.providerRegistry.getExecutionMode(w)});return{success:!0}}catch(Y){let D=vA(Y);return A.logger.error(`Failed to register provider: ${D}`),{success:!1}}}async function EWw(A,Q){let w=eY0.safeParse(Q);if(!w.success)return A.logger.warn("Invalid publish asset registration",{error:w.error.message}),{success:!1};return A.publishAssetRegistry.register(w.data),A.logger.info("Registered publish asset",{entityType:w.data.entityType,attachmentType:w.data.attachmentType,mediaEntityType:w.data.mediaEntityType}),{success:!0}}async function gWw(A,Q,w){try{if(Q.publishAssetRegistry.list(w.entityType).length===0)return{success:!0};let B=w.entity??await A.entityService.getEntity({entityType:w.entityType,id:w.entityId});if(!TWw(B))return{success:!0};return await Q.publishAssetPreflight.ensureForEntity(B),{success:!0}}catch(B){return Q.logger.warn("Failed to run publish asset preflight for entity event",{entityType:w.entityType,entityId:w.entityId,error:vA(B)}),{success:!1}}}function TWw(A){if(!A)return!1;let Q=Jo1.safeParse(A.metadata);return Q.success&&Q.data.status==="published"}async function SWw(A,Q,w){let{entityType:B,entityId:$}=w;try{let Y=w.authContext??fo;A.permissions.assertEntityActionAllowed(B,"publish",Y);let D=await Q.queueManager.add(B,$,Y);return await A.messaging.send({type:RY.QUEUED,payload:{entityType:B,entityId:$,position:D.position}}),Q.logger.debug(`Entity queued: ${$}`,{entityType:B,position:D.position}),{success:!0}}catch(Y){let D=vA(Y);return Q.logger.error(`Failed to queue entity: ${D}`),{success:!1}}}async function mWw(A,Q,w){let{entityType:B,entityId:$}=w,Y=w.authContext??fo;try{if(A.permissions.assertEntityActionAllowed(B,"publish",Y),!Q.providerRegistry.has(B))return Q.scheduler.failPublish(B,$,`No publish provider registered for ${B}`),{success:!1};let D=await Q.publishExecutor.publish({entityType:B,id:$});if("error"in D)return Q.scheduler.failPublish(B,$,D.error),{success:!1};return Q.scheduler.completePublish(B,$,D.result),Q.logger.debug(`Direct publish completed: ${$}`,{entityType:B}),{success:!0}}catch(D){let X=vA(D);return Q.logger.error(`Failed direct publish request: ${X}`),{success:!1}}}async function uWw(A,Q){let{entityType:w,entityId:B}=Q;try{return await A.queueManager.remove(w,B),A.logger.debug(`Entity removed from queue: ${B}`,{entityType:w}),{success:!0}}catch($){let Y=vA($);return A.logger.error(`Failed to remove entity: ${Y}`),{success:!1}}}async function cWw(A,Q){let{entityType:w,entityId:B,position:$}=Q;try{return await A.queueManager.reorder(w,B,$),A.logger.debug(`Entity reordered: ${B}`,{entityType:w,newPosition:$}),{success:!0}}catch(Y){let D=vA(Y);return A.logger.error(`Failed to reorder entity: ${D}`),{success:!1}}}async function lWw(A,Q,w){let{entityType:B}=w;try{let $=await Q.queueManager.list(B);return await A.messaging.send({type:RY.LIST_RESPONSE,payload:{entityType:B,queue:$.map((Y)=>({entityId:Y.entityId,position:Y.position,queuedAt:Y.queuedAt}))}}),{success:!0}}catch($){let Y=vA($);return Q.logger.error(`Failed to list queue: ${Y}`),{success:!1}}}async function pWw(A,Q){let{entityType:w,entityId:B,result:$}=Q;return A.scheduler.completePublish(w,B,$),A.logger.info(`Publish reported success: ${B}`,{entityType:w}),{success:!0}}async function iWw(A,Q){let{entityType:w,entityId:B,error:$}=Q;A.scheduler.failPublish(w,B,$);let Y=A.retryTracker.getRetryInfo(B);return A.logger.info(`Publish reported failure: ${B}`,{entityType:w,error:$,retryCount:Y?.retryCount}),{success:!0}}async function dWw(A,Q){let{entityType:w,entityId:B}=Q;return A.scheduler.completeGeneration(w,B),A.logger.info("Generation completed",{entityType:w,entityId:B}),{success:!0}}async function nWw(A,Q){let{entityType:w,error:B}=Q;return A.scheduler.failGeneration(w,B),A.logger.warn("Generation failed",{entityType:w,error:B}),{success:!0}}Z0();async function So1(A,Q,w,B){try{if(B.skipIfDraftExists!==!1){if((await A.listEntities({entityType:w,options:{filter:{metadata:{status:"draft"}},limit:1}})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(B.maxUnpublishedDrafts!==void 0){let $=await A.listEntities({entityType:w,options:{filter:{metadata:{status:"draft"}},limit:B.maxUnpublishedDrafts+1}});if($.length>=B.maxUnpublishedDrafts)return{shouldGenerate:!1,reason:`Max unpublished drafts reached (${$.length}/${B.maxUnpublishedDrafts})`}}if(B.minSourceEntities!==void 0&&B.sourceEntityType){let $=await A.listEntities({entityType:B.sourceEntityType,options:{publishedOnly:!0,limit:B.minSourceEntities}});if($.length<B.minSourceEntities)return{shouldGenerate:!1,reason:`Not enough source entities (${$.length}/${B.minSourceEntities} ${B.sourceEntityType})`}}return{shouldGenerate:!0}}catch($){return Q.error("Failed to check generation conditions",{entityType:w,error:vA($)}),{shouldGenerate:!1,reason:`Condition check failed: ${vA($)}`}}}function mo1(A){let{context:Q,config:w,queueManager:B,providerRegistry:$,retryTracker:Y,publishExecutor:D,logger:X}=A,H=rWw(Q);return LK.createFresh({queueManager:B,providerRegistry:$,retryTracker:Y,logger:X,backend:new tY0,...w.entitySchedules&&{entitySchedules:w.entitySchedules},...w.generationSchedules&&{generationSchedules:w.generationSchedules},...w.generationConditions&&{generationConditions:w.generationConditions},messageBus:H,publishExecutor:D,onCheckGenerationConditions:(W,f)=>So1(Q.entityService,X,W,f)})}function rWw(A){return{send:async($)=>{return A.messaging.send({type:$.type,payload:$.payload,...$.target!==void 0?{target:$.target}:{},...$.metadata!==void 0?{metadata:$.metadata}:{},...$.broadcast!==void 0?{broadcast:$.broadcast}:{}})},subscribe:()=>()=>{},unsubscribe:()=>{}}}async function uo1(A,Q,w){let B=A.getEntityTypes();for(let Y of B){let D=await A.listEntities({entityType:Y,options:{filter:{metadata:{status:"queued"}}}});for(let X of D)await Q.add(X.entityType,X.id)}let $=0;for(let Y of B){let D=await Q.list(Y);$+=D.length}if($>0)w.info(`Rebuilt queue with ${$} queued entities`)}var oWw=["draft","queued","published","failed"];async function co1(A,Q){await A.messaging.send({type:"dashboard:register-widget",payload:{id:"publication-pipeline",pluginId:Q,title:"Publication Pipeline",section:"secondary",priority:100,rendererName:"PipelineWidget",visibility:"anchor",dataProvider:()=>sWw(A)}})}async function sWw(A){let Q=A.entityService.getEntityTypes(),w=[],B={draft:0,queued:0,published:0,failed:0};for(let $ of Q){let Y=await A.entityService.listEntities({entityType:$});for(let D of Y){let X=aWw(D.metadata.status);if(!X)continue;B[X]++,w.push({id:D.id,title:tWw(D.id,D.metadata.title),type:$,status:X})}}return{summary:B,items:w}}function aWw(A){return oWw.find((Q)=>Q===A)}function tWw(A,Q){return typeof Q==="string"?Q:A}var lo1={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.135",description:"Content pipeline plugin for managing entity publishing queues, scheduling, and generation",type:"module",main:"src/index.ts",types:"src/index.ts",scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",croner:"^9.1.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",typescript:"^5.3.3"},exports:{".":{types:"./src/index.ts",default:"./src/index.ts"}},files:["src"]};class $n0 extends IQ{pluginContext;queueManager;providerRegistry;retryTracker;publishExecutor;publishAssetRegistry;publishAssetPreflight;scheduler;constructor(A){super("content-pipeline",lo1,A??{},Lo1)}async onRegister(A){this.pluginContext=A,this.queueManager=sG.createFresh(),this.providerRegistry=aG.createFresh(),this.retryTracker=tG.createFresh(),this.publishAssetRegistry=eG.createFresh(),this.publishAssetPreflight=new AD0({context:A,registry:this.publishAssetRegistry}),this.publishExecutor=new jE({context:A,providerRegistry:this.providerRegistry,publishAssetPreflight:this.publishAssetPreflight}),this.scheduler=mo1({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,logger:this.logger}),To1(A,{queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,publishAssetRegistry:this.publishAssetRegistry,publishAssetPreflight:this.publishAssetPreflight,scheduler:this.scheduler,logger:this.logger})}async onReady(A){await uo1(A.entityService,this.queueManager,this.logger),await co1(A,this.id),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[QD0(this.pluginContext,this.id,this.queueManager),BD0(this.pluginContext,this.id,this.providerRegistry,this.publishExecutor),$D0(this.pluginContext,this.id,this.publishAssetRegistry,this.publishAssetPreflight)]}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). This tool has its own confirmation flow; call it without `confirmed` when the user asks to publish instead of asking for plain-text confirmation.\n- Use `content-pipeline_ensure-assets` to reconcile missing publish assets such as generated OG images for already-published content.\n- When users ask about their "publish queue", "publishing queue", or "what\'s queued", use `content-pipeline_queue`.'}getQueueManager(){return this.queueManager}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getPublishAssetRegistry(){return this.publishAssetRegistry}getScheduler(){return this.scheduler}async onShutdown(){await this.scheduler.stop(),sG.resetInstance(),aG.resetInstance(),tG.resetInstance(),eG.resetInstance()}}function Yn0(A){return new $n0(A)}c0();Z0();var po1=K.object({accountId:K.string().describe("Cloudflare account ID"),apiToken:K.string().describe("Cloudflare API token with Analytics:Read permission"),siteTag:K.string().describe("Cloudflare Web Analytics site tag")}),Dn0=K.object({cloudflare:po1.optional()});c0();Z0();var Afw=K.object({date:K.string().describe("Single date in YYYY-MM-DD format").optional(),days:K.number().min(1).max(365).describe("Number of days back from yesterday (e.g., 7 for last week)").optional(),startDate:K.string().describe("Start date in YYYY-MM-DD format (use with endDate)").optional(),endDate:K.string().describe("End date in YYYY-MM-DD format (use with startDate)").optional(),limit:K.number().min(1).max(100).default(20).describe("Maximum items for breakdowns (pages, referrers, countries)")});function Qfw(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 io1(A,Q,w){let B=[];if(!w)return B;return B.push(Sw(A,"query",`Query website analytics from Cloudflare.
6622
+ ${w.content}`:w.prompt??"Write an engaging LinkedIn post";return A.ai.generate({prompt:B,templateName:`social-media:${w.platform}`})}),A.eval.registerHandler("create",async(Q)=>{let w=nHw.parse(Q),B=[],$=D7.from(async(W)=>{let f={progress:W.progress};if(W.message!==void 0)f.message=W.message;B.push(f)});if(!$)throw Error("Failed to create progress reporter");let D=await new kP(A.logger,A).process(w,`eval-${Date.now()}`,$),X=!1,H;if(D.success&&D.entityId){let W=await A.entityService.getEntity({entityType:"social-post",id:D.entityId});X=!!W,H=W?.content.slice(0,300)}return{...D,entityExists:X,entityPreview:H,progressSteps:B}})}Z0();c0();class Ho{sendMessage;logger;entityService;providers;permissions;resolveAttachment;constructor(A){this.sendMessage=A.sendMessage,this.logger=A.logger,this.entityService=A.entityService,this.providers=A.providers,this.permissions=A.permissions,this.resolveAttachment=A.resolveAttachment}async handle(A){let{entityType:Q,entityId:w}=A;if(Q!=="social-post")return;this.permissions.assertEntityActionAllowed(Q,"publish",A.authContext??{userPermissionLevel:"anchor"}),this.logger.debug("Handling publish:execute",{entityId:w});try{let B=await this.entityService.getEntity({entityType:"social-post",id:w});if(!B){await this.reportFailure(Q,w,`Post not found: ${w}`);return}let $=B;if($.metadata.status==="published"){this.logger.debug("Post already published, skipping",{entityId:w});return}let Y=$.metadata.platform,D=this.providers.get(Y);if(!D){await this.reportFailure(Q,w,`No provider configured for platform: ${Y}`);return}let X=v2($.content,Df),H;if(X.metadata.coverImageId)H=await this.fetchImageData(X.metadata.coverImageId);let W=X.metadata.documents??[],f=await this.fetchDocumentData(W);try{if(W.length>0&&f.length===0)throw Error(`Refusing to publish: ${W.length} document(s) referenced but none could be fetched`);let Z=W.length===0?await this.resolveSourceAttachment(X.metadata):[],G=f.length>0?f:Z,F=G.length?await D.publish(X.content,$.metadata,H,G):await D.publish(X.content,$.metadata,H),V=new Date().toISOString(),b=F.id||void 0,L={...X.metadata,status:"published",publishedAt:V,...b&&{platformPostId:b}},N=h7.createPostContent(L,X.content);await this.entityService.updateEntity({entity:{...$,content:N,metadata:{...$.metadata,status:"published",publishedAt:V,platformPostId:b}}}),await this.reportSuccess(Q,w,F.id),this.logger.info(`Post published successfully: ${w}`,{platform:Y,platformPostId:b})}catch(Z){let G=Z instanceof Error?Z.message:String(Z),F={...X.metadata,status:"failed"},V=h7.createPostContent(F,X.content);await this.entityService.updateEntity({entity:{...$,content:V,metadata:{...$.metadata,status:"failed"}}}),await this.reportFailure(Q,w,G),this.logger.error(`Post publish failed: ${w}`,{platform:Y,error:G})}}catch(B){let $=vA(B);this.logger.error("Unexpected error in publish handler",{entityId:w,error:$}),await this.reportFailure(Q,w,$)}}async reportSuccess(A,Q,w){await this.sendMessage({type:"publish:report:success",payload:{entityType:A,entityId:Q,result:{id:w}}})}async reportFailure(A,Q,w){await this.sendMessage({type:"publish:report:failure",payload:{entityType:A,entityId:Q,error:w}})}async resolveSourceAttachment(A){if(!this.resolveAttachment||!A.sourceEntityType||!A.sourceEntityId)return[];let Q=await this.resolveAttachment({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:"carousel"});return Q?[Q]:[]}async fetchDocumentData(A){if(!A?.length)return[];let Q=[];for(let w of A){let B=await this.fetchSingleDocumentData(w.id);if(B)Q.push(B)}return Q}async fetchSingleDocumentData(A){try{let Q=await this.entityService.getEntity({entityType:"document",id:A});if(!Q){this.logger.warn("Document not found",{documentId:A});return}let w=Q.content.match(/^data:application\/pdf;base64,(.+)$/);if(!w?.[1]){this.logger.warn("Invalid document data URL format",{documentId:A});return}let B=typeof Q.metadata.filename==="string"?Q.metadata.filename:`${A}.pdf`;return{type:"document",data:Buffer.from(w[1],"base64"),mimeType:"application/pdf",filename:B}}catch(Q){this.logger.warn("Failed to fetch document",{documentId:A,error:Q});return}}async fetchImageData(A){try{let Q=await this.entityService.getEntity({entityType:"image",id:A});if(!Q){this.logger.warn("Cover image not found",{imageId:A});return}let B=Q.content.match(/^data:([^;]+);base64,(.+)$/);if(!B?.[1]||!B[2]){this.logger.warn("Invalid image data URL format",{imageId:A});return}let $=B[1],Y=B[2];return{data:Buffer.from(Y,"base64"),mimeType:$}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function Ko1(A,Q,w){if(Q.size===0){w.debug("No providers configured, skipping publish-pipeline registration");return}A.messaging.subscribe("system:plugins:ready",async()=>{let B=Q.values().next().value;return await A.messaging.send({type:"publish:register",payload:{entityType:"social-post",provider:B,config:{publishResultIdField:"platformPostId"}}}),w.info("Registered social-post with publish-pipeline"),{success:!0}})}function Uo1(A,Q,w){let B=new Ho({sendMessage:A.messaging.send,logger:w.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q,permissions:A.permissions,resolveAttachment:A.attachments.resolve});A.messaging.subscribe("publish:execute",async($)=>{return await B.handle($.payload),{success:!0}}),w.debug("Subscribed to publish:execute messages")}Z0();function Go1(A,Q){A.messaging.subscribe("entity:updated",async(w)=>{let{entityType:B,entityId:$,entity:Y}=w.payload;if(B!=="post")return{success:!0};if(Y.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:$}},limit:1}})).length>0)return Q.debug(`Social post already exists for ${$}, skipping auto-generate`),{success:!0};return await A.messaging.send({type:"social:auto-generate",payload:{sourceEntityType:B,sourceEntityId:$,platform:"linkedin"}}),Q.info(`Auto-generate social post triggered for queued post ${$}`),{success:!0}}catch(X){let H=vA(X);return Q.error(`Failed to trigger auto-generate for ${$}:`,{error:H}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function zo1(A,Q){A.messaging.subscribe("social:auto-generate",async(w)=>{let{sourceEntityType:B,sourceEntityId:$,platform:Y}=w.payload;try{let D=await A.jobs.enqueue({type:`${h7.entityType}:generation`,data:{sourceEntityType:B,sourceEntityId:$,platform:Y,addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info(`Social post generation job enqueued for ${B}/${$}`,{jobId:D}),{success:!0,jobId:D}}catch(D){let X=vA(D);return Q.error(`Failed to enqueue social post generation for ${$}:`,{error:X}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function qo1(A,Q){A.messaging.subscribe("generate:execute",async(w)=>{let{entityType:B}=w.payload;if(B!=="social-post")return{success:!0};Q.info("Received generate:execute for social-post");try{let $=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:5}});if($.length===0)return Q.info("No published posts found for social post generation"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"No published posts available for social post generation"}}),{success:!0};let Y=null;for(let X of $)if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:X.id}},limit:1}})).length===0){Y=X;break}if(!Y)return Q.info("All recent posts already have social posts"),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:"All recent posts already have social posts generated"}}),{success:!0};let D=await A.jobs.enqueue({type:`${h7.entityType}:generation`,data:{sourceEntityType:"post",sourceEntityId:Y.id,platform:"linkedin",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info("Social post generation job queued",{jobId:D,sourcePostId:Y.id}),{success:!0}}catch($){let Y=vA($);return Q.error("Failed to handle generate:execute:",{error:Y}),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:Y}}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}async function Fo1({entity:A,config:Q}){let w=Eb.parse(A),B=h7.parsePostFrontmatter(w),$=h7.getPostContent(w);return{$type:"ai.rizom.brain.socialPost",title:B.title,platform:B.platform,body:$,format:"text/markdown",status:B.status,...B.publishedAt&&{publishedAt:B.publishedAt},...B.platformPostId&&{platformPostId:B.platformPostId},...B.sourceEntityType&&{sourceLocalEntityType:B.sourceEntityType},...B.sourceEntityId&&{sourceLocalEntityId:B.sourceEntityId},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"social-post",sourceEntityId:w.id,createdAt:w.created,...w.updated&&{updatedAt:w.updated}}}function Sd0(){return{entityType:"social-post",collection:"ai.rizom.brain.socialPost",lexicon:MB["ai.rizom.brain.socialPost"],validate:!1,buildRecord:Fo1}}var Vo1={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class md0 extends kQ{entityType=h7.entityType;schema=Eb;adapter=h7;providers=new Map;unregisterAtprotoProjection;constructor(A){super("social-media",Vo1,A,hd0)}createGenerationHandler(A){return new kP(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return fo1()}getDataSources(){return[new dY0(this.logger.child("SocialPostDataSource"))]}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}async onRegister(A){if(this.initializeProviders(),Ko1(A,this.providers,this.logger),Uo1(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)Go1(A,this.logger),zo1(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");qo1(A,this.logger),Zo1(A),this.unregisterAtprotoProjection=U5.getInstance().register(Sd0()),this.logger.info("Social media plugin registered successfully")}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}initializeProviders(){if(this.config.linkedin?.accessToken){let A=Td0(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function Wo(A){return new md0(A)}Z0();var oHw=K.enum(["draft","queued","published","failed"]),Jo1=K.object({status:oHw.default("draft"),queueOrder:K.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:K.string().datetime().optional()});class ud0{name="internal";async publish(A,Q){return{id:"internal"}}}var fo={interfaceType:"system",userId:"system",userPermissionLevel:"anchor",authorization:"system"},RY={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",QUEUED:"publish:queued",COMPLETED:"publish:completed",FAILED:"publish:failed",LIST_RESPONSE:"publish:list:response"},gb={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"},Io1={REGISTER:"publish-assets:register"};Z0();var sHw=K.enum(["provider"]),bo1=K.object({executionMode:sHw.optional(),publishResultIdField:K.string().min(1).optional(),publishTimestampField:K.string().min(1).optional(),enabled:K.boolean().optional()}).strict();var aHw=K.object({skipIfDraftExists:K.boolean().optional(),minSourceEntities:K.number().optional(),maxUnpublishedDrafts:K.number().optional(),sourceEntityType:K.string().optional()}),Lo1=K.object({entitySchedules:K.record(K.string(),K.string()).optional(),generationSchedules:K.record(K.string(),K.string()).optional(),generationConditions:K.record(K.string(),aHw).optional()});class sG{static instance=null;queues=new Map;static getInstance(){return sG.instance??=new sG,sG.instance}static resetInstance(){sG.instance=null}static createFresh(){return new sG}constructor(){}async add(A,Q,w=fo){let B=this.getOrCreateQueue(A),$=B.find((X)=>X.entityId===Q);if($)return{position:$.position};let Y=B.length+1,D={entityId:Q,entityType:A,position:Y,queuedAt:new Date().toISOString(),authContext:{...w}};return B.push(D),{position:Y}}async remove(A,Q){let w=this.queues.get(A);if(!w)return;let B=w.findIndex(($)=>$.entityId===Q);if(B===-1)return;w.splice(B,1),this.recalculatePositions(w)}async reorder(A,Q,w){let B=this.queues.get(A);if(!B)return;let $=B.findIndex((X)=>X.entityId===Q);if($===-1)return;let[Y]=B.splice($,1);if(!Y)return;let D=Math.max(0,Math.min(w-1,B.length));B.splice(D,0,Y),this.recalculatePositions(B)}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 w=Q[0];if(!w)continue;if(!A||w.queuedAt<A.queuedAt)A=w}return A}async popNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let w=Q.shift()??null;if(w)this.recalculatePositions(Q);return w}getRegisteredTypes(){return Array.from(this.queues.keys())}async getQueuedEntityTypes(){let A=[];for(let[Q,w]of this.queues.entries())if(w.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,w)=>{Q.position=w+1})}}class aG{static instance=null;providers=new Map;executionModes=new Map;publishResultIdFields=new Map;publishTimestampFields=new Map;defaultProvider=new ud0;static getInstance(){return aG.instance??=new aG,aG.instance}static resetInstance(){aG.instance=null}static createFresh(){return new aG}constructor(){}register(A,Q,w){let B=this.providers.get(A);if(B&&B.name!=="internal"&&Q.name==="internal")return;if(this.providers.set(A,Q),this.executionModes.set(A,w?.executionMode??"provider"),w?.publishResultIdField)this.publishResultIdFields.set(A,w.publishResultIdField);else this.publishResultIdFields.delete(A);if(w?.publishTimestampField)this.publishTimestampFields.set(A,w.publishTimestampField);else this.publishTimestampFields.delete(A)}get(A){return this.providers.get(A)??this.defaultProvider}getExecutionMode(A){return this.executionModes.get(A)??"provider"}getPublishResultIdField(A){return this.publishResultIdFields.get(A)}getPublishTimestampField(A){return this.publishTimestampFields.get(A)}has(A){return this.providers.has(A)}unregister(A){this.providers.delete(A),this.executionModes.delete(A),this.publishResultIdFields.delete(A),this.publishTimestampFields.delete(A)}getRegisteredTypes(){return Array.from(this.providers.keys())}}Z0();Z0();async function No1(A,Q){if(!Q.publishExecutor){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"Publish executor not configured",retryCount:0,willRetry:!1});return}await tHw(A,Q)}async function tHw(A,Q){if(!Q.publishExecutor)return;try{let w=await Q.publishExecutor.publish({entityType:A.entityType,id:A.entityId});if("error"in w){let B={entityType:A.entityType,entityId:A.entityId,error:w.error,retryCount:0,willRetry:!1};if(Q.messageBus)await Q.messageBus.send({type:RY.FAILED,payload:B,sender:"publish-service"});Q.onFailed?.(B);return}cd0(A.entityType,A.entityId,w.result,Q)}catch(w){let B=vA(w);Q.retryTracker.recordFailure(A.entityId,B);let $=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:B,retryCount:$?.retryCount??1,willRetry:!1})}}function cd0(A,Q,w,B){if(B.retryTracker.clearRetries(Q),B.messageBus)B.messageBus.send({type:RY.COMPLETED,payload:{entityType:A,entityId:Q,result:w},sender:"publish-service"});B.onPublish?.({entityType:A,entityId:Q,result:w})}function jo1(A,Q,w,B){B.retryTracker.recordFailure(Q,w);let $=B.retryTracker.getRetryInfo(Q),Y={entityType:A,entityId:Q,error:w,retryCount:$?.retryCount??1,willRetry:!1};if(B.messageBus)B.messageBus.send({type:RY.FAILED,payload:Y,sender:"publish-service"});B.onFailed?.(Y)}async function Mo1(A,Q){let w=Q.generationConditions[A];if(w&&Q.onCheckGenerationConditions){let $=await Q.onCheckGenerationConditions(A,w);if(!$.shouldGenerate){if(Q.messageBus)Q.messageBus.send({type:gb.SKIPPED,payload:{entityType:A,reason:$.reason??"Conditions not met"},sender:"content-pipeline"});return}}let B={entityType:A};if(Q.messageBus)await Q.messageBus.send({type:gb.EXECUTE,payload:B,sender:"content-pipeline"});Q.onGenerate?.(B)}function _o1(A,Q,w){if(w)w.send({type:gb.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function Po1(A,Q,w){if(w)w.send({type:gb.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var eHw=1000;class ld0{deps;publishJobs=new Map;immediateIntervalJob=null;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.entitySchedules)){let w=this.deps.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,w)}this.immediateIntervalJob=this.deps.config.backend.scheduleInterval(eHw,()=>this.processUnscheduledTypes())}stop(){if(AWw(this.publishJobs),this.immediateIntervalJob)this.immediateIntervalJob.stop(),this.immediateIntervalJob=null}async processEntityType(A){if(!this.deps.isRunning())return;try{let Q=await this.deps.config.queueManager.getNext(A);if(Q)await this.processEntry(Q)}catch(Q){this.deps.config.logger.error(`Scheduler error for ${A}:`,Q)}}async processUnscheduledTypes(){if(!this.deps.isRunning())return;try{let A=await this.deps.config.queueManager.getQueuedEntityTypes();for(let Q of A)if(!this.entitySchedules[Q]){let w=await this.deps.config.queueManager.getNext(Q);if(w){await this.processEntry(w);break}}}catch(A){this.deps.config.logger.error("Scheduler error for unscheduled types:",A)}}async processEntry(A){await this.deps.config.queueManager.remove(A.entityType,A.entityId);let Q=this.deps.getPublishDeps();await No1(A,Q)}get entitySchedules(){return this.deps.config.entitySchedules}}function AWw(A){for(let Q of A.values())Q.stop();A.clear()}class pd0{deps;generationJobs=new Map;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.generationSchedules)){let w=this.deps.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,w)}}stop(){QWw(this.generationJobs)}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await Mo1(A,this.deps.getGenerationDeps())}catch(Q){this.deps.config.logger.error(`Generation trigger error for ${A}:`,Q)}}get generationSchedules(){return this.deps.config.generationSchedules}}function QWw(A){for(let Q of A.values())Q.stop();A.clear()}class LK{static instance=null;config;publishRunner;generationRunner;running=!1;static getInstance(A){return LK.instance??=new LK(A),LK.instance}static resetInstance(){if(LK.instance)LK.instance.stop();LK.instance=null}static createFresh(A){return new LK(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new ld0({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new pd0({config:this.config,getGenerationDeps:()=>this.generationDeps,isRunning:()=>this.running})}async start(){if(this.running)return;this.running=!0,this.publishRunner.start(),this.generationRunner.start()}async stop(){this.running=!1,this.publishRunner.stop(),this.generationRunner.stop()}isRunning(){return this.running}completePublish(A,Q,w){cd0(A,Q,w,this.publishDeps)}failPublish(A,Q,w){jo1(A,Q,w,this.publishDeps)}completeGeneration(A,Q){_o1(A,Q,this.config.messageBus)}failGeneration(A,Q){Po1(A,Q,this.config.messageBus)}get entitySchedules(){return this.config.entitySchedules}get generationSchedules(){return this.config.generationSchedules}get publishDeps(){return{retryTracker:this.config.retryTracker,messageBus:this.config.messageBus,publishExecutor:this.config.publishExecutor,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,w){try{this.config.backend.validateCron(Q)}catch(B){throw Error(`Invalid ${w} cron expression for ${A}: "${Q}" - ${vA(B)}`)}}}class tG{static instance=null;retries=new Map;static getInstance(){return tG.instance??=new tG,tG.instance}static resetInstance(){tG.instance=null}static createFresh(){return new tG}constructor(){}recordFailure(A,Q){let B=(this.retries.get(A)?.retryCount??0)+1;this.retries.set(A,{entityId:A,retryCount:B,lastError:Q})}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}}}function P4(A,Q,w,B,$,Y,D,X){return P4.fromTZ(P4.tp(A,Q,w,B,$,Y,D),X)}P4.fromTZISO=(A,Q,w)=>P4.fromTZ(wWw(A,Q),w);P4.fromTZ=function(A,Q){let w=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),B=id0(A.tz,w),$=new Date(w.getTime()-B),Y=id0(A.tz,$);if(Y-B===0)return $;{let D=new Date(w.getTime()-Y),X=id0(A.tz,D);if(X-Y===0)return D;if(!Q&&X-Y>0)return D;if(Q)throw Error("Invalid date passed to fromTZ()");return $}};P4.toTZ=function(A,Q){let w=A.toLocaleString("en-US",{timeZone:Q}).replace(/[\u202f]/," "),B=new Date(w);return{y:B.getFullYear(),m:B.getMonth()+1,d:B.getDate(),h:B.getHours(),i:B.getMinutes(),s:B.getSeconds(),tz:Q}};P4.tp=(A,Q,w,B,$,Y,D)=>({y:A,m:Q,d:w,h:B,i:$,s:Y,tz:D});function id0(A,Q=new Date){let w=Q.toLocaleString("en-US",{timeZone:A,timeZoneName:"shortOffset"}).split(" ").slice(-1)[0],B=Q.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${B} GMT`)-Date.parse(`${B} ${w}`)}function wWw(A,Q){let w=new Date(Date.parse(A));if(isNaN(w))throw Error("minitz: Invalid ISO8601 passed to parser.");let B=A.substring(9);return A.includes("Z")||B.includes("-")||B.includes("+")?P4.tp(w.getUTCFullYear(),w.getUTCMonth()+1,w.getUTCDate(),w.getUTCHours(),w.getUTCMinutes(),w.getUTCSeconds(),"Etc/UTC"):P4.tp(w.getFullYear(),w.getMonth()+1,w.getDate(),w.getHours(),w.getMinutes(),w.getSeconds(),Q)}P4.minitz=P4;var dd0=32,Ko=31|dd0,Ro1=[1,2,4,8,16],ko1=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 Xf(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,Ko),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(A,Q,w,B){let $=this[A],Y=A==="day"&&this.lastDayOfMonth;if(Q===""&&!Y)throw TypeError("CronPattern: configuration entry "+A+" ("+Q+") is empty, check for trailing spaces.");if(Q==="*")return $.fill(B);let D=Q.split(",");if(D.length>1)for(let X=0;X<D.length;X++)this.partToArray(A,D[X],w,B);else Q.indexOf("-")!==-1&&Q.indexOf("/")!==-1?this.handleRangeWithStepping(Q,A,w,B):Q.indexOf("-")!==-1?this.handleRange(Q,A,w,B):Q.indexOf("/")!==-1?this.handleStepping(Q,A,w,B):Q!==""&&this.handleNumber(Q,A,w,B)}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,w,B){let $=this.extractNth(A,Q),Y=parseInt($[0],10)+w;if(isNaN(Y))throw TypeError("CronPattern: "+Q+" is not a number: '"+A+"'");this.setPart(Q,Y,$[1]||B)}setPart(A,Q,w){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,w);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]=w}handleRangeWithStepping(A,Q,w,B){let $=this.extractNth(A,Q),Y=$[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(Y===null)throw TypeError("CronPattern: Syntax error, illegal range with stepping: '"+A+"'");let[,D,X,H]=Y,W=parseInt(D,10)+w,f=parseInt(X,10)+w,Z=parseInt(H,10);if(isNaN(W))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(f))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(Z))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(Z===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(Z>this[Q].length)throw TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[Q].length+")");if(W>f)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let G=W;G<=f;G+=Z)this.setPart(Q,G,$[1]||B)}extractNth(A,Q){let w=A,B;if(w.includes("#")){if(Q!=="dayOfWeek")throw Error("CronPattern: nth (#) only allowed in day-of-week field");B=w.split("#")[1],w=w.split("#")[0]}return[w,B]}handleRange(A,Q,w,B){let $=this.extractNth(A,Q),Y=$[0].split("-");if(Y.length!==2)throw TypeError("CronPattern: Syntax error, illegal range: '"+A+"'");let D=parseInt(Y[0],10)+w,X=parseInt(Y[1],10)+w;if(isNaN(D))throw TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(X))throw TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(D>X)throw TypeError("CronPattern: From value is larger than to value: '"+A+"'");for(let H=D;H<=X;H++)this.setPart(Q,H,$[1]||B)}handleStepping(A,Q,w,B){let $=this.extractNth(A,Q),Y=$[0].split("/");if(Y.length!==2)throw TypeError("CronPattern: Syntax error, illegal stepping: '"+A+"'");Y[0]===""&&(Y[0]="*");let D=0;Y[0]!=="*"&&(D=parseInt(Y[0],10)+w);let X=parseInt(Y[1],10);if(isNaN(X))throw TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(X===0)throw TypeError("CronPattern: Syntax error, illegal stepping: 0");if(X>this[Q].length)throw TypeError("CronPattern: Syntax error, max steps for part is ("+this[Q].length+")");for(let H=D;H<this[Q].length;H+=X)this.setPart(Q,H,$[1]||B)}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]|dd0;else if(Q===Ko)this.dayOfWeek[A]=Ko;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|Ro1[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Oo1=[31,28,31,30,31,30,31,31,30,31,30,31],JF=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]],Xf=class A{tz;ms;second;minute;hour;day;month;year;constructor(Q,w){if(this.tz=w,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,w,B,$){let Y=new Date(Date.UTC(Q,w,B)).getUTCDay(),D=0;for(let X=1;X<=B;X++)new Date(Date.UTC(Q,w,X)).getUTCDay()===Y&&D++;if($&Ko&&Ro1[D-1]&$)return!0;if($&dd0){let X=new Date(Date.UTC(Q,w+1,0)).getUTCDate();for(let H=B+1;H<=X;H++)if(new Date(Date.UTC(Q,w,H)).getUTCDay()===Y)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 w=P4.toTZ(Q,this.tz);this.ms=Q.getMilliseconds(),this.second=w.s,this.minute=w.i,this.hour=w.h,this.day=w.d,this.month=w.m-1,this.year=w.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>Oo1[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 w=P4.fromTZISO(Q);this.ms=w.getUTCMilliseconds(),this.second=w.getUTCSeconds(),this.minute=w.getUTCMinutes(),this.hour=w.getUTCHours(),this.day=w.getUTCDate(),this.month=w.getUTCMonth(),this.year=w.getUTCFullYear(),this.apply()}else return this.fromDate(P4.fromTZISO(Q,this.tz))}findNext(Q,w,B,$){let Y=this[w],D;B.lastDayOfMonth&&(this.month!==1?D=Oo1[this.month]:D=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate());let X=!B.starDOW&&w=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let H=this[w]+$;H<B[w].length;H++){let W=B[w][H];if(w==="day"&&B.lastDayOfMonth&&H-$==D&&(W=1),w==="day"&&!B.starDOW){let f=B.dayOfWeek[(X+(H-$-1))%7];if(f&&f&Ko)f=this.isNthWeekdayOfMonth(this.year,this.month,H-$,f)?1:0;else if(f)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${f}`);Q.legacyMode&&!B.starDOM?W=W||f:W=W&&f}if(W)return this[w]=H-$,Y!==this[w]?2:1}return 3}recurse(Q,w,B){let $=this.findNext(w,JF[B][0],Q,JF[B][2]);if($>1){let Y=B+1;for(;Y<JF.length;)this[JF[Y][0]]=-JF[Y][2],Y++;if($===3)return this[JF[B][1]]++,this[JF[B][0]]=-JF[B][2],this.apply(),this.recurse(Q,w,0);if(this.apply())return this.recurse(Q,w,B-1)}return B+=1,B>=JF.length?this:this.year>=3000?null:this.recurse(Q,w,B)}increment(Q,w,B){return this.second+=w.interval!==void 0&&w.interval>1&&B?w.interval:1,this.ms=0,this.apply(),this.recurse(Q,w,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)):P4.fromTZ(P4.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function BWw(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 Xf(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new Xf(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 Zo(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function $Ww(A){return Zo(A)}function YWw(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var xo1=30000,aY0=[],nd0=class{name;options;_states;fn;constructor(A,Q,w){let B,$;if(Zo(Q))$=Q;else if(typeof Q=="object")B=Q;else if(Q!==void 0)throw Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");if(Zo(w))$=w;else if(typeof w=="object")B=w;else if(w!==void 0)throw Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");if(this.name=B?.name,this.options=BWw(B),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:B?B.maxRuns:void 0,paused:B?B.paused:!1,pattern:new ko1("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new Xf(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new ko1(A,this.options.timezone),this.name){if(aY0.find((Y)=>Y.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");aY0.push(this)}return $!==void 0&&$Ww($)&&(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 w=[],B=Q||this._states.currentRun||void 0;for(;A--&&(B=this.nextRun(B));)w.push(B);return w}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let A=this.nextRun(this._states.currentRun),Q=!this._states.paused,w=this.fn!==void 0,B=!this._states.kill;return Q&&w&&B&&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 Xf||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new Xf(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=aY0.indexOf(this);A>=0&&aY0.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(),w=this.nextRun(this._states.currentRun);return Q==null||isNaN(Q)||w===null?this:(Q>xo1&&(Q=xo1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(w),Q),this._states.currentTimeout&&this.options.unref&&YWw(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new Xf(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){Zo(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Xf(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,w=!this._states.paused&&Q.getTime()>=A.getTime(),B=this._states.blocking&&this.options.protect;w&&!B?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):w&&B&&Zo(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(A){let Q=!!(A||this._states.currentRun),w=!1;!A&&this.options.startAt&&this.options.interval&&([A,Q]=this._calculatePreviousRun(A,Q),w=!A),A=new Xf(A,this.options.timezone||this.options.utcOffset),this.options.startAt&&A&&A.getTime()<this.options.startAt.getTime()&&(A=this.options.startAt);let B=this._states.once||new Xf(A,this.options.timezone||this.options.utcOffset);return!w&&B!==this._states.once&&(B=B.increment(this._states.pattern,this.options,Q)),this._states.once&&this._states.once.getTime()<=A.getTime()||B===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&B.getTime()>=this.options.stopAt.getTime()?null:B}_calculatePreviousRun(A,Q){let w=new Xf(void 0,this.options.timezone||this.options.utcOffset),B=A;if(this.options.startAt.getTime()<=w.getTime()){B=this.options.startAt;let $=B.getTime()+this.options.interval*1000;for(;$<=w.getTime();)B=new Xf(B,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),$=B.getTime()+this.options.interval*1000;Q=!0}return B===null&&(B=void 0),[B,Q]}};class tY0{scheduleCron(A,Q){let w=new nd0(A,()=>{Q()});return{stop:()=>w.stop()}}scheduleInterval(A,Q){let w=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(w)}}validateCron(A){new nd0(A).stop()}}Z0();var ho1=K.union([K.string().min(1),K.object({location:K.enum(["metadata","frontmatter"]),field:K.string().min(1)})]),eY0=K.object({entityType:K.string().min(1),attachmentType:K.string().min(1),mediaEntityType:K.enum(["image","document"]),targetEntityField:ho1.optional(),requiredWhen:K.object({status:K.string().min(1).optional(),visibility:K.string().min(1).optional()}).optional(),autoGenerate:K.boolean().optional(),requiredForPublish:K.boolean().optional(),jobType:K.string().min(1).optional()});function rd0(A){return`${A.entityType}:${A.attachmentType}`}class eG{static instance=null;definitions=new Map;static getInstance(){return eG.instance??=new eG,eG.instance}static resetInstance(){eG.instance=null}static createFresh(){return new eG}constructor(){}register(A){let Q=eY0.parse(A),w=rd0(Q);return this.definitions.set(w,Q),()=>this.unregister(Q.entityType,Q.attachmentType)}get(A,Q){return this.definitions.get(rd0({entityType:A,attachmentType:Q}))}list(A){let Q=Array.from(this.definitions.values());return A?Q.filter((w)=>w.entityType===A):Q}has(A,Q){return this.get(A,Q)!==void 0}unregister(A,Q){this.definitions.delete(rd0({entityType:A,attachmentType:Q}))}clear(){this.definitions.clear()}}Z0();class AD0{deps;constructor(A){this.deps=A}async ensureForEntity(A,Q={}){let w=this.deps.registry.list(A.entityType).filter(($)=>$.autoGenerate===!0).filter(($)=>!Q.attachmentType||$.attachmentType===Q.attachmentType),B={checked:w.length,enqueued:0,skipped:0};for(let $ of w)if(await this.ensureDefinition(A,$))B.enqueued+=1;else B.skipped+=1;return B}async ensureDefinition(A,Q){if(!this.matchesPolicy(A,Q))return!1;if(this.hasTargetField(A,Q.targetEntityField))return!1;if(!this.deps.context.attachments.hasProvider(A.entityType,Q.attachmentType))return!1;let w=this.resolveJobType(Q);if(!w)return!1;let B=this.getPredictedMediaId(A,Q),$=this.getDeduplicationKey(A,Q);return await this.deps.context.jobs.enqueue({type:w,data:{sourceEntityType:A.entityType,sourceEntityId:A.id,attachmentType:Q.attachmentType,imageId:B,dedupKey:$,targetEntityType:A.entityType,targetEntityId:A.id,...this.getTargetImageFieldData(Q.targetEntityField)},options:{source:"content-pipeline",metadata:{operationType:"content_operations"},deduplication:"skip",deduplicationKey:$}}),this.deps.context.logger.debug("Queued publish asset generation",{entityType:A.entityType,entityId:A.id,attachmentType:Q.attachmentType,jobType:w}),!0}matchesPolicy(A,Q){let{requiredWhen:w}=Q;if(!w)return!0;if(w.status&&A.metadata.status!==w.status)return!1;if(w.visibility&&A.visibility!==w.visibility)return!1;return!0}hasTargetField(A,Q){if(!Q)return!1;if(typeof Q==="string")return od0(A.metadata[Q]);if(Q.location==="metadata")return od0(A.metadata[Q.field]);let{frontmatter:w}=lw(A.content);return od0(w[Q.field])}resolveJobType(A){if(A.jobType)return A.jobType;if(A.mediaEntityType==="image")return"image:image-render-source";return}getPredictedMediaId(A,Q){let w=Q.attachmentType==="og-image"?"og":Q.attachmentType;return w1(`${w}-${A.entityType}-${A.id}`)}getDeduplicationKey(A,Q){return`publish-asset:${Q.attachmentType}:${A.entityType}:${A.id}`}getTargetImageFieldData(A){let Q=typeof A==="string"?A:A?.field;if(Q==="coverImageId"||Q==="ogImageId")return{targetImageField:Q};return{}}}function od0(A){return typeof A==="string"?A.length>0:A!==void 0}c0();Z0();var DWw=K.object({id:K.string().min(1)});async function Co1(A,Q){let{bodyContent:w,coverImageId:B,documents:$,sourceEntityType:Y,sourceEntityId:D}=XWw(Q.content),X=B?await fWw(A,B):void 0,H;if($&&$.length>0){let f=await ZWw(A,$);if(f.length>0)H=f}H??=await WWw(A,Y,D);let W={bodyContent:w};if(X)W.imageData=X;if(H&&H.length>0)W.documentData=H;return W}function XWw(A){try{let Q=v2(A,K.record(K.unknown())),w=Q.metadata.coverImageId,B=typeof w==="string"?w:void 0,$=HWw(Q.metadata.documents),Y=vo1(Q.metadata.sourceEntityType),D=vo1(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...B&&{coverImageId:B},...$.length>0&&{documents:$},...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}}}catch{return{bodyContent:A}}}function HWw(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let w=DWw.safeParse(Q);return w.success?[w.data]:[]})}function vo1(A){return typeof A==="string"&&A.length>0?A:void 0}async function WWw(A,Q,w){if(!Q||!w)return;let B=await A.attachments.resolve({sourceEntityType:Q,sourceEntityId:w,attachmentType:"carousel"});return B?[B]:void 0}async function fWw(A,Q){let w=await A.entityService.getEntity({entityType:"image",id:Q});if(!w?.content)return;let B=yo1(w.content);if(!B?.mimeType.startsWith("image/"))return;return{data:B.data,mimeType:B.mimeType}}async function ZWw(A,Q){return(await Promise.all(Q.map((B)=>KWw(A,B)))).filter((B)=>B!==void 0)}async function KWw(A,Q){let w=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!w?.content)return;let B=yo1(w.content);if(B?.mimeType!=="application/pdf")return;return{type:"document",data:B.data,mimeType:"application/pdf",filename:UWw(w,Q.id)}}function yo1(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function UWw(A,Q){let w=A.metadata.filename;return typeof w==="string"&&w.length>0?w:`${Q}.pdf`}Z0();var GWw=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;async function sd0(A,Q,w,B={}){let $=B.publishTimestampField??"publishedAt",Y=Q.metadata[$],D=B.publishedAt??(typeof Y==="string"?Y:void 0)??new Date().toISOString(),X={...Q.metadata,status:"published",[$]:D,platformId:w.id,...zWw(w.id,B.publishResultIdField)},H={...Q,content:Eo1(Q.content,D,w.id,B.publishResultIdField,$),metadata:X};return await A.entityService.updateEntity({entity:H}),H}function Eo1(A,Q,w,B,$="publishedAt"){if(!GWw.test(A))return A;let Y=o4(o4(A,"status","published"),$,Q);if(!w||!B)return Y;return o4(Y,B,w)}function zWw(A,Q){if(!Q||Q==="platformId")return{};return{[Q]:A}}class jE{deps;constructor(A){this.deps=A}async resolveCandidate(A){let{entityType:Q,id:w,slug:B}=A;if(!w&&!B)return{error:"Either 'id' or 'slug' must be provided"};let $=await this.findPublishableEntity(Q,w,B);if(!$)return{error:`Entity not found: ${Q}:${w??B}`};if($.visibility!=="public")return{error:`Cannot publish ${Q}:${$.id} to a public provider because visibility is ${$.visibility}`};if($.metadata.status==="published")return{error:"Entity is already published"};if(!this.deps.providerRegistry.has(Q))return{error:`No publish provider registered for ${Q}. Check that the required credentials are configured.`};return{entity:$}}async publish(A){let Q=await this.resolveCandidate(A);if("error"in Q)return Q;let{entity:w}=Q,{entityType:B}=A,$=this.deps.providerRegistry.get(B),{bodyContent:Y,imageData:D,documentData:X}=await Co1(this.deps.context,w),H=await $.publish(Y,w.metadata,D,X),W=this.deps.providerRegistry.getPublishResultIdField(B),f=this.deps.providerRegistry.getPublishTimestampField(B),Z=await sd0(this.deps.context,w,H,{...W?{publishResultIdField:W}:{},...f?{publishTimestampField:f}:{}});return await this.runPublishAssetPreflight(Z),{entity:Z,result:H}}async runPublishAssetPreflight(A){if(!this.deps.publishAssetPreflight)return;try{await this.deps.publishAssetPreflight.ensureForEntity(A)}catch(Q){this.deps.context.logger.warn("Publish asset preflight failed",{entityType:A.entityType,entityId:A.id,error:Q instanceof Error?Q.message:String(Q)})}}async findPublishableEntity(A,Q,w){if(Q)return this.deps.context.entityService.getEntity({entityType:A,id:Q});if(!w)return null;return(await this.deps.context.entityService.listEntities({entityType:A,options:{filter:{metadata:{slug:w}},limit:1}}))[0]??null}}c0();Z0();var ad0=K.object({action:K.enum(["list","add","remove","reorder"]).describe("Queue action to perform"),entityType:K.string().optional().describe("Entity type (required for add/remove/reorder, optional for list)"),entityId:K.string().optional().describe("Entity ID (required for add/remove/reorder)"),position:K.number().optional().describe("New position for reorder action (1-based)")}),td0=K.object({position:K.number(),entityType:K.string(),entityId:K.string(),queuedAt:K.string()}),qWw=K.object({success:K.literal(!0),message:K.string().optional(),data:K.object({queue:K.array(td0).optional(),entityType:K.string().optional(),entityId:K.string().optional(),position:K.number().optional()}).optional()}),FWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),ed0=K.union([qWw,FWw]);function QD0(A,Q,w){return{...Sw(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",ad0,async($,Y)=>{let{action:D,entityType:X,entityId:H,position:W}=$;switch(D){case"list":return VWw(w,X);case"add":return JWw(A,w,X,H,Y);case"remove":return IWw(A,w,X,H,Y);case"reorder":return bWw(A,w,X,H,W,Y);default:return{success:!1,error:`Unknown action: ${D}`}}},{sideEffects:"writes"}),outputSchema:ed0}}async function VWw(A,Q){let w=[];if(Q)w=await A.list(Q);else{let $=A.getRegisteredTypes();for(let Y of $){let D=await A.list(Y);w.push(...D)}w.sort((Y,D)=>new Date(Y.queuedAt).getTime()-new Date(D.queuedAt).getTime())}if(w.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:w.map(($,Y)=>({position:Y+1,entityType:$.entityType,entityId:$.entityId,queuedAt:$.queuedAt}))},message:`${w.length} items in queue`}}async function JWw(A,Q,w,B,$){let Y=An0("add",w,B);if(!Y.success)return Y.error;A.permissions.assertEntityActionAllowed(Y.entityType,"publish",$??{});let D=await Q.add(Y.entityType,Y.entityId,{...$,authorization:"user"});return{success:!0,data:{entityType:Y.entityType,entityId:Y.entityId,position:D.position},message:`Added to queue at position ${D.position}`}}async function IWw(A,Q,w,B,$){let Y=An0("remove",w,B);if(!Y.success)return Y.error;return A.permissions.assertEntityActionAllowed(Y.entityType,"update",$??{}),await Q.remove(Y.entityType,Y.entityId),{success:!0,data:{entityType:Y.entityType,entityId:Y.entityId},message:"Removed from queue"}}async function bWw(A,Q,w,B,$,Y){let D=An0("reorder",w,B);if(!D.success)return D.error;let X=LWw($);if(!X.success)return X.error;return A.permissions.assertEntityActionAllowed(D.entityType,"update",Y??{}),await Q.reorder(D.entityType,D.entityId,X.position),{success:!0,data:{entityType:D.entityType,entityId:D.entityId,position:X.position},message:`Moved to position ${X.position}`}}function An0(A,Q,w){if(!Q)return{success:!1,error:{success:!1,error:`entityType is required for ${A} action`}};if(!w)return{success:!1,error:{success:!1,error:`entityId is required for ${A} action`}};return{success:!0,entityType:Q,entityId:w}}function LWw(A){if(A===void 0)return{success:!1,error:{success:!1,error:"position is required for reorder action"}};if(A<1)return{success:!1,error:{success:!1,error:"position must be a positive number"}};return{success:!0,position:A}}Z0();import{createHash as NWw}from"crypto";var wD0=K.object({entityType:K.string().describe("Entity type to publish (e.g., social-post, post, deck)"),id:K.string().optional().describe("Entity ID to publish"),slug:K.string().optional().describe("Entity slug to publish"),confirmed:K.boolean().optional(),confirmationToken:K.string().optional(),contentHash:K.string().optional(),expiresAt:K.string().datetime().optional()}),jWw=K.object({success:K.literal(!0),message:K.string().optional(),data:K.object({entityType:K.string().optional(),entityId:K.string().optional(),platformId:K.string().optional(),url:K.string().optional()}).optional()}),MWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),_Ww=K.object({success:K.literal(!1).optional(),error:K.string().optional(),needsConfirmation:K.literal(!0),toolName:K.string(),summary:K.string(),preview:K.string().optional(),args:K.unknown()}),Qn0=K.union([jWw,MWw,_Ww]),PWw=900000;function BD0(A,Q,w,B){let $=B??new jE({context:A,providerRegistry:w}),Y=`${Q}_publish`;return{name:Y,description:"Publish an entity directly to its platform. Call this when the user asks to publish; the tool will request confirmation itself. Works with any registered entity type (social-post, post, deck, etc.)",inputSchema:wD0.shape,outputSchema:Qn0,visibility:"anchor",sideEffects:"external",handler:async(D,X)=>{let H=wD0.safeParse(D);if(!H.success)return{success:!1,error:`Invalid input: ${H.error.errors.map((b)=>`${b.path.join(".")}: ${b.message}`).join(", ")}`};let W=H.data,{entityType:f,id:Z,slug:G}=W;try{A.permissions.assertEntityActionAllowed(f,"publish",X)}catch(b){return{success:!1,error:b instanceof Error?b.message:String(b)}}let F=await $.resolveCandidate({entityType:f,id:Z,slug:G});if("error"in F)return{success:!1,error:F.error};let{entity:V}=F;if(W.confirmed){let b=OWw(Y,W,V);if(b!==null)return b;let L;try{L=await $.publish({entityType:f,id:V.id})}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}if("error"in L)return{success:!1,error:L.error};let{entity:N,result:_}=L;return{success:!0,data:{entityType:f,entityId:N.id,platformId:_.id,url:_.url},message:`Published ${f}:${N.id}`}}return kWw(Y,W,V)}}}function kWw(A,Q,w){let B=new Date(Date.now()+PWw).toISOString(),$=go1(A,w,B),Y=xWw(w);return{needsConfirmation:!0,toolName:A,summary:`Publish "${Y}"?`,preview:`This will publish ${w.entityType}:${w.id} to its registered public publish provider.`,args:{...Q,id:w.id,slug:void 0,confirmed:!0,confirmationToken:$,contentHash:w.contentHash,expiresAt:B}}}function OWw(A,Q,w){let{confirmationToken:B,contentHash:$,expiresAt:Y}=Q;if(!B||!Y)return{success:!1,error:"Invalid publish confirmation token. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};let D=Date.parse(Y);if(Number.isNaN(D))return{success:!1,error:"Invalid publish confirmation expiry. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};if(D<=Date.now())return{success:!1,error:"Publish confirmation expired. Request confirmation again before publishing.",code:"EXPIRED_CONFIRMATION_TOKEN"};if($&&$!==w.contentHash)return{success:!1,error:`Cannot publish ${w.entityType}:${w.id} because it changed after confirmation. Review it and try again.`};if(B!==go1(A,w,Y))return{success:!1,error:"Invalid publish confirmation token. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};return null}function go1(A,Q,w){return NWw("sha256").update(A).update("\x00").update(Q.entityType).update("\x00").update(Q.id).update("\x00").update(Q.contentHash).update("\x00").update(w).digest("hex")}function xWw(A){let Q=A.metadata.title;if(typeof Q==="string"&&Q.length>0)return Q;let w=A.metadata.subject;if(typeof w==="string"&&w.length>0)return w;let B=A.metadata.slug;if(typeof B==="string"&&B.length>0)return B;return A.id}c0();Z0();var wn0=K.object({entityType:K.string().min(1).describe("Entity type to reconcile"),status:K.string().min(1).optional().describe("Optional metadata status filter, e.g. published"),assetType:K.string().min(1).optional().describe("Optional attachment type filter, e.g. og-image")}),Bn0=K.object({success:K.literal(!0),data:K.object({entityType:K.string(),assetType:K.string().optional(),checkedEntities:K.number(),checkedAssets:K.number(),enqueued:K.number(),skipped:K.number()}),message:K.string().optional()});function $D0(A,Q,w,B){return{...Sw(Q,"ensure-assets","Reconcile configured publish assets for existing entities, queueing missing generated assets such as OG images.",wn0,async(Y,D)=>{if(A.permissions.assertEntityActionAllowed(Y.entityType,"publish",D),w.list(Y.entityType).filter((G)=>G.autoGenerate===!0).filter((G)=>!Y.assetType||G.attachmentType===Y.assetType).length===0)return{success:!0,data:{entityType:Y.entityType,...Y.assetType&&{assetType:Y.assetType},checkedEntities:0,checkedAssets:0,enqueued:0,skipped:0},message:`No publish assets configured for ${Y.entityType}`};let H=await A.entityService.listEntities({entityType:Y.entityType,options:{...Y.status&&{filter:{metadata:{status:Y.status}}}}}),W=0,f=0,Z=0;for(let G of H){let F=await B.ensureForEntity(G,{...Y.assetType&&{attachmentType:Y.assetType}});W+=F.checked,f+=F.enqueued,Z+=F.skipped}return{success:!0,data:{entityType:Y.entityType,...Y.assetType&&{assetType:Y.assetType},checkedEntities:H.length,checkedAssets:W,enqueued:f,skipped:Z},message:`Queued ${f} publish asset job(s)`}},{sideEffects:"writes"}),outputSchema:Bn0}}c0();Z0();function To1(A,Q){RWw(A,Q),hWw(A,Q),vWw(A,Q),CWw(A,Q)}function RWw(A,Q){A.messaging.subscribe(RY.REGISTER,async(w)=>yWw(Q,w.payload)),A.messaging.subscribe(RY.QUEUE,async(w)=>SWw(A,Q,w.payload)),A.messaging.subscribe(RY.DIRECT,async(w)=>mWw(A,Q,w.payload)),A.messaging.subscribe(RY.REMOVE,async(w)=>uWw(Q,w.payload)),A.messaging.subscribe(RY.REORDER,async(w)=>cWw(Q,w.payload)),A.messaging.subscribe(RY.LIST,async(w)=>lWw(A,Q,w.payload)),A.messaging.subscribe(RY.REPORT_SUCCESS,async(w)=>pWw(Q,w.payload)),A.messaging.subscribe(RY.REPORT_FAILURE,async(w)=>iWw(Q,w.payload)),Q.logger.debug("Subscribed to publish messages")}function hWw(A,Q){A.messaging.subscribe(gb.REPORT_SUCCESS,async(w)=>dWw(Q,w.payload)),A.messaging.subscribe(gb.REPORT_FAILURE,async(w)=>nWw(Q,w.payload)),Q.logger.debug("Subscribed to generation messages")}function vWw(A,Q){A.messaging.subscribe(Io1.REGISTER,async(w)=>EWw(Q,w.payload)),Q.logger.debug("Subscribed to publish asset messages")}function CWw(A,Q){let w=async(B)=>gWw(A,Q,B.payload);A.messaging.subscribe("entity:created",w),A.messaging.subscribe("entity:updated",w),Q.logger.debug("Subscribed to entity change messages for publish assets")}async function yWw(A,Q){let{entityType:w,provider:B,config:$}=Q;try{let Y=$?bo1.safeParse($):void 0;if(Y&&!Y.success)return A.logger.warn("Invalid publish provider config",{entityType:w,error:Y.error.message}),{success:!1};if(B)A.providerRegistry.register(w,B,Y?.data),A.logger.info(`Registered provider for entity type: ${w}`,{providerName:B.name,executionMode:A.providerRegistry.getExecutionMode(w)});return{success:!0}}catch(Y){let D=vA(Y);return A.logger.error(`Failed to register provider: ${D}`),{success:!1}}}async function EWw(A,Q){let w=eY0.safeParse(Q);if(!w.success)return A.logger.warn("Invalid publish asset registration",{error:w.error.message}),{success:!1};return A.publishAssetRegistry.register(w.data),A.logger.info("Registered publish asset",{entityType:w.data.entityType,attachmentType:w.data.attachmentType,mediaEntityType:w.data.mediaEntityType}),{success:!0}}async function gWw(A,Q,w){try{if(Q.publishAssetRegistry.list(w.entityType).length===0)return{success:!0};let B=w.entity??await A.entityService.getEntity({entityType:w.entityType,id:w.entityId});if(!TWw(B))return{success:!0};return await Q.publishAssetPreflight.ensureForEntity(B),{success:!0}}catch(B){return Q.logger.warn("Failed to run publish asset preflight for entity event",{entityType:w.entityType,entityId:w.entityId,error:vA(B)}),{success:!1}}}function TWw(A){if(!A)return!1;let Q=Jo1.safeParse(A.metadata);return Q.success&&Q.data.status==="published"}async function SWw(A,Q,w){let{entityType:B,entityId:$}=w;try{let Y=w.authContext??fo;A.permissions.assertEntityActionAllowed(B,"publish",Y);let D=await Q.queueManager.add(B,$,Y);return await A.messaging.send({type:RY.QUEUED,payload:{entityType:B,entityId:$,position:D.position}}),Q.logger.debug(`Entity queued: ${$}`,{entityType:B,position:D.position}),{success:!0}}catch(Y){let D=vA(Y);return Q.logger.error(`Failed to queue entity: ${D}`),{success:!1}}}async function mWw(A,Q,w){let{entityType:B,entityId:$}=w,Y=w.authContext??fo;try{if(A.permissions.assertEntityActionAllowed(B,"publish",Y),!Q.providerRegistry.has(B))return Q.scheduler.failPublish(B,$,`No publish provider registered for ${B}`),{success:!1};let D=await Q.publishExecutor.publish({entityType:B,id:$});if("error"in D)return Q.scheduler.failPublish(B,$,D.error),{success:!1};return Q.scheduler.completePublish(B,$,D.result),Q.logger.debug(`Direct publish completed: ${$}`,{entityType:B}),{success:!0}}catch(D){let X=vA(D);return Q.logger.error(`Failed direct publish request: ${X}`),{success:!1}}}async function uWw(A,Q){let{entityType:w,entityId:B}=Q;try{return await A.queueManager.remove(w,B),A.logger.debug(`Entity removed from queue: ${B}`,{entityType:w}),{success:!0}}catch($){let Y=vA($);return A.logger.error(`Failed to remove entity: ${Y}`),{success:!1}}}async function cWw(A,Q){let{entityType:w,entityId:B,position:$}=Q;try{return await A.queueManager.reorder(w,B,$),A.logger.debug(`Entity reordered: ${B}`,{entityType:w,newPosition:$}),{success:!0}}catch(Y){let D=vA(Y);return A.logger.error(`Failed to reorder entity: ${D}`),{success:!1}}}async function lWw(A,Q,w){let{entityType:B}=w;try{let $=await Q.queueManager.list(B);return await A.messaging.send({type:RY.LIST_RESPONSE,payload:{entityType:B,queue:$.map((Y)=>({entityId:Y.entityId,position:Y.position,queuedAt:Y.queuedAt}))}}),{success:!0}}catch($){let Y=vA($);return Q.logger.error(`Failed to list queue: ${Y}`),{success:!1}}}async function pWw(A,Q){let{entityType:w,entityId:B,result:$}=Q;return A.scheduler.completePublish(w,B,$),A.logger.info(`Publish reported success: ${B}`,{entityType:w}),{success:!0}}async function iWw(A,Q){let{entityType:w,entityId:B,error:$}=Q;A.scheduler.failPublish(w,B,$);let Y=A.retryTracker.getRetryInfo(B);return A.logger.info(`Publish reported failure: ${B}`,{entityType:w,error:$,retryCount:Y?.retryCount}),{success:!0}}async function dWw(A,Q){let{entityType:w,entityId:B}=Q;return A.scheduler.completeGeneration(w,B),A.logger.info("Generation completed",{entityType:w,entityId:B}),{success:!0}}async function nWw(A,Q){let{entityType:w,error:B}=Q;return A.scheduler.failGeneration(w,B),A.logger.warn("Generation failed",{entityType:w,error:B}),{success:!0}}Z0();async function So1(A,Q,w,B){try{if(B.skipIfDraftExists!==!1){if((await A.listEntities({entityType:w,options:{filter:{metadata:{status:"draft"}},limit:1}})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(B.maxUnpublishedDrafts!==void 0){let $=await A.listEntities({entityType:w,options:{filter:{metadata:{status:"draft"}},limit:B.maxUnpublishedDrafts+1}});if($.length>=B.maxUnpublishedDrafts)return{shouldGenerate:!1,reason:`Max unpublished drafts reached (${$.length}/${B.maxUnpublishedDrafts})`}}if(B.minSourceEntities!==void 0&&B.sourceEntityType){let $=await A.listEntities({entityType:B.sourceEntityType,options:{publishedOnly:!0,limit:B.minSourceEntities}});if($.length<B.minSourceEntities)return{shouldGenerate:!1,reason:`Not enough source entities (${$.length}/${B.minSourceEntities} ${B.sourceEntityType})`}}return{shouldGenerate:!0}}catch($){return Q.error("Failed to check generation conditions",{entityType:w,error:vA($)}),{shouldGenerate:!1,reason:`Condition check failed: ${vA($)}`}}}function mo1(A){let{context:Q,config:w,queueManager:B,providerRegistry:$,retryTracker:Y,publishExecutor:D,logger:X}=A,H=rWw(Q);return LK.createFresh({queueManager:B,providerRegistry:$,retryTracker:Y,logger:X,backend:new tY0,...w.entitySchedules&&{entitySchedules:w.entitySchedules},...w.generationSchedules&&{generationSchedules:w.generationSchedules},...w.generationConditions&&{generationConditions:w.generationConditions},messageBus:H,publishExecutor:D,onCheckGenerationConditions:(W,f)=>So1(Q.entityService,X,W,f)})}function rWw(A){return{send:async($)=>{return A.messaging.send({type:$.type,payload:$.payload,...$.target!==void 0?{target:$.target}:{},...$.metadata!==void 0?{metadata:$.metadata}:{},...$.broadcast!==void 0?{broadcast:$.broadcast}:{}})},subscribe:()=>()=>{},unsubscribe:()=>{}}}async function uo1(A,Q,w){let B=A.getEntityTypes();for(let Y of B){let D=await A.listEntities({entityType:Y,options:{filter:{metadata:{status:"queued"}}}});for(let X of D)await Q.add(X.entityType,X.id)}let $=0;for(let Y of B){let D=await Q.list(Y);$+=D.length}if($>0)w.info(`Rebuilt queue with ${$} queued entities`)}var oWw=["draft","queued","published","failed"];async function co1(A,Q){await A.messaging.send({type:"dashboard:register-widget",payload:{id:"publication-pipeline",pluginId:Q,title:"Publication Pipeline",section:"secondary",priority:100,rendererName:"PipelineWidget",visibility:"anchor",dataProvider:()=>sWw(A)}})}async function sWw(A){let Q=A.entityService.getEntityTypes(),w=[],B={draft:0,queued:0,published:0,failed:0};for(let $ of Q){let Y=await A.entityService.listEntities({entityType:$});for(let D of Y){let X=aWw(D.metadata.status);if(!X)continue;B[X]++,w.push({id:D.id,title:tWw(D.id,D.metadata.title),type:$,status:X})}}return{summary:B,items:w}}function aWw(A){return oWw.find((Q)=>Q===A)}function tWw(A,Q){return typeof Q==="string"?Q:A}var lo1={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.136",description:"Content pipeline plugin for managing entity publishing queues, scheduling, and generation",type:"module",main:"src/index.ts",types:"src/index.ts",scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",croner:"^9.1.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.1.14",typescript:"^5.3.3"},exports:{".":{types:"./src/index.ts",default:"./src/index.ts"}},files:["src"]};class $n0 extends IQ{pluginContext;queueManager;providerRegistry;retryTracker;publishExecutor;publishAssetRegistry;publishAssetPreflight;scheduler;constructor(A){super("content-pipeline",lo1,A??{},Lo1)}async onRegister(A){this.pluginContext=A,this.queueManager=sG.createFresh(),this.providerRegistry=aG.createFresh(),this.retryTracker=tG.createFresh(),this.publishAssetRegistry=eG.createFresh(),this.publishAssetPreflight=new AD0({context:A,registry:this.publishAssetRegistry}),this.publishExecutor=new jE({context:A,providerRegistry:this.providerRegistry,publishAssetPreflight:this.publishAssetPreflight}),this.scheduler=mo1({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,logger:this.logger}),To1(A,{queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,publishAssetRegistry:this.publishAssetRegistry,publishAssetPreflight:this.publishAssetPreflight,scheduler:this.scheduler,logger:this.logger})}async onReady(A){await uo1(A.entityService,this.queueManager,this.logger),await co1(A,this.id),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[QD0(this.pluginContext,this.id,this.queueManager),BD0(this.pluginContext,this.id,this.providerRegistry,this.publishExecutor),$D0(this.pluginContext,this.id,this.publishAssetRegistry,this.publishAssetPreflight)]}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). This tool has its own confirmation flow; call it without `confirmed` when the user asks to publish instead of asking for plain-text confirmation.\n- Use `content-pipeline_ensure-assets` to reconcile missing publish assets such as generated OG images for already-published content.\n- When users ask about their "publish queue", "publishing queue", or "what\'s queued", use `content-pipeline_queue`.'}getQueueManager(){return this.queueManager}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getPublishAssetRegistry(){return this.publishAssetRegistry}getScheduler(){return this.scheduler}async onShutdown(){await this.scheduler.stop(),sG.resetInstance(),aG.resetInstance(),tG.resetInstance(),eG.resetInstance()}}function Yn0(A){return new $n0(A)}c0();Z0();var po1=K.object({accountId:K.string().describe("Cloudflare account ID"),apiToken:K.string().describe("Cloudflare API token with Analytics:Read permission"),siteTag:K.string().describe("Cloudflare Web Analytics site tag")}),Dn0=K.object({cloudflare:po1.optional()});c0();Z0();var Afw=K.object({date:K.string().describe("Single date in YYYY-MM-DD format").optional(),days:K.number().min(1).max(365).describe("Number of days back from yesterday (e.g., 7 for last week)").optional(),startDate:K.string().describe("Start date in YYYY-MM-DD format (use with endDate)").optional(),endDate:K.string().describe("End date in YYYY-MM-DD format (use with startDate)").optional(),limit:K.number().min(1).max(100).default(20).describe("Maximum items for breakdowns (pages, referrers, countries)")});function Qfw(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 io1(A,Q,w){let B=[];if(!w)return B;return B.push(Sw(A,"query",`Query website analytics from Cloudflare.
6623
6623
 
6624
6624
  Date range options (use only one):
6625
6625
  - No params: yesterday only
@@ -6757,7 +6757,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,Afw,
6757
6757
  }
6758
6758
  }
6759
6759
  }
6760
- `,variables:w})});if(!B.ok){let D=await B.text();throw Error(`Cloudflare API error: ${B.status} - ${D}`)}let $=await B.json();if($.errors&&$.errors.length>0)throw Error(`Cloudflare GraphQL error: ${$.errors.map((D)=>D.message).join(", ")}`);return($.data.viewer.accounts[0]?.rumPageloadEventsAdaptiveGroups??[]).map((D)=>({country:D.dimensions.countryName,visits:D.sum.visits}))}}Z0();var Hn0=7,wfw=10;function no1(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=KO(),w=Nt(Hn0),B=OV(w),$=OV(Q);try{let[Y,D]=await Promise.all([A.getWebsiteStats({startDate:B,endDate:$}),A.getTopPages({startDate:B,endDate:$,limit:wfw})]);return{days:Hn0,startDate:B,endDate:$,pageviews:Y.pageviews,visitors:Y.visitors,topPages:D}}catch(Y){return{error:Y instanceof Error?Y.message:"Failed to fetch analytics",days:Hn0}}}}var ro1={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.135",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 oo1 extends IQ{cloudflareClient;constructor(A={}){super("analytics",ro1,A,Dn0)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new Xn0(this.config.cloudflare):void 0,A.insights.register("traffic-overview",no1(this.cloudflareClient))}async onReady(A){let Q=this.config.cloudflare?.siteTag;if(!Q)return;await A.messaging.send({type:"plugin:site-builder:head-script:register",payload:{pluginId:this.id,script:do1(Q)}})}async getTools(){return io1(this.id,this.getContext(),this.cloudflareClient)}}function $fw(A={}){return new oo1(A)}var YD0=$fw;import{randomBytes as ffw}from"crypto";c0();Z0();aB();var Yfw=new Set(["description","excerpt","summary","tagline","story"]);function Dfw(A){if(A.endsWith("s"))return A;return KX(A)}function Wn0(A,Q=!1,w){let B=A._def.typeName;if(B==="ZodOptional"||B==="ZodNullable")return Wn0(A._def.innerType,!0,w);if(B==="ZodDefault")return Wn0(A._def.innerType,Q,A._def.defaultValue());return{inner:A,isOptional:Q,defaultValue:w}}function fn0(A,Q){let{inner:w,isOptional:B,defaultValue:$}=Wn0(Q),Y=w._def.typeName,D={name:A,label:YU(A),widget:"string",...B&&{required:!1},...$!==void 0&&{default:$}};switch(Y){case"ZodString":{if((w._def.checks??[]).some((H)=>H.kind==="datetime"))return{...D,widget:"datetime"};if(Yfw.has(A))return{...D,widget:"text"};return{...D,widget:"string"}}case"ZodNumber":return{...D,widget:"number"};case"ZodBoolean":return{...D,widget:"boolean"};case"ZodEnum":{let X=w._def.values;return{...D,widget:"select",options:X}}case"ZodArray":{let X=w._def.type,H=fn0("item",X);if(H.widget==="object"&&H.fields)return{...D,widget:"list",fields:H.fields};return{...D,widget:"list",field:{name:A,label:YU(A),widget:H.widget}}}case"ZodObject":{let X=w.shape,H=Object.entries(X).map(([W,f])=>fn0(W,f));return{...D,widget:"object",fields:H}}default:return{...D,widget:"string"}}}function so1(A,Q){let w=Object.entries(A.shape).map(([B,$])=>fn0(B,$));if(Q)w.push({name:"body",label:"Body",widget:"markdown"});return w}function ao1(A){let Q=[],w=[];for(let B of A.entityTypes){let $=A.getFrontmatterSchema(B);if(!$)continue;let Y=A.getAdapter(B),D=Y?.hasBody!==!1,X=A.entityDisplay?.[B],H=B===Ce?"Note":YU(B),W=X?.label??H,f=X?.pluralName??Dfw(W);if(Y?.isSingleton){w.push({name:B,label:W,file:`${B}/${B}.md`,fields:so1($,D)});continue}if(B===Ce){Q.push({name:B,label:f,folder:".",create:!0,extension:"md",format:"raw",fields:[{name:"body",label:"Body",widget:"markdown"}]});continue}Q.push({name:B,label:f,folder:B,create:!0,extension:"md",format:"frontmatter",fields:so1($,D)})}if(w.length>0)Q.push({name:"settings",label:"Settings",files:w});return{backend:{name:"github",repo:A.repo,branch:A.branch,...A.baseUrl&&{base_url:A.baseUrl},...A.authEndpoint&&{auth_endpoint:A.authEndpoint}},media_folder:"image",public_folder:"/images",collections:Q}}var Xfw=new RegExp("[<>&\\u2028\\u2029]","g");function ME(A){return JSON.stringify(A).replace(Xfw,(Q)=>`\\u${Q.charCodeAt(0).toString(16).padStart(4,"0")}`)}var to1="https://unpkg.com/@sveltia/cms@0.165.1/dist/sveltia-cms.js";function DD0(A){let Q=`<script src="${to1}"></script>`;return`<!doctype html>
6760
+ `,variables:w})});if(!B.ok){let D=await B.text();throw Error(`Cloudflare API error: ${B.status} - ${D}`)}let $=await B.json();if($.errors&&$.errors.length>0)throw Error(`Cloudflare GraphQL error: ${$.errors.map((D)=>D.message).join(", ")}`);return($.data.viewer.accounts[0]?.rumPageloadEventsAdaptiveGroups??[]).map((D)=>({country:D.dimensions.countryName,visits:D.sum.visits}))}}Z0();var Hn0=7,wfw=10;function no1(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=KO(),w=Nt(Hn0),B=OV(w),$=OV(Q);try{let[Y,D]=await Promise.all([A.getWebsiteStats({startDate:B,endDate:$}),A.getTopPages({startDate:B,endDate:$,limit:wfw})]);return{days:Hn0,startDate:B,endDate:$,pageviews:Y.pageviews,visitors:Y.visitors,topPages:D}}catch(Y){return{error:Y instanceof Error?Y.message:"Failed to fetch analytics",days:Hn0}}}}var ro1={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.136",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 oo1 extends IQ{cloudflareClient;constructor(A={}){super("analytics",ro1,A,Dn0)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new Xn0(this.config.cloudflare):void 0,A.insights.register("traffic-overview",no1(this.cloudflareClient))}async onReady(A){let Q=this.config.cloudflare?.siteTag;if(!Q)return;await A.messaging.send({type:"plugin:site-builder:head-script:register",payload:{pluginId:this.id,script:do1(Q)}})}async getTools(){return io1(this.id,this.getContext(),this.cloudflareClient)}}function $fw(A={}){return new oo1(A)}var YD0=$fw;import{randomBytes as ffw}from"crypto";c0();Z0();aB();var Yfw=new Set(["description","excerpt","summary","tagline","story"]);function Dfw(A){if(A.endsWith("s"))return A;return KX(A)}function Wn0(A,Q=!1,w){let B=A._def.typeName;if(B==="ZodOptional"||B==="ZodNullable")return Wn0(A._def.innerType,!0,w);if(B==="ZodDefault")return Wn0(A._def.innerType,Q,A._def.defaultValue());return{inner:A,isOptional:Q,defaultValue:w}}function fn0(A,Q){let{inner:w,isOptional:B,defaultValue:$}=Wn0(Q),Y=w._def.typeName,D={name:A,label:YU(A),widget:"string",...B&&{required:!1},...$!==void 0&&{default:$}};switch(Y){case"ZodString":{if((w._def.checks??[]).some((H)=>H.kind==="datetime"))return{...D,widget:"datetime"};if(Yfw.has(A))return{...D,widget:"text"};return{...D,widget:"string"}}case"ZodNumber":return{...D,widget:"number"};case"ZodBoolean":return{...D,widget:"boolean"};case"ZodEnum":{let X=w._def.values;return{...D,widget:"select",options:X}}case"ZodArray":{let X=w._def.type,H=fn0("item",X);if(H.widget==="object"&&H.fields)return{...D,widget:"list",fields:H.fields};return{...D,widget:"list",field:{name:A,label:YU(A),widget:H.widget}}}case"ZodObject":{let X=w.shape,H=Object.entries(X).map(([W,f])=>fn0(W,f));return{...D,widget:"object",fields:H}}default:return{...D,widget:"string"}}}function so1(A,Q){let w=Object.entries(A.shape).map(([B,$])=>fn0(B,$));if(Q)w.push({name:"body",label:"Body",widget:"markdown"});return w}function ao1(A){let Q=[],w=[];for(let B of A.entityTypes){let $=A.getFrontmatterSchema(B);if(!$)continue;let Y=A.getAdapter(B),D=Y?.hasBody!==!1,X=A.entityDisplay?.[B],H=B===Ce?"Note":YU(B),W=X?.label??H,f=X?.pluralName??Dfw(W);if(Y?.isSingleton){w.push({name:B,label:W,file:`${B}/${B}.md`,fields:so1($,D)});continue}if(B===Ce){Q.push({name:B,label:f,folder:".",create:!0,extension:"md",format:"raw",fields:[{name:"body",label:"Body",widget:"markdown"}]});continue}Q.push({name:B,label:f,folder:B,create:!0,extension:"md",format:"frontmatter",fields:so1($,D)})}if(w.length>0)Q.push({name:"settings",label:"Settings",files:w});return{backend:{name:"github",repo:A.repo,branch:A.branch,...A.baseUrl&&{base_url:A.baseUrl},...A.authEndpoint&&{auth_endpoint:A.authEndpoint}},media_folder:"image",public_folder:"/images",collections:Q}}var Xfw=new RegExp("[<>&\\u2028\\u2029]","g");function ME(A){return JSON.stringify(A).replace(Xfw,(Q)=>`\\u${Q.charCodeAt(0).toString(16).padStart(4,"0")}`)}var to1="https://unpkg.com/@sveltia/cms@0.165.1/dist/sveltia-cms.js";function DD0(A){let Q=`<script src="${to1}"></script>`;return`<!doctype html>
6761
6761
  <html>
6762
6762
  <head>
6763
6763
  <meta charset="utf-8" />
@@ -6796,7 +6796,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,Afw,
6796
6796
  showError(error instanceof Error ? error.message : String(error));
6797
6797
  }
6798
6798
  })();
6799
- `}Z0();var eo1={name:"@brains/cms",private:!0,version:"0.2.0-alpha.135",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/auth-service":"workspace:*","@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 Kn0="brains_cms_oauth_state",Zfw=600,Kfw="auth",Ufw=K.object({label:K.string().optional(),pluralName:K.string().optional()}).passthrough(),Gfw=K.object({clientId:K.string().optional(),clientSecret:K.string().optional(),scope:K.string().optional()}),zfw=K.object({contentRepoToken:K.string().optional()}),qfw=K.object({entityDisplay:K.record(Ufw).optional(),routePath:K.string().default("/cms"),githubOAuth:Gfw.optional(),passkeyLogin:zfw.optional()}).refine((A)=>{let Q=Boolean(OP(A.githubOAuth?.clientId)&&OP(A.githubOAuth?.clientSecret)),w=Boolean(OP(A.passkeyLogin?.contentRepoToken));return!(Q&&w)},{message:"CMS login supports a single method per brain: configure githubOAuth or passkeyLogin, not both."});function Ffw(A){return`${A.endsWith("/")?A:`${A}/`}config.yml`}function OP(A){if(!A)return;let Q=A.trim();return Q.length>0?Q:void 0}function Vfw(A){let Q=OP(A.githubOAuth?.clientId),w=OP(A.githubOAuth?.clientSecret),B=OP(A.passkeyLogin?.contentRepoToken);return{...Q&&w?{githubOAuth:{clientId:Q,clientSecret:w,scope:OP(A.githubOAuth?.scope)??"repo"}}:{},...B?{passkeyLogin:{contentRepoToken:B}}:{}}}function Jfw(A){return Boolean(A.githubOAuth??A.passkeyLogin)}function Ifw(A,Q,w){let B=A.entityDisplay??w?.entityDisplay;return{...B?{entityDisplay:B}:{},...Jfw(Q)?{authEndpoint:Kfw}:{}}}async function bfw(A){let Q=await A.messaging.send({type:"git-sync:get-repo-info",payload:{}});if("noop"in Q||!Q.success||!Q.data)throw Error("CMS config unavailable: git-sync repo info unavailable");let{repo:w,branch:B}=Q.data;if(!w||!B)throw Error("CMS config unavailable: git-sync repo info incomplete");return{repo:w,branch:B}}async function Lfw(A,Q={}){let{repo:w,branch:B}=await bfw(A);return ao1({repo:w,branch:B,...Q.baseUrl&&{baseUrl:Q.baseUrl},...Q.authEndpoint&&{authEndpoint:Q.authEndpoint},entityTypes:A.entityService.getEntityTypes(),getFrontmatterSchema:($)=>A.entities.getEffectiveFrontmatterSchema($),getAdapter:($)=>A.entities.getAdapter($),...Q.entityDisplay&&{entityDisplay:Q.entityDisplay}})}async function ws1(A,Q={}){return $U(await Lfw(A,Q))}class Un0 extends IQ{constructor(A={}){super("cms",eo1,A,qfw)}async onRegister(A){await super.onRegister(A),A.endpoints.register({label:"CMS",url:this.config.routePath,priority:40,visibility:"anchor"}),A.interactions.register({id:"cms",label:"CMS",description:"Edit and manage content through the browser CMS.",href:this.config.routePath,kind:"admin",priority:40,visibility:"anchor"})}getWebRoutes(){let A=Ffw(this.config.routePath),Q=Vfw(this.config),w=[];if(Q.githubOAuth||Q.passkeyLogin)w.push({path:"/auth",method:"GET",public:!0,handler:async(B)=>this.handleAuth(B,Q)});if(Q.githubOAuth){let B=Q.githubOAuth;w.push({path:"/auth/callback",method:"GET",public:!0,handler:async($)=>this.handleGitHubCallback($,B)})}if(Q.passkeyLogin){let B=Q.passkeyLogin;w.push({path:"/auth/cms-token",method:"POST",public:!0,handler:async($)=>this.handleCmsToken($,B)})}return[{path:this.config.routePath,method:"GET",public:!0,handler:async(B)=>{if(Q.passkeyLogin){if(!await Qs1(B))return new Response(null,{status:302,headers:{Location:`/login?return_to=${encodeURIComponent(this.config.routePath)}`,"Cache-Control":"no-store"}});return Go(DD0({cmsConfigPath:A,authTokenEndpoint:"/auth/cms-token"}))}return Go(DD0({cmsConfigPath:A}))}},{path:A,method:"GET",public:!0,handler:async(B)=>{try{let $=Ifw(this.config,Q,this.getContext()),Y=await ws1(this.getContext(),{...$,...$.authEndpoint?{baseUrl:Uo(this.getContext(),B)}:{}});return new Response(Y,{headers:{"Content-Type":"application/yaml; charset=utf-8"}})}catch($){return new Response($ instanceof Error?$.message:"CMS unavailable",{status:503,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}},...w]}async handleAuth(A,Q){if(Q.githubOAuth)return this.redirectToGitHub(A,Q.githubOAuth);if(Q.passkeyLogin){let w=await Qs1(A)?Ofw:kfw;return Go(w(Uo(this.getContext(),A)))}return Pfw("CMS login is not enabled",404)}redirectToGitHub(A,Q){let w=ffw(32).toString("base64url"),B=`${Uo(this.getContext(),A)}/auth/callback`,$=new URL("https://github.com/login/oauth/authorize");return $.searchParams.set("client_id",Q.clientId),$.searchParams.set("redirect_uri",B),$.searchParams.set("scope",Q.scope),$.searchParams.set("state",w),new Response(null,{status:302,headers:{Location:$.toString(),"Set-Cookie":Mfw(w,A),"Cache-Control":"no-store"}})}async handleGitHubCallback(A,Q){let w=new URL(A.url),B=w.searchParams.get("error");if(B){let W=w.searchParams.get("error_description")??B;return XD0(`GitHub OAuth failed: ${W}`)}let $=w.searchParams.get("state"),Y=_fw(A.headers.get("cookie"),Kn0);if(!$||!Y||$!==Y)return XD0("GitHub OAuth state did not match");let D=w.searchParams.get("code");if(!D)return XD0("GitHub OAuth callback did not include a code");let X=`${Uo(this.getContext(),A)}/auth/callback`,H=await Nfw(Q,D,X);if(!H.success)return XD0(H.error);return Go(xfw(H.token,Uo(this.getContext(),A)),200,{"Set-Cookie":$s1()})}async handleCmsToken(A,Q){if(!await EW()?.getOperatorSession(A))return As1({error:"Operator session required"},401);return As1({token:Q.contentRepoToken,provider:"github"},200,{"Cache-Control":"no-store"})}}function xP(A){return new Un0(A)}async function Nfw(A,Q,w){let B=new URLSearchParams({client_id:A.clientId,client_secret:A.clientSecret,code:Q,redirect_uri:w}),$=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:B}),Y;try{Y=await $.json()}catch{return{success:!1,error:"GitHub token response was not JSON"}}if(!$.ok)return{success:!1,error:jfw(Y)??"GitHub token exchange failed"};if(Zn0(Y)&&typeof Y.error==="string")return{success:!1,error:typeof Y.error_description==="string"?Y.error_description:Y.error};let D=Zn0(Y)?Y.access_token:void 0;if(typeof D!=="string"||D.length===0)return{success:!1,error:"GitHub token response omitted token"};return{success:!0,token:D}}function jfw(A){if(!Zn0(A))return;if(typeof A.error_description==="string")return A.error_description;return typeof A.error==="string"?A.error:void 0}function Zn0(A){return Boolean(A&&typeof A==="object"&&!Array.isArray(A))}function Uo(A,Q){let w=new URL(Q.url).origin;if(Bs1(w))return w;return A.siteUrl??w}function Bs1(A){let{hostname:Q}=new URL(A);return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"||Q==="[::1]"}function Mfw(A,Q){let w=Bs1(new URL(Q.url).origin)?"":"; Secure";return`${Kn0}=${A}; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=${Zfw}${w}`}function $s1(){return`${Kn0}=; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=0`}function _fw(A,Q){if(!A)return;for(let w of A.split(";")){let[B,...$]=w.trim().split("=");if(B===Q)return $.join("=")}return}function Go(A,Q=200,w={}){return new Response(A,{status:Q,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",...w}})}function Pfw(A,Q=200){return new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}})}function As1(A,Q=200,w={}){return new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store",...w}})}function XD0(A){return Go(`<!doctype html><html><body><h1>CMS login failed</h1><p>${vfw(A)}</p></body></html>`,400,{"Set-Cookie":$s1()})}async function Qs1(A){return Boolean(await EW()?.getOperatorSession(A))}function kfw(A){return`<!doctype html>
6799
+ `}Z0();var eo1={name:"@brains/cms",private:!0,version:"0.2.0-alpha.136",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/auth-service":"workspace:*","@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 Kn0="brains_cms_oauth_state",Zfw=600,Kfw="auth",Ufw=K.object({label:K.string().optional(),pluralName:K.string().optional()}).passthrough(),Gfw=K.object({clientId:K.string().optional(),clientSecret:K.string().optional(),scope:K.string().optional()}),zfw=K.object({contentRepoToken:K.string().optional()}),qfw=K.object({entityDisplay:K.record(Ufw).optional(),routePath:K.string().default("/cms"),githubOAuth:Gfw.optional(),passkeyLogin:zfw.optional()}).refine((A)=>{let Q=Boolean(OP(A.githubOAuth?.clientId)&&OP(A.githubOAuth?.clientSecret)),w=Boolean(OP(A.passkeyLogin?.contentRepoToken));return!(Q&&w)},{message:"CMS login supports a single method per brain: configure githubOAuth or passkeyLogin, not both."});function Ffw(A){return`${A.endsWith("/")?A:`${A}/`}config.yml`}function OP(A){if(!A)return;let Q=A.trim();return Q.length>0?Q:void 0}function Vfw(A){let Q=OP(A.githubOAuth?.clientId),w=OP(A.githubOAuth?.clientSecret),B=OP(A.passkeyLogin?.contentRepoToken);return{...Q&&w?{githubOAuth:{clientId:Q,clientSecret:w,scope:OP(A.githubOAuth?.scope)??"repo"}}:{},...B?{passkeyLogin:{contentRepoToken:B}}:{}}}function Jfw(A){return Boolean(A.githubOAuth??A.passkeyLogin)}function Ifw(A,Q,w){let B=A.entityDisplay??w?.entityDisplay;return{...B?{entityDisplay:B}:{},...Jfw(Q)?{authEndpoint:Kfw}:{}}}async function bfw(A){let Q=await A.messaging.send({type:"git-sync:get-repo-info",payload:{}});if("noop"in Q||!Q.success||!Q.data)throw Error("CMS config unavailable: git-sync repo info unavailable");let{repo:w,branch:B}=Q.data;if(!w||!B)throw Error("CMS config unavailable: git-sync repo info incomplete");return{repo:w,branch:B}}async function Lfw(A,Q={}){let{repo:w,branch:B}=await bfw(A);return ao1({repo:w,branch:B,...Q.baseUrl&&{baseUrl:Q.baseUrl},...Q.authEndpoint&&{authEndpoint:Q.authEndpoint},entityTypes:A.entityService.getEntityTypes(),getFrontmatterSchema:($)=>A.entities.getEffectiveFrontmatterSchema($),getAdapter:($)=>A.entities.getAdapter($),...Q.entityDisplay&&{entityDisplay:Q.entityDisplay}})}async function ws1(A,Q={}){return $U(await Lfw(A,Q))}class Un0 extends IQ{constructor(A={}){super("cms",eo1,A,qfw)}async onRegister(A){await super.onRegister(A),A.endpoints.register({label:"CMS",url:this.config.routePath,priority:40,visibility:"anchor"}),A.interactions.register({id:"cms",label:"CMS",description:"Edit and manage content through the browser CMS.",href:this.config.routePath,kind:"admin",priority:40,visibility:"anchor"})}getWebRoutes(){let A=Ffw(this.config.routePath),Q=Vfw(this.config),w=[];if(Q.githubOAuth||Q.passkeyLogin)w.push({path:"/auth",method:"GET",public:!0,handler:async(B)=>this.handleAuth(B,Q)});if(Q.githubOAuth){let B=Q.githubOAuth;w.push({path:"/auth/callback",method:"GET",public:!0,handler:async($)=>this.handleGitHubCallback($,B)})}if(Q.passkeyLogin){let B=Q.passkeyLogin;w.push({path:"/auth/cms-token",method:"POST",public:!0,handler:async($)=>this.handleCmsToken($,B)})}return[{path:this.config.routePath,method:"GET",public:!0,handler:async(B)=>{if(Q.passkeyLogin){if(!await Qs1(B))return new Response(null,{status:302,headers:{Location:`/login?return_to=${encodeURIComponent(this.config.routePath)}`,"Cache-Control":"no-store"}});return Go(DD0({cmsConfigPath:A,authTokenEndpoint:"/auth/cms-token"}))}return Go(DD0({cmsConfigPath:A}))}},{path:A,method:"GET",public:!0,handler:async(B)=>{try{let $=Ifw(this.config,Q,this.getContext()),Y=await ws1(this.getContext(),{...$,...$.authEndpoint?{baseUrl:Uo(this.getContext(),B)}:{}});return new Response(Y,{headers:{"Content-Type":"application/yaml; charset=utf-8"}})}catch($){return new Response($ instanceof Error?$.message:"CMS unavailable",{status:503,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}},...w]}async handleAuth(A,Q){if(Q.githubOAuth)return this.redirectToGitHub(A,Q.githubOAuth);if(Q.passkeyLogin){let w=await Qs1(A)?Ofw:kfw;return Go(w(Uo(this.getContext(),A)))}return Pfw("CMS login is not enabled",404)}redirectToGitHub(A,Q){let w=ffw(32).toString("base64url"),B=`${Uo(this.getContext(),A)}/auth/callback`,$=new URL("https://github.com/login/oauth/authorize");return $.searchParams.set("client_id",Q.clientId),$.searchParams.set("redirect_uri",B),$.searchParams.set("scope",Q.scope),$.searchParams.set("state",w),new Response(null,{status:302,headers:{Location:$.toString(),"Set-Cookie":Mfw(w,A),"Cache-Control":"no-store"}})}async handleGitHubCallback(A,Q){let w=new URL(A.url),B=w.searchParams.get("error");if(B){let W=w.searchParams.get("error_description")??B;return XD0(`GitHub OAuth failed: ${W}`)}let $=w.searchParams.get("state"),Y=_fw(A.headers.get("cookie"),Kn0);if(!$||!Y||$!==Y)return XD0("GitHub OAuth state did not match");let D=w.searchParams.get("code");if(!D)return XD0("GitHub OAuth callback did not include a code");let X=`${Uo(this.getContext(),A)}/auth/callback`,H=await Nfw(Q,D,X);if(!H.success)return XD0(H.error);return Go(xfw(H.token,Uo(this.getContext(),A)),200,{"Set-Cookie":$s1()})}async handleCmsToken(A,Q){if(!await EW()?.getOperatorSession(A))return As1({error:"Operator session required"},401);return As1({token:Q.contentRepoToken,provider:"github"},200,{"Cache-Control":"no-store"})}}function xP(A){return new Un0(A)}async function Nfw(A,Q,w){let B=new URLSearchParams({client_id:A.clientId,client_secret:A.clientSecret,code:Q,redirect_uri:w}),$=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:B}),Y;try{Y=await $.json()}catch{return{success:!1,error:"GitHub token response was not JSON"}}if(!$.ok)return{success:!1,error:jfw(Y)??"GitHub token exchange failed"};if(Zn0(Y)&&typeof Y.error==="string")return{success:!1,error:typeof Y.error_description==="string"?Y.error_description:Y.error};let D=Zn0(Y)?Y.access_token:void 0;if(typeof D!=="string"||D.length===0)return{success:!1,error:"GitHub token response omitted token"};return{success:!0,token:D}}function jfw(A){if(!Zn0(A))return;if(typeof A.error_description==="string")return A.error_description;return typeof A.error==="string"?A.error:void 0}function Zn0(A){return Boolean(A&&typeof A==="object"&&!Array.isArray(A))}function Uo(A,Q){let w=new URL(Q.url).origin;if(Bs1(w))return w;return A.siteUrl??w}function Bs1(A){let{hostname:Q}=new URL(A);return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"||Q==="[::1]"}function Mfw(A,Q){let w=Bs1(new URL(Q.url).origin)?"":"; Secure";return`${Kn0}=${A}; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=${Zfw}${w}`}function $s1(){return`${Kn0}=; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=0`}function _fw(A,Q){if(!A)return;for(let w of A.split(";")){let[B,...$]=w.trim().split("=");if(B===Q)return $.join("=")}return}function Go(A,Q=200,w={}){return new Response(A,{status:Q,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",...w}})}function Pfw(A,Q=200){return new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}})}function As1(A,Q=200,w={}){return new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store",...w}})}function XD0(A){return Go(`<!doctype html><html><body><h1>CMS login failed</h1><p>${vfw(A)}</p></body></html>`,400,{"Set-Cookie":$s1()})}async function Qs1(A){return Boolean(await EW()?.getOperatorSession(A))}function kfw(A){return`<!doctype html>
6800
6800
  <html lang="en">
6801
6801
  <head>
6802
6802
  <meta charset="utf-8" />
@@ -8201,7 +8201,7 @@ ${Ds1}`;import{jsxDEV as NK,Fragment as Ws1}from"preact/jsx-dev-runtime";functio
8201
8201
  }
8202
8202
  });
8203
8203
  })();`;function GZw({input:A}){let Q=A.appInfo.entities,w=A.appInfo.entityCounts,B=ZZw(A.widgets),$=Boolean(A.character.role)||Boolean(A.character.purpose)||A.character.values.length>0,Y=A.appInfo.interactions,D=`layout${$?" has-identity":""}`,X=A.operatorAccess&&!A.operatorAccess.isOperator&&A.operatorAccess.hiddenWidgetCount>0,H=new Date;return Lw("html",{lang:"en","data-theme":"dark",children:[Lw("head",{children:[Lw("meta",{charSet:"utf-8"},void 0,!1,void 0,this),Lw("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0"},void 0,!1,void 0,this),Lw("title",{children:A.title},void 0,!1,void 0,this),Lw("link",{rel:"preconnect",href:"https://fonts.googleapis.com"},void 0,!1,void 0,this),Lw("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"},void 0,!1,void 0,this),Lw("link",{href:fZw,rel:"stylesheet"},void 0,!1,void 0,this),A.themeCSS!==void 0&&Lw("style",{"data-dashboard-theme":!0,dangerouslySetInnerHTML:{__html:A.themeCSS}},void 0,!1,void 0,this),Lw("style",{"data-dashboard-styles":!0,dangerouslySetInnerHTML:{__html:Hs1}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Lw("body",{children:[Lw("main",{class:"console","data-component":"dashboard:dashboard",children:[Lw(fs1,{title:A.title,tagline:A.profile.description,operatorAccess:A.operatorAccess},void 0,!1,void 0,this),Lw("section",{class:D,children:[$&&Lw("div",{class:"identity-column",children:[Lw(Ks1,{character:A.character},void 0,!1,void 0,this),Lw(Fn0,{interactions:Y,baseUrl:A.baseUrl},void 0,!1,void 0,this),X&&A.operatorAccess&&Lw(Js1,{hiddenWidgetCount:A.operatorAccess.hiddenWidgetCount,loginUrl:A.operatorAccess.loginUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Lw("div",{class:"main-column",children:[Lw(Zs1,{total:Q,entityCounts:w},void 0,!1,void 0,this),!$&&X&&A.operatorAccess&&Lw(Js1,{hiddenWidgetCount:A.operatorAccess.hiddenWidgetCount,loginUrl:A.operatorAccess.loginUrl},void 0,!1,void 0,this),B.primary.map((W)=>Lw(ZD0,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this)),B.secondary.map((W)=>Lw(ZD0,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this))]},void 0,!0,void 0,this),Lw("div",{class:"sidebar-column",children:[!$&&Lw(Fn0,{interactions:Y,baseUrl:A.baseUrl},void 0,!1,void 0,this),B.sidebar.map((W)=>Lw(ZD0,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this)),Lw(Us1,{endpoints:A.appInfo.endpoints,baseUrl:A.baseUrl},void 0,!1,void 0,this),Lw(Fs1,{appInfo:A.appInfo,now:H},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Lw(Vs1,{title:A.title,appInfo:A.appInfo,baseUrl:A.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Lw("script",{dangerouslySetInnerHTML:{__html:KZw}},void 0,!1,void 0,this),Lw("script",{dangerouslySetInnerHTML:{__html:UZw}},void 0,!1,void 0,this),A.widgetScripts.map((W,f)=>Lw("script",{dangerouslySetInnerHTML:{__html:W}},`widget-script:${f}`,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Is1(A){return`<!doctype html>
8204
- ${WZw(Lw(GZw,{input:A},void 0,!1,void 0,this))}`}function bs1(A,Q){let w={},B=new Set;for(let[$,Y]of Object.entries(A)){let D=Q?.get(Y.widget.pluginId,Y.widget.id);if(w[$]={...Y,...D?.component?{component:D.component}:{}},D?.clientScript)B.add(D.clientScript)}return{widgets:w,widgetScripts:Array.from(B)}}var Ls1={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.135",description:"Dashboard plugin with extensible widget system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var qZw=K.object({version:K.string().default("1.0.0"),routePath:K.string().default("/dashboard"),themeCSS:K.string().optional()}),FZw=K.object({id:K.string(),pluginId:K.string(),title:K.string(),description:K.string().optional(),priority:K.number().default(50),section:K.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:K.string(),visibility:s4.default("public"),component:K.custom().optional(),clientScript:K.string().optional(),dataProvider:K.function().returns(K.promise(K.unknown()))}).superRefine((A,Q)=>{if(!qn0(A.rendererName)&&!A.component)Q.addIssue({code:K.ZodIssueCode.custom,message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),VZw=K.object({pluginId:K.string(),widgetId:K.string().optional()});function JZw(A){return{id:A.id,pluginId:A.pluginId,title:A.title,...A.description?{description:A.description}:{},priority:A.priority,section:A.section,rendererName:A.rendererName,visibility:A.visibility,...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider}}class Jn0 extends IQ{widgetRegistry=null;datasource=null;siteUrl;ctx;constructor(A){super("dashboard",Ls1,A??{},qZw)}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new WD0(this.logger),this.datasource=new fD0(this.widgetRegistry,this.logger),A.entities.registerDataSource(this.datasource),A.endpoints.register({label:"Dashboard",url:this.config.routePath,priority:30,visibility:"public"}),A.interactions.register({id:"dashboard",label:"Dashboard",description:"Inspect runtime status, endpoints, and dashboard widgets.",href:this.config.routePath,kind:"admin",priority:30,visibility:"public"}),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let w=FZw.parse(Q.payload),B=JZw(w);return this.widgetRegistry?.register(B),this.logger.debug("Widget registered via messaging",{widgetId:w.id,pluginId:w.pluginId,rendererName:w.rendererName,builtIn:HD0.includes(w.rendererName)}),{success:!0}}catch(w){return this.logger.error("Failed to register widget",{error:vA(w),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{let w=VZw.parse(Q.payload);return this.widgetRegistry?.unregister(w.pluginId,w.widgetId),this.logger.debug("Widget unregistered via messaging",{pluginId:w.pluginId,widgetId:w.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,w=await EW()?.getOperatorSession(A),B=Boolean(w),$=B?"anchor":"public",Y=this.widgetRegistry?.list({permissionLevel:"anchor"})??[],D=Y.filter((g)=>m$.hasPermission($,g.visibility)),X=Y.length-D.length,[H,W]=await Promise.all([this.datasource.getDashboardData({permissionLevel:$,widgets:D}),Q.appInfo()]),f=Q.identity.get(),Z=Q.identity.getProfile(),G=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),F={...W,endpoints:W.endpoints.filter((g)=>m$.hasPermission($,g.visibility)),interactions:W.interactions.filter((g)=>m$.hasPermission($,g.visibility))},V=Z.name||W.model||"Brain Dashboard",b=new URL(A.url),L=`${b.pathname}${b.search}`,N=encodeURIComponent(L),_=bs1(H.widgets,this.widgetRegistry),j={title:V,baseUrl:G,widgets:_.widgets,widgetScripts:_.widgetScripts,character:f,profile:Z,appInfo:F,...this.config.themeCSS!==void 0&&{themeCSS:this.config.themeCSS},operatorAccess:{isOperator:B,hiddenWidgetCount:X,loginUrl:`/login?return_to=${N}`,logoutUrl:`/logout?return_to=${N}`}};return new Response(Is1(j),{headers:{"Content-Type":"text/html; charset=utf-8"}})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function Sb(A){return new Jn0(A)}c0();Z0();var IZw=K.object({id:K.string(),pluginId:K.string(),title:K.string(),description:K.string().optional(),priority:K.number(),section:K.enum(["primary","secondary","sidebar"]),rendererName:K.string(),visibility:s4,component:K.custom().optional()}),bZw=K.object({widget:IZw,data:K.unknown()}),LZw=K.object({widgets:K.record(bZw)});Z0();c0();Z0();import{h as EZw}from"preact";Z0();IX();c0();var _E=K.enum(["generating","draft","queued","published","failed"]),qo=K.object({subject:K.string(),status:_E,entityIds:K.array(K.string()).optional(),scheduledFor:K.string().datetime().optional(),sentAt:K.string().datetime().optional(),buttondownId:K.string().optional(),sourceEntityType:K.string().optional()}),Ns1=qo.pick({subject:!0,status:!0,entityIds:!0,scheduledFor:!0,sentAt:!0,buttondownId:!0,sourceEntityType:!0}).extend({error:K.string().optional()}),Fo=o1.extend({entityType:K.literal("newsletter"),metadata:Ns1});c0();class js1 extends J2{constructor(){super({entityType:"newsletter",purpose:"An email newsletter issue composed for subscribers.",schema:Fo,frontmatterSchema:qo})}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}}buildStub(A){let Q={subject:A.title,status:"generating"};return{content:this.buildMarkdown("",Q),metadata:Q}}}var Ms1=new js1;c0();c0();Z0();var NZw=qU.extend({status:K.enum(["generating","draft","queued","published","failed"]).optional()}),jZw=FU.extend({query:NZw.optional()});function _s1(A){try{let{content:Q}=v2(A.content,qo);return Q}catch{return A.content}}class In0 extends f${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=jZw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=_s1(A),w={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:X7(Q,150),created:A.created,url:`/newsletters/${A.id}`};if(A.metadata.sentAt)w.sentAt=A.metadata.sentAt;return w}buildListResult(A,Q,w){return{newsletters:A,totalCount:Q?.totalItems??A.length,pagination:Q}}async fetch(A,Q,w){let{query:B}=this.parseQuery(A),$=w.entityService;if(B.id)return this.fetchSingleNewsletter(B.id,Q,$);let Y=B.status,D=Y?{filter:{metadata:{status:Y}}}:void 0,{items:X,pagination:H}=await this.fetchList(B,$,D);return Q.parse(this.buildListResult(X,H,B))}async fetchSingleNewsletter(A,Q,w){let B=await w.getEntity({entityType:this.config.entityType,id:A});if(!B)throw Error(`Newsletter not found: ${A}`);let $=await this.resolveNavigation(B,w),Y=[];if(B.metadata.entityIds?.length){let H=B.metadata.sourceEntityType??"post";Y=(await Promise.all(B.metadata.entityIds.map(async(f)=>{let Z=await w.getEntity({entityType:H,id:f});if(Z){let G=Z.metadata;return{id:f,title:G.title??f,url:`/${H}s/${G.slug??f}`}}return null}))).filter((f)=>f!==null)}let D=_s1(B),X={id:B.id,subject:B.metadata.subject,status:B.metadata.status,content:D,created:B.created,updated:B.updated,sentAt:B.metadata.sentAt,scheduledFor:B.metadata.scheduledFor,newsletter:B,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:Y.length>0?Y:void 0};return Q.parse(X)}}c0();Z0();var MZw=K.object({prompt:K.string().optional().describe("AI generation prompt"),sourceEntityIds:K.array(K.string()).optional().describe("Entity IDs to include in newsletter (e.g., blog posts)"),sourceEntityType:K.enum(["post"]).optional().describe("Type of source entities"),content:K.string().optional().describe("Direct content (skip AI)"),subject:K.string().optional().describe("Newsletter subject (AI-generated if not provided)"),addToQueue:K.boolean().optional().describe("Create as queued (true) or draft (false)")});class bn0 extends Q4{constructor(A,Q){super(A,Q,{schema:MZw,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let w=A.addToQueue??!1,{prompt:B,sourceEntityIds:$,sourceEntityType:Y}=A,{content:D,subject:X}=A;if(D){if(!X)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if($&&$.length>0){let G=Y??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${$.length} source entities`});let V=(await Promise.all($.map((j)=>this.context.entityService.getEntity({entityType:G,id:j})))).filter((j)=>j!=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:
8204
+ ${WZw(Lw(GZw,{input:A},void 0,!1,void 0,this))}`}function bs1(A,Q){let w={},B=new Set;for(let[$,Y]of Object.entries(A)){let D=Q?.get(Y.widget.pluginId,Y.widget.id);if(w[$]={...Y,...D?.component?{component:D.component}:{}},D?.clientScript)B.add(D.clientScript)}return{widgets:w,widgetScripts:Array.from(B)}}var Ls1={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.136",description:"Dashboard plugin with extensible widget system",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/auth-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2","preact-render-to-string":"^6.3.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var qZw=K.object({version:K.string().default("1.0.0"),routePath:K.string().default("/dashboard"),themeCSS:K.string().optional()}),FZw=K.object({id:K.string(),pluginId:K.string(),title:K.string(),description:K.string().optional(),priority:K.number().default(50),section:K.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:K.string(),visibility:s4.default("public"),component:K.custom().optional(),clientScript:K.string().optional(),dataProvider:K.function().returns(K.promise(K.unknown()))}).superRefine((A,Q)=>{if(!qn0(A.rendererName)&&!A.component)Q.addIssue({code:K.ZodIssueCode.custom,message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),VZw=K.object({pluginId:K.string(),widgetId:K.string().optional()});function JZw(A){return{id:A.id,pluginId:A.pluginId,title:A.title,...A.description?{description:A.description}:{},priority:A.priority,section:A.section,rendererName:A.rendererName,visibility:A.visibility,...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider}}class Jn0 extends IQ{widgetRegistry=null;datasource=null;siteUrl;ctx;constructor(A){super("dashboard",Ls1,A??{},qZw)}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new WD0(this.logger),this.datasource=new fD0(this.widgetRegistry,this.logger),A.entities.registerDataSource(this.datasource),A.endpoints.register({label:"Dashboard",url:this.config.routePath,priority:30,visibility:"public"}),A.interactions.register({id:"dashboard",label:"Dashboard",description:"Inspect runtime status, endpoints, and dashboard widgets.",href:this.config.routePath,kind:"admin",priority:30,visibility:"public"}),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let w=FZw.parse(Q.payload),B=JZw(w);return this.widgetRegistry?.register(B),this.logger.debug("Widget registered via messaging",{widgetId:w.id,pluginId:w.pluginId,rendererName:w.rendererName,builtIn:HD0.includes(w.rendererName)}),{success:!0}}catch(w){return this.logger.error("Failed to register widget",{error:vA(w),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{let w=VZw.parse(Q.payload);return this.widgetRegistry?.unregister(w.pluginId,w.widgetId),this.logger.debug("Widget unregistered via messaging",{pluginId:w.pluginId,widgetId:w.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,w=await EW()?.getOperatorSession(A),B=Boolean(w),$=B?"anchor":"public",Y=this.widgetRegistry?.list({permissionLevel:"anchor"})??[],D=Y.filter((g)=>m$.hasPermission($,g.visibility)),X=Y.length-D.length,[H,W]=await Promise.all([this.datasource.getDashboardData({permissionLevel:$,widgets:D}),Q.appInfo()]),f=Q.identity.get(),Z=Q.identity.getProfile(),G=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),F={...W,endpoints:W.endpoints.filter((g)=>m$.hasPermission($,g.visibility)),interactions:W.interactions.filter((g)=>m$.hasPermission($,g.visibility))},V=Z.name||W.model||"Brain Dashboard",b=new URL(A.url),L=`${b.pathname}${b.search}`,N=encodeURIComponent(L),_=bs1(H.widgets,this.widgetRegistry),j={title:V,baseUrl:G,widgets:_.widgets,widgetScripts:_.widgetScripts,character:f,profile:Z,appInfo:F,...this.config.themeCSS!==void 0&&{themeCSS:this.config.themeCSS},operatorAccess:{isOperator:B,hiddenWidgetCount:X,loginUrl:`/login?return_to=${N}`,logoutUrl:`/logout?return_to=${N}`}};return new Response(Is1(j),{headers:{"Content-Type":"text/html; charset=utf-8"}})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function Sb(A){return new Jn0(A)}c0();Z0();var IZw=K.object({id:K.string(),pluginId:K.string(),title:K.string(),description:K.string().optional(),priority:K.number(),section:K.enum(["primary","secondary","sidebar"]),rendererName:K.string(),visibility:s4,component:K.custom().optional()}),bZw=K.object({widget:IZw,data:K.unknown()}),LZw=K.object({widgets:K.record(bZw)});Z0();c0();Z0();import{h as EZw}from"preact";Z0();IX();c0();var _E=K.enum(["generating","draft","queued","published","failed"]),qo=K.object({subject:K.string(),status:_E,entityIds:K.array(K.string()).optional(),scheduledFor:K.string().datetime().optional(),sentAt:K.string().datetime().optional(),buttondownId:K.string().optional(),sourceEntityType:K.string().optional()}),Ns1=qo.pick({subject:!0,status:!0,entityIds:!0,scheduledFor:!0,sentAt:!0,buttondownId:!0,sourceEntityType:!0}).extend({error:K.string().optional()}),Fo=o1.extend({entityType:K.literal("newsletter"),metadata:Ns1});c0();class js1 extends J2{constructor(){super({entityType:"newsletter",purpose:"An email newsletter issue composed for subscribers.",schema:Fo,frontmatterSchema:qo})}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}}buildStub(A){let Q={subject:A.title,status:"generating"};return{content:this.buildMarkdown("",Q),metadata:Q}}}var Ms1=new js1;c0();c0();Z0();var NZw=qU.extend({status:K.enum(["generating","draft","queued","published","failed"]).optional()}),jZw=FU.extend({query:NZw.optional()});function _s1(A){try{let{content:Q}=v2(A.content,qo);return Q}catch{return A.content}}class In0 extends f${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=jZw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=_s1(A),w={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:X7(Q,150),created:A.created,url:`/newsletters/${A.id}`};if(A.metadata.sentAt)w.sentAt=A.metadata.sentAt;return w}buildListResult(A,Q,w){return{newsletters:A,totalCount:Q?.totalItems??A.length,pagination:Q}}async fetch(A,Q,w){let{query:B}=this.parseQuery(A),$=w.entityService;if(B.id)return this.fetchSingleNewsletter(B.id,Q,$);let Y=B.status,D=Y?{filter:{metadata:{status:Y}}}:void 0,{items:X,pagination:H}=await this.fetchList(B,$,D);return Q.parse(this.buildListResult(X,H,B))}async fetchSingleNewsletter(A,Q,w){let B=await w.getEntity({entityType:this.config.entityType,id:A});if(!B)throw Error(`Newsletter not found: ${A}`);let $=await this.resolveNavigation(B,w),Y=[];if(B.metadata.entityIds?.length){let H=B.metadata.sourceEntityType??"post";Y=(await Promise.all(B.metadata.entityIds.map(async(f)=>{let Z=await w.getEntity({entityType:H,id:f});if(Z){let G=Z.metadata;return{id:f,title:G.title??f,url:`/${H}s/${G.slug??f}`}}return null}))).filter((f)=>f!==null)}let D=_s1(B),X={id:B.id,subject:B.metadata.subject,status:B.metadata.status,content:D,created:B.created,updated:B.updated,sentAt:B.metadata.sentAt,scheduledFor:B.metadata.scheduledFor,newsletter:B,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:Y.length>0?Y:void 0};return Q.parse(X)}}c0();Z0();var MZw=K.object({prompt:K.string().optional().describe("AI generation prompt"),sourceEntityIds:K.array(K.string()).optional().describe("Entity IDs to include in newsletter (e.g., blog posts)"),sourceEntityType:K.enum(["post"]).optional().describe("Type of source entities"),content:K.string().optional().describe("Direct content (skip AI)"),subject:K.string().optional().describe("Newsletter subject (AI-generated if not provided)"),addToQueue:K.boolean().optional().describe("Create as queued (true) or draft (false)")});class bn0 extends Q4{constructor(A,Q){super(A,Q,{schema:MZw,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let w=A.addToQueue??!1,{prompt:B,sourceEntityIds:$,sourceEntityType:Y}=A,{content:D,subject:X}=A;if(D){if(!X)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if($&&$.length>0){let G=Y??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${$.length} source entities`});let V=(await Promise.all($.map((j)=>this.context.entityService.getEntity({entityType:G,id:j})))).filter((j)=>j!=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:
8205
8205
 
8206
8206
  ${V.map((j)=>`## ${j.metadata.title}
8207
8207
 
@@ -8270,17 +8270,17 @@ Newsletter-specific guidelines:
8270
8270
  - "Reply and let me know..."
8271
8271
  - "Until next time..."
8272
8272
 
8273
- The goal is to build a relationship with readers through valuable, authentic content.`});Z0();c0();import{jsxDEV as hY,Fragment as xZw}from"preact/jsx-dev-runtime";var PZw=K.object({id:K.string(),subject:K.string(),status:_E,excerpt:K.string(),created:K.string(),sentAt:K.string().optional(),url:K.string()}),kZw=K.object({newsletters:K.array(PZw),totalCount:K.number(),pagination:e7.nullable()}),OZw=({newsletters:A,totalCount:Q,pageTitle:w,pagination:B,baseUrl:$="/newsletters"})=>{let Y=w??"Newsletters",D=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return hY(xZw,{children:[hY(jQ,{title:Y,description:D},void 0,!1,void 0,this),hY("div",{className:"newsletter-list bg-theme",children:hY("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[hY("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:Y},void 0,!1,void 0,this),A.length===0?hY("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):hY("div",{className:"space-y-4",children:A.map((X)=>hY(uw,{href:X.url,children:[hY(d9,{className:"text-lg",children:X.subject},void 0,!1,void 0,this),hY(j7,{children:hY("div",{className:"flex items-center gap-3",children:[hY(vD,{status:X.status},void 0,!1,void 0,this),hY("span",{className:"text-sm text-theme-muted",children:Z5(X.sentAt??X.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X.excerpt&&hY("p",{className:"text-theme-muted line-clamp-2",children:X.excerpt},void 0,!1,void 0,this)]},X.id,!0,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&hY(o3,{currentPage:B.currentPage,totalPages:B.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)},ks1=R1({name:"newsletter-list",description:"Newsletter list page template",schema:kZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:OZw}});Z0();c0();import{jsxDEV as y8,Fragment as CZw}from"preact/jsx-dev-runtime";var RZw=K.object({id:K.string(),title:K.string(),url:K.string()}),Os1=K.object({id:K.string(),subject:K.string(),url:K.string()}),hZw=K.object({id:K.string(),subject:K.string(),status:_E,content:K.string(),created:K.string(),updated:K.string(),sentAt:K.string().optional(),scheduledFor:K.string().optional(),sourceEntities:K.array(RZw).optional(),prevNewsletter:Os1.nullable().optional(),nextNewsletter:Os1.nullable().optional()}),vZw=({subject:A,status:Q,content:w,created:B,sentAt:$,scheduledFor:Y,sourceEntities:D,prevNewsletter:X,nextNewsletter:H})=>{let W=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],f=$??B,Z=$?"Sent":"Created";return y8(CZw,{children:[y8(jQ,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),y8("section",{className:"newsletter-detail-section",children:y8("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:y8("div",{className:"max-w-3xl mx-auto",children:[y8(_G,{items:W},void 0,!1,void 0,this),y8("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),y8("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[y8(vD,{status:Q},void 0,!1,void 0,this),y8("span",{children:[Z,": ",Z5(f,{style:"long"})]},void 0,!0,void 0,this),Y&&Q==="queued"&&y8("span",{children:["Scheduled for: ",Z5(Y,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D&&D.length>0&&y8(uw,{variant:"compact",className:"mb-8",children:[y8("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),y8("ul",{className:"space-y-1",children:D.map((G)=>y8("li",{children:y8("a",{href:G.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:G.title},void 0,!1,void 0,this)},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y8($9,{markdown:w},void 0,!1,void 0,this),(X??H)&&y8("nav",{className:"mt-12 pt-8 border-t border-theme",children:y8("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[X?y8(uw,{href:X.url,variant:"compact",children:[y8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),y8("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):y8("div",{},void 0,!1,void 0,this),H&&y8(uw,{href:H.url,variant:"compact",className:"md:text-right",children:[y8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),y8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:H.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)},xs1=R1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:hZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:vZw}});var Rs1={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.135",description:"Newsletter entity type with AI generation and publish pipeline",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts,.tsx","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var gZw=K.object({});class Ln0 extends kQ{entityType="newsletter";schema=Fo;adapter=Ms1;constructor(A={}){super("newsletter",Rs1,A,gZw)}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}createGenerationHandler(A){return new bn0(this.logger,A)}getTemplates(){return{generation:Ps1,"newsletter-list":ks1,"newsletter-detail":xs1}}getDataSources(){return[new In0(this.logger.child("NewsletterDataSource"))]}async onRegister(A){this.deferPublishRegistration(A),this.subscribeToGenerateExecute(A),this.registerEvalHandlers(A),A.messaging.subscribe("system:plugins:ready",async()=>{let Q=await A.messaging.send({type:"buttondown:is-configured",payload:{}});if(!("noop"in Q)&&Q.success)await A.messaging.send({type:"plugin:site-builder:slot:register",payload:{pluginId:this.id,slotName:"footer-top",render:()=>EZw(su0,{variant:"inline"})}});return{success:!0}}),this.logger.debug("Newsletter plugin registered")}deferPublishRegistration(A){let Q={name:"internal",publish:async(w,B)=>{let $=typeof B.subject==="string"?B.subject:"",Y=await A.messaging.send({type:"buttondown:send",payload:{entityId:"",subject:$,content:w}});return{id:!("noop"in Y)&&Y.data?.emailId?Y.data.emailId:"internal"}}};A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"newsletter",provider:Q,config:{publishResultIdField:"buttondownId",publishTimestampField:"sentAt"}}}),{success:!0}})}subscribeToGenerateExecute(A){A.messaging.subscribe("generate:execute",async(Q)=>{if(Q.payload.entityType!=="newsletter")return{success:!0};try{let w=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:10}});if(w.length===0)return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:"No published posts available for newsletter"}}),{success:!0};return await A.jobs.enqueue({type:"newsletter:generation",data:{sourceEntityIds:w.map((B)=>B.id),sourceEntityType:"post",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}}),{success:!0}}catch(w){return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:vA(w)}}),{success:!0}}})}registerEvalHandlers(A){let Q=K.object({prompt:K.string().optional(),content:K.string().optional()});A.eval.registerHandler("generation",async(w)=>{let B=Q.parse(w),$=B.content?`Create an engaging newsletter based on this content:
8273
+ The goal is to build a relationship with readers through valuable, authentic content.`});Z0();c0();import{jsxDEV as hY,Fragment as xZw}from"preact/jsx-dev-runtime";var PZw=K.object({id:K.string(),subject:K.string(),status:_E,excerpt:K.string(),created:K.string(),sentAt:K.string().optional(),url:K.string()}),kZw=K.object({newsletters:K.array(PZw),totalCount:K.number(),pagination:e7.nullable()}),OZw=({newsletters:A,totalCount:Q,pageTitle:w,pagination:B,baseUrl:$="/newsletters"})=>{let Y=w??"Newsletters",D=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return hY(xZw,{children:[hY(jQ,{title:Y,description:D},void 0,!1,void 0,this),hY("div",{className:"newsletter-list bg-theme",children:hY("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[hY("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:Y},void 0,!1,void 0,this),A.length===0?hY("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):hY("div",{className:"space-y-4",children:A.map((X)=>hY(uw,{href:X.url,children:[hY(d9,{className:"text-lg",children:X.subject},void 0,!1,void 0,this),hY(j7,{children:hY("div",{className:"flex items-center gap-3",children:[hY(vD,{status:X.status},void 0,!1,void 0,this),hY("span",{className:"text-sm text-theme-muted",children:Z5(X.sentAt??X.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X.excerpt&&hY("p",{className:"text-theme-muted line-clamp-2",children:X.excerpt},void 0,!1,void 0,this)]},X.id,!0,void 0,this))},void 0,!1,void 0,this),B&&B.totalPages>1&&hY(o3,{currentPage:B.currentPage,totalPages:B.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)},ks1=R1({name:"newsletter-list",description:"Newsletter list page template",schema:kZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:OZw}});Z0();c0();import{jsxDEV as y8,Fragment as CZw}from"preact/jsx-dev-runtime";var RZw=K.object({id:K.string(),title:K.string(),url:K.string()}),Os1=K.object({id:K.string(),subject:K.string(),url:K.string()}),hZw=K.object({id:K.string(),subject:K.string(),status:_E,content:K.string(),created:K.string(),updated:K.string(),sentAt:K.string().optional(),scheduledFor:K.string().optional(),sourceEntities:K.array(RZw).optional(),prevNewsletter:Os1.nullable().optional(),nextNewsletter:Os1.nullable().optional()}),vZw=({subject:A,status:Q,content:w,created:B,sentAt:$,scheduledFor:Y,sourceEntities:D,prevNewsletter:X,nextNewsletter:H})=>{let W=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],f=$??B,Z=$?"Sent":"Created";return y8(CZw,{children:[y8(jQ,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),y8("section",{className:"newsletter-detail-section",children:y8("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:y8("div",{className:"max-w-3xl mx-auto",children:[y8(_G,{items:W},void 0,!1,void 0,this),y8("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),y8("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[y8(vD,{status:Q},void 0,!1,void 0,this),y8("span",{children:[Z,": ",Z5(f,{style:"long"})]},void 0,!0,void 0,this),Y&&Q==="queued"&&y8("span",{children:["Scheduled for: ",Z5(Y,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D&&D.length>0&&y8(uw,{variant:"compact",className:"mb-8",children:[y8("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),y8("ul",{className:"space-y-1",children:D.map((G)=>y8("li",{children:y8("a",{href:G.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:G.title},void 0,!1,void 0,this)},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),y8($9,{markdown:w},void 0,!1,void 0,this),(X??H)&&y8("nav",{className:"mt-12 pt-8 border-t border-theme",children:y8("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[X?y8(uw,{href:X.url,variant:"compact",children:[y8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),y8("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):y8("div",{},void 0,!1,void 0,this),H&&y8(uw,{href:H.url,variant:"compact",className:"md:text-right",children:[y8("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),y8("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:H.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)},xs1=R1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:hZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:vZw}});var Rs1={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.136",description:"Newsletter entity type with AI generation and publish pipeline",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint src test --ext .ts,.tsx","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/contracts":"workspace:*","@brains/entity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var gZw=K.object({});class Ln0 extends kQ{entityType="newsletter";schema=Fo;adapter=Ms1;constructor(A={}){super("newsletter",Rs1,A,gZw)}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}createGenerationHandler(A){return new bn0(this.logger,A)}getTemplates(){return{generation:Ps1,"newsletter-list":ks1,"newsletter-detail":xs1}}getDataSources(){return[new In0(this.logger.child("NewsletterDataSource"))]}async onRegister(A){this.deferPublishRegistration(A),this.subscribeToGenerateExecute(A),this.registerEvalHandlers(A),A.messaging.subscribe("system:plugins:ready",async()=>{let Q=await A.messaging.send({type:"buttondown:is-configured",payload:{}});if(!("noop"in Q)&&Q.success)await A.messaging.send({type:"plugin:site-builder:slot:register",payload:{pluginId:this.id,slotName:"footer-top",render:()=>EZw(su0,{variant:"inline"})}});return{success:!0}}),this.logger.debug("Newsletter plugin registered")}deferPublishRegistration(A){let Q={name:"internal",publish:async(w,B)=>{let $=typeof B.subject==="string"?B.subject:"",Y=await A.messaging.send({type:"buttondown:send",payload:{entityId:"",subject:$,content:w}});return{id:!("noop"in Y)&&Y.data?.emailId?Y.data.emailId:"internal"}}};A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"publish:register",payload:{entityType:"newsletter",provider:Q,config:{publishResultIdField:"buttondownId",publishTimestampField:"sentAt"}}}),{success:!0}})}subscribeToGenerateExecute(A){A.messaging.subscribe("generate:execute",async(Q)=>{if(Q.payload.entityType!=="newsletter")return{success:!0};try{let w=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:10}});if(w.length===0)return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:"No published posts available for newsletter"}}),{success:!0};return await A.jobs.enqueue({type:"newsletter:generation",data:{sourceEntityIds:w.map((B)=>B.id),sourceEntityType:"post",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}}),{success:!0}}catch(w){return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:vA(w)}}),{success:!0}}})}registerEvalHandlers(A){let Q=K.object({prompt:K.string().optional(),content:K.string().optional()});A.eval.registerHandler("generation",async(w)=>{let B=Q.parse(w),$=B.content?`Create an engaging newsletter based on this content:
8274
8274
 
8275
- ${B.content}`:B.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function Nn0(A={}){return new Ln0(A)}c0();Z0();class PE{config;logger;constructor(A,Q){this.config=A;this.logger=Q}async request(A,Q={}){let w=`https://api.buttondown.email/v1${A}`;this.logger.debug("Buttondown API request",{endpoint:A,method:Q.method??"GET"});let B=await fetch(w,{...Q,headers:{Authorization:`Token ${this.config.apiKey}`,"Content-Type":"application/json",...Q.headers}});if(!B.ok){let $=await B.json().catch(()=>({})),Y=$.detail??$.message??`HTTP ${B.status}`;throw this.logger.error("Buttondown API error",{endpoint:A,status:B.status,error:Y}),Error(`Buttondown API error: ${Y}`)}return B.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(w){if(w instanceof Error&&w.message.includes("already subscribed")){let B=w.message.match(/id=([a-f0-9-]+)/);return this.logger.info("Subscriber already exists",{email:A.email}),{id:B?.[1]??"existing",email:A.email,subscriber_type:"already_subscribed"}}throw w}}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 w=Q.toString(),B=w?`/subscribers?${w}`:"/subscribers";return this.request(B)}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}}}c0();Z0();var TZw=K.object({email:K.string().email().describe("Email address to subscribe"),name:K.string().optional().describe("Subscriber name (optional)"),tags:K.array(K.string()).optional().describe("Tags to apply to subscriber (optional)")}),SZw=K.object({email:K.string().email().describe("Email address to unsubscribe")}),mZw=K.object({type:K.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:K.number().optional().describe("Maximum number of results")});function hs1(A,Q,w){let B=new PE(Q,w);return[Sw(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",TZw,async($)=>{try{let Y=await B.createSubscriber({email:$.email,...$.name&&{name:$.name},...$.tags&&{tags:$.tags}}),D=Y.subscriber_type==="already_subscribed";return l8({subscriberId:Y.id,email:Y.email,status:Y.subscriber_type,message:D?"already_subscribed":"subscribed"},D?`${$.email} is already subscribed`:`Subscribed ${$.email} successfully`)}catch(Y){return P9(vA(Y))}}),Sw(A,"unsubscribe","Unsubscribe an email address from the newsletter.",SZw,async($)=>{try{return await B.unsubscribe($.email),l8({email:$.email},`Unsubscribed ${$.email} successfully`)}catch(Y){return P9(vA(Y))}}),Sw(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",mZw,async($)=>{try{let Y=await B.listSubscribers({...$.type&&{type:$.type},...$.limit&&{limit:$.limit}});return l8({subscribers:Y.results.map((D)=>({id:D.id,email:D.email,status:D.subscriber_type})),count:Y.count},`Found ${Y.count} subscribers`)}catch(Y){return P9(vA(Y))}})]}Z0();async function vs1(A,Q,w,B){if(A.entityType!=="post")return{success:!0,skipped:!0,reason:"Only post entity types trigger auto-send"};let $=await w.getEntity({entityType:"post",id:A.entityId});if(!$)return{success:!1,error:`Post ${A.entityId} not found`};B.info("Auto-sending newsletter for published post",{postId:$.id,title:$.metadata.title});try{let Y=await Q.createEmail({subject:$.metadata.title,body:$.content,status:"about_to_send"});return B.info("Newsletter sent for post",{postId:$.id,emailId:Y.id}),{success:!0,emailId:Y.id}}catch(Y){let D=vA(Y);return B.error("Failed to send newsletter for post",{postId:$.id,error:D}),{success:!1,error:D}}}var Cs1={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.135",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 cZw=K.object({apiKey:K.string().optional().describe("Buttondown API key"),doubleOptIn:K.boolean().default(!0).describe("Require email confirmation for new subscribers"),autoSendOnPublish:K.boolean().default(!1).describe("Automatically send newsletter when a blog post is published")});class jn0 extends IQ{constructor(A={}){super("buttondown",Cs1,A,cZw)}async onRegister(A){if(A.messaging.subscribe("buttondown:is-configured",async()=>{return{success:!!this.config.apiKey}}),this.config.apiKey){let Q=new PE({apiKey:this.config.apiKey,doubleOptIn:this.config.doubleOptIn},this.logger);if(A.messaging.subscribe("buttondown:send",async(w)=>{try{return{success:!0,data:{emailId:(await Q.createEmail({subject:w.payload.subject,body:w.payload.content,status:"about_to_send"})).id}}}catch(B){return this.logger.error("Buttondown send failed",{error:vA(B)}),{success:!1}}}),this.config.autoSendOnPublish)A.messaging.subscribe("publish:completed",async(w)=>{return await vs1(w.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 hs1(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 Mn0(A={}){return new jn0(A)}var lZw=K.object({apiKey:K.string().optional().describe("Buttondown API key"),doubleOptIn:K.boolean().optional().describe("Require email confirmation for new subscribers"),autoSendOnPublish:K.boolean().optional().describe("Automatically send newsletter when a blog post is published")});function ys1(A={}){let Q=lZw.parse(A);return[Nn0({}),Mn0({...Q.apiKey!==void 0&&{apiKey:Q.apiKey},...Q.doubleOptIn!==void 0&&{doubleOptIn:Q.doubleOptIn},...Q.autoSendOnPublish!==void 0&&{autoSendOnPublish:Q.autoSendOnPublish}})]}c0();Z0();import{existsSync as QKw,mkdirSync as wKw,writeFileSync as BKw}from"fs";import{join as bF}from"path";Z0();var _n0=K.object({baseFolder:K.string().default("_obsidian")});Z0();function pZw(A){let Q=A,w=!0,B=void 0,$=!1,Y=!0;while(Y){if(Y=!1,Q instanceof K.ZodOptional)w=!1,Q=Q._def.innerType,Y=!0;if(Q instanceof K.ZodDefault)w=!1,$=!0,B=Q._def.defaultValue(),Q=Q._def.innerType,Y=!0;if(Q instanceof K.ZodNullable)w=!1,Q=Q._def.innerType,Y=!0}let D={inner:Q,required:w};if($)D.defaultValue=B;return D}function iZw(A){if(A instanceof K.ZodEnum)return{type:"enum",enumValues:A._def.values};if(A instanceof K.ZodLiteral)return{type:"string",defaultValue:A._def.value};if(A instanceof K.ZodString)return{type:"string"};if(A instanceof K.ZodNumber)return{type:"number"};if(A instanceof K.ZodBoolean)return{type:"boolean"};if(A instanceof K.ZodArray)return{type:"array"};if(A instanceof K.ZodDate)return{type:"date"};if(A instanceof K.ZodPipeline){if(A._def.out instanceof K.ZodDate)return{type:"date"}}return{type:"unknown"}}function Es1(A){let Q=A.shape,w=[];for(let[B,$]of Object.entries(Q)){let{inner:Y,required:D,defaultValue:X}=pZw($),H=iZw(Y),W={name:B,type:H.type,required:D},f=X!==void 0?X:H.defaultValue;if(f!==void 0)W.defaultValue=f;if(H.enumValues)W.enumValues=H.enumValues;w.push(W)}return w}function dZw(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 gs1(A,Q,w=""){let B=["---"];for(let $ of Q){let Y=dZw($,A);if(Y==="")B.push(`${$.name}:`);else B.push(`${$.name}: ${Y}`)}if(B.push("---"),B.push(""),w)B.push(w);else B.push("<!-- Write your content here -->"),B.push("");return B.join(`
8275
+ ${B.content}`:B.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function Nn0(A={}){return new Ln0(A)}c0();Z0();class PE{config;logger;constructor(A,Q){this.config=A;this.logger=Q}async request(A,Q={}){let w=`https://api.buttondown.email/v1${A}`;this.logger.debug("Buttondown API request",{endpoint:A,method:Q.method??"GET"});let B=await fetch(w,{...Q,headers:{Authorization:`Token ${this.config.apiKey}`,"Content-Type":"application/json",...Q.headers}});if(!B.ok){let $=await B.json().catch(()=>({})),Y=$.detail??$.message??`HTTP ${B.status}`;throw this.logger.error("Buttondown API error",{endpoint:A,status:B.status,error:Y}),Error(`Buttondown API error: ${Y}`)}return B.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(w){if(w instanceof Error&&w.message.includes("already subscribed")){let B=w.message.match(/id=([a-f0-9-]+)/);return this.logger.info("Subscriber already exists",{email:A.email}),{id:B?.[1]??"existing",email:A.email,subscriber_type:"already_subscribed"}}throw w}}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 w=Q.toString(),B=w?`/subscribers?${w}`:"/subscribers";return this.request(B)}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}}}c0();Z0();var TZw=K.object({email:K.string().email().describe("Email address to subscribe"),name:K.string().optional().describe("Subscriber name (optional)"),tags:K.array(K.string()).optional().describe("Tags to apply to subscriber (optional)")}),SZw=K.object({email:K.string().email().describe("Email address to unsubscribe")}),mZw=K.object({type:K.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:K.number().optional().describe("Maximum number of results")});function hs1(A,Q,w){let B=new PE(Q,w);return[Sw(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",TZw,async($)=>{try{let Y=await B.createSubscriber({email:$.email,...$.name&&{name:$.name},...$.tags&&{tags:$.tags}}),D=Y.subscriber_type==="already_subscribed";return l8({subscriberId:Y.id,email:Y.email,status:Y.subscriber_type,message:D?"already_subscribed":"subscribed"},D?`${$.email} is already subscribed`:`Subscribed ${$.email} successfully`)}catch(Y){return P9(vA(Y))}}),Sw(A,"unsubscribe","Unsubscribe an email address from the newsletter.",SZw,async($)=>{try{return await B.unsubscribe($.email),l8({email:$.email},`Unsubscribed ${$.email} successfully`)}catch(Y){return P9(vA(Y))}}),Sw(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",mZw,async($)=>{try{let Y=await B.listSubscribers({...$.type&&{type:$.type},...$.limit&&{limit:$.limit}});return l8({subscribers:Y.results.map((D)=>({id:D.id,email:D.email,status:D.subscriber_type})),count:Y.count},`Found ${Y.count} subscribers`)}catch(Y){return P9(vA(Y))}})]}Z0();async function vs1(A,Q,w,B){if(A.entityType!=="post")return{success:!0,skipped:!0,reason:"Only post entity types trigger auto-send"};let $=await w.getEntity({entityType:"post",id:A.entityId});if(!$)return{success:!1,error:`Post ${A.entityId} not found`};B.info("Auto-sending newsletter for published post",{postId:$.id,title:$.metadata.title});try{let Y=await Q.createEmail({subject:$.metadata.title,body:$.content,status:"about_to_send"});return B.info("Newsletter sent for post",{postId:$.id,emailId:Y.id}),{success:!0,emailId:Y.id}}catch(Y){let D=vA(Y);return B.error("Failed to send newsletter for post",{postId:$.id,error:D}),{success:!1,error:D}}}var Cs1={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.136",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 cZw=K.object({apiKey:K.string().optional().describe("Buttondown API key"),doubleOptIn:K.boolean().default(!0).describe("Require email confirmation for new subscribers"),autoSendOnPublish:K.boolean().default(!1).describe("Automatically send newsletter when a blog post is published")});class jn0 extends IQ{constructor(A={}){super("buttondown",Cs1,A,cZw)}async onRegister(A){if(A.messaging.subscribe("buttondown:is-configured",async()=>{return{success:!!this.config.apiKey}}),this.config.apiKey){let Q=new PE({apiKey:this.config.apiKey,doubleOptIn:this.config.doubleOptIn},this.logger);if(A.messaging.subscribe("buttondown:send",async(w)=>{try{return{success:!0,data:{emailId:(await Q.createEmail({subject:w.payload.subject,body:w.payload.content,status:"about_to_send"})).id}}}catch(B){return this.logger.error("Buttondown send failed",{error:vA(B)}),{success:!1}}}),this.config.autoSendOnPublish)A.messaging.subscribe("publish:completed",async(w)=>{return await vs1(w.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 hs1(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 Mn0(A={}){return new jn0(A)}var lZw=K.object({apiKey:K.string().optional().describe("Buttondown API key"),doubleOptIn:K.boolean().optional().describe("Require email confirmation for new subscribers"),autoSendOnPublish:K.boolean().optional().describe("Automatically send newsletter when a blog post is published")});function ys1(A={}){let Q=lZw.parse(A);return[Nn0({}),Mn0({...Q.apiKey!==void 0&&{apiKey:Q.apiKey},...Q.doubleOptIn!==void 0&&{doubleOptIn:Q.doubleOptIn},...Q.autoSendOnPublish!==void 0&&{autoSendOnPublish:Q.autoSendOnPublish}})]}c0();Z0();import{existsSync as QKw,mkdirSync as wKw,writeFileSync as BKw}from"fs";import{join as bF}from"path";Z0();var _n0=K.object({baseFolder:K.string().default("_obsidian")});Z0();function pZw(A){let Q=A,w=!0,B=void 0,$=!1,Y=!0;while(Y){if(Y=!1,Q instanceof K.ZodOptional)w=!1,Q=Q._def.innerType,Y=!0;if(Q instanceof K.ZodDefault)w=!1,$=!0,B=Q._def.defaultValue(),Q=Q._def.innerType,Y=!0;if(Q instanceof K.ZodNullable)w=!1,Q=Q._def.innerType,Y=!0}let D={inner:Q,required:w};if($)D.defaultValue=B;return D}function iZw(A){if(A instanceof K.ZodEnum)return{type:"enum",enumValues:A._def.values};if(A instanceof K.ZodLiteral)return{type:"string",defaultValue:A._def.value};if(A instanceof K.ZodString)return{type:"string"};if(A instanceof K.ZodNumber)return{type:"number"};if(A instanceof K.ZodBoolean)return{type:"boolean"};if(A instanceof K.ZodArray)return{type:"array"};if(A instanceof K.ZodDate)return{type:"date"};if(A instanceof K.ZodPipeline){if(A._def.out instanceof K.ZodDate)return{type:"date"}}return{type:"unknown"}}function Es1(A){let Q=A.shape,w=[];for(let[B,$]of Object.entries(Q)){let{inner:Y,required:D,defaultValue:X}=pZw($),H=iZw(Y),W={name:B,type:H.type,required:D},f=X!==void 0?X:H.defaultValue;if(f!==void 0)W.defaultValue=f;if(H.enumValues)W.enumValues=H.enumValues;w.push(W)}return w}function dZw(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 gs1(A,Q,w=""){let B=["---"];for(let $ of Q){let Y=dZw($,A);if(Y==="")B.push(`${$.name}:`);else B.push(`${$.name}: ${Y}`)}if(B.push("---"),B.push(""),w)B.push(w);else B.push("<!-- Write your content here -->"),B.push("");return B.join(`
8276
8276
  `)}Z0();var nZw={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function rZw(A){let Q={name:A.name,id:A.name,type:nZw[A.type]};if(A.type==="enum"&&A.enumValues){let w={};A.enumValues.forEach((B,$)=>{w[String($)]=B}),Q.options=w}return Q}function Ts1(A,Q){let w={filesPaths:A,fields:Q.map(rZw)};return`---
8277
8277
  ${$U(w)}---
8278
- `}Z0();var oZw=new Set(["entityType"]),sZw={base:"Notes"},aZw=new Set(["note"]);function tZw(A){let Q=["file.name"];for(let w of A)if(!oZw.has(w.name))Q.push(w.name);return Q}function eZw(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function Ss1(A,Q){let w=sZw[A]??bt(A),B=eZw(Q),$=tZw(Q),Y=[{type:"table",name:`All ${w}`,order:$}];if(B)Y.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:$});let X={filters:{and:[aZw.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:Y};return{filename:`${w}.base`,content:$U(X),hasStatus:B}}function ms1(A){if(A.length===0)return null;let Q=A.map((B)=>`file.inFolder("${B}")`),w={filters:{and:[Q.length===1?Q[0]:{or:Q}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return $U(w)}function us1(A){if(A.length===0)return null;let Q=A.map((B)=>`file.inFolder("${B.entityType}")`),w={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 $U(w)}var cs1={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.135",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 $Kw={mkdir:wKw,writeFile:BKw,existsFile:QKw},YKw=K.object({entityTypes:K.array(K.string()).optional().describe("Entity types to generate templates for (default: all)")});class Pn0 extends IQ{deps;constructor(A={},Q={}){super("obsidian-vault",cs1,A,_n0);this.deps={...$Kw,...Q}}async onReady(A){this.logger.info("Auto-syncing Obsidian templates, fileClasses, and bases"),await this.sync(A)}async getTools(){let A=this.getContext();return[Sw(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",YKw,async(Q)=>{return this.sync(A,Q.entityTypes)},{sideEffects:"external"})]}async sync(A,Q){try{let w=A.entityService.getEntityTypes(),B=Q?w.filter((L)=>Q.includes(L)):w,$=bF(A.dataDir,this.config.baseFolder),Y=bF($,"templates"),D=bF($,"fileClasses"),X=bF($,"bases");this.deps.mkdir(Y,{recursive:!0}),this.deps.mkdir(D,{recursive:!0}),this.deps.mkdir(X,{recursive:!0});let H=[],W=[],f=[],Z=[],G=[],F=[];for(let L of B){let N=A.entities.getEffectiveFrontmatterSchema(L);if(!N){this.logger.debug(`Skipping ${L}: no frontmatter schema`),W.push(L);continue}let _=Es1(N),j=A.entities.getAdapter(L),g=j?.isSingleton===!0,E=Ts1(L,_);if(this.deps.writeFile(bF(D,`${L}.md`),E),f.push(L),g){G.push(L),this.logger.debug(`Generated fileClass (singleton): ${L}`);continue}let y=j?.getBodyTemplate()??"",h=gs1(L,_,y);this.deps.writeFile(bF(Y,`${L}.md`),h),H.push(L);let T=Ss1(L,_),S=bF(X,T.filename);if(!this.deps.existsFile(S))this.deps.writeFile(S,T.content),Z.push(L),this.logger.debug(`Generated base: ${T.filename}`);if(T.hasStatus)F.push({entityType:L,fields:_});this.logger.debug(`Generated template + fileClass: ${L}`)}let V=ms1(G);if(V){let L=bF(X,"Settings.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,V),Z.push("Settings"),this.logger.debug("Generated Settings.base")}let b=us1(F);if(b){let L=bF(X,"Pipeline.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,b),Z.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${H.length} templates, ${f.length} fileClasses, ${Z.length} bases (${W.length} skipped)`),l8({generated:H,skipped:W,fileClasses:f,bases:Z})}catch(w){return this.logger.error("Failed to sync",{error:w}),P9(w instanceof Error?w.message:"Unknown error")}}}function kn0(A,Q){return new Pn0(A,Q)}c0();c0();Z0();l$();c0();Z0();var On0=K.enum(["draft","active","archived"]),xn0=K.enum(["anchor","trusted","public"]),Rn0=K.enum(["agent-confirmed","manual"]),mD=K.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,K.string().min(1).optional()),ls1=K.object({event:K.string().min(1),target:K.string().min(1),operatorAction:K.boolean().optional(),label:mD,description:mD,operatorDescription:mD}),ps1=K.object({id:K.string().min(1),title:K.string().min(1),prompt:mD,requiredDetails:K.array(K.string().min(1)).default([]),instructions:K.array(K.string().min(1)).default([]),doneWhen:K.array(K.string().min(1)).default([]),transitions:K.array(ls1).default([])}),hn0=K.object({purpose:K.string().min(1),operatingRules:K.array(K.string().min(1)).default([]),initialState:K.string().min(1),states:K.array(ps1).min(1),finalStates:K.array(K.string().min(1)).min(1),nextPrompts:K.array(K.string().min(1)).default([])}),Vo=K.object({title:K.string(),status:On0.default("active"),audience:xn0.default("anchor"),trigger:mD,lifecycle:mD,once:K.boolean().optional(),starterText:mD,description:mD,starterPrompt:mD,completionMode:Rn0.default("agent-confirmed")}),is1=K.object({title:K.string(),status:On0,audience:xn0,trigger:mD,lifecycle:mD,once:K.boolean().optional(),starterText:mD,description:mD,starterPrompt:mD,completionMode:Rn0}),Jo=o1.extend({entityType:K.literal("playbook"),metadata:is1}),vn0=K.object({});class En0 extends pw{constructor(){super(hn0,{title:"Playbook",mappings:[{key:"purpose",label:"Purpose",type:"string"},{key:"operatingRules",label:"Operating Rules",type:"array",itemType:"string"},{key:"initialState",label:"Initial State",type:"string"},{key:"states",label:"States",type:"array",itemType:"object",itemMappings:[{key:"id",label:"ID",type:"string"},{key:"title",label:"Title",type:"string"},{key:"prompt",label:"Prompt",type:"custom",formatter:Cn0,parser:yn0},{key:"requiredDetails",label:"Required Details",type:"array",itemType:"string"},{key:"instructions",label:"Instructions",type:"array",itemType:"string"},{key:"doneWhen",label:"Done When",type:"array",itemType:"string"},{key:"transitions",label:"Transitions",type:"array",itemType:"object",itemMappings:[{key:"event",label:"Event",type:"string"},{key:"target",label:"Target",type:"string"},{key:"operatorAction",label:"User Choice",type:"custom",formatter:DKw,parser:XKw},{key:"label",label:"Label",type:"custom",formatter:Cn0,parser:yn0},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:Cn0,parser:yn0}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var KD0=new En0;function Cn0(A){return typeof A==="string"?A:""}function yn0(A){let Q=A.trim();return Q.length>0?Q:void 0}function DKw(A){return typeof A==="boolean"?String(A):""}function XKw(A){let Q=A.trim().toLowerCase();if(Q==="true")return!0;if(Q==="false")return!1;return}function ds1(A){let Q=[],w=new Set,B=new Set;for(let $ of A.states){if(w.has($.id))B.add($.id);w.add($.id)}if(!w.has(A.initialState))Q.push(`Playbook initial state '${A.initialState}' is not defined.`);for(let $ of B)Q.push(`Duplicate playbook state id '${$}'.`);for(let $ of A.finalStates)if(!w.has($))Q.push(`Playbook final state '${$}' is not defined.`);for(let $ of A.states)for(let Y of $.transitions)if(!w.has(Y.target))Q.push(`Playbook transition '${$.id}' -> '${Y.target}' targets an undefined state.`);for(let $ of HKw(A,w))Q.push(`Playbook state '${$}' is unreachable.`);return{valid:Q.length===0,errors:Q}}function Io(A){let Q=ds1(A);if(!Q.valid)throw Error(Q.errors.join(`
8278
+ `}Z0();var oZw=new Set(["entityType"]),sZw={base:"Notes"},aZw=new Set(["note"]);function tZw(A){let Q=["file.name"];for(let w of A)if(!oZw.has(w.name))Q.push(w.name);return Q}function eZw(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function Ss1(A,Q){let w=sZw[A]??bt(A),B=eZw(Q),$=tZw(Q),Y=[{type:"table",name:`All ${w}`,order:$}];if(B)Y.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:$});let X={filters:{and:[aZw.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:Y};return{filename:`${w}.base`,content:$U(X),hasStatus:B}}function ms1(A){if(A.length===0)return null;let Q=A.map((B)=>`file.inFolder("${B}")`),w={filters:{and:[Q.length===1?Q[0]:{or:Q}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return $U(w)}function us1(A){if(A.length===0)return null;let Q=A.map((B)=>`file.inFolder("${B.entityType}")`),w={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 $U(w)}var cs1={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.136",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 $Kw={mkdir:wKw,writeFile:BKw,existsFile:QKw},YKw=K.object({entityTypes:K.array(K.string()).optional().describe("Entity types to generate templates for (default: all)")});class Pn0 extends IQ{deps;constructor(A={},Q={}){super("obsidian-vault",cs1,A,_n0);this.deps={...$Kw,...Q}}async onReady(A){this.logger.info("Auto-syncing Obsidian templates, fileClasses, and bases"),await this.sync(A)}async getTools(){let A=this.getContext();return[Sw(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",YKw,async(Q)=>{return this.sync(A,Q.entityTypes)},{sideEffects:"external"})]}async sync(A,Q){try{let w=A.entityService.getEntityTypes(),B=Q?w.filter((L)=>Q.includes(L)):w,$=bF(A.dataDir,this.config.baseFolder),Y=bF($,"templates"),D=bF($,"fileClasses"),X=bF($,"bases");this.deps.mkdir(Y,{recursive:!0}),this.deps.mkdir(D,{recursive:!0}),this.deps.mkdir(X,{recursive:!0});let H=[],W=[],f=[],Z=[],G=[],F=[];for(let L of B){let N=A.entities.getEffectiveFrontmatterSchema(L);if(!N){this.logger.debug(`Skipping ${L}: no frontmatter schema`),W.push(L);continue}let _=Es1(N),j=A.entities.getAdapter(L),g=j?.isSingleton===!0,E=Ts1(L,_);if(this.deps.writeFile(bF(D,`${L}.md`),E),f.push(L),g){G.push(L),this.logger.debug(`Generated fileClass (singleton): ${L}`);continue}let y=j?.getBodyTemplate()??"",h=gs1(L,_,y);this.deps.writeFile(bF(Y,`${L}.md`),h),H.push(L);let T=Ss1(L,_),S=bF(X,T.filename);if(!this.deps.existsFile(S))this.deps.writeFile(S,T.content),Z.push(L),this.logger.debug(`Generated base: ${T.filename}`);if(T.hasStatus)F.push({entityType:L,fields:_});this.logger.debug(`Generated template + fileClass: ${L}`)}let V=ms1(G);if(V){let L=bF(X,"Settings.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,V),Z.push("Settings"),this.logger.debug("Generated Settings.base")}let b=us1(F);if(b){let L=bF(X,"Pipeline.base");if(!this.deps.existsFile(L))this.deps.writeFile(L,b),Z.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${H.length} templates, ${f.length} fileClasses, ${Z.length} bases (${W.length} skipped)`),l8({generated:H,skipped:W,fileClasses:f,bases:Z})}catch(w){return this.logger.error("Failed to sync",{error:w}),P9(w instanceof Error?w.message:"Unknown error")}}}function kn0(A,Q){return new Pn0(A,Q)}c0();c0();Z0();l$();c0();Z0();var On0=K.enum(["draft","active","archived"]),xn0=K.enum(["anchor","trusted","public"]),Rn0=K.enum(["agent-confirmed","manual"]),mD=K.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,K.string().min(1).optional()),ls1=K.object({event:K.string().min(1),target:K.string().min(1),operatorAction:K.boolean().optional(),label:mD,description:mD,operatorDescription:mD}),ps1=K.object({id:K.string().min(1),title:K.string().min(1),prompt:mD,requiredDetails:K.array(K.string().min(1)).default([]),instructions:K.array(K.string().min(1)).default([]),doneWhen:K.array(K.string().min(1)).default([]),transitions:K.array(ls1).default([])}),hn0=K.object({purpose:K.string().min(1),operatingRules:K.array(K.string().min(1)).default([]),initialState:K.string().min(1),states:K.array(ps1).min(1),finalStates:K.array(K.string().min(1)).min(1),nextPrompts:K.array(K.string().min(1)).default([])}),Vo=K.object({title:K.string(),status:On0.default("active"),audience:xn0.default("anchor"),trigger:mD,lifecycle:mD,once:K.boolean().optional(),starterText:mD,description:mD,starterPrompt:mD,completionMode:Rn0.default("agent-confirmed")}),is1=K.object({title:K.string(),status:On0,audience:xn0,trigger:mD,lifecycle:mD,once:K.boolean().optional(),starterText:mD,description:mD,starterPrompt:mD,completionMode:Rn0}),Jo=o1.extend({entityType:K.literal("playbook"),metadata:is1}),vn0=K.object({});class En0 extends pw{constructor(){super(hn0,{title:"Playbook",mappings:[{key:"purpose",label:"Purpose",type:"string"},{key:"operatingRules",label:"Operating Rules",type:"array",itemType:"string"},{key:"initialState",label:"Initial State",type:"string"},{key:"states",label:"States",type:"array",itemType:"object",itemMappings:[{key:"id",label:"ID",type:"string"},{key:"title",label:"Title",type:"string"},{key:"prompt",label:"Prompt",type:"custom",formatter:Cn0,parser:yn0},{key:"requiredDetails",label:"Required Details",type:"array",itemType:"string"},{key:"instructions",label:"Instructions",type:"array",itemType:"string"},{key:"doneWhen",label:"Done When",type:"array",itemType:"string"},{key:"transitions",label:"Transitions",type:"array",itemType:"object",itemMappings:[{key:"event",label:"Event",type:"string"},{key:"target",label:"Target",type:"string"},{key:"operatorAction",label:"User Choice",type:"custom",formatter:DKw,parser:XKw},{key:"label",label:"Label",type:"custom",formatter:Cn0,parser:yn0},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:Cn0,parser:yn0}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var KD0=new En0;function Cn0(A){return typeof A==="string"?A:""}function yn0(A){let Q=A.trim();return Q.length>0?Q:void 0}function DKw(A){return typeof A==="boolean"?String(A):""}function XKw(A){let Q=A.trim().toLowerCase();if(Q==="true")return!0;if(Q==="false")return!1;return}function ds1(A){let Q=[],w=new Set,B=new Set;for(let $ of A.states){if(w.has($.id))B.add($.id);w.add($.id)}if(!w.has(A.initialState))Q.push(`Playbook initial state '${A.initialState}' is not defined.`);for(let $ of B)Q.push(`Duplicate playbook state id '${$}'.`);for(let $ of A.finalStates)if(!w.has($))Q.push(`Playbook final state '${$}' is not defined.`);for(let $ of A.states)for(let Y of $.transitions)if(!w.has(Y.target))Q.push(`Playbook transition '${$.id}' -> '${Y.target}' targets an undefined state.`);for(let $ of HKw(A,w))Q.push(`Playbook state '${$}' is unreachable.`);return{valid:Q.length===0,errors:Q}}function Io(A){let Q=ds1(A);if(!Q.valid)throw Error(Q.errors.join(`
8279
8279
  `))}function HKw(A,Q){if(!Q.has(A.initialState))return[];let w=new Set,B=[A.initialState];while(B.length>0){let $=B.shift();if(!$||w.has($))continue;w.add($);let Y=A.states.find((D)=>D.id===$);if(!Y)continue;for(let D of Y.transitions)if(Q.has(D.target)&&!w.has(D.target))B.push(D.target)}return A.states.map(($)=>$.id).filter(($)=>!w.has($))}class gn0 extends J2{constructor(){super({entityType:"playbook",purpose:"A guided multi-step workflow the assistant runs together with the user.",schema:Jo,frontmatterSchema:Vo})}createPlaybookContent(A,Q){return this.buildMarkdown(KD0.format(Q),A)}parsePlaybookContent(A){let Q=this.parseFrontMatter(A,Vo),w=this.extractBody(A).trim(),B=WKw(w)?fKw(w):KD0.parse(w);return Io(B),{frontmatter:Vo.parse(Q),body:B,bodyMarkdown:w}}fromMarkdown(A){let{frontmatter:Q}=this.parsePlaybookContent(A);return{content:A,entityType:"playbook",metadata:{title:Q.title,status:Q.status,audience:Q.audience,...Q.trigger?{trigger:Q.trigger}:{},...Q.lifecycle?{lifecycle:Q.lifecycle}:{},...Q.once!==void 0?{once:Q.once}:{},...Q.starterText?{starterText:Q.starterText}:{},...Q.description?{description:Q.description}:{},...Q.starterPrompt?{starterPrompt:Q.starterPrompt}:{},completionMode:Q.completionMode}}}}var RP=new gn0;function WKw(A){return/^##\s+Steps\s*$/im.test(A)}function fKw(A){let Q=ZKw(Tn0(A,"Steps"));if(Q.length===0)throw Error("Playbook must declare at least one step.");let w=Q.map((B,$)=>{let Y=$===Q.length-1;if(!Y&&B.doneWhen.length===0&&B.choices.length===0&&!B.skip)throw Error(`Playbook step '${B.title}' must declare Done when, Choices, or Skip.`);return{id:B.id,title:B.title,...B.prompt?{prompt:B.prompt}:{},requiredDetails:B.requiredDetails,instructions:B.instructions,doneWhen:B.doneWhen,transitions:[...B.doneWhen.length>0&&!Y?[{event:"NEXT",target:Q[$+1]?.id??B.id}]:[],...B.choices.map((D,X)=>({event:`CHOICE_${X+1}`,target:w1(D.target),operatorAction:!0,label:D.label})),...B.skip?[{event:"SKIP",target:w1(B.skip.target),operatorAction:!0,label:B.skip.label}]:[]]}});return{purpose:KKw(A,"Purpose"),operatingRules:ns1(A,"Operating Rules"),initialState:Q[0]?.id??"",states:w,finalStates:[Q.at(-1)?.id??""],nextPrompts:ns1(A,"Next Prompts")}}function ZKw(A){let Q=[],w;for(let B of A.split(/\r?\n/)){let $=/^###\s+(.+?)\s*$/.exec(B);if($){w={title:$[1]??"",content:[]},Q.push(w);continue}w?.content.push(B)}return Q.map((B)=>{let $=B.content.join(`
8280
8280
  `);return{title:B.title,id:w1(B.title),...rs1($,"Say")?{prompt:rs1($,"Say")}:{},requiredDetails:UD0($,"Required details"),instructions:UD0($,"To do"),doneWhen:UD0($,"Done when"),choices:UKw($,"Choices"),...os1($)?{skip:os1($)}:{}}})}function Tn0(A,Q){let w=A.split(/\r?\n/),B=w.findIndex((Y)=>Y.trim().toLowerCase()===`## ${Q.toLowerCase()}`);if(B===-1)return"";let $=[];for(let Y of w.slice(B+1)){if(/^##\s+/.test(Y))break;$.push(Y)}return $.join(`
8281
8281
  `).trim()}function KKw(A,Q){return Tn0(A,Q).split(/\r?\n/).map((w)=>w.trim()).filter((w)=>w.length>0&&!w.startsWith("#")).join(`
8282
8282
  `).trim()}function ns1(A,Q){return ss1(Tn0(A,Q))}function rs1(A,Q){return new RegExp(`^${zKw(Q)}:\\s*(.+?)\\s*$`,"im").exec(A)?.[1]?.trim()}function UD0(A,Q){let w=A.split(/\r?\n/),B=w.findIndex((Y)=>Y.trim().toLowerCase()===`${Q.toLowerCase()}:`);if(B===-1)return[];let $=[];for(let Y of w.slice(B+1)){let D=Y.trim();if(D.length===0)continue;if(/^[A-Za-z][A-Za-z ]+:/.test(D)||/^#{1,6}\s+/.test(D))break;$.push(Y)}return ss1($.join(`
8283
- `))}function UKw(A,Q){return UD0(A,Q).map(GKw)}function GKw(A){let Q=/^(.+?)\s*(?:\u2192|->)\s*(.+)$/.exec(A);if(!Q)throw Error(`Invalid playbook choice '${A}'. Expected "Label \u2192 Step".`);return{label:Q[1]?.trim()??"",target:Q[2]?.trim()??""}}function os1(A){let Q=/^Skip:\s*(.+?)\s*(?:\u2192|->)\s*(.+?)\s*$/im.exec(A);if(!Q)return;return{label:Q[1]?.trim()??"",target:Q[2]?.trim()??""}}function ss1(A){return A.split(/\r?\n/).map((Q)=>/^-\s+(.+?)\s*$/.exec(Q)?.[1]?.trim()).filter((Q)=>Boolean(Q))}function zKw(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var as1={name:"@brains/playbook",private:!0,version:"0.2.0-alpha.135",description:"Playbook entity for durable guided agent workflows",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class ts1 extends kQ{entityType=RP.entityType;schema=Jo;adapter=RP;constructor(A={}){super("playbook",as1,A,vn0)}async getInstructions(){return"Playbook entities describe durable, editable guided workflows for the agent. Use them as operating guidance when a playbook run is active; do not treat them as content to publish unless the user explicitly asks."}}function es1(A={}){return new ts1(A)}CB();c0();Z0();IX();b10();var Aa1={name:"@brains/playbooks",private:!0,version:"0.2.0-alpha.135",description:"Runtime orchestration for chat-native playbook runs",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/contracts":"workspace:*","@brains/playbook":"workspace:*","@brains/plugins":"workspace:*","@brains/runtime-state":"workspace:*","@brains/utils":"workspace:*",xstate:"^5.28.0"},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"}};Z0();var wa1=K.enum(["offered","active","completed","dismissed"]),GD0=K.object({id:K.string().min(1),kind:K.enum(["entity_event"]),stateId:K.string().min(1).optional(),observedAt:K.string().datetime(),data:K.record(K.string(),K.unknown())}).strict(),Ba1=K.object({stateId:K.string().min(1),goal:K.array(K.string().min(1)),met:K.boolean(),reason:K.string().min(1),evaluatedAt:K.string().datetime()}).strict(),hP=K.object({id:K.string().min(1),playbookId:K.string().min(1),playbookVersion:K.string().min(1),lifecycle:K.string().min(1).optional(),status:wa1,conversationId:K.string().min(1).optional(),currentState:K.string().min(1),completedStates:K.array(K.string().min(1)).default([]),snapshot:K.unknown().optional(),context:K.record(K.string(),K.unknown()).default({}),evidence:K.array(GD0).default([]),gateVerdicts:K.array(Ba1).default([]),startedAt:K.string().datetime().optional(),completedAt:K.string().datetime().optional(),updatedAt:K.string().datetime()}).strict(),VKw="playbooks.runs",JKw=hP;class zD0{store;writeQueue=Promise.resolve();constructor(A){this.store=A.scoped({namespace:VKw,schema:JKw})}async list(){return await this.waitForWrites(),(await this.store.list()).map((Q)=>Q.value)}async findById(A){return await this.store.get(A)??void 0}async findActiveByPlaybook(A){return(await this.list()).find((Q)=>Q.playbookId===A&&(Q.status==="active"||Q.status==="offered"))}async findByLifecycle(A){return(await this.list()).find((Q)=>Q.lifecycle===A)}async findActiveByConversation(A){return(await this.listActiveByConversation(A))[0]}async listActiveByConversation(A){return(await this.list()).filter((Q)=>Q.conversationId===A&&(Q.status==="active"||Q.status==="offered"))}async upsert(A){return this.enqueueMutation(async()=>{let Q=await this.store.get(A.id),w=hP.parse({...A,evidence:Qa1(Q?.evidence??[],A.evidence),gateVerdicts:IKw(Q?.gateVerdicts??[],A.gateVerdicts),updatedAt:new Date().toISOString()});return await this.store.set(w.id,w),w})}async appendEvidence(A,Q){return this.enqueueMutation(async()=>{let w=await this.store.get(A);if(!w)throw Error(`Playbook run not found: ${A}`);let B=hP.parse({...w,evidence:Qa1(w.evidence,[Q]),updatedAt:new Date().toISOString()});return await this.store.set(B.id,B),B})}async reset(A){await this.enqueueMutation(async()=>{if(!A){await this.store.clear();return}await this.store.delete(A)})}async enqueueMutation(A){let Q=this.writeQueue,w=()=>{};this.writeQueue=new Promise((B)=>{w=B}),await Q;try{return await A()}finally{w()}}async waitForWrites(){await this.writeQueue}}function Sn0(A){let Q=new Date().toISOString();return hP.parse({id:_V("playbook_run"),playbookId:A.playbookId,playbookVersion:A.playbookVersion,...A.lifecycle?{lifecycle:A.lifecycle}:{},status:A.status??"active",...A.conversationId?{conversationId:A.conversationId}:{},currentState:A.initialState,completedStates:[],...A.snapshot!==void 0?{snapshot:A.snapshot}:{},context:{},evidence:[],gateVerdicts:[],...A.status==="active"||A.status===void 0?{startedAt:Q}:{},updatedAt:Q})}function Qa1(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(B.id,B);return Array.from(w.values())}function IKw(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(bKw(B),B);return Array.from(w.values())}function bKw(A){return[A.stateId,...A.goal].join("\x00")}var Ga1="playbooks:lifecycle-starters",qD0="playbooks:register-lifecycle-starter",za1=K.object({trigger:K.string().min(1),playbookId:K.string().min(1),once:K.boolean().default(!0),starterText:K.string().min(1),description:K.string().min(1).optional(),starterPrompt:K.string().min(1)}).strict(),LKw=K.object({lifecycle:K.record(K.string(),za1).default({}),triggers:K.record(K.string(),K.boolean()).default({})}).strict(),NKw=K.object({lifecycle:K.string().min(1).optional(),interfaceType:K.string().min(1),userPermissionLevel:K.enum(["anchor","trusted","public"])}).strict(),jKw=K.object({id:K.string().min(1),trigger:K.string().min(1),playbookId:K.string().min(1),once:K.boolean().default(!0),starterText:K.string().min(1),description:K.string().min(1).optional(),starterPrompt:K.string().min(1)}).strict(),$a1=K.object({id:K.string().min(1),entityType:K.literal("playbook"),content:K.string().min(1),metadata:K.object({title:K.string().min(1),status:K.enum(["draft","active","archived"]),audience:K.enum(["anchor","trusted","public"]),trigger:K.string().min(1).optional(),lifecycle:K.string().min(1).optional(),once:K.boolean().optional(),starterText:K.string().min(1).optional(),description:K.string().min(1).optional(),starterPrompt:K.string().min(1).optional(),completionMode:K.enum(["agent-confirmed","manual"])}).passthrough()}).passthrough(),Ya1={runId:K.string().min(1).optional(),playbookId:K.string().min(1).optional(),lifecycle:K.string().min(1).optional()},Da1={playbookId:K.string().min(1),lifecycle:K.string().min(1).optional()},Xa1={runId:K.string().min(1).optional(),event:K.string().min(1),context:K.record(K.string(),K.unknown()).optional()},MKw=K.object({met:K.boolean(),reason:K.string().min(1)}).strict(),_Kw=K.object({event:K.string().min(1),target:K.string().min(1),operatorAction:K.boolean().optional(),label:K.string().min(1).optional(),description:K.string().min(1).optional(),operatorDescription:K.string().min(1).optional()}).strict(),PKw=K.object({id:K.string().min(1),title:K.string().min(1),instructions:K.array(K.string().min(1)),requiredDetails:K.array(K.string().min(1)).default([]),doneWhen:K.array(K.string().min(1)).default([]),transitions:K.array(_Kw).default([])}).passthrough(),kKw=K.object({run:hP,state:PKw,goal:K.array(K.string().min(1)),evidence:K.array(GD0).default([])}).strict();class cn0 extends IQ{store;ctx;goalCheck;injectedGoalCheck;startLocks=new Map;registeredLifecycleStarters=new Map;constructor(A={},Q={}){super("playbooks",Aa1,A,LKw);this.injectedGoalCheck=Q.goalCheck,this.goalCheck=Q.goalCheck??cKw}async onRegister(A){await super.onRegister(A),this.ctx=A,this.store=new zD0(A.runtimeState),this.goalCheck=this.injectedGoalCheck??TKw(A),A.registerInstructions(this.buildInstructions()),A.eval.registerHandler("goalCheck",async(Q)=>this.goalCheck.evaluate(kKw.parse(Q))),A.messaging.subscribe(Ga1,async(Q)=>{let w=NKw.parse(Q.payload);return{success:!0,data:{starters:await this.resolveLifecycleStarters(w)}}}),A.messaging.subscribe(qD0,async(Q)=>{let w=jKw.parse(Q.payload);return{success:!0,data:this.registerLifecycleStarter(w,Q.source)}}),A.messaging.subscribe(XN,async(Q)=>{let w=lT.parse(Q.payload),B=await this.buildAgentContextItem(w.conversationId);return{success:!0,data:{items:B?[B]:[]}}}),A.messaging.subscribe(uT,async(Q)=>{let w=hZ0.parse(Q.payload),B=await this.handleAgentAction(w);return B?{success:!0,data:B}:{success:!1}}),A.messaging.subscribe("entity:created",async(Q)=>({success:!0,data:await this.recordEntityEventEvidence("created",Q.payload)})),A.messaging.subscribe("entity:updated",async(Q)=>({success:!0,data:await this.recordEntityEventEvidence("updated",Q.payload)}))}async getTools(){return[{name:"playbook_status",description:"Get playbook lifecycle config, active runs, current state, valid events, and parsed playbook body. After meaningful tool actions, use the reported current state as source of truth. Do not send an extra NEXT after runtime evidence already advanced the run. Do not claim the playbook is finished unless the run has reached a final state.",inputSchema:Ya1,visibility:"anchor",sideEffects:"none",handler:async(A,Q)=>{let w=K.object(Ya1).parse(A);try{return{success:!0,data:await this.getStatus({...w,conversationId:Q.conversationId})}}catch(B){return{success:!1,error:mn0(B)}}}},{name:"playbook_start",description:"Start a playbook run, or resume an existing active run. If the operator asks to start a playbook by title, use the stable slug/id form when known (for example lowercase words joined by hyphens) instead of claiming it is unavailable without calling this tool. Do not call this to continue an already active playbook; use playbook_status and playbook_send_event with a valid event instead.",inputSchema:Da1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Da1).parse(A),B=Q.conversationId,$=B?`${B}:${w.playbookId}`:`playbook:${w.playbookId}`;return this.withStartLock($,async()=>{let Y=await this.requirePlaybook(w.playbookId);Io(Y.body);let D=Y.entity.metadata.lifecycle??w.lifecycle,X=B?(await this.store.listActiveByConversation(B)).find((f)=>f.playbookId===w.playbookId):await this.store.findActiveByPlaybook(w.playbookId),H=X?await this.store.upsert({...X,status:"active",...B?{conversationId:B}:{},...X.startedAt?{}:{startedAt:new Date().toISOString()}}):await this.createStartedRun({playbookId:w.playbookId,playbookVersion:Y.version,body:Y.body,lifecycle:D,conversationId:B});return{success:!0,data:await this.getStatus({runId:H.id})}})}},{name:"playbook_send_event",description:"Send an event to a playbook run state machine and persist the resulting state. Invalid events return an error. Only use this when the operator positively selects a valid event/action or when a gated Done When condition is actually met. For durable gated states, user-provided details are not enough; do not send NEXT until the required system_create/system_update/system_delete tool has succeeded or current run evidence already shows the Done When condition is met. Operator actions and choices are not generic continuation events; do not use this for generic next/continue to select an operator action, even if only one operator action is currently valid. Do not use this when the operator explicitly says they have not chosen, selected, asked for, or used the available action. Skip-style events require a positive request to skip. This tool only changes playbook state; it does not retrieve, show, save, create, update, or transform domain entities. When the operator message only selects a playbook action, call this tool without unrelated domain mutation tools such as system_create or system_update. If the operator also asks to find/show/retrieve content, call system_get or system_search before answering.",inputSchema:Xa1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Xa1).parse(A),B=await this.resolveScopedRunResponse({runId:w.runId,conversationId:Q.conversationId});if(!B.success)return B;let $=await this.sendEventForRun(B.data,w.event,w.context);return $.success?{success:!0,data:$.data}:{success:!1,error:$.error}}}]}async withStartLock(A,Q){let w=this.startLocks.get(A);if(w)return w;let B=Q().finally(()=>{this.startLocks.delete(A)});return this.startLocks.set(A,B),B}async handleAgentAction(A){if(A.userPermissionLevel!=="anchor")return;let Q=await this.resolveScopedRunResponse({conversationId:A.conversationId});if(!Q.success)return;let w=await this.sendEventForRun(Q.data,A.action.event);if(!w.success)return{text:`I couldn't continue the playbook: ${w.error}`,toolResults:[{toolName:"playbook_send_event",args:{runId:Q.data.id,event:A.action.event}}],usage:Wa1()};let B=this.getCurrentRunState(w.data);return{text:hKw(B),...w.data.cards?{cards:w.data.cards}:{},toolResults:[{toolName:"playbook_send_event",args:{runId:Q.data.id,event:A.action.event},data:w.data}],usage:Wa1()}}getCurrentRunState(A){return A.currentState}async sendEventForRun(A,Q,w){let B=await this.requirePlaybook(A.playbookId);if(A.playbookVersion!==B.version)return{success:!1,error:`Playbook definition changed for '${A.playbookId}'. Run version ${A.playbookVersion} does not match current version ${B.version}.`};let $=this.getState(B.body,A.currentState),Y=$?.transitions.find((f)=>f.event===Q),D=await this.transitionRun(A,B.body,Q);if(!D.success){if(D.gateVerdicts)await this.store.upsert({...A,gateVerdicts:D.gateVerdicts});return{success:!1,error:D.error}}let X=B.body.finalStates.includes(D.currentState),H=await this.store.upsert({...A,currentState:D.currentState,completedStates:fa1(A.completedStates,A.currentState),snapshot:D.snapshot,gateVerdicts:D.gateVerdicts,context:{...A.context,...w??{}},...X?{status:"completed",completedAt:new Date().toISOString()}:{}}),W=await this.getStatus({runId:H.id});return{success:!0,data:$&&Y?.operatorAction===!0?OKw(W,$,Y):W}}async createStartedRun(A){let Q=Sn0({playbookId:A.playbookId,playbookVersion:A.playbookVersion,initialState:A.body.initialState,lifecycle:A.lifecycle,conversationId:A.conversationId}),w=this.buildMachine(A.playbookId,A.body,Q),B=E1.createActor(w);B.start();let $=B.getPersistedSnapshot();return B.stop(),this.store.upsert({...Q,snapshot:$})}async transitionRun(A,Q,w){let B=this.getState(Q,A.currentState);if(!B)return{success:!1,error:`Playbook state not found: ${A.currentState}`};let $=await this.prepareGateVerdicts(A,B,w);if(!$.success)return $;let Y={...A,gateVerdicts:$.gateVerdicts},D=this.buildMachine(A.playbookId,Q,Y),X=E1.createActor(D,{...A.snapshot?{snapshot:A.snapshot}:{}});X.start();let H=X.getSnapshot(),W={type:w};if(!H.can(W))return X.stop(),{success:!1,error:`Invalid playbook event '${w}' from state '${A.currentState}'.`,gateVerdicts:$.gateVerdicts};X.send(W);let f=X.getSnapshot(),Z=String(f.value),G=B.transitions.find((V)=>V.event===w)?.target;if(G&&Z!==G)return X.stop(),{success:!1,error:`Playbook event '${w}' is blocked from state '${A.currentState}'. Complete the state's Done When conditions before sending this event.`,gateVerdicts:$.gateVerdicts};let F=X.getPersistedSnapshot();return X.stop(),{success:!0,currentState:Z,snapshot:F,gateVerdicts:$.gateVerdicts}}async prepareGateVerdicts(A,Q,w){if(!this.transitionRequiresGateVerdict(Q,w))return{success:!0,gateVerdicts:A.gateVerdicts};if(this.hasSatisfiedGateVerdicts(Q,A))return{success:!0,gateVerdicts:A.gateVerdicts};let B=this.evidenceForState(A,Q.id),$;try{$=await this.goalCheck.evaluate({run:A,state:Q,goal:Q.doneWhen,evidence:B})}catch(X){$={met:!1,reason:`Playbook goal check failed: ${mn0(X)}`}}let Y={stateId:Q.id,goal:Q.doneWhen,met:$.met,reason:$.reason,evaluatedAt:new Date().toISOString()};return{success:!0,gateVerdicts:yKw(A.gateVerdicts,[Y])}}evidenceForState(A,Q){return A.evidence.filter((w)=>!w.stateId||w.stateId===Q)}buildMachine(A,Q,w){return E1.createMachine({id:A,initial:Q.initialState,states:Object.fromEntries(Q.states.map((B)=>{let $=Q.finalStates.includes(B.id);return[B.id,{...$?{type:"final"}:{},...$?{}:{on:Object.fromEntries(B.transitions.map((Y)=>[Y.event,{target:Y.target,...this.transitionRequiresGateVerdict(B,Y.event)?{guard:()=>this.hasSatisfiedGateVerdicts(B,w)}:{}}]))}}]}))})}async resolveLifecycleStarters(A){if(A.interfaceType!=="web-chat"||A.userPermissionLevel!=="anchor")return[];let Q=[],w=new Set,B=Object.entries(this.config.lifecycle).filter(([Y])=>!A.lifecycle||Y===A.lifecycle);for(let[Y,D]of B){let X=await this.resolveConfiguredLifecycleStarter(Y,D);if(!X)continue;Q.push(X),w.add(Y)}for(let[Y,D]of this.registeredLifecycleStarters){if(A.lifecycle&&Y!==A.lifecycle)continue;if(w.has(Y))continue;let X=await this.resolveConfiguredLifecycleStarter(Y,D.config);if(!X)continue;Q.push(X),w.add(Y)}let $=new Set(Object.entries(this.config.triggers).filter(([,Y])=>Y).map(([Y])=>Y));if($.size===0)return Q;for(let Y of await this.listPlaybooks()){let D=Y.entity.metadata;if(D.status!=="active"||D.audience!=="anchor")continue;let X=D.trigger;if(!X||!$.has(X))continue;let H=D.lifecycle??Y.entity.id;if(w.has(H))continue;if(A.lifecycle&&H!==A.lifecycle)continue;let W=await this.store.findByLifecycle(H);if((D.once??!0)&&(W?.status==="completed"||W?.status==="dismissed"))continue;Q.push({id:H,title:D.starterText??D.title,...D.description??Y.body.purpose?{description:D.description??Y.body.purpose}:{},playbookId:Y.entity.id,lifecycle:H,starterPrompt:D.starterPrompt??`Start the ${D.title} playbook.`}),w.add(H)}return Q}registerLifecycleStarter(A,Q){let w=this.registeredLifecycleStarters.get(A.id),B=za1.parse({trigger:A.trigger,playbookId:A.playbookId,once:A.once,starterText:A.starterText,...A.description?{description:A.description}:{},starterPrompt:A.starterPrompt});if(w){if(w.source===Q&&CKw(w.config,B))return{registered:!0,id:A.id};return this.logger.warn("Ignoring conflicting playbook lifecycle starter",{id:A.id,source:Q,existingSource:w.source}),{registered:!1,id:A.id,ignored:!0,reason:`Lifecycle starter '${A.id}' is already registered by '${w.source}'.`}}return this.registeredLifecycleStarters.set(A.id,{source:Q,config:B}),{registered:!0,id:A.id}}async resolveConfiguredLifecycleStarter(A,Q){let w=await this.store.findByLifecycle(A);if(Q.once&&(w?.status==="completed"||w?.status==="dismissed"))return;if((await this.getPlaybook(Q.playbookId))?.entity.metadata.status!=="active")return;return{id:A,title:Q.starterText,...Q.description?{description:Q.description}:{},playbookId:Q.playbookId,lifecycle:A,starterPrompt:Q.starterPrompt}}async listPlaybooks(){if(!this.ctx)return[];return(await this.ctx.entityService.listEntities({entityType:"playbook"})).flatMap((Q)=>{let w=$a1.safeParse(Q);if(!w.success)return[];let{body:B}=RP.parsePlaybookContent(w.data.content);return[{entity:w.data,body:B,version:xw(w.data.content)}]})}async getStatus(A){let Q=await this.store.list(),w=A.conversationId?Q.filter((b)=>b.conversationId===A.conversationId):[],B=w.filter((b)=>b.status==="active"||b.status==="offered"),$=vKw(w.filter((b)=>(!A.playbookId||b.playbookId===A.playbookId)&&(!A.lifecycle||b.lifecycle===A.lifecycle))),Y=A.runId?Q.find((b)=>b.id===A.runId)??$:A.conversationId&&A.lifecycle?B.find((b)=>b.lifecycle===A.lifecycle)??$:A.conversationId&&A.playbookId?B.find((b)=>b.playbookId===A.playbookId)??$:A.conversationId?B.length>0?await this.requireScopedRun({conversationId:A.conversationId}):$:A.lifecycle?Q.find((b)=>b.lifecycle===A.lifecycle):A.playbookId?Q.find((b)=>b.playbookId===A.playbookId):void 0;if(A.conversationId&&!Y&&!A.runId&&!A.playbookId&&!A.lifecycle)throw Error(`No active or completed playbook run for conversation '${A.conversationId}'.`);let D=A.playbookId??Y?.playbookId??(A.lifecycle?this.config.lifecycle[A.lifecycle]?.playbookId:void 0),X=D?await this.getPlaybook(D):void 0,H=X&&Y?this.getState(X.body,Y.currentState):void 0,W=H&&Y&&X?this.getValidTransitions(Y,X.body,H):H?.transitions??[],f=W.filter((b)=>b.operatorAction!==!0),Z=W.filter((b)=>b.operatorAction===!0),G=H&&Y&&X?this.getBlockedTransitions(Y,X.body,H):[],F=H&&Y&&X?this.buildStateGuidance(Y,X.body,H):void 0,V=Y&&X&&Z.length>0?RKw({run:Y,title:X.entity.metadata.title,transitions:Z}):void 0;return{runs:(A.conversationId?w:Q).map(Ha1),...Y?{activeRun:Ha1(Y)}:{},...X?{playbook:X.entity}:{},...X?{body:X.body}:{},...H?{currentState:H}:{},...f.length>0?{validEvents:f}:{},...Z.length>0?{operatorActions:Z}:{},...G.length>0?{blockedEvents:G}:{},...F?{guidance:F}:{},...V?{cards:[V]}:{},lifecycle:this.config.lifecycle}}buildStateGuidance(A,Q,w){let B=this.getValidTransitions(A,Q,w),$=B.filter((H)=>H.operatorAction!==!0),Y=B.filter((H)=>H.operatorAction===!0),D=this.getBlockedTransitions(A,Q,w),X=A.gateVerdicts.find((H)=>H.stateId===w.id&&un0(H.goal,w.doneWhen));return[`Current state: ${w.id} (${w.title})`,"Instructions:",...w.instructions.map((H)=>`- ${H}`),"Done When:",...w.doneWhen.length>0?w.doneWhen.map((H)=>`- ${H}`):["- none"],"Goal status:",X?`- ${X.met?"Met":"Not yet met"}: ${X.reason}`:"- Not checked yet.","Current-state information rules:","- If this state asks the operator for information, ask the operator for the missing current-run information.","- If the current operator message partially answers the state's prompt, do not repeat the original prompt; ask only for the next missing detail required by the state instructions.","- Do not answer the state's operator-facing prompt from memory, existing durable records, profile data, search, or retrieval tools.","- Setup facts must come from current-run evidence or current operator input, not ambient records.","Event selection rules:","- Blocked events are not valid events; do not call playbook_send_event with a blocked event.","- For gated durable states, operator-provided details are not enough to send NEXT; first complete the required system_create/system_update/system_delete action or use existing current-run evidence that the Done When condition has already been met.","- If the operator explicitly says they have not chosen, selected, asked for, or used one of the available actions, do not send any event.",'- Operator actions and choices are not generic continuation events; even if only one operator action is available, generic continuation like "yes", "next", or "continue" is not a valid selection.',"- If multiple events are available, ask the operator to pick one labeled action.","- A Skip-style operator action is never a default continuation; send it only when the operator positively selects or asks to skip.","Valid continuation events:",...$.length>0?$.map((H)=>this.formatTransition(H)):["- none"],"Available operator actions:",...Y.length>0?Y.map((H)=>this.formatTransition(H)):["- none"],"Blocked events:",...D.length>0?D.map((H)=>this.formatTransition(H)):["- none"]].join(`
8283
+ `))}function UKw(A,Q){return UD0(A,Q).map(GKw)}function GKw(A){let Q=/^(.+?)\s*(?:\u2192|->)\s*(.+)$/.exec(A);if(!Q)throw Error(`Invalid playbook choice '${A}'. Expected "Label \u2192 Step".`);return{label:Q[1]?.trim()??"",target:Q[2]?.trim()??""}}function os1(A){let Q=/^Skip:\s*(.+?)\s*(?:\u2192|->)\s*(.+?)\s*$/im.exec(A);if(!Q)return;return{label:Q[1]?.trim()??"",target:Q[2]?.trim()??""}}function ss1(A){return A.split(/\r?\n/).map((Q)=>/^-\s+(.+?)\s*$/.exec(Q)?.[1]?.trim()).filter((Q)=>Boolean(Q))}function zKw(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var as1={name:"@brains/playbook",private:!0,version:"0.2.0-alpha.136",description:"Playbook entity for durable guided agent workflows",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class ts1 extends kQ{entityType=RP.entityType;schema=Jo;adapter=RP;constructor(A={}){super("playbook",as1,A,vn0)}async getInstructions(){return"Playbook entities describe durable, editable guided workflows for the agent. Use them as operating guidance when a playbook run is active; do not treat them as content to publish unless the user explicitly asks."}}function es1(A={}){return new ts1(A)}CB();c0();Z0();IX();b10();var Aa1={name:"@brains/playbooks",private:!0,version:"0.2.0-alpha.136",description:"Runtime orchestration for chat-native playbook runs",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/contracts":"workspace:*","@brains/playbook":"workspace:*","@brains/plugins":"workspace:*","@brains/runtime-state":"workspace:*","@brains/utils":"workspace:*",xstate:"^5.28.0"},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"}};Z0();var wa1=K.enum(["offered","active","completed","dismissed"]),GD0=K.object({id:K.string().min(1),kind:K.enum(["entity_event"]),stateId:K.string().min(1).optional(),observedAt:K.string().datetime(),data:K.record(K.string(),K.unknown())}).strict(),Ba1=K.object({stateId:K.string().min(1),goal:K.array(K.string().min(1)),met:K.boolean(),reason:K.string().min(1),evaluatedAt:K.string().datetime()}).strict(),hP=K.object({id:K.string().min(1),playbookId:K.string().min(1),playbookVersion:K.string().min(1),lifecycle:K.string().min(1).optional(),status:wa1,conversationId:K.string().min(1).optional(),currentState:K.string().min(1),completedStates:K.array(K.string().min(1)).default([]),snapshot:K.unknown().optional(),context:K.record(K.string(),K.unknown()).default({}),evidence:K.array(GD0).default([]),gateVerdicts:K.array(Ba1).default([]),startedAt:K.string().datetime().optional(),completedAt:K.string().datetime().optional(),updatedAt:K.string().datetime()}).strict(),VKw="playbooks.runs",JKw=hP;class zD0{store;writeQueue=Promise.resolve();constructor(A){this.store=A.scoped({namespace:VKw,schema:JKw})}async list(){return await this.waitForWrites(),(await this.store.list()).map((Q)=>Q.value)}async findById(A){return await this.store.get(A)??void 0}async findActiveByPlaybook(A){return(await this.list()).find((Q)=>Q.playbookId===A&&(Q.status==="active"||Q.status==="offered"))}async findByLifecycle(A){return(await this.list()).find((Q)=>Q.lifecycle===A)}async findActiveByConversation(A){return(await this.listActiveByConversation(A))[0]}async listActiveByConversation(A){return(await this.list()).filter((Q)=>Q.conversationId===A&&(Q.status==="active"||Q.status==="offered"))}async upsert(A){return this.enqueueMutation(async()=>{let Q=await this.store.get(A.id),w=hP.parse({...A,evidence:Qa1(Q?.evidence??[],A.evidence),gateVerdicts:IKw(Q?.gateVerdicts??[],A.gateVerdicts),updatedAt:new Date().toISOString()});return await this.store.set(w.id,w),w})}async appendEvidence(A,Q){return this.enqueueMutation(async()=>{let w=await this.store.get(A);if(!w)throw Error(`Playbook run not found: ${A}`);let B=hP.parse({...w,evidence:Qa1(w.evidence,[Q]),updatedAt:new Date().toISOString()});return await this.store.set(B.id,B),B})}async reset(A){await this.enqueueMutation(async()=>{if(!A){await this.store.clear();return}await this.store.delete(A)})}async enqueueMutation(A){let Q=this.writeQueue,w=()=>{};this.writeQueue=new Promise((B)=>{w=B}),await Q;try{return await A()}finally{w()}}async waitForWrites(){await this.writeQueue}}function Sn0(A){let Q=new Date().toISOString();return hP.parse({id:_V("playbook_run"),playbookId:A.playbookId,playbookVersion:A.playbookVersion,...A.lifecycle?{lifecycle:A.lifecycle}:{},status:A.status??"active",...A.conversationId?{conversationId:A.conversationId}:{},currentState:A.initialState,completedStates:[],...A.snapshot!==void 0?{snapshot:A.snapshot}:{},context:{},evidence:[],gateVerdicts:[],...A.status==="active"||A.status===void 0?{startedAt:Q}:{},updatedAt:Q})}function Qa1(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(B.id,B);return Array.from(w.values())}function IKw(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(bKw(B),B);return Array.from(w.values())}function bKw(A){return[A.stateId,...A.goal].join("\x00")}var Ga1="playbooks:lifecycle-starters",qD0="playbooks:register-lifecycle-starter",za1=K.object({trigger:K.string().min(1),playbookId:K.string().min(1),once:K.boolean().default(!0),starterText:K.string().min(1),description:K.string().min(1).optional(),starterPrompt:K.string().min(1)}).strict(),LKw=K.object({lifecycle:K.record(K.string(),za1).default({}),triggers:K.record(K.string(),K.boolean()).default({})}).strict(),NKw=K.object({lifecycle:K.string().min(1).optional(),interfaceType:K.string().min(1),userPermissionLevel:K.enum(["anchor","trusted","public"])}).strict(),jKw=K.object({id:K.string().min(1),trigger:K.string().min(1),playbookId:K.string().min(1),once:K.boolean().default(!0),starterText:K.string().min(1),description:K.string().min(1).optional(),starterPrompt:K.string().min(1)}).strict(),$a1=K.object({id:K.string().min(1),entityType:K.literal("playbook"),content:K.string().min(1),metadata:K.object({title:K.string().min(1),status:K.enum(["draft","active","archived"]),audience:K.enum(["anchor","trusted","public"]),trigger:K.string().min(1).optional(),lifecycle:K.string().min(1).optional(),once:K.boolean().optional(),starterText:K.string().min(1).optional(),description:K.string().min(1).optional(),starterPrompt:K.string().min(1).optional(),completionMode:K.enum(["agent-confirmed","manual"])}).passthrough()}).passthrough(),Ya1={runId:K.string().min(1).optional(),playbookId:K.string().min(1).optional(),lifecycle:K.string().min(1).optional()},Da1={playbookId:K.string().min(1),lifecycle:K.string().min(1).optional()},Xa1={runId:K.string().min(1).optional(),event:K.string().min(1),context:K.record(K.string(),K.unknown()).optional()},MKw=K.object({met:K.boolean(),reason:K.string().min(1)}).strict(),_Kw=K.object({event:K.string().min(1),target:K.string().min(1),operatorAction:K.boolean().optional(),label:K.string().min(1).optional(),description:K.string().min(1).optional(),operatorDescription:K.string().min(1).optional()}).strict(),PKw=K.object({id:K.string().min(1),title:K.string().min(1),instructions:K.array(K.string().min(1)),requiredDetails:K.array(K.string().min(1)).default([]),doneWhen:K.array(K.string().min(1)).default([]),transitions:K.array(_Kw).default([])}).passthrough(),kKw=K.object({run:hP,state:PKw,goal:K.array(K.string().min(1)),evidence:K.array(GD0).default([])}).strict();class cn0 extends IQ{store;ctx;goalCheck;injectedGoalCheck;startLocks=new Map;registeredLifecycleStarters=new Map;constructor(A={},Q={}){super("playbooks",Aa1,A,LKw);this.injectedGoalCheck=Q.goalCheck,this.goalCheck=Q.goalCheck??cKw}async onRegister(A){await super.onRegister(A),this.ctx=A,this.store=new zD0(A.runtimeState),this.goalCheck=this.injectedGoalCheck??TKw(A),A.registerInstructions(this.buildInstructions()),A.eval.registerHandler("goalCheck",async(Q)=>this.goalCheck.evaluate(kKw.parse(Q))),A.messaging.subscribe(Ga1,async(Q)=>{let w=NKw.parse(Q.payload);return{success:!0,data:{starters:await this.resolveLifecycleStarters(w)}}}),A.messaging.subscribe(qD0,async(Q)=>{let w=jKw.parse(Q.payload);return{success:!0,data:this.registerLifecycleStarter(w,Q.source)}}),A.messaging.subscribe(XN,async(Q)=>{let w=lT.parse(Q.payload),B=await this.buildAgentContextItem(w.conversationId);return{success:!0,data:{items:B?[B]:[]}}}),A.messaging.subscribe(uT,async(Q)=>{let w=hZ0.parse(Q.payload),B=await this.handleAgentAction(w);return B?{success:!0,data:B}:{success:!1}}),A.messaging.subscribe("entity:created",async(Q)=>({success:!0,data:await this.recordEntityEventEvidence("created",Q.payload)})),A.messaging.subscribe("entity:updated",async(Q)=>({success:!0,data:await this.recordEntityEventEvidence("updated",Q.payload)}))}async getTools(){return[{name:"playbook_status",description:"Get playbook lifecycle config, active runs, current state, valid events, and parsed playbook body. After meaningful tool actions, use the reported current state as source of truth. Do not send an extra NEXT after runtime evidence already advanced the run. Do not claim the playbook is finished unless the run has reached a final state.",inputSchema:Ya1,visibility:"anchor",sideEffects:"none",handler:async(A,Q)=>{let w=K.object(Ya1).parse(A);try{return{success:!0,data:await this.getStatus({...w,conversationId:Q.conversationId})}}catch(B){return{success:!1,error:mn0(B)}}}},{name:"playbook_start",description:"Start a playbook run, or resume an existing active run. If the operator asks to start a playbook by title, use the stable slug/id form when known (for example lowercase words joined by hyphens) instead of claiming it is unavailable without calling this tool. Do not call this to continue an already active playbook; use playbook_status and playbook_send_event with a valid event instead.",inputSchema:Da1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Da1).parse(A),B=Q.conversationId,$=B?`${B}:${w.playbookId}`:`playbook:${w.playbookId}`;return this.withStartLock($,async()=>{let Y=await this.requirePlaybook(w.playbookId);Io(Y.body);let D=Y.entity.metadata.lifecycle??w.lifecycle,X=B?(await this.store.listActiveByConversation(B)).find((f)=>f.playbookId===w.playbookId):await this.store.findActiveByPlaybook(w.playbookId),H=X?await this.store.upsert({...X,status:"active",...B?{conversationId:B}:{},...X.startedAt?{}:{startedAt:new Date().toISOString()}}):await this.createStartedRun({playbookId:w.playbookId,playbookVersion:Y.version,body:Y.body,lifecycle:D,conversationId:B});return{success:!0,data:await this.getStatus({runId:H.id})}})}},{name:"playbook_send_event",description:"Send an event to a playbook run state machine and persist the resulting state. Invalid events return an error. Only use this when the operator positively selects a valid event/action or when a gated Done When condition is actually met. For durable gated states, user-provided details are not enough; do not send NEXT until the required system_create/system_update/system_delete tool has succeeded or current run evidence already shows the Done When condition is met. Operator actions and choices are not generic continuation events; do not use this for generic next/continue to select an operator action, even if only one operator action is currently valid. Do not use this when the operator explicitly says they have not chosen, selected, asked for, or used the available action. Skip-style events require a positive request to skip. This tool only changes playbook state; it does not retrieve, show, save, create, update, or transform domain entities. When the operator message only selects a playbook action, call this tool without unrelated domain mutation tools such as system_create or system_update. If the operator also asks to find/show/retrieve content, call system_get or system_search before answering.",inputSchema:Xa1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Xa1).parse(A),B=await this.resolveScopedRunResponse({runId:w.runId,conversationId:Q.conversationId});if(!B.success)return B;let $=await this.sendEventForRun(B.data,w.event,w.context);return $.success?{success:!0,data:$.data}:{success:!1,error:$.error}}}]}async withStartLock(A,Q){let w=this.startLocks.get(A);if(w)return w;let B=Q().finally(()=>{this.startLocks.delete(A)});return this.startLocks.set(A,B),B}async handleAgentAction(A){if(A.userPermissionLevel!=="anchor")return;let Q=await this.resolveScopedRunResponse({conversationId:A.conversationId});if(!Q.success)return;let w=await this.sendEventForRun(Q.data,A.action.event);if(!w.success)return{text:`I couldn't continue the playbook: ${w.error}`,toolResults:[{toolName:"playbook_send_event",args:{runId:Q.data.id,event:A.action.event}}],usage:Wa1()};let B=this.getCurrentRunState(w.data);return{text:hKw(B),...w.data.cards?{cards:w.data.cards}:{},toolResults:[{toolName:"playbook_send_event",args:{runId:Q.data.id,event:A.action.event},data:w.data}],usage:Wa1()}}getCurrentRunState(A){return A.currentState}async sendEventForRun(A,Q,w){let B=await this.requirePlaybook(A.playbookId);if(A.playbookVersion!==B.version)return{success:!1,error:`Playbook definition changed for '${A.playbookId}'. Run version ${A.playbookVersion} does not match current version ${B.version}.`};let $=this.getState(B.body,A.currentState),Y=$?.transitions.find((f)=>f.event===Q),D=await this.transitionRun(A,B.body,Q);if(!D.success){if(D.gateVerdicts)await this.store.upsert({...A,gateVerdicts:D.gateVerdicts});return{success:!1,error:D.error}}let X=B.body.finalStates.includes(D.currentState),H=await this.store.upsert({...A,currentState:D.currentState,completedStates:fa1(A.completedStates,A.currentState),snapshot:D.snapshot,gateVerdicts:D.gateVerdicts,context:{...A.context,...w??{}},...X?{status:"completed",completedAt:new Date().toISOString()}:{}}),W=await this.getStatus({runId:H.id});return{success:!0,data:$&&Y?.operatorAction===!0?OKw(W,$,Y):W}}async createStartedRun(A){let Q=Sn0({playbookId:A.playbookId,playbookVersion:A.playbookVersion,initialState:A.body.initialState,lifecycle:A.lifecycle,conversationId:A.conversationId}),w=this.buildMachine(A.playbookId,A.body,Q),B=E1.createActor(w);B.start();let $=B.getPersistedSnapshot();return B.stop(),this.store.upsert({...Q,snapshot:$})}async transitionRun(A,Q,w){let B=this.getState(Q,A.currentState);if(!B)return{success:!1,error:`Playbook state not found: ${A.currentState}`};let $=await this.prepareGateVerdicts(A,B,w);if(!$.success)return $;let Y={...A,gateVerdicts:$.gateVerdicts},D=this.buildMachine(A.playbookId,Q,Y),X=E1.createActor(D,{...A.snapshot?{snapshot:A.snapshot}:{}});X.start();let H=X.getSnapshot(),W={type:w};if(!H.can(W))return X.stop(),{success:!1,error:`Invalid playbook event '${w}' from state '${A.currentState}'.`,gateVerdicts:$.gateVerdicts};X.send(W);let f=X.getSnapshot(),Z=String(f.value),G=B.transitions.find((V)=>V.event===w)?.target;if(G&&Z!==G)return X.stop(),{success:!1,error:`Playbook event '${w}' is blocked from state '${A.currentState}'. Complete the state's Done When conditions before sending this event.`,gateVerdicts:$.gateVerdicts};let F=X.getPersistedSnapshot();return X.stop(),{success:!0,currentState:Z,snapshot:F,gateVerdicts:$.gateVerdicts}}async prepareGateVerdicts(A,Q,w){if(!this.transitionRequiresGateVerdict(Q,w))return{success:!0,gateVerdicts:A.gateVerdicts};if(this.hasSatisfiedGateVerdicts(Q,A))return{success:!0,gateVerdicts:A.gateVerdicts};let B=this.evidenceForState(A,Q.id),$;try{$=await this.goalCheck.evaluate({run:A,state:Q,goal:Q.doneWhen,evidence:B})}catch(X){$={met:!1,reason:`Playbook goal check failed: ${mn0(X)}`}}let Y={stateId:Q.id,goal:Q.doneWhen,met:$.met,reason:$.reason,evaluatedAt:new Date().toISOString()};return{success:!0,gateVerdicts:yKw(A.gateVerdicts,[Y])}}evidenceForState(A,Q){return A.evidence.filter((w)=>!w.stateId||w.stateId===Q)}buildMachine(A,Q,w){return E1.createMachine({id:A,initial:Q.initialState,states:Object.fromEntries(Q.states.map((B)=>{let $=Q.finalStates.includes(B.id);return[B.id,{...$?{type:"final"}:{},...$?{}:{on:Object.fromEntries(B.transitions.map((Y)=>[Y.event,{target:Y.target,...this.transitionRequiresGateVerdict(B,Y.event)?{guard:()=>this.hasSatisfiedGateVerdicts(B,w)}:{}}]))}}]}))})}async resolveLifecycleStarters(A){if(A.interfaceType!=="web-chat"||A.userPermissionLevel!=="anchor")return[];let Q=[],w=new Set,B=Object.entries(this.config.lifecycle).filter(([Y])=>!A.lifecycle||Y===A.lifecycle);for(let[Y,D]of B){let X=await this.resolveConfiguredLifecycleStarter(Y,D);if(!X)continue;Q.push(X),w.add(Y)}for(let[Y,D]of this.registeredLifecycleStarters){if(A.lifecycle&&Y!==A.lifecycle)continue;if(w.has(Y))continue;let X=await this.resolveConfiguredLifecycleStarter(Y,D.config);if(!X)continue;Q.push(X),w.add(Y)}let $=new Set(Object.entries(this.config.triggers).filter(([,Y])=>Y).map(([Y])=>Y));if($.size===0)return Q;for(let Y of await this.listPlaybooks()){let D=Y.entity.metadata;if(D.status!=="active"||D.audience!=="anchor")continue;let X=D.trigger;if(!X||!$.has(X))continue;let H=D.lifecycle??Y.entity.id;if(w.has(H))continue;if(A.lifecycle&&H!==A.lifecycle)continue;let W=await this.store.findByLifecycle(H);if((D.once??!0)&&(W?.status==="completed"||W?.status==="dismissed"))continue;Q.push({id:H,title:D.starterText??D.title,...D.description??Y.body.purpose?{description:D.description??Y.body.purpose}:{},playbookId:Y.entity.id,lifecycle:H,starterPrompt:D.starterPrompt??`Start the ${D.title} playbook.`}),w.add(H)}return Q}registerLifecycleStarter(A,Q){let w=this.registeredLifecycleStarters.get(A.id),B=za1.parse({trigger:A.trigger,playbookId:A.playbookId,once:A.once,starterText:A.starterText,...A.description?{description:A.description}:{},starterPrompt:A.starterPrompt});if(w){if(w.source===Q&&CKw(w.config,B))return{registered:!0,id:A.id};return this.logger.warn("Ignoring conflicting playbook lifecycle starter",{id:A.id,source:Q,existingSource:w.source}),{registered:!1,id:A.id,ignored:!0,reason:`Lifecycle starter '${A.id}' is already registered by '${w.source}'.`}}return this.registeredLifecycleStarters.set(A.id,{source:Q,config:B}),{registered:!0,id:A.id}}async resolveConfiguredLifecycleStarter(A,Q){let w=await this.store.findByLifecycle(A);if(Q.once&&(w?.status==="completed"||w?.status==="dismissed"))return;if((await this.getPlaybook(Q.playbookId))?.entity.metadata.status!=="active")return;return{id:A,title:Q.starterText,...Q.description?{description:Q.description}:{},playbookId:Q.playbookId,lifecycle:A,starterPrompt:Q.starterPrompt}}async listPlaybooks(){if(!this.ctx)return[];return(await this.ctx.entityService.listEntities({entityType:"playbook"})).flatMap((Q)=>{let w=$a1.safeParse(Q);if(!w.success)return[];let{body:B}=RP.parsePlaybookContent(w.data.content);return[{entity:w.data,body:B,version:xw(w.data.content)}]})}async getStatus(A){let Q=await this.store.list(),w=A.conversationId?Q.filter((b)=>b.conversationId===A.conversationId):[],B=w.filter((b)=>b.status==="active"||b.status==="offered"),$=vKw(w.filter((b)=>(!A.playbookId||b.playbookId===A.playbookId)&&(!A.lifecycle||b.lifecycle===A.lifecycle))),Y=A.runId?Q.find((b)=>b.id===A.runId)??$:A.conversationId&&A.lifecycle?B.find((b)=>b.lifecycle===A.lifecycle)??$:A.conversationId&&A.playbookId?B.find((b)=>b.playbookId===A.playbookId)??$:A.conversationId?B.length>0?await this.requireScopedRun({conversationId:A.conversationId}):$:A.lifecycle?Q.find((b)=>b.lifecycle===A.lifecycle):A.playbookId?Q.find((b)=>b.playbookId===A.playbookId):void 0;if(A.conversationId&&!Y&&!A.runId&&!A.playbookId&&!A.lifecycle)throw Error(`No active or completed playbook run for conversation '${A.conversationId}'.`);let D=A.playbookId??Y?.playbookId??(A.lifecycle?this.config.lifecycle[A.lifecycle]?.playbookId:void 0),X=D?await this.getPlaybook(D):void 0,H=X&&Y?this.getState(X.body,Y.currentState):void 0,W=H&&Y&&X?this.getValidTransitions(Y,X.body,H):H?.transitions??[],f=W.filter((b)=>b.operatorAction!==!0),Z=W.filter((b)=>b.operatorAction===!0),G=H&&Y&&X?this.getBlockedTransitions(Y,X.body,H):[],F=H&&Y&&X?this.buildStateGuidance(Y,X.body,H):void 0,V=Y&&X&&Z.length>0?RKw({run:Y,title:X.entity.metadata.title,transitions:Z}):void 0;return{runs:(A.conversationId?w:Q).map(Ha1),...Y?{activeRun:Ha1(Y)}:{},...X?{playbook:X.entity}:{},...X?{body:X.body}:{},...H?{currentState:H}:{},...f.length>0?{validEvents:f}:{},...Z.length>0?{operatorActions:Z}:{},...G.length>0?{blockedEvents:G}:{},...F?{guidance:F}:{},...V?{cards:[V]}:{},lifecycle:this.config.lifecycle}}buildStateGuidance(A,Q,w){let B=this.getValidTransitions(A,Q,w),$=B.filter((H)=>H.operatorAction!==!0),Y=B.filter((H)=>H.operatorAction===!0),D=this.getBlockedTransitions(A,Q,w),X=A.gateVerdicts.find((H)=>H.stateId===w.id&&un0(H.goal,w.doneWhen));return[`Current state: ${w.id} (${w.title})`,"Instructions:",...w.instructions.map((H)=>`- ${H}`),"Done When:",...w.doneWhen.length>0?w.doneWhen.map((H)=>`- ${H}`):["- none"],"Goal status:",X?`- ${X.met?"Met":"Not yet met"}: ${X.reason}`:"- Not checked yet.","Current-state information rules:","- If this state asks the operator for information, ask the operator for the missing current-run information.","- If the current operator message partially answers the state's prompt, do not repeat the original prompt; ask only for the next missing detail required by the state instructions.","- Do not answer the state's operator-facing prompt from memory, existing durable records, profile data, search, or retrieval tools.","- Setup facts must come from current-run evidence or current operator input, not ambient records.","Event selection rules:","- Blocked events are not valid events; do not call playbook_send_event with a blocked event.","- For gated durable states, operator-provided details are not enough to send NEXT; first complete the required system_create/system_update/system_delete action or use existing current-run evidence that the Done When condition has already been met.","- If the operator explicitly says they have not chosen, selected, asked for, or used one of the available actions, do not send any event.",'- Operator actions and choices are not generic continuation events; even if only one operator action is available, generic continuation like "yes", "next", or "continue" is not a valid selection.',"- If multiple events are available, ask the operator to pick one labeled action.","- A Skip-style operator action is never a default continuation; send it only when the operator positively selects or asks to skip.","Valid continuation events:",...$.length>0?$.map((H)=>this.formatTransition(H)):["- none"],"Available operator actions:",...Y.length>0?Y.map((H)=>this.formatTransition(H)):["- none"],"Blocked events:",...D.length>0?D.map((H)=>this.formatTransition(H)):["- none"]].join(`
8284
8284
  `)}async recordEntityEventEvidence(A,Q){let w=kE(Q,"entityType"),B=kE(Q,"entityId");if(!w||!B)return{recorded:!1};let $=kE(Q,"runId"),Y=kE(Q,"conversationId"),D=$?await this.store.findById($):Y?await this.store.findActiveByConversation(Y):void 0;if(D?.status!=="active")return{recorded:!1};let X={id:_V("playbook_evidence"),kind:"entity_event",stateId:D.currentState,observedAt:new Date().toISOString(),data:{entityType:w,entityId:B,operation:A,...EKw(Q),...Y?{conversationId:Y}:{},...kE(Q,"toolCallId")?{toolCallId:kE(Q,"toolCallId")}:{}}},H=await this.store.appendEvidence(D.id,X);return await this.evaluateGateAfterEvidence(H),{recorded:!0}}async evaluateGateAfterEvidence(A){if(this.hasSatisfiedGateForCurrentState(A))return;let Q=await this.getPlaybook(A.playbookId);if(A.playbookVersion!==Q?.version)return;let w=this.getState(Q.body,A.currentState);if(!w?.doneWhen.length)return;if(w.transitions.filter((H)=>H.event==="NEXT").length!==1)return;let $=await this.prepareGateVerdicts(A,w,"NEXT");if(!$.success)return;let Y={...A,gateVerdicts:$.gateVerdicts};if(!this.hasSatisfiedGateVerdicts(w,Y)){await this.store.upsert(Y);return}let D=await this.transitionRun(Y,Q.body,"NEXT");if(!D.success){await this.store.upsert(Y);return}let X=Q.body.finalStates.includes(D.currentState);await this.store.upsert({...Y,currentState:D.currentState,completedStates:fa1(Y.completedStates,Y.currentState),snapshot:D.snapshot,gateVerdicts:D.gateVerdicts,...X?{status:"completed",completedAt:new Date().toISOString()}:{}})}hasSatisfiedGateForCurrentState(A){return A.gateVerdicts.some((Q)=>Q.stateId===A.currentState&&Q.met)}async getPlaybook(A){if(!this.ctx)return;let Q=await this.ctx.entityService.getEntity({entityType:"playbook",id:A,visibilityScope:p8("anchor")}),w=$a1.safeParse(Q);if(!w.success)return;let{body:B}=RP.parsePlaybookContent(w.data.content);return{entity:w.data,body:B,version:xw(w.data.content)}}async requirePlaybook(A){let Q=await this.getPlaybook(A);if(!Q)throw Error(`Playbook not found: ${A}`);return Q}async requireRun(A){let Q=await this.store.findById(A);if(!Q)throw Error(`Playbook run not found: ${A}`);return Q}async resolveScopedRunResponse(A){try{return{success:!0,data:await this.requireScopedRun(A)}}catch(Q){return{success:!1,error:mn0(Q)}}}async requireScopedRun(A){if(A.runId)return this.requireRun(A.runId);let Q=A.conversationId;if(!Q)throw Error("Missing runId and no active conversation id.");let w=await this.store.listActiveByConversation(Q);if(w.length===0)throw Error(`No active playbook run for conversation '${Q}'.`);if(w.length>1)throw Error(`Multiple active playbook runs for conversation '${Q}'. Provide runId explicitly.`);let B=w[0];if(!B)throw Error(`No active playbook run for conversation '${Q}'.`);return B}transitionRequiresGateVerdict(A,Q){return Q==="NEXT"&&A.doneWhen.length>0}hasSatisfiedGateVerdicts(A,Q){return Q.gateVerdicts.some((w)=>w.stateId===A.id&&un0(w.goal,A.doneWhen)&&w.met)}getValidTransitions(A,Q,w){return w.transitions.filter((B)=>this.canTransition(A,Q,B.event))}getBlockedTransitions(A,Q,w){let B=new Set(this.getValidTransitions(A,Q,w).map(($)=>`${$.event}\x00${$.target}`));return w.transitions.filter(($)=>!B.has(`${$.event}\x00${$.target}`))}canTransition(A,Q,w){let B=this.buildMachine(A.playbookId,Q,A),$=E1.createActor(B,{...A.snapshot?{snapshot:A.snapshot}:{}});$.start();let Y=$.getSnapshot().can({type:w});return $.stop(),Y}formatTransition(A){let Q=A.operatorDescription??A.description??A.label;return Q?`- ${A.event} -> ${A.target}: ${Q}`:`- ${A.event} -> ${A.target}`}getState(A,Q){return A.states.find((w)=>w.id===Q)}formatVerifierStatus(A,Q){if(Q.doneWhen.length===0)return"- no gated Done When conditions";let w=A.gateVerdicts.find((B)=>B.stateId===Q.id&&un0(B.goal,Q.doneWhen));if(!w)return`- Not yet met: ${Q.doneWhen.join("; ")}`;return w.met?`- Met: ${w.reason}`:`- Not yet met: ${w.reason}`}async buildAgentContextItem(A){let Q=await this.store.findActiveByConversation(A);if(!Q)return;let w=await this.getPlaybook(Q.playbookId);if(!w)return;let B=this.getState(w.body,Q.currentState);if(!B)return;let $=this.getValidTransitions(Q,w.body,B),Y=$.filter((L)=>L.operatorAction!==!0),D=$.filter((L)=>L.operatorAction===!0),X=new Set($.map((L)=>`${L.event}\x00${L.target}`)),H=B.transitions.filter((L)=>!X.has(`${L.event}\x00${L.target}`)),W=Y.map((L)=>this.formatTransition(L)).join(`
8285
8285
  `),f=D.map((L)=>this.formatTransition(L)).join(`
8286
8286
  `),Z=H.map((L)=>this.formatTransition(L)).join(`
@@ -8353,9 +8353,9 @@ ${Object.entries(this.config.lifecycle).map(([Q,w])=>`- ${Q}: playbookId=${w.pla
8353
8353
  ${A.guidance}`:$}}function Ha1(A){return{...A,evidence:A.evidence.map((Q)=>({...Q,data:xKw(Q.data)}))}}function xKw(A){return Object.fromEntries(["entityType","entityId","operation"].flatMap((Q)=>A[Q]!==void 0?[[Q,A[Q]]]:[]))}function RKw(A){return{kind:"actions",id:`actions:playbook:${A.run.id}`,title:A.title,defaultOpen:!0,actions:A.transitions.map((Q)=>({type:"event",id:`playbook:${A.run.id}:${Q.event}`,label:Q.label??Q.operatorDescription??Q.description??Q.event,event:Q.event,...Q.operatorDescription??Q.description?{description:Q.operatorDescription??Q.description}:{}}))}}function hKw(A){if(!A)return"Continuing.";return A.prompt??`Continuing to ${A.title}.`}function Wa1(){return{promptTokens:0,completionTokens:0,totalTokens:0}}function fa1(A,Q){return A.includes(Q)?A:[...A,Q]}function vKw(A){return[...A].sort((Q,w)=>(w.completedAt??w.updatedAt).localeCompare(Q.completedAt??Q.updatedAt))[0]}function mn0(A){return A instanceof Error?A.message:String(A)}function un0(A,Q){return A.length===Q.length&&A.every((w,B)=>w===Q[B])}function CKw(A,Q){return A.trigger===Q.trigger&&A.playbookId===Q.playbookId&&A.once===Q.once&&A.starterText===Q.starterText&&A.description===Q.description&&A.starterPrompt===Q.starterPrompt}function yKw(A,Q){let w=new Set(Q.map(Za1));return[...A.filter((B)=>!w.has(Za1(B))),...Q]}function Za1(A){return[A.stateId,...A.goal].join("\x00")}function kE(A,Q){let w=A[Q];return typeof w==="string"&&w.length>0?w:void 0}function EKw(A){let Q=Ka1(A.entity);if(!Q)return{};let w=Ka1(Q.metadata),B=Ua1(w?.title,w?.name,Q.title),$=Ua1(Q.content),Y=$?gKw($):void 0;return{...B?{title:B}:{},...Y?{contentPreview:Y}:{}}}function Ka1(A){if(typeof A!=="object"||A===null||Array.isArray(A))return;return A}function Ua1(...A){return A.find((Q)=>typeof Q==="string"&&Q.trim().length>0)?.trim()}function gKw(A){let Q=A.replace(/\s+/g," ").trim();return Q.length>500?`${Q.slice(0,497)}...`:Q}function TKw(A){return{async evaluate(Q){let w=Q.goal.join(`
8354
8354
  `),B=await A.entityService.search({query:w,options:{limit:8,excludeTypes:["playbook"],visibilityScope:p8("anchor")}}),$=SKw(Q,B),{verdict:Y}=await A.judge({instruction:"Decide whether the playbook goal is satisfied by the supplied current-run runtime evidence and KB excerpts. Current-run runtime evidence is authoritative for playbook completion; use KB excerpts as supporting context, not to override clear runtime evidence from this run. Return met=true only when the outcome clearly holds. If evidence is missing or ambiguous, return met=false with a short reason.",material:$,schema:MKw});return Y}}}function SKw(A,Q){return["## Playbook run",`runId: ${A.run.id}`,`playbookId: ${A.run.playbookId}`,`currentState: ${A.state.id} (${A.state.title})`,"","## State instructions",...A.state.instructions.map((w)=>`- ${w}`),"","## Done When goal",...A.goal.map((w)=>`- ${w}`),"","## Runtime evidence",...A.evidence.length>0?A.evidence.map((w,B)=>mKw(B+1,w)):["No runtime evidence collected for this state."],"","## KB excerpts",...Q.length>0?Q.map((w,B)=>uKw(B+1,w)):["No relevant KB excerpts found."]].join(`
8355
8355
  `)}function mKw(A,Q){return`${A}. ${Q.kind} at ${Q.observedAt}: ${qa1(Q.data)}`}function uKw(A,Q){return[`${A}. ${Q.entity.entityType}/${Q.entity.id} (score ${Q.score})`,`Excerpt: ${Q.excerpt}`,`Content: ${Fa1(Q.entity.content,1200)}`,`Metadata: ${qa1(Q.entity.metadata)}`].join(`
8356
- `)}function qa1(A){try{return Fa1(JSON.stringify(A),1200)}catch{return"[unserializable]"}}function Fa1(A,Q){return A.length>Q?`${A.slice(0,Q)}\u2026`:A}var cKw={async evaluate(){return{met:!1,reason:"No playbook goal check is configured."}}};function ln0(A={},Q={}){return new cn0(A,Q)}import{readFile as pKw}from"fs/promises";import{join as iKw}from"path";c0();Z0();var Va1={name:"@brains/rover-onboarding",private:!0,version:"0.2.0-alpha.135",description:"Rover onboarding playbook bundle and activation plugin",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/playbooks":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/playbook":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var dKw=K.object({enabled:K.boolean().default(!1)}).strict(),Ja1=[{id:"rover-onboarding",fileName:"rover-onboarding.md",starter:{id:"onboarding",trigger:"first-anchor-web-chat",playbookId:"rover-onboarding",once:!0,starterText:"Set up Rover",description:"Tune Rover's identity and anchor profile before using the knowledge loop.",starterPrompt:"Start playbook rover-onboarding."}},{id:"rover-first-knowledge-loop",fileName:"rover-first-knowledge-loop.md"}];class Ia1 extends IQ{dependencies=["playbook","playbooks"];constructor(A={}){super("rover-onboarding",Va1,A,dKw)}async onReady(A){if(!this.config.enabled)return;for(let Q of Ja1)await this.seedPlaybookIfMissing(A,Q);for(let Q of Ja1){if(!Q.starter)continue;await A.messaging.send({type:qD0,payload:Q.starter})}}async seedPlaybookIfMissing(A,Q){if(await A.entityService.getEntity({entityType:"playbook",id:Q.id,visibilityScope:"restricted"}))return;let B=await pKw(iKw(import.meta.dir,"..","content","playbook",Q.fileName),"utf8");await A.entityService.createEntityFromMarkdown({input:{entityType:"playbook",id:Q.id,markdown:B}})}}function ba1(A={}){return new Ia1(A)}c0();Z0();c0();var pn0=K.enum(["new","planned","in-progress","done","declined"]),in0=K.enum(["low","medium","high","critical"]),bo=K.object({title:K.string(),status:pn0,priority:in0.default("medium"),requested:K.number().int().default(1),declinedReason:K.string().optional()}),La1=K.object({title:K.string(),status:pn0,priority:in0,requested:K.number().int(),slug:K.string()}),Lo=o1.extend({entityType:K.literal("wish"),metadata:La1}),dn0=K.object({});c0();Z0();class No extends J2{constructor(){super({entityType:"wish",purpose:"An explicitly recorded capability or outcome the assistant cannot currently fulfill, kept for future planning.",schema:Lo,frontmatterSchema:bo})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,bo);return{frontmatter:bo.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),w=w1(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:w}}}}var nn0=new No;Z0();Z0();async function Na1(A,Q){let w=`${Q.title}: ${Q.description}`,$=(await A.search({query:w,options:{types:["wish"],limit:1}}))[0];if($&&$.score>=A.similarityThreshold)return $.entity;let Y=w1(Q.title);return A.getEntity({entityType:"wish",id:Y})}class FD0{logger;context;adapter=new No;constructor(A,Q){this.logger=A;this.context=Q}async process(A,Q,w){let B=A.title??A.prompt??"Untitled wish",$=A.content??A.prompt??"",Y=await Na1({search:(W)=>this.context.entityService.search(W),getEntity:(W)=>this.context.entityService.getEntity(W),similarityThreshold:0.85},{title:B,description:$});if(Y){let{frontmatter:W,description:f}=this.adapter.parseWishContent(Y.content),Z=W.requested+1,G=this.adapter.createWishContent({...W,requested:Z},f);return await this.context.entityService.updateEntity({entity:{...Y,content:G,metadata:{...Y.metadata,requested:Z}}}),this.logger.info("Incremented wish request count",{id:Y.id,requested:Z}),{success:!0,entityId:Y.id,existed:!0,requested:Z}}let D=w1(B),X=A.options?.priority??"medium",H=this.adapter.createWishContent({title:B,status:"new",priority:X,requested:1},$);return await this.context.entityService.createEntity({entity:{id:D,entityType:"wish",content:H,metadata:{title:B,status:"new",priority:X,requested:1,slug:D}}}),this.logger.info("Created new wish",{id:D,title:B}),{success:!0,entityId:D,existed:!1,requested:1}}}var ja1={critical:0,high:1,medium:2,low:3};function Ma1(A){A.sort((Q,w)=>{let B=w.metadata.requested-Q.metadata.requested;if(B!==0)return B;return ja1[Q.metadata.priority]-ja1[w.metadata.priority]})}var _a1={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.135",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 Pa1 extends kQ{entityType=nn0.entityType;schema=Lo;adapter=nn0;constructor(A={}){super("wishlist",_a1,A,dn0)}async interceptCreate(A,Q,w){let B=await new FD0(this.logger,w).process({...A.title?{title:A.title}:{},...A.prompt?{prompt:A.prompt}:{},...A.content?{content:A.content}:{}},`wish-create-${Date.now()}`,{});if(!B.success)return{kind:"handled",result:{success:!1,error:B.error??"Failed to create wish"}};return{kind:"handled",result:{success:!0,data:{...B.entityId?{entityId:B.entityId}:{},status:B.existed?"updated":"created"}}}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"top-wishes",pluginId:this.id,title:"Top Wishes",section:"secondary",priority:30,rendererName:"ListWidget",dataProvider:async()=>{let w=await A.entityService.listEntities({entityType:"wish",options:{limit:10}});return Ma1(w),{items:w.map((B)=>({id:B.id,name:B.metadata.title,count:B.metadata.requested,priority:B.metadata.priority,status:B.metadata.status}))}}}}),{success:!0}});let Q=new FD0(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:(w)=>w})}async getInstructions(){return"Wish entities record explicitly requested capabilities or desired end states whose literal completion is outside the available toolset. They may capture outcomes the assistant can advise about but cannot directly perform. They track demand, priority, and status for future capability planning; they are not a substitute for first-class entities that already support the requested action. To show the whole wishlist, call system_list once with entityType wish and omit status; only include status when the user asks for a specific wish status."}}function rKw(A={}){return new Pa1(A)}var VD0=rKw;c0();Z0();c0();var jo=K.object({title:K.string(),target:K.string()}),ka1=K.object({title:K.string(),target:K.string(),slug:K.string().optional()}),Mo=o1.extend({entityType:K.literal("prompt"),metadata:ka1});c0();Z0();class rn0 extends J2{constructor(){super({entityType:"prompt",purpose:"A reusable prompt or instruction template.",schema:Mo,frontmatterSchema:jo})}toMarkdown(A){let Q=this.extractBody(A.content),w=this.parseFrontMatter(A.content,jo);return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,jo),w=w1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:w}}}}var JD0=new rn0;var Oa1={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.135",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 on0 extends kQ{entityType=JD0.entityType;schema=Mo;adapter=JD0;constructor(){super("prompt",Oa1,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function vP(){return new on0}c0();Z0();class ID0{apiKey;fetchFn;baseUrl="https://api.unsplash.com";constructor(A,Q){this.apiKey=A,this.fetchFn=Q}async searchPhotos(A,Q){let w=new URL(`${this.baseUrl}/search/photos`);w.searchParams.set("query",A),w.searchParams.set("page",String(Q.page)),w.searchParams.set("per_page",String(Q.perPage));let B=await this.fetchFn(w.toString(),{headers:{Authorization:`Client-ID ${this.apiKey}`}});if(!B.ok)throw Error(`Unsplash API error: ${B.status} ${B.statusText}`);let $=await B.json();return{photos:$.results.map(sKw),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function sKw(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}}Z0();var xa1={query:K.string().describe("Search terms for stock photos"),perPage:K.number().min(1).max(30).default(10).describe("Results per page (1-30)"),page:K.number().min(1).default(1).describe("Page number")},Ra1={photoId:K.string().describe("Photo ID from search results"),downloadLocation:K.string().url().describe("Download tracking URL (required by provider ToS)"),photographerName:K.string().describe("Photographer name for attribution"),photographerUrl:K.string().url().describe("Photographer profile URL for attribution"),sourceUrl:K.string().url().describe("Photo page URL on provider"),imageUrl:K.string().url().describe("Image URL to download"),title:K.string().optional().describe("Image entity title"),alt:K.string().optional().describe("Alt text for the image"),targetEntityType:K.string().optional().describe("Entity type to set cover image on"),targetEntityId:K.string().optional().describe("Entity ID to set cover image on")};function ha1(A,Q){return[aKw(A,Q),tKw(A,Q)]}function aKw(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:xa1,visibility:"anchor",sideEffects:"none",handler:async(w)=>{let B=K.object(xa1).safeParse(w);if(!B.success)return{success:!1,error:`Invalid input: ${B.error.message}`};try{return{success:!0,data:await Q.provider.searchPhotos(B.data.query,{page:B.data.page,perPage:B.data.perPage})}}catch($){return{success:!1,error:$ instanceof Error?$.message:"Search failed"}}}}}function tKw(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:Ra1,visibility:"anchor",sideEffects:"external",handler:async(w)=>{let B=K.object(Ra1).safeParse(w);if(!B.success)return{success:!1,error:`Invalid input: ${B.error.message}`};let{photoId:$,downloadLocation:Y,photographerName:D,photographerUrl:X,sourceUrl:H,imageUrl:W,title:f,alt:Z,targetEntityType:G,targetEntityId:F}=B.data,V={photographerName:D,photographerUrl:X,sourceUrl:H},b=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:W}}}});if(b[0]){let _={imageEntityId:b[0].id,alreadyExisted:!0,attribution:V};if(G&&F)await eKw(Q.entityService,G,F,b[0].id),_.coverSet=!0;return{success:!0,data:_}}let L=await Q.jobs.enqueue({type:"select-photo",data:{photoId:$,downloadLocation:Y,photographerName:D,photographerUrl:X,sourceUrl:H,imageUrl:W,...f!==void 0?{title:f}:{},...Z!==void 0?{alt:Z}:{},...G!==void 0?{targetEntityType:G}:{},...F!==void 0?{targetEntityId:F}:{}}}),N={imageEntityId:$,alreadyExisted:!1,attribution:V,jobId:L,status:"generating"};if(G&&F)N.coverSet=!0;return{success:!0,data:N}}}}async function eKw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}c0();Z0();D4();var AUw=K.object({photoId:K.string(),downloadLocation:K.string().url(),photographerName:K.string(),photographerUrl:K.string().url(),sourceUrl:K.string().url(),imageUrl:K.string().url(),title:K.string().optional(),alt:K.string().optional(),targetEntityType:K.string().optional(),targetEntityId:K.string().optional()});class sn0 extends _w{deps;constructor(A,Q){super(A,{schema:AUw,jobTypeName:"select-photo"});this.deps=Q}async process(A,Q,w){await this.reportProgress(w,{progress:10,message:"Tracking stock photo download"}),await this.deps.provider.triggerDownload(A.downloadLocation),await this.reportProgress(w,{progress:35,message:"Downloading stock photo"});let B=await this.deps.fetchImage(A.imageUrl),$=A.title??`Stock photo ${A.photoId}`,Y=hX.createImageEntity({dataUrl:B,title:$,alt:A.alt??$});await this.reportProgress(w,{progress:75,message:"Saving stock photo"});let{entityId:D}=await this.deps.entityService.createEntity({entity:{id:A.photoId,...Y,metadata:{...Y.metadata,sourceUrl:A.imageUrl}}}),X={imageEntityId:D,alreadyExisted:!1};if(A.targetEntityType&&A.targetEntityId)await QUw(this.deps.entityService,A.targetEntityType,A.targetEntityId,D),X.coverSet=!0;return await this.reportProgress(w,{progress:100,message:"Stock photo selected"}),X}summarizeDataForLog(A){return{photoId:A.photoId,hasTarget:A.targetEntityType!==void 0}}}async function QUw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}D4();var va1={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.135",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 BUw=K.object({provider:K.enum(["unsplash"]).default("unsplash"),apiKey:K.string().optional().describe("Stock photo provider API key")});class an0 extends IQ{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",va1,A,BUw);this.deps=Q}async getTools(){if(!this.config.apiKey)return[];if(this.cachedTools)return this.cachedTools;let A=this.getContext(),Q=this.createProvider();return this.cachedTools=ha1(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??LW,jobs:A.jobs}),this.cachedTools}async registerJobHandlers(){if(!this.config.apiKey)return;let A=this.getContext();A.jobs.registerHandler("select-photo",new sn0(this.logger.child("SelectPhotoJobHandler"),{provider:this.createProvider(),entityService:A.entityService,fetchImage:this.deps.fetchImage??LW}))}createProvider(){return new ID0(this.config.apiKey??"",this.deps.fetch??globalThis.fetch)}}function tn0(A={},Q={}){return new an0(A,Q)}c0();Z0();c0();c0();Z0();var Ca1=K.enum(["ai","foundation","work"]),ya1=K.object({suffix:Ca1,title:K.string(),body:K.string(),linkLabel:K.string(),linkHref:K.string()}),_o=K.object({eyebrow:K.string(),headline:K.string(),cards:K.array(ya1).min(1)}),bD0=K.object({title:K.string(),slug:K.string(),status:K.enum(["draft","published"])}),Po=o1.extend({entityType:K.literal("ecosystem-section"),metadata:bD0});class Ea1 extends J2{constructor(){super({entityType:"ecosystem-section",purpose:"A section of the Rizom ecosystem overview.",schema:Po,frontmatterSchema:bD0})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var en0=new Ea1;Z0();function $Uw(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function Ar0(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function ko(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function LD0(A){let Q=$Uw(A),B=Ar0(Q,"Cards").split(/^### Card \d+\s*$/m).map(($)=>$.trim()).filter(Boolean);return _o.parse({eyebrow:Ar0(Q,"Eyebrow"),headline:Ar0(Q,"Headline"),cards:B.map(($)=>({suffix:ko($,"Suffix"),title:ko($,"Title"),body:ko($,"Body"),linkLabel:ko($,"Link Label"),linkHref:ko($,"Link Href")}))})}function ga1(A){return["# Ecosystem Section","","## Eyebrow",A.eyebrow,"","## Headline",A.headline,"","## Cards","",...A.cards.flatMap((Q,w)=>[`### Card ${w+1}`,"","#### Suffix",Q.suffix,"","#### Title",Q.title,"","#### Body",Q.body,"","#### Link Label",Q.linkLabel,"","#### Link Href",Q.linkHref,""])].join(`
8356
+ `)}function qa1(A){try{return Fa1(JSON.stringify(A),1200)}catch{return"[unserializable]"}}function Fa1(A,Q){return A.length>Q?`${A.slice(0,Q)}\u2026`:A}var cKw={async evaluate(){return{met:!1,reason:"No playbook goal check is configured."}}};function ln0(A={},Q={}){return new cn0(A,Q)}import{readFile as pKw}from"fs/promises";import{join as iKw}from"path";c0();Z0();var Va1={name:"@brains/rover-onboarding",private:!0,version:"0.2.0-alpha.136",description:"Rover onboarding playbook bundle and activation plugin",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/playbooks":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/playbook":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var dKw=K.object({enabled:K.boolean().default(!1)}).strict(),Ja1=[{id:"rover-onboarding",fileName:"rover-onboarding.md",starter:{id:"onboarding",trigger:"first-anchor-web-chat",playbookId:"rover-onboarding",once:!0,starterText:"Set up Rover",description:"Tune Rover's identity and anchor profile before using the knowledge loop.",starterPrompt:"Start playbook rover-onboarding."}},{id:"rover-first-knowledge-loop",fileName:"rover-first-knowledge-loop.md"}];class Ia1 extends IQ{dependencies=["playbook","playbooks"];constructor(A={}){super("rover-onboarding",Va1,A,dKw)}async onReady(A){if(!this.config.enabled)return;for(let Q of Ja1)await this.seedPlaybookIfMissing(A,Q);for(let Q of Ja1){if(!Q.starter)continue;await A.messaging.send({type:qD0,payload:Q.starter})}}async seedPlaybookIfMissing(A,Q){if(await A.entityService.getEntity({entityType:"playbook",id:Q.id,visibilityScope:"restricted"}))return;let B=await pKw(iKw(import.meta.dir,"..","content","playbook",Q.fileName),"utf8");await A.entityService.createEntityFromMarkdown({input:{entityType:"playbook",id:Q.id,markdown:B}})}}function ba1(A={}){return new Ia1(A)}c0();Z0();c0();var pn0=K.enum(["new","planned","in-progress","done","declined"]),in0=K.enum(["low","medium","high","critical"]),bo=K.object({title:K.string(),status:pn0,priority:in0.default("medium"),requested:K.number().int().default(1),declinedReason:K.string().optional()}),La1=K.object({title:K.string(),status:pn0,priority:in0,requested:K.number().int(),slug:K.string()}),Lo=o1.extend({entityType:K.literal("wish"),metadata:La1}),dn0=K.object({});c0();Z0();class No extends J2{constructor(){super({entityType:"wish",purpose:"An explicitly recorded capability or outcome the assistant cannot currently fulfill, kept for future planning.",schema:Lo,frontmatterSchema:bo})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,bo);return{frontmatter:bo.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),w=w1(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:w}}}}var nn0=new No;Z0();Z0();async function Na1(A,Q){let w=`${Q.title}: ${Q.description}`,$=(await A.search({query:w,options:{types:["wish"],limit:1}}))[0];if($&&$.score>=A.similarityThreshold)return $.entity;let Y=w1(Q.title);return A.getEntity({entityType:"wish",id:Y})}class FD0{logger;context;adapter=new No;constructor(A,Q){this.logger=A;this.context=Q}async process(A,Q,w){let B=A.title??A.prompt??"Untitled wish",$=A.content??A.prompt??"",Y=await Na1({search:(W)=>this.context.entityService.search(W),getEntity:(W)=>this.context.entityService.getEntity(W),similarityThreshold:0.85},{title:B,description:$});if(Y){let{frontmatter:W,description:f}=this.adapter.parseWishContent(Y.content),Z=W.requested+1,G=this.adapter.createWishContent({...W,requested:Z},f);return await this.context.entityService.updateEntity({entity:{...Y,content:G,metadata:{...Y.metadata,requested:Z}}}),this.logger.info("Incremented wish request count",{id:Y.id,requested:Z}),{success:!0,entityId:Y.id,existed:!0,requested:Z}}let D=w1(B),X=A.options?.priority??"medium",H=this.adapter.createWishContent({title:B,status:"new",priority:X,requested:1},$);return await this.context.entityService.createEntity({entity:{id:D,entityType:"wish",content:H,metadata:{title:B,status:"new",priority:X,requested:1,slug:D}}}),this.logger.info("Created new wish",{id:D,title:B}),{success:!0,entityId:D,existed:!1,requested:1}}}var ja1={critical:0,high:1,medium:2,low:3};function Ma1(A){A.sort((Q,w)=>{let B=w.metadata.requested-Q.metadata.requested;if(B!==0)return B;return ja1[Q.metadata.priority]-ja1[w.metadata.priority]})}var _a1={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.136",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 Pa1 extends kQ{entityType=nn0.entityType;schema=Lo;adapter=nn0;constructor(A={}){super("wishlist",_a1,A,dn0)}async interceptCreate(A,Q,w){let B=await new FD0(this.logger,w).process({...A.title?{title:A.title}:{},...A.prompt?{prompt:A.prompt}:{},...A.content?{content:A.content}:{}},`wish-create-${Date.now()}`,{});if(!B.success)return{kind:"handled",result:{success:!1,error:B.error??"Failed to create wish"}};return{kind:"handled",result:{success:!0,data:{...B.entityId?{entityId:B.entityId}:{},status:B.existed?"updated":"created"}}}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"top-wishes",pluginId:this.id,title:"Top Wishes",section:"secondary",priority:30,rendererName:"ListWidget",dataProvider:async()=>{let w=await A.entityService.listEntities({entityType:"wish",options:{limit:10}});return Ma1(w),{items:w.map((B)=>({id:B.id,name:B.metadata.title,count:B.metadata.requested,priority:B.metadata.priority,status:B.metadata.status}))}}}}),{success:!0}});let Q=new FD0(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:(w)=>w})}async getInstructions(){return"Wish entities record explicitly requested capabilities or desired end states whose literal completion is outside the available toolset. They may capture outcomes the assistant can advise about but cannot directly perform. They track demand, priority, and status for future capability planning; they are not a substitute for first-class entities that already support the requested action. To show the whole wishlist, call system_list once with entityType wish and omit status; only include status when the user asks for a specific wish status."}}function rKw(A={}){return new Pa1(A)}var VD0=rKw;c0();Z0();c0();var jo=K.object({title:K.string(),target:K.string()}),ka1=K.object({title:K.string(),target:K.string(),slug:K.string().optional()}),Mo=o1.extend({entityType:K.literal("prompt"),metadata:ka1});c0();Z0();class rn0 extends J2{constructor(){super({entityType:"prompt",purpose:"A reusable prompt or instruction template.",schema:Mo,frontmatterSchema:jo})}toMarkdown(A){let Q=this.extractBody(A.content),w=this.parseFrontMatter(A.content,jo);return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,jo),w=w1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:w}}}}var JD0=new rn0;var Oa1={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.136",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 on0 extends kQ{entityType=JD0.entityType;schema=Mo;adapter=JD0;constructor(){super("prompt",Oa1,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function vP(){return new on0}c0();Z0();class ID0{apiKey;fetchFn;baseUrl="https://api.unsplash.com";constructor(A,Q){this.apiKey=A,this.fetchFn=Q}async searchPhotos(A,Q){let w=new URL(`${this.baseUrl}/search/photos`);w.searchParams.set("query",A),w.searchParams.set("page",String(Q.page)),w.searchParams.set("per_page",String(Q.perPage));let B=await this.fetchFn(w.toString(),{headers:{Authorization:`Client-ID ${this.apiKey}`}});if(!B.ok)throw Error(`Unsplash API error: ${B.status} ${B.statusText}`);let $=await B.json();return{photos:$.results.map(sKw),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function sKw(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}}Z0();var xa1={query:K.string().describe("Search terms for stock photos"),perPage:K.number().min(1).max(30).default(10).describe("Results per page (1-30)"),page:K.number().min(1).default(1).describe("Page number")},Ra1={photoId:K.string().describe("Photo ID from search results"),downloadLocation:K.string().url().describe("Download tracking URL (required by provider ToS)"),photographerName:K.string().describe("Photographer name for attribution"),photographerUrl:K.string().url().describe("Photographer profile URL for attribution"),sourceUrl:K.string().url().describe("Photo page URL on provider"),imageUrl:K.string().url().describe("Image URL to download"),title:K.string().optional().describe("Image entity title"),alt:K.string().optional().describe("Alt text for the image"),targetEntityType:K.string().optional().describe("Entity type to set cover image on"),targetEntityId:K.string().optional().describe("Entity ID to set cover image on")};function ha1(A,Q){return[aKw(A,Q),tKw(A,Q)]}function aKw(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:xa1,visibility:"anchor",sideEffects:"none",handler:async(w)=>{let B=K.object(xa1).safeParse(w);if(!B.success)return{success:!1,error:`Invalid input: ${B.error.message}`};try{return{success:!0,data:await Q.provider.searchPhotos(B.data.query,{page:B.data.page,perPage:B.data.perPage})}}catch($){return{success:!1,error:$ instanceof Error?$.message:"Search failed"}}}}}function tKw(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:Ra1,visibility:"anchor",sideEffects:"external",handler:async(w)=>{let B=K.object(Ra1).safeParse(w);if(!B.success)return{success:!1,error:`Invalid input: ${B.error.message}`};let{photoId:$,downloadLocation:Y,photographerName:D,photographerUrl:X,sourceUrl:H,imageUrl:W,title:f,alt:Z,targetEntityType:G,targetEntityId:F}=B.data,V={photographerName:D,photographerUrl:X,sourceUrl:H},b=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:W}}}});if(b[0]){let _={imageEntityId:b[0].id,alreadyExisted:!0,attribution:V};if(G&&F)await eKw(Q.entityService,G,F,b[0].id),_.coverSet=!0;return{success:!0,data:_}}let L=await Q.jobs.enqueue({type:"select-photo",data:{photoId:$,downloadLocation:Y,photographerName:D,photographerUrl:X,sourceUrl:H,imageUrl:W,...f!==void 0?{title:f}:{},...Z!==void 0?{alt:Z}:{},...G!==void 0?{targetEntityType:G}:{},...F!==void 0?{targetEntityId:F}:{}}}),N={imageEntityId:$,alreadyExisted:!1,attribution:V,jobId:L,status:"generating"};if(G&&F)N.coverSet=!0;return{success:!0,data:N}}}}async function eKw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}c0();Z0();D4();var AUw=K.object({photoId:K.string(),downloadLocation:K.string().url(),photographerName:K.string(),photographerUrl:K.string().url(),sourceUrl:K.string().url(),imageUrl:K.string().url(),title:K.string().optional(),alt:K.string().optional(),targetEntityType:K.string().optional(),targetEntityId:K.string().optional()});class sn0 extends _w{deps;constructor(A,Q){super(A,{schema:AUw,jobTypeName:"select-photo"});this.deps=Q}async process(A,Q,w){await this.reportProgress(w,{progress:10,message:"Tracking stock photo download"}),await this.deps.provider.triggerDownload(A.downloadLocation),await this.reportProgress(w,{progress:35,message:"Downloading stock photo"});let B=await this.deps.fetchImage(A.imageUrl),$=A.title??`Stock photo ${A.photoId}`,Y=hX.createImageEntity({dataUrl:B,title:$,alt:A.alt??$});await this.reportProgress(w,{progress:75,message:"Saving stock photo"});let{entityId:D}=await this.deps.entityService.createEntity({entity:{id:A.photoId,...Y,metadata:{...Y.metadata,sourceUrl:A.imageUrl}}}),X={imageEntityId:D,alreadyExisted:!1};if(A.targetEntityType&&A.targetEntityId)await QUw(this.deps.entityService,A.targetEntityType,A.targetEntityId,D),X.coverSet=!0;return await this.reportProgress(w,{progress:100,message:"Stock photo selected"}),X}summarizeDataForLog(A){return{photoId:A.photoId,hasTarget:A.targetEntityType!==void 0}}}async function QUw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}D4();var va1={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.136",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 BUw=K.object({provider:K.enum(["unsplash"]).default("unsplash"),apiKey:K.string().optional().describe("Stock photo provider API key")});class an0 extends IQ{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",va1,A,BUw);this.deps=Q}async getTools(){if(!this.config.apiKey)return[];if(this.cachedTools)return this.cachedTools;let A=this.getContext(),Q=this.createProvider();return this.cachedTools=ha1(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??LW,jobs:A.jobs}),this.cachedTools}async registerJobHandlers(){if(!this.config.apiKey)return;let A=this.getContext();A.jobs.registerHandler("select-photo",new sn0(this.logger.child("SelectPhotoJobHandler"),{provider:this.createProvider(),entityService:A.entityService,fetchImage:this.deps.fetchImage??LW}))}createProvider(){return new ID0(this.config.apiKey??"",this.deps.fetch??globalThis.fetch)}}function tn0(A={},Q={}){return new an0(A,Q)}c0();Z0();c0();c0();Z0();var Ca1=K.enum(["ai","foundation","work"]),ya1=K.object({suffix:Ca1,title:K.string(),body:K.string(),linkLabel:K.string(),linkHref:K.string()}),_o=K.object({eyebrow:K.string(),headline:K.string(),cards:K.array(ya1).min(1)}),bD0=K.object({title:K.string(),slug:K.string(),status:K.enum(["draft","published"])}),Po=o1.extend({entityType:K.literal("ecosystem-section"),metadata:bD0});class Ea1 extends J2{constructor(){super({entityType:"ecosystem-section",purpose:"A section of the Rizom ecosystem overview.",schema:Po,frontmatterSchema:bD0})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var en0=new Ea1;Z0();function $Uw(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function Ar0(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function ko(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function LD0(A){let Q=$Uw(A),B=Ar0(Q,"Cards").split(/^### Card \d+\s*$/m).map(($)=>$.trim()).filter(Boolean);return _o.parse({eyebrow:Ar0(Q,"Eyebrow"),headline:Ar0(Q,"Headline"),cards:B.map(($)=>({suffix:ko($,"Suffix"),title:ko($,"Title"),body:ko($,"Body"),linkLabel:ko($,"Link Label"),linkHref:ko($,"Link Href")}))})}function ga1(A){return["# Ecosystem Section","","## Eyebrow",A.eyebrow,"","## Headline",A.headline,"","## Cards","",...A.cards.flatMap((Q,w)=>[`### Card ${w+1}`,"","#### Suffix",Q.suffix,"","#### Title",Q.title,"","#### Body",Q.body,"","#### Link Label",Q.linkLabel,"","#### Link Href",Q.linkHref,""])].join(`
8357
8357
  `)}var YUw=K.object({query:K.object({id:K.string().optional()}).optional()}).passthrough();class ND0{id="rizom-ecosystem:entities";name="Rizom Ecosystem";description="Fetches an ecosystem-section entity for rendering";async fetch(A,Q,w){let $=YUw.parse(A??{}).query?.id??"rizom-ecosystem",Y=await w.entityService.getEntity({entityType:"ecosystem-section",id:$});if(!Y)throw Error(`Ecosystem section not found: ${$}`);return Q.parse(LD0(Y.content))}}c0();var DUw=p$0({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 Az(...A){return DUw(Qy(A))}import{jsxDEV as S86}from"preact/jsx-dev-runtime";import{jsxDEV as l86}from"preact/jsx-dev-runtime";import{jsxDEV as n86}from"preact/jsx-dev-runtime";import{jsxDEV as HUw}from"preact/jsx-dev-runtime";var Qr0="px-6 md:px-10 xl:px-20",XUw=`${Qr0} relative z-[1]`,wr0=({id:A,className:Q,children:w})=>HUw("section",{id:A,className:Az(XUw,Q),children:w},void 0,!1,void 0,this);import{jsxDEV as jD0}from"preact/jsx-dev-runtime";var WUw=new Map([["work","text-accent"],["foundation","text-secondary"],["ai","text-accent-bright"]]),Oo=({name:A="rizom",brandSuffix:Q,className:w,dotClassName:B,suffixClassName:$})=>{let Y=WUw.get(Q);return jD0("span",{className:Az("inline-flex items-baseline gap-0 font-display font-medium tracking-[-0.015em] [font-variation-settings:'opsz'_24]",w),children:[jD0("span",{className:"text-theme",children:A},void 0,!1,void 0,this),jD0("span",{className:Az(Y??"text-accent",B),children:"."},void 0,!1,void 0,this),jD0("span",{className:Az("italic font-normal text-theme-muted",$),children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as Y66}from"preact/jsx-dev-runtime";import{jsxDEV as W66}from"preact/jsx-dev-runtime";import{jsxDEV as U66,Fragment as K66}from"preact/jsx-dev-runtime";import{jsxDEV as q66}from"preact/jsx-dev-runtime";import{Fragment as Br0}from"preact";import{jsxDEV as xo}from"preact/jsx-dev-runtime";var fUw=/(\*[^*]+\*)/;function $r0(A,Q){let w=A.split(`
8358
- `);return xo(Br0,{children:w.map((B,$)=>xo(Br0,{children:[$>0&&xo("br",{},void 0,!1,void 0,this),B.split(fUw).map((Y,D)=>{if(Y.length>=3&&Y.startsWith("*")&&Y.endsWith("*"))return xo("span",{className:Q,children:Y.slice(1,-1)},D,!1,void 0,this);return xo(Br0,{children:Y},D,!1,void 0,this)})]},$,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as uD,Fragment as bUw}from"preact/jsx-dev-runtime";var ZUw="italic text-accent font-normal",KUw="You are here",UUw={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},GUw={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},zUw={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},qUw="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",FUw="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",VUw="font-label text-[10.5px] uppercase tracking-[0.22em] text-theme-muted self-start mt-[18px] pb-1 border-b border-white/10 transition-colors hover:text-theme",JUw="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",IUw=({card:A})=>{let Q=A.linkLabel===KUw,w=A.linkHref.trim().length===0,B=uD(bUw,{children:[uD(Oo,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),uD("span",{className:`${qUw} ${UUw[A.suffix]}`,children:A.title},void 0,!1,void 0,this),uD("p",{className:FUw,children:A.body},void 0,!1,void 0,this),Q?uD("span",{className:JUw,children:A.linkLabel},void 0,!1,void 0,this):uD("span",{className:VUw,children:A.linkLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$=`flex flex-col gap-[14px] border-t pt-7 ${Q?GUw[A.suffix]:"border-white/10"}`;return Q||w?uD("div",{className:$,children:B},void 0,!1,void 0,this):uD("a",{href:A.linkHref,className:`${$} text-inherit no-underline transition-colors ${zUw[A.suffix]}`,children:B},void 0,!1,void 0,this)},Yr0=({eyebrow:A,headline:Q,cards:w})=>uD(wr0,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[uD("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[uD("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),uD("h2",{className:"mt-5 font-display text-[clamp(34px,4.4vw,60px)] font-[380] leading-[1.04] tracking-[-0.02em] text-heading [font-variation-settings:'opsz'_96]",children:$r0(Q,ZUw)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),uD("div",{className:"mx-auto grid max-w-[1180px] grid-cols-3 gap-16 max-[768px]:grid-cols-1 max-[768px]:gap-7",children:w.map((B)=>uD(IUw,{card:B},B.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);var LUw=[{suffix:"work",title:"The service",body:"Workshops and consulting that apply the methodology in live engagements.",linkLabel:"Visit rizom.work \u2192",linkHref:"https://rizom.work"},{suffix:"foundation",title:"The source",body:"The non-profit that holds the IP and stewards the methodology independently.",linkLabel:"Read the manifesto \u2192",linkHref:"https://rizom.foundation"},{suffix:"ai",title:"The tools",body:"Open-source AI agents built on the methodology, the technical layer underneath.",linkLabel:"See the platform \u2192",linkHref:"https://rizom.ai"}];function Ta1(A){return{eyebrow:"The Ecosystem",headline:"One practice. *Three faces.*",cards:LUw.map((Q)=>Q.suffix===A?{...Q,linkLabel:"You are here",linkHref:""}:Q)}}var NUw=Ta1();var Dr0=R1({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:_o,formatter:{parse:LD0,format:ga1},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:Yr0}});var Sa1={name:"@brains/rizom-ecosystem",private:!0,version:"0.2.0-alpha.135",description:"Entity-backed Rizom ecosystem section",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@rizom/ui":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Xr0 extends kQ{entityType="ecosystem-section";schema=Po;adapter=en0;constructor(A={}){super("rizom-ecosystem",Sa1,A,K.object({}).default({}))}getTemplates(){return{ecosystem:Dr0}}getDataSources(){return[new ND0]}}function CP(A={}){return new Xr0(A)}Z0();c0();c0();Z0();l$();Z0();c0();var K9="agent",ma1="agent-discovery";var ua1="agent-network",ca1="AgentNetworkWidget",Ro="agent-discovery:entities",Hr0="agent-list",Wr0="agent-detail",z5="skill",la1="skill",MD0="skill-derivation",pa1="skill:project",ia1="skill-derivation",da1="skill:skill-derivation",na1="skills";var OE=K.object({name:K.string(),description:K.string(),tags:K.array(K.string())}),Hf=K.enum(["discovered","approved"]).describe("Discovered for review or approved for calling"),jK=QZ.pick({name:!0,kind:!0,organization:!0}).extend({brainName:K.string().describe("Name of the brain instance"),url:K.string().url().describe("Brain endpoint URL"),did:K.string().optional().describe("Decentralized identifier (public)"),repoDid:K.string().optional().describe("ATProto repo DID"),brainDid:K.string().optional().describe("ATProto brain DID"),anchorDid:K.string().optional().describe("ATProto anchor DID"),cardUri:K.string().optional().describe("ATProto brain card URI"),cardCid:K.string().optional().describe("ATProto brain card CID"),a2aEndpoint:K.string().url().optional().describe("A2A endpoint URL"),status:Hf,discoveredAt:K.string().datetime().describe("When this agent was first discovered")}),ra1=jK.pick({name:!0,url:!0,status:!0}).extend({discoveredAt:K.string().datetime().optional(),slug:K.string(),repoDid:K.string().optional(),brainDid:K.string().optional(),anchorDid:K.string().optional(),cardUri:K.string().optional(),cardCid:K.string().optional(),a2aEndpoint:K.string().url().optional()}),xE=o1.extend({entityType:K.literal(K9),metadata:ra1}),ho=xE.extend({frontmatter:jK,about:K.string(),skills:K.array(OE),notes:K.string()}),RE=ho.extend({url:K.string().optional(),typeLabel:K.string().optional()}),MUw=ho.extend({url:K.string(),typeLabel:K.string()});Z0();var _Uw=K.array(OE);function oa1(A){let Q=_Uw.safeParse(A);if(!Q.success||Q.data.length===0)return"";return Q.data.map((w)=>{let B=w.tags.length>0?` [${w.tags.join(", ")}]`:"";return`- ${w.name}: ${w.description}${B}`}).join(`
8358
+ `);return xo(Br0,{children:w.map((B,$)=>xo(Br0,{children:[$>0&&xo("br",{},void 0,!1,void 0,this),B.split(fUw).map((Y,D)=>{if(Y.length>=3&&Y.startsWith("*")&&Y.endsWith("*"))return xo("span",{className:Q,children:Y.slice(1,-1)},D,!1,void 0,this);return xo(Br0,{children:Y},D,!1,void 0,this)})]},$,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as uD,Fragment as bUw}from"preact/jsx-dev-runtime";var ZUw="italic text-accent font-normal",KUw="You are here",UUw={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},GUw={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},zUw={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},qUw="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",FUw="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",VUw="font-label text-[10.5px] uppercase tracking-[0.22em] text-theme-muted self-start mt-[18px] pb-1 border-b border-white/10 transition-colors hover:text-theme",JUw="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",IUw=({card:A})=>{let Q=A.linkLabel===KUw,w=A.linkHref.trim().length===0,B=uD(bUw,{children:[uD(Oo,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),uD("span",{className:`${qUw} ${UUw[A.suffix]}`,children:A.title},void 0,!1,void 0,this),uD("p",{className:FUw,children:A.body},void 0,!1,void 0,this),Q?uD("span",{className:JUw,children:A.linkLabel},void 0,!1,void 0,this):uD("span",{className:VUw,children:A.linkLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$=`flex flex-col gap-[14px] border-t pt-7 ${Q?GUw[A.suffix]:"border-white/10"}`;return Q||w?uD("div",{className:$,children:B},void 0,!1,void 0,this):uD("a",{href:A.linkHref,className:`${$} text-inherit no-underline transition-colors ${zUw[A.suffix]}`,children:B},void 0,!1,void 0,this)},Yr0=({eyebrow:A,headline:Q,cards:w})=>uD(wr0,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[uD("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[uD("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),uD("h2",{className:"mt-5 font-display text-[clamp(34px,4.4vw,60px)] font-[380] leading-[1.04] tracking-[-0.02em] text-heading [font-variation-settings:'opsz'_96]",children:$r0(Q,ZUw)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),uD("div",{className:"mx-auto grid max-w-[1180px] grid-cols-3 gap-16 max-[768px]:grid-cols-1 max-[768px]:gap-7",children:w.map((B)=>uD(IUw,{card:B},B.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);var LUw=[{suffix:"work",title:"The service",body:"Workshops and consulting that apply the methodology in live engagements.",linkLabel:"Visit rizom.work \u2192",linkHref:"https://rizom.work"},{suffix:"foundation",title:"The source",body:"The non-profit that holds the IP and stewards the methodology independently.",linkLabel:"Read the manifesto \u2192",linkHref:"https://rizom.foundation"},{suffix:"ai",title:"The tools",body:"Open-source AI agents built on the methodology, the technical layer underneath.",linkLabel:"See the platform \u2192",linkHref:"https://rizom.ai"}];function Ta1(A){return{eyebrow:"The Ecosystem",headline:"One practice. *Three faces.*",cards:LUw.map((Q)=>Q.suffix===A?{...Q,linkLabel:"You are here",linkHref:""}:Q)}}var NUw=Ta1();var Dr0=R1({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:_o,formatter:{parse:LD0,format:ga1},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:Yr0}});var Sa1={name:"@brains/rizom-ecosystem",private:!0,version:"0.2.0-alpha.136",description:"Entity-backed Rizom ecosystem section",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@rizom/ui":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Xr0 extends kQ{entityType="ecosystem-section";schema=Po;adapter=en0;constructor(A={}){super("rizom-ecosystem",Sa1,A,K.object({}).default({}))}getTemplates(){return{ecosystem:Dr0}}getDataSources(){return[new ND0]}}function CP(A={}){return new Xr0(A)}Z0();c0();c0();Z0();l$();Z0();c0();var K9="agent",ma1="agent-discovery";var ua1="agent-network",ca1="AgentNetworkWidget",Ro="agent-discovery:entities",Hr0="agent-list",Wr0="agent-detail",z5="skill",la1="skill",MD0="skill-derivation",pa1="skill:project",ia1="skill-derivation",da1="skill:skill-derivation",na1="skills";var OE=K.object({name:K.string(),description:K.string(),tags:K.array(K.string())}),Hf=K.enum(["discovered","approved"]).describe("Discovered for review or approved for calling"),jK=QZ.pick({name:!0,kind:!0,organization:!0}).extend({brainName:K.string().describe("Name of the brain instance"),url:K.string().url().describe("Brain endpoint URL"),did:K.string().optional().describe("Decentralized identifier (public)"),repoDid:K.string().optional().describe("ATProto repo DID"),brainDid:K.string().optional().describe("ATProto brain DID"),anchorDid:K.string().optional().describe("ATProto anchor DID"),cardUri:K.string().optional().describe("ATProto brain card URI"),cardCid:K.string().optional().describe("ATProto brain card CID"),a2aEndpoint:K.string().url().optional().describe("A2A endpoint URL"),status:Hf,discoveredAt:K.string().datetime().describe("When this agent was first discovered")}),ra1=jK.pick({name:!0,url:!0,status:!0}).extend({discoveredAt:K.string().datetime().optional(),slug:K.string(),repoDid:K.string().optional(),brainDid:K.string().optional(),anchorDid:K.string().optional(),cardUri:K.string().optional(),cardCid:K.string().optional(),a2aEndpoint:K.string().url().optional()}),xE=o1.extend({entityType:K.literal(K9),metadata:ra1}),ho=xE.extend({frontmatter:jK,about:K.string(),skills:K.array(OE),notes:K.string()}),RE=ho.extend({url:K.string().optional(),typeLabel:K.string().optional()}),MUw=ho.extend({url:K.string(),typeLabel:K.string()});Z0();var _Uw=K.array(OE);function oa1(A){let Q=_Uw.safeParse(A);if(!Q.success||Q.data.length===0)return"";return Q.data.map((w)=>{let B=w.tags.length>0?` [${w.tags.join(", ")}]`:"";return`- ${w.name}: ${w.description}${B}`}).join(`
8359
8359
  `)}function sa1(A){if(!A.trim())return[];let Q=[];for(let w of A.split(`
8360
8360
  `)){let B=w.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/);if(!B)continue;let $=B[1]??"",Y=B[2]??"",D=B[3],X=D?D.split(",").map((H)=>H.trim()).filter(Boolean):[];Q.push({name:$,description:Y,tags:X})}return Q}var PUw=K.object({about:K.string(),skills:K.array(OE),notes:K.string()}),aa1=new pw(PUw,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:oa1,parser:sa1},{key:"notes",label:"Notes",type:"string"}]});class k4 extends J2{constructor(){super({entityType:K9,purpose:"A saved remote peer-brain contact in the local agent directory.",schema:xE,frontmatterSchema:jK})}fromMarkdown(A){let Q=this.parseFrontMatter(A,jK),w=PV(Q.url);return{content:A,entityType:K9,metadata:{name:Q.name,url:Q.url,status:Q.status,discoveredAt:Q.discoveredAt,slug:w,...Q.repoDid&&{repoDid:Q.repoDid},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},...Q.cardUri&&{cardUri:Q.cardUri},...Q.cardCid&&{cardCid:Q.cardCid},...Q.a2aEndpoint&&{a2aEndpoint:Q.a2aEndpoint}}}}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},...A.repoDid&&{repoDid:A.repoDid},...A.brainDid&&{brainDid:A.brainDid},...A.anchorDid&&{anchorDid:A.anchorDid},...A.cardUri&&{cardUri:A.cardUri},...A.cardCid&&{cardCid:A.cardCid},...A.a2aEndpoint&&{a2aEndpoint:A.a2aEndpoint},status:Hf.parse(A.status),discoveredAt:A.discoveredAt},w=aa1.format({about:A.about,skills:A.skills,notes:A.notes});return this.buildMarkdown(w,Q)}parseAgentContent(A){let Q=this.extractBody(A);if(!Q.trim())return{about:"",skills:[],notes:""};try{let w=aa1.parse(Q);return{about:w.about,skills:w.skills,notes:w.notes}}catch{return{about:"",skills:[],notes:""}}}parseEntity(A){return{frontmatter:this.parseFrontMatter(A.content,jK),body:this.parseAgentContent(A.content)}}}c0();var kUw=new k4,OUw=qU.extend({status:Hf.optional()}),xUw=FU.extend({query:OUw.optional()});function RUw(A){let Q=v2(A.content,jK),w=kUw.parseAgentContent(A.content);return ho.parse({...A,frontmatter:Q.metadata,about:w.about,skills:w.skills,notes:w.notes})}class _D0 extends f${id=Ro;name="Agent Directory DataSource";description="Fetches and transforms agent entities for rendering";config={entityType:K9,defaultSort:[{field:"discoveredAt",direction:"desc"}],defaultLimit:50,lookupField:"slug",enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return RUw(A)}buildDetailResult(A,Q){return{agent:A,prevAgent:Q?.prev??null,nextAgent:Q?.next??null}}parseQuery(A){let Q=xUw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}buildListResult(A,Q,w){let B=Hf.safeParse(w.status);return{agents:A,pagination:Q,baseUrl:w.baseUrl,selectedStatus:B.success?B.data:"all"}}async fetch(A,Q,w){let{query:B}=this.parseQuery(A);if(B.id)return super.fetch(A,Q,w);let{items:$,pagination:Y}=await this.fetchList(B,w.entityService,B.status?{filter:{metadata:{status:B.status}}}:void 0);return Q.parse(this.buildListResult($,Y,B))}}c0();Z0();CB();c0();async function PD0(A,Q){let B=`${(A.startsWith("http")?A:`https://${A}`).replace(/\/$/,"")}/.well-known/agent-card.json`;try{let $=await Q(B);if(!$.ok)return null;let Y=await $.json();return gS(Y)}catch{return null}}function vo(A){let Q=A.trim();if(Q.startsWith("http://")||Q.startsWith("https://"))try{return new URL(Q).hostname}catch{return Q}let w=Q.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(w)try{return new URL(w[0]).hostname}catch{return w[0]}if(/^[^\s]+\.[^\s]+$/.test(Q))return Q;return""}Z0();var hUw=new k4;function ta1(A){return A.trim().toLowerCase().replace(/[_\s]+/g,"-")}function mb(A){let Q=new Set,w=[];for(let B of A){let $=ta1(B);if(!$||Q.has($))continue;Q.add($),w.push($)}return w}function vUw(A,Q){if(Q.count!==A.count)return Q.count-A.count;return A.tag.localeCompare(Q.tag)}async function ea1(A,Q={}){let w=Q.minCount??1,B=Q.topN??12,$=Q.visibilityScope??"public",Y=new Map,[D,X]=await Promise.all([A.entityService.listEntities({entityType:z5,options:{filter:{visibilityScope:$}}}),A.entityService.listEntities({entityType:K9,options:{filter:{visibilityScope:$}}})]),H=(W)=>{for(let f of mb(W))Y.set(f,(Y.get(f)??0)+1)};for(let W of D)H(W.metadata.tags);for(let W of X){let f=hUw.parseAgentContent(W.content);H(f.skills.flatMap((Z)=>Z.tags))}return Array.from(Y.entries()).map(([W,f])=>({tag:W,count:f})).filter((W)=>W.count>=w).sort(vUw).slice(0,B)}function At1(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:w})=>`- ${Q} (${w})`)].join(`
8361
8361
  `)}var CUw=new k4;function kD0(A,Q={}){let w=A.anchor?.name??A.brainName,B=A.anchor?.kind??"professional",$=[];if(A.anchor?.description)$.push(A.anchor.description);if(A.description)$.push(A.description);let Y=Q.status??"discovered",D=new Date().toISOString();return{content:CUw.createAgentContent({name:w,kind:B,...A.anchor?.organization&&{organization:A.anchor.organization},brainName:A.brainName,url:A.url,status:Y,discoveredAt:D,about:$.join(`
@@ -8456,7 +8456,7 @@ ${A.guidance}`:$}}function Ha1(A){return{...A,evidence:A.evidence.map((Q)=>({...
8456
8456
  setTagFilter("all");
8457
8457
  });
8458
8458
  })();`;import{jsxDEV as Aw}from"preact/jsx-dev-runtime";function lUw({item:A}){return Aw("li",{class:"list-item",children:[Aw("div",{class:"list-main",children:[Aw("span",{class:"list-name",children:A.name},void 0,!1,void 0,this),Aw("span",{class:"list-desc",children:A.description},void 0,!1,void 0,this),A.tags.length>0&&Aw("div",{class:"list-tags",children:A.tags.map((Q)=>Aw("span",{class:"tag",children:Q},`${A.id}:${Q}`,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Aw("div",{class:"list-meta",children:A.status==="discovered"&&Aw("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 pUw({item:A}){return Aw("li",{class:"list-item agent-network-skill-row","data-agent-network-skill-row":!0,"data-agent-network-tags":JSON.stringify(A.tags),children:[Aw("div",{class:"list-main",children:Aw("span",{class:"list-name",children:A.name},void 0,!1,void 0,this)},void 0,!1,void 0,this),Aw("div",{class:"list-meta",children:Aw("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 iUw({kind:A,items:Q,active:w}){return Aw("div",{class:`agent-network-panel${w?" is-active":""}`,"data-agent-network-panel":A,children:Q.length>0?Aw("ul",{class:"list agent-network-list",children:Q.map((B)=>Aw(lUw,{item:B},B.id,!1,void 0,this))},void 0,!1,void 0,this):Aw("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function dUw({skills:A,count:Q,filters:w}){return Aw("div",{class:"agent-network-panel","data-agent-network-panel":"skills",children:[Aw("div",{class:"agent-network-filter-row",role:"tablist","aria-label":"Filter skills by tag",children:[Aw("button",{class:"agent-network-filter is-active",type:"button","data-agent-network-tag-filter":"all","aria-pressed":"true",children:[Aw("span",{class:"count",children:Q},void 0,!1,void 0,this),Aw("span",{class:"label",children:"all"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.map((B)=>Aw("button",{class:`agent-network-filter${B.variant==="gap"?" is-gap":""}`,type:"button","data-agent-network-tag-filter":B.tag,"aria-pressed":"false",children:[Aw("span",{class:"count",children:B.count},void 0,!1,void 0,this),Aw("span",{class:"label",children:B.tag},void 0,!1,void 0,this)]},B.tag,!0,void 0,this))]},void 0,!0,void 0,this),A.length>0?Aw("ul",{class:"list agent-network-list agent-network-skills-list",children:A.map((B)=>Aw(pUw,{item:B},B.id,!1,void 0,this))},void 0,!1,void 0,this):Aw("p",{class:"agent-network-empty",children:"Nothing to show yet."},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Kr0({data:A}){let Q=Yt1.safeParse(A);if(!Q.success)return Aw("p",{class:"muted",children:"Nothing to show yet."},void 0,!1,void 0,this);let w=Q.data;return Aw("div",{"data-agent-network-widget":!0,"data-agent-network-view":"agents",children:[Aw("div",{class:"agent-network-view-tabs",role:"tablist","aria-label":"Browse the agent network",children:[Aw("button",{class:"agent-network-view-tab is-active",type:"button","data-agent-network-view-tab":"agents","aria-pressed":"true",children:["Agents",Aw("span",{class:"agent-network-view-count",children:w.counts.agents},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Aw("button",{class:"agent-network-view-tab",type:"button","data-agent-network-view-tab":"skills","aria-pressed":"false",children:["Skills",Aw("span",{class:"agent-network-view-count",children:w.counts.skills},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Aw("div",{class:"agent-network-kind-tabs",role:"tablist","aria-label":"Filter agents by kind",children:Zr0.map((B)=>{let $=B==="all";return Aw("button",{class:`agent-network-kind-tab${$?" is-active":""}`,type:"button","data-agent-network-kind-tab":B,"aria-pressed":$?"true":"false",children:[Aw("span",{class:"agent-network-kind-count",children:w.agents[B].length},void 0,!1,void 0,this),Aw("span",{class:"agent-network-kind-label",children:B},void 0,!1,void 0,this)]},B,!0,void 0,this)})},void 0,!1,void 0,this),Zr0.map((B)=>Aw(iUw,{kind:B,items:w.agents[B],active:B==="all"},B,!1,void 0,this)),Aw(dUw,{skills:w.skills,count:w.counts.skills,filters:w.skillFilters},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Xt1(A,Q){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:ua1,pluginId:Q,title:"Agent Network",section:"secondary",priority:15,rendererName:ca1,component:Kr0,clientScript:xD0,dataProvider:async()=>Dt1(A)}}),{success:!0}})}Z0();var Ht1=new k4;function nUw(A){return A.skills.map((Q)=>({name:Q.name,description:Q.description,tags:Q.tags??[]}))}function rUw(A){return new URL(A).hostname}function oUw(A){return[`ATProto card: ${A.uri}`,`ATProto card CID: ${A.cid}`,`ATProto repo DID: ${A.repoDid}`].join(`
8459
- `)}function sUw(A){let Q=A.record.brain.did,w=A.record.anchor.did;return{agentId:A.agent.id,name:A.agent.metadata.name,url:A.agent.metadata.url,status:A.agent.metadata.status,repoDid:A.repoDid,...Q&&{brainDid:Q},...w&&{anchorDid:w},cardUri:A.uri,cardCid:A.cid}}async function aUw(A,Q,w){await A.messaging.send({type:Q,payload:w,broadcast:!0})}async function tUw(A,Q,w=new Date().toISOString()){let{record:B}=Q,$=rUw(B.siteUrl),Y=await A.entityService.getEntity({entityType:"agent",id:$}),D=Y?Ht1.parseEntity(Y):void 0,X=B.brain.did,H=B.anchor.did,W=nUw(B),f=Y?.metadata.status??"discovered",Z=Y?.metadata.url??B.siteUrl,G=Y?.metadata.slug??PV(Z),F=Y?.metadata.name??B.anchor.name,V=D?.frontmatter.kind??B.anchor.kind,b=Y?.metadata.discoveredAt??w,L=B.brain.purpose||D?.body.about||"",N=W.length>0?W:D?.body.skills??[],_={...Y?.metadata??{},name:F,url:Z,status:f,discoveredAt:b,slug:G,repoDid:Q.repoDid,...X&&{brainDid:X},...H&&{anchorDid:H},cardUri:Q.uri,cardCid:Q.cid},j=Ht1.createAgentContent({name:F,kind:V,...D?.frontmatter.organization&&{organization:D.frontmatter.organization},brainName:B.brain.name,url:Z,...X&&{did:X,brainDid:X},...H&&{anchorDid:H},repoDid:Q.repoDid,cardUri:Q.uri,cardCid:Q.cid,...D?.frontmatter.a2aEndpoint&&{a2aEndpoint:D.frontmatter.a2aEndpoint},status:f,discoveredAt:b,about:L,skills:N,notes:oUw({repoDid:Q.repoDid,uri:Q.uri,cid:Q.cid})});if(Y){let E={...Y,content:j,metadata:_,updated:w};return await A.entityService.updateEntity({entity:E}),{agent:E,created:!1}}let g={id:$,entityType:"agent",content:j,metadata:_,contentHash:"",visibility:"public",created:w,updated:w};return await A.entityService.createEntity({entity:g}),{agent:g,created:!0}}function Wt1(A){A.messaging.subscribe(M40,async(Q)=>{let w=mp1.parse(Q.payload),B=await tUw(A,w),$=sUw({agent:B.agent,repoDid:w.repoDid,uri:w.uri,cid:w.cid,record:w.record});return await aUw(A,B.created?Tp1:Sp1,$),{success:!0,data:$}})}function ft1(){return["Agent entities represent saved peer-brain contacts in the local agent directory. List saved agent contacts with system_list on entityType agent.","Agent contact records are verified A2A peer contacts: connect/save them with agent_connect and a url source; a raw domain is a valid source, so preserve a bare domain as the bare domain string. agent_connect verifies the remote Agent Card and saves the contact as approved for future calls.","Agent lifecycle is tracked with status fields such as discovered, approved, and archived; approval and archive operations are system_update field changes for already saved discovered contacts. If the user asks to approve or archive a saved agent contact by exact id such as approval-candidate.io or old-agent.io, call system_update on entityType agent with that id and the requested status; do not use agent_connect for approval.","Calling remote agents and saving local contact records are separate capabilities. Archived agents are not active call targets."].join(" ")}c0();IB();Z0();import{jsxDEV as Zt1}from"preact/jsx-dev-runtime";function RD0(A){try{return new URL(A).hostname}catch{return A}}var hD0=({name:A,className:Q=""})=>{let w=A.charAt(0).toUpperCase(),B=0;for(let Y=0;Y<A.length;Y++)B=A.charCodeAt(Y)+((B<<5)-B);let $=Math.abs(B)%360;return Zt1("div",{className:`flex items-center justify-center rounded-full text-white font-bold flex-shrink-0 ${Q}`,style:{backgroundColor:`hsl(${$}, 55%, 45%)`},children:w},void 0,!1,void 0,this)},vD0=({kind:A,size:Q="md"})=>{let B={professional:"bg-status-success text-status-success",team:"bg-status-info text-status-info",collective:"bg-brand/10 text-brand"}[A]??"bg-status-neutral text-status-neutral";return Zt1("span",{className:`inline-flex items-center rounded-full font-medium ${Q==="sm"?"px-2 py-0.5 text-xs":"px-2.5 py-0.5 text-[13px]"} ${B}`,children:A},void 0,!1,void 0,this)};import{jsxDEV as j2,Fragment as QGw}from"preact/jsx-dev-runtime";var eUw=({skills:A})=>{if(A.length===0)return null;return j2("div",{className:"flex gap-1.5 flex-wrap mt-2",children:A.map((Q)=>j2("span",{className:"text-[11px] px-2 py-0.5 bg-theme-subtle rounded-md text-theme-muted",children:Q.name},Q.name,!1,void 0,this))},void 0,!1,void 0,this)};function AGw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Kt1(A,Q,w){let B=new URLSearchParams({status:Q});if(w>1)B.set("page",String(w));return`${A}?${B.toString()}`}var Ur0=({agent:A})=>{let{frontmatter:Q,about:w,skills:B,url:$}=A,Y=Q.status==="approved";return j2("a",{href:$,className:`flex items-start gap-5 p-6 rounded-xl border border-theme bg-theme-subtle hover:shadow-lg transition-shadow ${Y?"":"opacity-70"}`,children:[j2(hD0,{name:Q.name,className:"w-12 h-12 text-lg"},void 0,!1,void 0,this),j2("div",{className:"flex-1 min-w-0",children:[j2("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[j2("span",{className:"text-lg font-semibold text-heading",children:Q.name},void 0,!1,void 0,this),j2(vD0,{kind:Q.kind,size:"sm"},void 0,!1,void 0,this),Q.organization&&j2("span",{className:"text-xs text-theme-muted",children:["\xB7 ",Q.organization]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"text-sm text-theme-muted mb-1",children:Q.brainName},void 0,!1,void 0,this),w&&j2("p",{className:"text-sm text-theme-muted line-clamp-2 mb-0",children:w},void 0,!1,void 0,this),Y&&j2(eUw,{skills:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col items-end gap-1 flex-shrink-0 text-right",children:[j2("span",{className:"text-xs text-theme-muted",children:RD0(Q.url)},void 0,!1,void 0,this),j2("span",{className:"text-[11px] text-theme-muted opacity-60",children:Y?`Discovered ${AGw(Q.discoveredAt)}`:"Discovered \xB7 approve before calling"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Ut1=({agents:A,pageTitle:Q,pagination:w,baseUrl:B="/agents",selectedStatus:$})=>{let Y=Q??"Agent Directory",D=w?.totalItems??A.length,X=A.filter((G)=>G.frontmatter.status==="approved"),H=A.filter((G)=>G.frontmatter.status==="discovered"),W=X.length,f=H.length,Z=`Your network of ${D} ${D===1?"brain":"brains"} and their anchors`;return j2(QGw,{children:[j2(jQ,{title:Y,description:Z},void 0,!1,void 0,this),j2("div",{className:"agent-list bg-theme",children:j2("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[j2("div",{className:"mb-8 pb-6 border-b border-theme",children:[j2("h1",{className:"text-4xl font-bold text-heading mb-2",children:Y},void 0,!1,void 0,this),j2("p",{className:"text-theme-muted mb-4",children:Z},void 0,!1,void 0,this),j2("div",{className:"flex flex-wrap gap-2 text-sm mb-4",children:[j2("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-heading",children:[D," total"]},void 0,!0,void 0,this),j2("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-status-success",children:[W," approved"]},void 0,!0,void 0,this),j2("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-theme-muted",children:[f," discovered"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-wrap gap-2 text-sm",children:[j2("a",{href:B,className:`px-3 py-1 rounded-full border transition-colors ${$==="all"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"All"},void 0,!1,void 0,this),j2("a",{href:`${B}?status=approved`,className:`px-3 py-1 rounded-full border transition-colors ${$==="approved"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Approved"},void 0,!1,void 0,this),j2("a",{href:`${B}?status=discovered`,className:`px-3 py-1 rounded-full border transition-colors ${$==="discovered"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Discovered"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$==="all"&&X.length>0&&j2("section",{className:"mb-10",children:[j2("div",{className:"flex items-center justify-between mb-4",children:[j2("h2",{className:"text-lg font-semibold text-heading",children:"Approved brains"},void 0,!1,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:X.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col gap-4",children:X.map((G)=>j2(Ur0,{agent:G},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$==="all"&&H.length>0&&j2("section",{children:[j2("div",{className:"flex items-center justify-between mb-4",children:[j2("div",{children:[j2("h2",{className:"text-lg font-semibold text-heading",children:"Discovered brains"},void 0,!1,void 0,this),j2("p",{className:"text-sm text-theme-muted",children:"Review and approve these before calling them."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:H.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col gap-4",children:H.map((G)=>j2(Ur0,{agent:G},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$!=="all"&&A.length>0&&j2("section",{children:[j2("div",{className:"flex items-center justify-between mb-4",children:[j2("h2",{className:"text-lg font-semibold text-heading",children:$==="approved"?"Approved brains":"Discovered brains"},void 0,!1,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:A.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col gap-4",children:A.map((G)=>j2(Ur0,{agent:G},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.length===0&&j2("p",{className:"text-center text-theme-muted py-16",children:"No agents in your directory yet."},void 0,!1,void 0,this),w&&w.totalPages>1&&$==="all"&&j2("div",{className:"mt-12",children:j2(o3,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:B},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&w.totalPages>1&&$!=="all"&&j2("nav",{"aria-label":"Pagination",className:"flex items-center justify-center gap-3 mt-12",children:[w.hasPrevPage?j2("a",{href:Kt1(B,$,w.currentPage-1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"\u2190 Prev"},void 0,!1,void 0,this):j2("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"\u2190 Prev"},void 0,!1,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:["Page ",w.currentPage," of ",w.totalPages]},void 0,!0,void 0,this),w.hasNextPage?j2("a",{href:Kt1(B,$,w.currentPage+1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"Next \u2192"},void 0,!1,void 0,this):j2("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"Next \u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as U2,Fragment as YGw}from"preact/jsx-dev-runtime";function wGw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}var Co=({children:A})=>U2("h2",{className:"text-sm font-semibold text-theme-muted uppercase tracking-wide mb-3",children:A},void 0,!1,void 0,this),BGw=({skill:A})=>U2("div",{className:"flex items-start gap-3 px-4 py-3 bg-theme-subtle rounded-lg",children:[U2("div",{className:"flex-1",children:[U2("div",{className:"text-sm font-semibold text-heading",children:A.name},void 0,!1,void 0,this),U2("div",{className:"text-[13px] text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.tags.length>0&&U2("div",{className:"flex gap-1 flex-shrink-0",children:A.tags.map((Q)=>U2("span",{className:"text-[11px] px-2 py-0.5 bg-theme rounded-md text-theme-muted",children:Q},Q,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$Gw=({label:A,value:Q,valueClassName:w})=>U2("div",{className:"flex justify-between text-[13px]",children:[U2("span",{className:"text-theme-muted",children:A},void 0,!1,void 0,this),U2("span",{className:w??"text-heading",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Gt1=({agent:A,prevAgent:Q,nextAgent:w})=>{let{frontmatter:B,about:$,skills:Y,notes:D}=A,X=RD0(B.url),H=B.status==="approved";return U2(YGw,{children:[U2(jQ,{title:B.name,description:$||`Agent profile for ${B.name}`},void 0,!1,void 0,this),U2("article",{className:"agent-detail",children:U2("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:[U2("a",{href:"/agents",className:"text-sm text-theme-muted hover:text-brand transition-colors mb-6 inline-block",children:"\u2190 Back to Directory"},void 0,!1,void 0,this),U2("div",{className:"flex items-start gap-6 mb-8",children:[U2(hD0,{name:B.name,className:"w-[72px] h-[72px] text-3xl"},void 0,!1,void 0,this),U2("div",{children:[U2("div",{className:"flex items-center gap-3 mb-1",children:[U2("h1",{className:"text-3xl md:text-4xl font-bold text-heading",children:B.name},void 0,!1,void 0,this),U2(vD0,{kind:B.kind},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U2("div",{className:"text-base text-theme-muted mb-2",children:B.brainName},void 0,!1,void 0,this),U2("div",{className:"flex items-center gap-3 text-theme-muted",children:[B.organization&&U2("span",{className:"text-[15px]",children:B.organization},void 0,!1,void 0,this),B.organization&&U2("span",{className:"text-theme-muted opacity-40",children:"\xB7"},void 0,!1,void 0,this),U2("span",{className:"text-sm",children:["Discovered ",wGw(B.discoveredAt)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("div",{className:"border-b border-theme mb-8"},void 0,!1,void 0,this),!H&&U2("div",{className:"mb-8 rounded-xl border border-theme bg-theme-subtle px-5 py-4",children:[U2("div",{className:"text-sm font-semibold text-heading mb-1",children:"Saved for review"},void 0,!1,void 0,this),U2("p",{className:"text-sm text-theme-muted",children:"This brain is discovered but not approved yet, so it cannot be called until you approve it."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U2("div",{className:"flex flex-col md:flex-row gap-12",children:[U2("div",{className:"flex-[2] min-w-0",children:[$&&U2("section",{className:"mb-8",children:[U2(Co,{children:"About"},void 0,!1,void 0,this),U2("p",{className:"text-[15px] text-theme leading-relaxed",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.length>0&&U2("section",{className:"mb-8",children:[U2(Co,{children:"Skills"},void 0,!1,void 0,this),U2("div",{className:"flex flex-col gap-2.5",children:Y.map((W)=>U2(BGw,{skill:W},W.name,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D&&U2("section",{className:"mb-8",children:[U2(Co,{children:"Notes"},void 0,!1,void 0,this),U2("p",{className:"text-[15px] text-theme leading-relaxed",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("aside",{className:"flex-1 md:pl-8 md:border-l border-theme-muted/20",children:[U2("section",{className:"mb-8",children:[U2(Co,{children:"Brain"},void 0,!1,void 0,this),U2("div",{className:"p-4 bg-theme-subtle rounded-xl",children:[U2("div",{className:"text-[15px] font-semibold text-heading mb-1",children:B.brainName},void 0,!1,void 0,this),B.did&&U2("div",{className:"text-xs text-theme-muted font-mono",children:B.did},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("section",{className:"mb-8",children:[U2(Co,{children:"Connection"},void 0,!1,void 0,this),U2("div",{className:"flex flex-col gap-3",children:[U2("div",{children:[U2("div",{className:"text-[13px] text-theme-muted mb-0.5",children:"Endpoint"},void 0,!1,void 0,this),U2("div",{className:"text-xs text-heading font-mono",children:B.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U2($Gw,{label:"Status",value:B.status==="approved"?"Approved":"Discovered",valueClassName:B.status==="approved"?"text-status-success font-medium":"text-theme-muted"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("a",{href:B.url.replace(/\/a2a\/?$/,""),target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center px-5 py-3 bg-theme-dark text-theme-inverse rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:["Visit ",X," \u2197"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(Q??w)&&U2("nav",{className:"mt-12 pt-6 border-t border-theme flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[U2("div",{className:"min-h-[1px]",children:Q&&U2("a",{href:Q.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[U2("span",{children:"\u2190 Previous"},void 0,!1,void 0,this),U2("span",{className:"text-heading font-medium",children:Q.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),U2("div",{className:"min-h-[1px] md:text-right",children:w&&U2("a",{href:w.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[U2("span",{children:"Next \u2192"},void 0,!1,void 0,this),U2("span",{className:"text-heading font-medium",children:w.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};var DGw=K.object({agents:K.array(RE),pageTitle:K.string().optional(),pagination:e7.nullable(),baseUrl:K.string().optional(),selectedStatus:K.union([K.literal("all"),Hf])});function zt1(){return{[Hr0]:R1({name:Hr0,description:"Agent directory list page template",schema:DGw,dataSourceId:Ro,requiredPermission:"public",layout:{component:Ut1}}),[Wr0]:R1({name:Wr0,description:"Individual agent profile template",schema:K.object({agent:RE,prevAgent:RE.nullable(),nextAgent:RE.nullable()}),dataSourceId:Ro,requiredPermission:"public",layout:{component:Gt1}})}}var hE={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.135",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var HGw=new k4;class Gr0 extends kQ{entityType=K9;schema=xE;adapter=HGw;constructor(){super(ma1,hE)}createGenerationHandler(A){return new fr0(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return zt1()}getDataSources(){return[new _D0(this.logger.child("AgentDataSource"))]}async onRegister(A){Wt1(A),Xt1(A,this.id)}async getInstructions(){return ft1()}}function zr0(){return new Gr0}c0();Z0();k9();Z0();var qt1=K.object({source:K.object({kind:K.literal("url"),url:K.string().min(1).describe("Remote agent domain or URL to verify and connect. Preserve bare domains as bare domains.")}),confirmed:K.boolean().optional(),confirmationToken:K.string().optional()}),WGw=new k4;function fGw(A){let Q=vo(A);if(!Q)return null;return{domain:Q,fetchTarget:A.trim().startsWith("http")?A.trim():Q}}function ZGw(A,Q){return(vo(Q)||A).toLowerCase()}async function KGw(A){let{context:Q,entityId:w,card:B}=A,$=new Date().toISOString(),Y=await Q.entityService.getEntity({entityType:K9,id:w}),D=kD0(B,{status:"approved"}),H={...WGw.fromMarkdown(D.content).metadata,...D.metadata,a2aEndpoint:B.url};if(Y){let f={...Y,content:D.content,metadata:H,updated:$};return await Q.entityService.updateEntity({entity:f}),{entity:f,created:!1}}let W={id:w,entityType:K9,content:D.content,metadata:H,contentHash:"",visibility:"public",created:$,updated:$};return await Q.entityService.createEntity({entity:W}),{entity:W,created:!0}}function Ft1(A,Q=globalThis.fetch){let B=new lf;return{name:"agent_connect",description:"Verify and connect a remote A2A agent by fetching its Agent Card from /.well-known/agent-card.json, then save the verified contact in the local agent directory as approved for future calls. This establishes and approves the contact; it does not message the remote agent. Requires confirmation before verification and persistence. Call this tool without confirmed on the initial request; the tool returns confirmation args for the user to approve.",inputSchema:qt1.shape,visibility:"trusted",sideEffects:"external",handler:async($,Y)=>{let D=qt1.safeParse($);if(!D.success)return{success:!1,error:`Invalid input: ${D.error.errors.map((f)=>`${f.path.join(".")}: ${f.message}`).join(", ")}`};let X=D.data,H=fGw(X.source.url);if(!H)return{success:!1,error:"Provide a valid remote agent domain or URL to connect.",code:"invalid_agent_url"};try{A.permissions.assertEntityActionAllowed(K9,"create",Y)}catch(f){return{success:!1,error:f instanceof Error?f.message:String(f)}}if(X.confirmed){let f=X.confirmationToken,Z=B.validate(f,X);if(Z.status==="missing")return{success:!1,error:"No pending agent connection confirmation found. Please request connection again and confirm the new approval."};if(Z.status==="mismatch")return{success:!1,error:"Confirmed agent connection arguments do not match the pending approval. Please request connection again and confirm the new approval."};let G=await PD0(H.fetchTarget,Q);if(!G)return{success:!1,error:`Could not verify an A2A Agent Card for ${H.domain}.`,code:"not_an_agent"};let F=ZGw(H.domain,G.url),{entity:V,created:b}=await KGw({context:A,entityId:F,sourceUrl:X.source.url,card:G});return{success:!0,data:{status:V.metadata.status,entityId:V.id,connected:!0,created:b,a2aEndpoint:G.url,skills:G.skills.map((L)=>({name:L.name,description:L.description,tags:L.tags}))}}}let W=B.create((f)=>({source:X.source,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"agent_connect",summary:`Verify and connect agent ${H.domain}?`,preview:`This will fetch and validate ${H.domain}'s A2A Agent Card, then save the verified contact as approved for future calls. It will not message the remote agent.`,args:W}}}}var UGw=K.object({}).strict();class qr0 extends IQ{fetchFn;constructor(A){super("agent",hE,{},UGw);this.fetchFn=A}async getTools(){return[Ft1(this.getContext(),this.fetchFn)]}}function Fr0(){return new qr0}c0();Z0();c0();var vE=NX,Vt1=NX,yo=o1.extend({entityType:K.literal(z5),metadata:Vt1});c0();class CE extends J2{constructor(){super({entityType:z5,purpose:"A capability advertised by a remote agent.",schema:yo,frontmatterSchema:vE})}fromMarkdown(A){let Q=this.parseFrontMatter(A,vE);return{content:A,entityType:z5,metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}c0();Z0();var GGw=K.object({skills:K.array(vE).max(4)}),Jt1=R1({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:GGw,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
8459
+ `)}function sUw(A){let Q=A.record.brain.did,w=A.record.anchor.did;return{agentId:A.agent.id,name:A.agent.metadata.name,url:A.agent.metadata.url,status:A.agent.metadata.status,repoDid:A.repoDid,...Q&&{brainDid:Q},...w&&{anchorDid:w},cardUri:A.uri,cardCid:A.cid}}async function aUw(A,Q,w){await A.messaging.send({type:Q,payload:w,broadcast:!0})}async function tUw(A,Q,w=new Date().toISOString()){let{record:B}=Q,$=rUw(B.siteUrl),Y=await A.entityService.getEntity({entityType:"agent",id:$}),D=Y?Ht1.parseEntity(Y):void 0,X=B.brain.did,H=B.anchor.did,W=nUw(B),f=Y?.metadata.status??"discovered",Z=Y?.metadata.url??B.siteUrl,G=Y?.metadata.slug??PV(Z),F=Y?.metadata.name??B.anchor.name,V=D?.frontmatter.kind??B.anchor.kind,b=Y?.metadata.discoveredAt??w,L=B.brain.purpose||D?.body.about||"",N=W.length>0?W:D?.body.skills??[],_={...Y?.metadata??{},name:F,url:Z,status:f,discoveredAt:b,slug:G,repoDid:Q.repoDid,...X&&{brainDid:X},...H&&{anchorDid:H},cardUri:Q.uri,cardCid:Q.cid},j=Ht1.createAgentContent({name:F,kind:V,...D?.frontmatter.organization&&{organization:D.frontmatter.organization},brainName:B.brain.name,url:Z,...X&&{did:X,brainDid:X},...H&&{anchorDid:H},repoDid:Q.repoDid,cardUri:Q.uri,cardCid:Q.cid,...D?.frontmatter.a2aEndpoint&&{a2aEndpoint:D.frontmatter.a2aEndpoint},status:f,discoveredAt:b,about:L,skills:N,notes:oUw({repoDid:Q.repoDid,uri:Q.uri,cid:Q.cid})});if(Y){let E={...Y,content:j,metadata:_,updated:w};return await A.entityService.updateEntity({entity:E}),{agent:E,created:!1}}let g={id:$,entityType:"agent",content:j,metadata:_,contentHash:"",visibility:"public",created:w,updated:w};return await A.entityService.createEntity({entity:g}),{agent:g,created:!0}}function Wt1(A){A.messaging.subscribe(M40,async(Q)=>{let w=mp1.parse(Q.payload),B=await tUw(A,w),$=sUw({agent:B.agent,repoDid:w.repoDid,uri:w.uri,cid:w.cid,record:w.record});return await aUw(A,B.created?Tp1:Sp1,$),{success:!0,data:$}})}function ft1(){return["Agent entities represent saved peer-brain contacts in the local agent directory. List saved agent contacts with system_list on entityType agent.","Agent contact records are verified A2A peer contacts: connect/save them with agent_connect and a url source; a raw domain is a valid source, so preserve a bare domain as the bare domain string. agent_connect verifies the remote Agent Card and saves the contact as approved for future calls.","Agent lifecycle is tracked with status fields such as discovered, approved, and archived; approval and archive operations are system_update field changes for already saved discovered contacts. If the user asks to approve or archive a saved agent contact by exact id such as approval-candidate.io or old-agent.io, call system_update on entityType agent with that id and the requested status; do not use agent_connect for approval.","Calling remote agents and saving local contact records are separate capabilities. Archived agents are not active call targets."].join(" ")}c0();IB();Z0();import{jsxDEV as Zt1}from"preact/jsx-dev-runtime";function RD0(A){try{return new URL(A).hostname}catch{return A}}var hD0=({name:A,className:Q=""})=>{let w=A.charAt(0).toUpperCase(),B=0;for(let Y=0;Y<A.length;Y++)B=A.charCodeAt(Y)+((B<<5)-B);let $=Math.abs(B)%360;return Zt1("div",{className:`flex items-center justify-center rounded-full text-white font-bold flex-shrink-0 ${Q}`,style:{backgroundColor:`hsl(${$}, 55%, 45%)`},children:w},void 0,!1,void 0,this)},vD0=({kind:A,size:Q="md"})=>{let B={professional:"bg-status-success text-status-success",team:"bg-status-info text-status-info",collective:"bg-brand/10 text-brand"}[A]??"bg-status-neutral text-status-neutral";return Zt1("span",{className:`inline-flex items-center rounded-full font-medium ${Q==="sm"?"px-2 py-0.5 text-xs":"px-2.5 py-0.5 text-[13px]"} ${B}`,children:A},void 0,!1,void 0,this)};import{jsxDEV as j2,Fragment as QGw}from"preact/jsx-dev-runtime";var eUw=({skills:A})=>{if(A.length===0)return null;return j2("div",{className:"flex gap-1.5 flex-wrap mt-2",children:A.map((Q)=>j2("span",{className:"text-[11px] px-2 py-0.5 bg-theme-subtle rounded-md text-theme-muted",children:Q.name},Q.name,!1,void 0,this))},void 0,!1,void 0,this)};function AGw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Kt1(A,Q,w){let B=new URLSearchParams({status:Q});if(w>1)B.set("page",String(w));return`${A}?${B.toString()}`}var Ur0=({agent:A})=>{let{frontmatter:Q,about:w,skills:B,url:$}=A,Y=Q.status==="approved";return j2("a",{href:$,className:`flex items-start gap-5 p-6 rounded-xl border border-theme bg-theme-subtle hover:shadow-lg transition-shadow ${Y?"":"opacity-70"}`,children:[j2(hD0,{name:Q.name,className:"w-12 h-12 text-lg"},void 0,!1,void 0,this),j2("div",{className:"flex-1 min-w-0",children:[j2("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[j2("span",{className:"text-lg font-semibold text-heading",children:Q.name},void 0,!1,void 0,this),j2(vD0,{kind:Q.kind,size:"sm"},void 0,!1,void 0,this),Q.organization&&j2("span",{className:"text-xs text-theme-muted",children:["\xB7 ",Q.organization]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"text-sm text-theme-muted mb-1",children:Q.brainName},void 0,!1,void 0,this),w&&j2("p",{className:"text-sm text-theme-muted line-clamp-2 mb-0",children:w},void 0,!1,void 0,this),Y&&j2(eUw,{skills:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col items-end gap-1 flex-shrink-0 text-right",children:[j2("span",{className:"text-xs text-theme-muted",children:RD0(Q.url)},void 0,!1,void 0,this),j2("span",{className:"text-[11px] text-theme-muted opacity-60",children:Y?`Discovered ${AGw(Q.discoveredAt)}`:"Discovered \xB7 approve before calling"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Ut1=({agents:A,pageTitle:Q,pagination:w,baseUrl:B="/agents",selectedStatus:$})=>{let Y=Q??"Agent Directory",D=w?.totalItems??A.length,X=A.filter((G)=>G.frontmatter.status==="approved"),H=A.filter((G)=>G.frontmatter.status==="discovered"),W=X.length,f=H.length,Z=`Your network of ${D} ${D===1?"brain":"brains"} and their anchors`;return j2(QGw,{children:[j2(jQ,{title:Y,description:Z},void 0,!1,void 0,this),j2("div",{className:"agent-list bg-theme",children:j2("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[j2("div",{className:"mb-8 pb-6 border-b border-theme",children:[j2("h1",{className:"text-4xl font-bold text-heading mb-2",children:Y},void 0,!1,void 0,this),j2("p",{className:"text-theme-muted mb-4",children:Z},void 0,!1,void 0,this),j2("div",{className:"flex flex-wrap gap-2 text-sm mb-4",children:[j2("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-heading",children:[D," total"]},void 0,!0,void 0,this),j2("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-status-success",children:[W," approved"]},void 0,!0,void 0,this),j2("span",{className:"px-3 py-1 rounded-full bg-theme-subtle text-theme-muted",children:[f," discovered"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-wrap gap-2 text-sm",children:[j2("a",{href:B,className:`px-3 py-1 rounded-full border transition-colors ${$==="all"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"All"},void 0,!1,void 0,this),j2("a",{href:`${B}?status=approved`,className:`px-3 py-1 rounded-full border transition-colors ${$==="approved"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Approved"},void 0,!1,void 0,this),j2("a",{href:`${B}?status=discovered`,className:`px-3 py-1 rounded-full border transition-colors ${$==="discovered"?"border-theme text-heading bg-theme-subtle":"border-theme text-theme-muted hover:text-heading"}`,children:"Discovered"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$==="all"&&X.length>0&&j2("section",{className:"mb-10",children:[j2("div",{className:"flex items-center justify-between mb-4",children:[j2("h2",{className:"text-lg font-semibold text-heading",children:"Approved brains"},void 0,!1,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:X.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col gap-4",children:X.map((G)=>j2(Ur0,{agent:G},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$==="all"&&H.length>0&&j2("section",{children:[j2("div",{className:"flex items-center justify-between mb-4",children:[j2("div",{children:[j2("h2",{className:"text-lg font-semibold text-heading",children:"Discovered brains"},void 0,!1,void 0,this),j2("p",{className:"text-sm text-theme-muted",children:"Review and approve these before calling them."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:H.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col gap-4",children:H.map((G)=>j2(Ur0,{agent:G},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$!=="all"&&A.length>0&&j2("section",{children:[j2("div",{className:"flex items-center justify-between mb-4",children:[j2("h2",{className:"text-lg font-semibold text-heading",children:$==="approved"?"Approved brains":"Discovered brains"},void 0,!1,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:A.length},void 0,!1,void 0,this)]},void 0,!0,void 0,this),j2("div",{className:"flex flex-col gap-4",children:A.map((G)=>j2(Ur0,{agent:G},G.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.length===0&&j2("p",{className:"text-center text-theme-muted py-16",children:"No agents in your directory yet."},void 0,!1,void 0,this),w&&w.totalPages>1&&$==="all"&&j2("div",{className:"mt-12",children:j2(o3,{currentPage:w.currentPage,totalPages:w.totalPages,baseUrl:B},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&w.totalPages>1&&$!=="all"&&j2("nav",{"aria-label":"Pagination",className:"flex items-center justify-center gap-3 mt-12",children:[w.hasPrevPage?j2("a",{href:Kt1(B,$,w.currentPage-1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"\u2190 Prev"},void 0,!1,void 0,this):j2("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"\u2190 Prev"},void 0,!1,void 0,this),j2("span",{className:"text-sm text-theme-muted",children:["Page ",w.currentPage," of ",w.totalPages]},void 0,!0,void 0,this),w.hasNextPage?j2("a",{href:Kt1(B,$,w.currentPage+1),className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted hover:text-heading transition-colors",children:"Next \u2192"},void 0,!1,void 0,this):j2("span",{className:"px-3 py-2 rounded-md border border-theme text-sm text-theme-muted opacity-50",children:"Next \u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as U2,Fragment as YGw}from"preact/jsx-dev-runtime";function wGw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}var Co=({children:A})=>U2("h2",{className:"text-sm font-semibold text-theme-muted uppercase tracking-wide mb-3",children:A},void 0,!1,void 0,this),BGw=({skill:A})=>U2("div",{className:"flex items-start gap-3 px-4 py-3 bg-theme-subtle rounded-lg",children:[U2("div",{className:"flex-1",children:[U2("div",{className:"text-sm font-semibold text-heading",children:A.name},void 0,!1,void 0,this),U2("div",{className:"text-[13px] text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.tags.length>0&&U2("div",{className:"flex gap-1 flex-shrink-0",children:A.tags.map((Q)=>U2("span",{className:"text-[11px] px-2 py-0.5 bg-theme rounded-md text-theme-muted",children:Q},Q,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$Gw=({label:A,value:Q,valueClassName:w})=>U2("div",{className:"flex justify-between text-[13px]",children:[U2("span",{className:"text-theme-muted",children:A},void 0,!1,void 0,this),U2("span",{className:w??"text-heading",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Gt1=({agent:A,prevAgent:Q,nextAgent:w})=>{let{frontmatter:B,about:$,skills:Y,notes:D}=A,X=RD0(B.url),H=B.status==="approved";return U2(YGw,{children:[U2(jQ,{title:B.name,description:$||`Agent profile for ${B.name}`},void 0,!1,void 0,this),U2("article",{className:"agent-detail",children:U2("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:[U2("a",{href:"/agents",className:"text-sm text-theme-muted hover:text-brand transition-colors mb-6 inline-block",children:"\u2190 Back to Directory"},void 0,!1,void 0,this),U2("div",{className:"flex items-start gap-6 mb-8",children:[U2(hD0,{name:B.name,className:"w-[72px] h-[72px] text-3xl"},void 0,!1,void 0,this),U2("div",{children:[U2("div",{className:"flex items-center gap-3 mb-1",children:[U2("h1",{className:"text-3xl md:text-4xl font-bold text-heading",children:B.name},void 0,!1,void 0,this),U2(vD0,{kind:B.kind},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U2("div",{className:"text-base text-theme-muted mb-2",children:B.brainName},void 0,!1,void 0,this),U2("div",{className:"flex items-center gap-3 text-theme-muted",children:[B.organization&&U2("span",{className:"text-[15px]",children:B.organization},void 0,!1,void 0,this),B.organization&&U2("span",{className:"text-theme-muted opacity-40",children:"\xB7"},void 0,!1,void 0,this),U2("span",{className:"text-sm",children:["Discovered ",wGw(B.discoveredAt)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("div",{className:"border-b border-theme mb-8"},void 0,!1,void 0,this),!H&&U2("div",{className:"mb-8 rounded-xl border border-theme bg-theme-subtle px-5 py-4",children:[U2("div",{className:"text-sm font-semibold text-heading mb-1",children:"Saved for review"},void 0,!1,void 0,this),U2("p",{className:"text-sm text-theme-muted",children:"This brain is discovered but not approved yet, so it cannot be called until you approve it."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U2("div",{className:"flex flex-col md:flex-row gap-12",children:[U2("div",{className:"flex-[2] min-w-0",children:[$&&U2("section",{className:"mb-8",children:[U2(Co,{children:"About"},void 0,!1,void 0,this),U2("p",{className:"text-[15px] text-theme leading-relaxed",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y.length>0&&U2("section",{className:"mb-8",children:[U2(Co,{children:"Skills"},void 0,!1,void 0,this),U2("div",{className:"flex flex-col gap-2.5",children:Y.map((W)=>U2(BGw,{skill:W},W.name,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D&&U2("section",{className:"mb-8",children:[U2(Co,{children:"Notes"},void 0,!1,void 0,this),U2("p",{className:"text-[15px] text-theme leading-relaxed",children:D},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("aside",{className:"flex-1 md:pl-8 md:border-l border-theme-muted/20",children:[U2("section",{className:"mb-8",children:[U2(Co,{children:"Brain"},void 0,!1,void 0,this),U2("div",{className:"p-4 bg-theme-subtle rounded-xl",children:[U2("div",{className:"text-[15px] font-semibold text-heading mb-1",children:B.brainName},void 0,!1,void 0,this),B.did&&U2("div",{className:"text-xs text-theme-muted font-mono",children:B.did},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("section",{className:"mb-8",children:[U2(Co,{children:"Connection"},void 0,!1,void 0,this),U2("div",{className:"flex flex-col gap-3",children:[U2("div",{children:[U2("div",{className:"text-[13px] text-theme-muted mb-0.5",children:"Endpoint"},void 0,!1,void 0,this),U2("div",{className:"text-xs text-heading font-mono",children:B.url},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U2($Gw,{label:"Status",value:B.status==="approved"?"Approved":"Discovered",valueClassName:B.status==="approved"?"text-status-success font-medium":"text-theme-muted"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),U2("a",{href:B.url.replace(/\/a2a\/?$/,""),target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center px-5 py-3 bg-theme-dark text-theme-inverse rounded-lg text-sm font-medium hover:opacity-90 transition-opacity",children:["Visit ",X," \u2197"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(Q??w)&&U2("nav",{className:"mt-12 pt-6 border-t border-theme flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[U2("div",{className:"min-h-[1px]",children:Q&&U2("a",{href:Q.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[U2("span",{children:"\u2190 Previous"},void 0,!1,void 0,this),U2("span",{className:"text-heading font-medium",children:Q.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),U2("div",{className:"min-h-[1px] md:text-right",children:w&&U2("a",{href:w.url,className:"inline-flex flex-col text-sm text-theme-muted hover:text-heading transition-colors",children:[U2("span",{children:"Next \u2192"},void 0,!1,void 0,this),U2("span",{className:"text-heading font-medium",children:w.frontmatter.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};var DGw=K.object({agents:K.array(RE),pageTitle:K.string().optional(),pagination:e7.nullable(),baseUrl:K.string().optional(),selectedStatus:K.union([K.literal("all"),Hf])});function zt1(){return{[Hr0]:R1({name:Hr0,description:"Agent directory list page template",schema:DGw,dataSourceId:Ro,requiredPermission:"public",layout:{component:Ut1}}),[Wr0]:R1({name:Wr0,description:"Individual agent profile template",schema:K.object({agent:RE,prevAgent:RE.nullable(),nextAgent:RE.nullable()}),dataSourceId:Ro,requiredPermission:"public",layout:{component:Gt1}})}}var hE={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.136",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/atproto-contracts":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var HGw=new k4;class Gr0 extends kQ{entityType=K9;schema=xE;adapter=HGw;constructor(){super(ma1,hE)}createGenerationHandler(A){return new fr0(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return zt1()}getDataSources(){return[new _D0(this.logger.child("AgentDataSource"))]}async onRegister(A){Wt1(A),Xt1(A,this.id)}async getInstructions(){return ft1()}}function zr0(){return new Gr0}c0();Z0();k9();Z0();var qt1=K.object({source:K.object({kind:K.literal("url"),url:K.string().min(1).describe("Remote agent domain or URL to verify and connect. Preserve bare domains as bare domains.")}),confirmed:K.boolean().optional(),confirmationToken:K.string().optional()}),WGw=new k4;function fGw(A){let Q=vo(A);if(!Q)return null;return{domain:Q,fetchTarget:A.trim().startsWith("http")?A.trim():Q}}function ZGw(A,Q){return(vo(Q)||A).toLowerCase()}async function KGw(A){let{context:Q,entityId:w,card:B}=A,$=new Date().toISOString(),Y=await Q.entityService.getEntity({entityType:K9,id:w}),D=kD0(B,{status:"approved"}),H={...WGw.fromMarkdown(D.content).metadata,...D.metadata,a2aEndpoint:B.url};if(Y){let f={...Y,content:D.content,metadata:H,updated:$};return await Q.entityService.updateEntity({entity:f}),{entity:f,created:!1}}let W={id:w,entityType:K9,content:D.content,metadata:H,contentHash:"",visibility:"public",created:$,updated:$};return await Q.entityService.createEntity({entity:W}),{entity:W,created:!0}}function Ft1(A,Q=globalThis.fetch){let B=new lf;return{name:"agent_connect",description:"Verify and connect a remote A2A agent by fetching its Agent Card from /.well-known/agent-card.json, then save the verified contact in the local agent directory as approved for future calls. This establishes and approves the contact; it does not message the remote agent. Requires confirmation before verification and persistence. Call this tool without confirmed on the initial request; the tool returns confirmation args for the user to approve.",inputSchema:qt1.shape,visibility:"trusted",sideEffects:"external",handler:async($,Y)=>{let D=qt1.safeParse($);if(!D.success)return{success:!1,error:`Invalid input: ${D.error.errors.map((f)=>`${f.path.join(".")}: ${f.message}`).join(", ")}`};let X=D.data,H=fGw(X.source.url);if(!H)return{success:!1,error:"Provide a valid remote agent domain or URL to connect.",code:"invalid_agent_url"};try{A.permissions.assertEntityActionAllowed(K9,"create",Y)}catch(f){return{success:!1,error:f instanceof Error?f.message:String(f)}}if(X.confirmed){let f=X.confirmationToken,Z=B.validate(f,X);if(Z.status==="missing")return{success:!1,error:"No pending agent connection confirmation found. Please request connection again and confirm the new approval."};if(Z.status==="mismatch")return{success:!1,error:"Confirmed agent connection arguments do not match the pending approval. Please request connection again and confirm the new approval."};let G=await PD0(H.fetchTarget,Q);if(!G)return{success:!1,error:`Could not verify an A2A Agent Card for ${H.domain}.`,code:"not_an_agent"};let F=ZGw(H.domain,G.url),{entity:V,created:b}=await KGw({context:A,entityId:F,sourceUrl:X.source.url,card:G});return{success:!0,data:{status:V.metadata.status,entityId:V.id,connected:!0,created:b,a2aEndpoint:G.url,skills:G.skills.map((L)=>({name:L.name,description:L.description,tags:L.tags}))}}}let W=B.create((f)=>({source:X.source,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"agent_connect",summary:`Verify and connect agent ${H.domain}?`,preview:`This will fetch and validate ${H.domain}'s A2A Agent Card, then save the verified contact as approved for future calls. It will not message the remote agent.`,args:W}}}}var UGw=K.object({}).strict();class qr0 extends IQ{fetchFn;constructor(A){super("agent",hE,{},UGw);this.fetchFn=A}async getTools(){return[Ft1(this.getContext(),this.fetchFn)]}}function Fr0(){return new qr0}c0();Z0();c0();var vE=NX,Vt1=NX,yo=o1.extend({entityType:K.literal(z5),metadata:Vt1});c0();class CE extends J2{constructor(){super({entityType:z5,purpose:"A capability advertised by a remote agent.",schema:yo,frontmatterSchema:vE})}fromMarkdown(A){let Q=this.parseFrontMatter(A,vE);return{content:A,entityType:z5,metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}c0();Z0();var GGw=K.object({skills:K.array(vE).max(4)}),Jt1=R1({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:GGw,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
8460
8460
 
8461
8461
  Given knowledge domains, CONSOLIDATE related topics into broader skills.
8462
8462
  There should be FEWER skills than topics \u2014 combine related domains.
@@ -8606,9 +8606,9 @@ Context:
8606
8606
  ${JSON.stringify(B,null,2)}
8607
8607
 
8608
8608
  Draft SWOT:
8609
- ${JSON.stringify(w,null,2)}`}function uD0(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function EGw(A,Q){let w=["strengths","weaknesses","opportunities","threats"];for(let B of w){let $=new Set(A[B].map((Y)=>Y.theme.trim().toLowerCase()));for(let Y of Q[B]){let D=Y.sourceTheme.trim().toLowerCase();if(!$.has(D))throw Error(`SWOT refinement invented theme "${Y.sourceTheme}" in ${B}`)}}}class cD0{logger;context;adapter=new LF;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=Ir0.safeParse(A??{});return Q.success?Q.data:null}async process(A,Q,w){await w.report({progress:0.2,message:"Building SWOT context"});let B=await Mr0(this.context),$;if(B.summary.brainSkillCount+B.summary.approvedAgentCount+B.summary.discoveredAgentCount===0)$={strengths:[],weaknesses:[],opportunities:[],threats:[]};else{await w.report({progress:0.6,message:"Synthesizing SWOT analysis"});let{object:W}=await this.context.ai.generateObject(await vGw(this.context,B),br0),f=br0.parse(W);await w.report({progress:0.75,message:"Refining SWOT language"});let Z=await this.context.ai.generateObject(await yGw(this.context,B,f),TD0);$=TD0.parse(Z.object),EGw(f,$)}let D=new Date().toISOString(),X=this.adapter.createSwotContent({strengths:uD0($.strengths),weaknesses:uD0($.weaknesses),opportunities:uD0($.opportunities),threats:uD0($.threats),derivedAt:D});await w.report({progress:0.9,message:"Saving SWOT entity"});let H=await this.context.entityService.getEntity({entityType:"swot",id:"swot"});if(H)await this.context.entityService.updateEntity({entity:{...H,content:X,metadata:{derivedAt:D}}});else await this.context.entityService.createEntity({entity:{id:"swot",entityType:"swot",content:X,metadata:{derivedAt:D}}});return this.logger.info("SWOT derivation complete",{derivedAt:D,brainSkillCount:B.summary.brainSkillCount,approvedAgentCount:B.summary.approvedAgentCount,discoveredAgentCount:B.summary.discoveredAgentCount}),{entityId:"swot"}}}Z0();import{jsxDEV as O4}from"preact/jsx-dev-runtime";var lD0=K.object({title:K.string(),detail:K.string().optional()}),gGw=K.discriminatedUnion("status",[K.object({status:K.literal("generating")}),K.object({status:K.literal("ready"),strengths:K.array(lD0).default([]),weaknesses:K.array(lD0).default([]),opportunities:K.array(lD0).default([]),threats:K.array(lD0).default([]),derivedAt:K.string()})]);function TGw({items:A}){if(A.length===0)return O4("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return O4("ul",{class:"swot-list",children:A.map((Q)=>O4("li",{class:"swot-item",children:[O4("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?O4("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 pD0({title:A,tone:Q,items:w}){return O4("section",{class:`swot-cell is-${Q}`,children:[O4("div",{class:"swot-head",children:A},void 0,!1,void 0,this),O4(TGw,{items:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kr0({data:A}){let Q=gGw.safeParse(A);if(!Q.success||Q.data.status==="generating")return O4("div",{"data-swot-widget":!0,children:O4("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let w=Q.data;return O4("div",{"data-swot-widget":!0,children:O4("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[O4(pD0,{title:"Strengths",tone:"s",items:w.strengths},void 0,!1,void 0,this),O4(pD0,{title:"Weaknesses",tone:"w",items:w.weaknesses},void 0,!1,void 0,this),O4(pD0,{title:"Opportunities",tone:"o",items:w.opportunities},void 0,!1,void 0,this),O4(pD0,{title:"Threats",tone:"t",items:w.threats},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}Z0();var Or0={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.135",description:"Assessment outputs and capability-profile analysis",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var xr0=new LF;class Rr0 extends kQ{entityType="swot";schema=yE;adapter=xr0;initialSyncComplete=!1;constructor(){super("swot",Or0)}async onRegister(A){let Q=new cD0(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q),A.eval.registerHandler("deriveSwot",async()=>{let Y=D7.from(async()=>{});if(!Y)throw Error("Expected progress reporter to be created");await Q.process({reason:"eval"},"eval-swot-derive",Y);let D=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!D)throw Error("Expected SWOT entity to be created during eval");return xr0.parseSwotContent(D.content).frontmatter});let w=async(Y)=>{try{return await A.jobs.enqueue({type:"derive",data:{reason:Y},options:{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${Y}`}}})}catch(D){return this.logger.error("Failed to queue SWOT derivation",{error:D,reason:Y}),null}},B=async(Y)=>{if(!await A.entityService.getEntity({entityType:"swot",id:"swot"}))await w(Y)};A.messaging.subscribe("sync:initial:completed",async()=>{return this.initialSyncComplete=!0,await B("initial-missing-entity"),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"swot",pluginId:this.id,title:"SWOT",section:"secondary",priority:14,rendererName:"SwotWidget",component:kr0,dataProvider:async()=>{let Y=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!Y)return{status:"generating"};let{frontmatter:D}=xr0.parseSwotContent(Y.content);return{status:"ready",...D}}}}),{success:!0}});let $=async(Y)=>{let{entityType:D}=Y.payload;if(!this.initialSyncComplete)return{success:!0};if(D!=="agent"&&D!=="skill")return{success:!0};return await w("entity-change"),{success:!0}};A.messaging.subscribe("entity:created",$),A.messaging.subscribe("entity:updated",$),A.messaging.subscribe("entity:deleted",$)}}function hr0(){return new Rr0}c0();l$();Z0();var d76=new LF,vt1=K.object({name:K.string(),description:K.string(),tags:K.array(K.string())}),vr0=K.enum(["discovered","approved"]),mGw=K.object({name:K.string(),kind:K.enum(["professional","team","collective"]),organization:K.string().optional(),brainName:K.string(),url:K.string().url(),did:K.string().optional(),status:vr0,discoveredAt:K.string().datetime()}),uGw=o1.extend({entityType:K.literal("agent"),metadata:K.object({name:K.string(),url:K.string().url(),status:vr0,slug:K.string()})}),cGw=o1.extend({entityType:K.literal("skill"),metadata:NX}),lGw=K.object({about:K.string(),skills:K.array(vt1),notes:K.string()});function pGw(A){if(!Array.isArray(A)||A.length===0)return"";return A.map((w)=>{let B=w.tags.length>0?` [${w.tags.join(", ")}]`:"";return`- ${w.name}: ${w.description}${B}`}).join(`
8609
+ ${JSON.stringify(w,null,2)}`}function uD0(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function EGw(A,Q){let w=["strengths","weaknesses","opportunities","threats"];for(let B of w){let $=new Set(A[B].map((Y)=>Y.theme.trim().toLowerCase()));for(let Y of Q[B]){let D=Y.sourceTheme.trim().toLowerCase();if(!$.has(D))throw Error(`SWOT refinement invented theme "${Y.sourceTheme}" in ${B}`)}}}class cD0{logger;context;adapter=new LF;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=Ir0.safeParse(A??{});return Q.success?Q.data:null}async process(A,Q,w){await w.report({progress:0.2,message:"Building SWOT context"});let B=await Mr0(this.context),$;if(B.summary.brainSkillCount+B.summary.approvedAgentCount+B.summary.discoveredAgentCount===0)$={strengths:[],weaknesses:[],opportunities:[],threats:[]};else{await w.report({progress:0.6,message:"Synthesizing SWOT analysis"});let{object:W}=await this.context.ai.generateObject(await vGw(this.context,B),br0),f=br0.parse(W);await w.report({progress:0.75,message:"Refining SWOT language"});let Z=await this.context.ai.generateObject(await yGw(this.context,B,f),TD0);$=TD0.parse(Z.object),EGw(f,$)}let D=new Date().toISOString(),X=this.adapter.createSwotContent({strengths:uD0($.strengths),weaknesses:uD0($.weaknesses),opportunities:uD0($.opportunities),threats:uD0($.threats),derivedAt:D});await w.report({progress:0.9,message:"Saving SWOT entity"});let H=await this.context.entityService.getEntity({entityType:"swot",id:"swot"});if(H)await this.context.entityService.updateEntity({entity:{...H,content:X,metadata:{derivedAt:D}}});else await this.context.entityService.createEntity({entity:{id:"swot",entityType:"swot",content:X,metadata:{derivedAt:D}}});return this.logger.info("SWOT derivation complete",{derivedAt:D,brainSkillCount:B.summary.brainSkillCount,approvedAgentCount:B.summary.approvedAgentCount,discoveredAgentCount:B.summary.discoveredAgentCount}),{entityId:"swot"}}}Z0();import{jsxDEV as O4}from"preact/jsx-dev-runtime";var lD0=K.object({title:K.string(),detail:K.string().optional()}),gGw=K.discriminatedUnion("status",[K.object({status:K.literal("generating")}),K.object({status:K.literal("ready"),strengths:K.array(lD0).default([]),weaknesses:K.array(lD0).default([]),opportunities:K.array(lD0).default([]),threats:K.array(lD0).default([]),derivedAt:K.string()})]);function TGw({items:A}){if(A.length===0)return O4("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return O4("ul",{class:"swot-list",children:A.map((Q)=>O4("li",{class:"swot-item",children:[O4("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?O4("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 pD0({title:A,tone:Q,items:w}){return O4("section",{class:`swot-cell is-${Q}`,children:[O4("div",{class:"swot-head",children:A},void 0,!1,void 0,this),O4(TGw,{items:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kr0({data:A}){let Q=gGw.safeParse(A);if(!Q.success||Q.data.status==="generating")return O4("div",{"data-swot-widget":!0,children:O4("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let w=Q.data;return O4("div",{"data-swot-widget":!0,children:O4("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[O4(pD0,{title:"Strengths",tone:"s",items:w.strengths},void 0,!1,void 0,this),O4(pD0,{title:"Weaknesses",tone:"w",items:w.weaknesses},void 0,!1,void 0,this),O4(pD0,{title:"Opportunities",tone:"o",items:w.opportunities},void 0,!1,void 0,this),O4(pD0,{title:"Threats",tone:"t",items:w.threats},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}Z0();var Or0={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.136",description:"Assessment outputs and capability-profile analysis",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix",eval:"cd evals && bun run brain-eval"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var xr0=new LF;class Rr0 extends kQ{entityType="swot";schema=yE;adapter=xr0;initialSyncComplete=!1;constructor(){super("swot",Or0)}async onRegister(A){let Q=new cD0(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q),A.eval.registerHandler("deriveSwot",async()=>{let Y=D7.from(async()=>{});if(!Y)throw Error("Expected progress reporter to be created");await Q.process({reason:"eval"},"eval-swot-derive",Y);let D=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!D)throw Error("Expected SWOT entity to be created during eval");return xr0.parseSwotContent(D.content).frontmatter});let w=async(Y)=>{try{return await A.jobs.enqueue({type:"derive",data:{reason:Y},options:{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${Y}`}}})}catch(D){return this.logger.error("Failed to queue SWOT derivation",{error:D,reason:Y}),null}},B=async(Y)=>{if(!await A.entityService.getEntity({entityType:"swot",id:"swot"}))await w(Y)};A.messaging.subscribe("sync:initial:completed",async()=>{return this.initialSyncComplete=!0,await B("initial-missing-entity"),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"swot",pluginId:this.id,title:"SWOT",section:"secondary",priority:14,rendererName:"SwotWidget",component:kr0,dataProvider:async()=>{let Y=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!Y)return{status:"generating"};let{frontmatter:D}=xr0.parseSwotContent(Y.content);return{status:"ready",...D}}}}),{success:!0}});let $=async(Y)=>{let{entityType:D}=Y.payload;if(!this.initialSyncComplete)return{success:!0};if(D!=="agent"&&D!=="skill")return{success:!0};return await w("entity-change"),{success:!0}};A.messaging.subscribe("entity:created",$),A.messaging.subscribe("entity:updated",$),A.messaging.subscribe("entity:deleted",$)}}function hr0(){return new Rr0}c0();l$();Z0();var d76=new LF,vt1=K.object({name:K.string(),description:K.string(),tags:K.array(K.string())}),vr0=K.enum(["discovered","approved"]),mGw=K.object({name:K.string(),kind:K.enum(["professional","team","collective"]),organization:K.string().optional(),brainName:K.string(),url:K.string().url(),did:K.string().optional(),status:vr0,discoveredAt:K.string().datetime()}),uGw=o1.extend({entityType:K.literal("agent"),metadata:K.object({name:K.string(),url:K.string().url(),status:vr0,slug:K.string()})}),cGw=o1.extend({entityType:K.literal("skill"),metadata:NX}),lGw=K.object({about:K.string(),skills:K.array(vt1),notes:K.string()});function pGw(A){if(!Array.isArray(A)||A.length===0)return"";return A.map((w)=>{let B=w.tags.length>0?` [${w.tags.join(", ")}]`:"";return`- ${w.name}: ${w.description}${B}`}).join(`
8610
8610
  `)}function iGw(A){if(!A.trim())return[];return A.split(`
8611
- `).map((Q)=>Q.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/)).filter((Q)=>Q!==null).map((Q)=>({name:Q[1]??"",description:Q[2]??"",tags:Q[3]?Q[3].split(",").map((w)=>w.trim()).filter(Boolean):[]}))}var dGw=new pw(lGw,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:pGw,parser:iGw},{key:"notes",label:"Notes",type:"string"}]});class Ct1 extends J2{constructor(){super({entityType:"agent",purpose:"An agent entity used for SWOT evaluation.",schema:uGw,frontmatterSchema:mGw})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=dGw.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 yt1 extends J2{constructor(){super({entityType:"skill",purpose:"A skill entity used for SWOT evaluation.",schema:cGw,frontmatterSchema:NX})}fromMarkdown(A){let Q=this.parseFrontMatter(A,NX);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var n76=new Ct1,r76=new yt1,o76=K.object({skills:K.array(NX),agents:K.array(K.object({id:K.string().optional(),name:K.string(),kind:K.enum(["professional","team","collective"]),organization:K.string().optional(),brainName:K.string(),url:K.string().url(),did:K.string().optional(),status:vr0,discoveredAt:K.string().datetime().optional(),about:K.string(),skills:K.array(vt1),notes:K.string().default("")}))});var nGw=K.object({}).strict();function iD0(A={}){return nGw.parse(A),[hr0()]}c0();Z0();Z0();var Cr0=K.object({enabled:K.boolean().default(!0),pdsEndpoint:K.string().url().default("https://bsky.social").describe("AT Protocol PDS service endpoint"),identifier:K.string().optional().describe("PDS login identifier, usually a handle or account DID"),repoDid:K.string().optional().describe("DID of the PDS repo that owns records"),appPassword:K.string().optional().describe("App password for prototype authentication; supply via ${ENV_VAR} interpolation, never a committed literal"),anchorDid:K.string().optional().describe("Optional human/operator DID referenced from records; defaults to did:web:<site-host>:anchor when omitted"),brainDid:K.string().optional().describe("Optional public brain DID referenced from records; defaults to did:web:<site-host> when omitted")});function rGw(A){return A.replace(/\/+$/,"")}var oGw=(A,Q)=>fetch(A,Q);async function go(A){let Q=await A.json();if(!A.ok){let w=typeof Q==="object"&&Q!==null&&"message"in Q&&typeof Q.message==="string"?Q.message:`AT Protocol request failed with ${A.status}`;throw Error(w)}return Q}class To{pdsEndpoint;identifier;appPassword;fetchFn;session;constructor(A){this.pdsEndpoint=rGw(A.pdsEndpoint),this.identifier=A.identifier,this.appPassword=A.appPassword,this.fetchFn=A.fetch??oGw}async createSession(){let A=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.server.createSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:this.identifier,password:this.appPassword})}),Q=await go(A);return this.session=Q,Q}async createRecord(A){let Q=await this.getSession(),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.createRecord`,{method:"POST",headers:{Authorization:`Bearer ${Q.accessJwt}`,"Content-Type":"application/json"},body:JSON.stringify({repo:A.repo,collection:A.collection,record:A.record,...A.rkey&&{rkey:A.rkey},...A.validate!==void 0&&{validate:A.validate}})});return go(w)}async putRecord(A){let Q=await this.getSession(),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.putRecord`,{method:"POST",headers:{Authorization:`Bearer ${Q.accessJwt}`,"Content-Type":"application/json"},body:JSON.stringify({repo:A.repo,collection:A.collection,record:A.record,rkey:A.rkey,...A.validate!==void 0&&{validate:A.validate},...A.swapRecord!==void 0&&{swapRecord:A.swapRecord}})});return go(w)}async getRecord(A){let Q=new URLSearchParams({repo:A.repo,collection:A.collection,rkey:A.rkey}),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.getRecord?${Q.toString()}`,{method:"GET"});return go(w)}async uploadBlob(A){let Q=await this.getSession(),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.uploadBlob`,{method:"POST",headers:{Authorization:`Bearer ${Q.accessJwt}`,"Content-Type":A.mimeType},body:new Blob([new Uint8Array(A.data)],{type:A.mimeType})});return go(w)}async getSession(){return this.session??=await this.createSession(),this.session}}function EP(A){return A?.startsWith("did:web:")??!1}function dD0(A){if(!EP(A))return;let Q=A.slice(8);if(!Q)return;let[w]=Q.split(":");if(!w)return;try{return decodeURIComponent(w)}catch{return w}}function gt1(A){if(!EP(A))return;let Q=A.slice(8);if(!Q)return;let[,...w]=Q.split(":");if(w.length===0)return"/.well-known/did.json";return`/${w.map(($)=>{try{return decodeURIComponent($)}catch{return $}}).join("/")}/did.json`}function Tt1(A){return A.replace(/\/+$/,"")}function So(A){return`did:web:${encodeURIComponent(A)}`}function nD0(A){return`${So(A)}:anchor`}function yr0(A){return{"@context":["https://www.w3.org/ns/did/v1"],id:A}}function St1(A,Q){let w=A.identifier?.startsWith("did:")?void 0:A.identifier?[`at://${A.identifier}`]:void 0;return{...yr0(Q),...w&&{alsoKnownAs:w},service:[{id:"#atproto_pds",type:"AtprotoPersonalDataServer",serviceEndpoint:Tt1(A.pdsEndpoint)}]}}function mt1(A){if(!EP(A.brainDid))return null;return St1(A,A.brainDid)}function Et1(A,Q){if(!A||!Q)return;let w=dD0(A),B=gt1(A);if(!w||!B)return;return{path:B,hostname:w,document:Q}}function rD0(A){let Q=[],w=Et1(A.brainDid,mt1(A));if(w)Q.push(w);if(EP(A.anchorDid)&&A.anchorDid!==A.brainDid){let B=Et1(A.anchorDid,yr0(A.anchorDid));if(B)Q.push(B)}return Q}function Er0(A,Q){let w=[];if(!A.brainDid){let B=So(Q);w.push({path:"/.well-known/did.json",hostname:Q,document:St1(A,B)})}if(!A.anchorDid){let B=nD0(Q);w.push({path:"/anchor/did.json",hostname:Q,document:yr0(B)})}return w}function sGw(A,Q){if(!A)return;try{return new URL(A,Q).toString()}catch{return}}function aGw(A){let Q=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,200);return Q.length>0?Q:"skill"}function ut1(A,Q){let w=A[Q];return typeof w==="string"&&w.length>0?w:void 0}function ct1(A,Q){let w=A[Q];if(!Array.isArray(w))return;let B=w.filter(($)=>typeof $==="string"&&$.length>0);return B.length>0?B:void 0}function tGw(A){let Q=A.metadata,w=ut1(Q,"name"),B=ut1(Q,"description");if(!w||!B)return;let $=ct1(Q,"tags"),Y=ct1(Q,"examples");return{id:aGw(w),name:w,description:B,...$&&{tags:$},...Y&&{examples:Y}}}async function eGw(A){if(!A.entityService.hasEntityType("skill"))return[];return(await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}})).map((w)=>tGw(w)).filter((w)=>w!==void 0).slice(0,100)}async function gr0(A,Q,w=new Date){let B=A.identity.get(),$=A.identity.getProfile(),Y=await A.identity.getAppInfo(),D=sGw(A.siteUrl??$.website,void 0);if(!D)throw Error("AT Protocol brain card publishing requires siteUrl");let X=new URL(D).hostname,H=Q.brainDid??So(X),W=Q.anchorDid??nD0(X);if(EP(H)){if(dD0(H)!==X)throw Error("AT Protocol brain card did:web host must match siteUrl host")}let f=await eGw(A);return{$type:"ai.rizom.brain.card",siteUrl:D,brain:{did:H,name:B.name,role:B.role,purpose:B.purpose,values:B.values},anchor:{did:W,name:$.name,kind:$.kind},skills:f,model:Y.model,version:Y.version,createdAt:w.toISOString(),updatedAt:w.toISOString()}}var lt1={name:"@brains/atproto",private:!0,version:"0.2.0-alpha.135",description:"AT Protocol integration for identity, publishing, discovery, and feeds",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/atproto-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var pt1=MB["ai.rizom.brain.card"],Qzw="ai.rizom.brain.card",wzw="self",it1=50;class Tr0 extends IQ{deps;projectionRegistry;constructor(A={},Q={}){super("atproto",lt1,A,Cr0);this.deps=Q,this.projectionRegistry=Q.projectionRegistry??U5.getInstance()}getWebRoutes(){if(!this.config.enabled)return[];let A=rD0(this.config),Q=[...!this.config.brainDid?["/.well-known/did.json"]:[],...!this.config.anchorDid?["/anchor/did.json"]:[]];return[...new Set([...A.map((B)=>B.path),...Q])].map((B)=>({path:B,method:"GET",public:!0,handler:($)=>{let Y=new URL($.url).hostname,D=[...rD0(this.config),...Er0(this.config,Y)].filter((H)=>H.path===B),X=D.find((H)=>H.hostname===Y)??D[0];if(!X)return new Response("Not found",{status:404});return new Response(JSON.stringify(X.document),{headers:{"Content-Type":"application/did+json"}})}}))}async publishBrainCard(A,Q={}){let w=await gr0(A,this.config);Lb(pt1,w);let B=this.config.repoDid;if(Q.dryRun)return{record:w,dryRun:!0,...B&&{repo:B}};let $=this.resolveAppPassword();if(!this.config.identifier||!$)throw Error("AT Protocol publishing requires identifier and app password configuration");let Y=this.createPdsClient($),D=await Y.createSession(),X=B??D.did;if(!Y.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let H=await Y.putRecord({repo:X,collection:"ai.rizom.brain.card",rkey:"self",validate:!1,record:w});return{record:w,repo:X,uri:H.uri,cid:H.cid,dryRun:!1}}async publishEntity(A,Q){let w=this.projectionRegistry.get(Q.entityType);if(!w)throw Error(`No AT Protocol projection registered for ${Q.entityType}`);return this.publishProjectedEntity(A,Q,w)}async publishPost(A,Q){let w=this.projectionRegistry.get("post");if(!w)throw Error("No AT Protocol projection registered for post");return this.publishProjectedEntity(A,{entityType:"post",...Q},w)}async discoverBrainCards(A,Q){let w=[...new Set(Q.repos.map((Y)=>Y.trim()))].filter((Y)=>Y.length>0);if(w.length===0)throw Error("AT Protocol discovery requires at least one repo DID or handle");if(w.length>it1)throw Error(`AT Protocol discovery accepts at most ${it1} repos per batch`);let B=new Set,$=[];for(let Y of w)try{let D=await this.resolveRepoPdsEndpoint(Y),X=this.createPublicPdsClient(D.pdsEndpoint);if(!X.getRecord)throw Error("AT Protocol PDS client does not support record reads");let H=await X.getRecord({repo:D.repoDid,collection:Qzw,rkey:wzw});Lb(pt1,H.value);let W=$zw(H.uri)??D.repoDid,f=`${W}:${H.uri}:${H.cid}`;if(B.has(f)){$.push({repo:Y,status:"skipped",repoDid:W,uri:H.uri,cid:H.cid,error:"Duplicate brain card in discovery batch"});continue}B.add(f),await A.messaging.send({type:M40,payload:{repoDid:W,uri:H.uri,cid:H.cid,record:H.value},broadcast:!0}),$.push({repo:Y,status:"discovered",repoDid:W,uri:H.uri,cid:H.cid})}catch(D){$.push({repo:Y,status:"skipped",error:vA(D)})}return{discovered:$.filter((Y)=>Y.status==="discovered").length,skipped:$.filter((Y)=>Y.status==="skipped").length,results:$}}async validatePdsCredentials(){let A=this.resolveAppPassword();if(!this.config.identifier||!A)return!1;try{return await this.createPdsClient(A).createSession(),!0}catch(Q){return this.logger.warn("AT Protocol PDS authentication failed",{error:vA(Q)}),!1}}async getTools(){return[]}async publishProjectedEntity(A,Q,w){let B=await this.findPublishEntity(A,Q),$=Q.entityId??Q.slug;if(!$)throw Error(`${Q.entityType} publish requires entityId or slug`);if(!B)throw Error(`${Q.entityType} not found: ${$}`);if(B.visibility!=="public")throw Error(`Cannot publish non-public ${Q.entityType}: ${$}`);let Y=this.config.repoDid;if(Q.dryRun){let G=await w.buildRecord({entity:B,context:A,config:this.config,...Q.topics&&{topics:Q.topics},dryRun:!0});return Lb(w.lexicon,G),{record:G,dryRun:!0,...Y&&{repo:Y}}}let D=this.resolveAppPassword();if(!this.config.identifier||!D)throw Error("AT Protocol publishing requires identifier and app password configuration");let X=this.createPdsClient(D),H=await X.createSession(),W=Y??H.did,f=await w.buildRecord({entity:B,context:A,config:this.config,client:X,...Q.topics&&{topics:Q.topics}});if(Lb(w.lexicon,f),!X.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let Z=await X.putRecord({repo:W,collection:w.collection,rkey:Bzw(B.id),...w.validate!==void 0&&{validate:w.validate},record:f});return await w.onPublished?.({entity:B,context:A,record:f,uri:Z.uri,cid:Z.cid}),{record:f,repo:W,uri:Z.uri,cid:Z.cid,dryRun:!1}}async findPublishEntity(A,Q){if(Q.entityId)return A.entityService.getEntity({entityType:Q.entityType,id:Q.entityId});if(Q.slug)return(await A.entityService.listEntities({entityType:Q.entityType,options:{filter:{metadata:{slug:Q.slug}}}}))[0]??null;return null}createPublicPdsClient(A){if(this.deps.createPdsClient)return this.deps.createPdsClient({pdsEndpoint:A,identifier:this.config.identifier??"",appPassword:this.config.appPassword??""});return new To({pdsEndpoint:A,identifier:this.config.identifier??"",appPassword:this.config.appPassword??""})}async resolveRepoPdsEndpoint(A){let Q=A.startsWith("did:")?A:await this.resolveHandleToDid(A);if(!Q)throw Error(`Could not resolve AT Protocol repo: ${A}`);let w=await this.resolveDidToPdsEndpoint(Q);if(!w)throw Error(`Could not resolve AT Protocol PDS for repo: ${Q}`);return{repoDid:Q,pdsEndpoint:w}}async resolveHandleToDid(A){let Q=new URL("/xrpc/com.atproto.identity.resolveHandle",this.config.pdsEndpoint);Q.searchParams.set("handle",A);let w=await this.fetch(Q.toString());if(!w.ok)return;let B=await w.json();if(typeof B!=="object"||B===null||!("did"in B))return;return typeof B.did==="string"?B.did:void 0}async resolveDidToPdsEndpoint(A){let Q=A.startsWith("did:plc:")?await this.fetchJson(`https://plc.directory/${encodeURIComponent(A)}`):A.startsWith("did:web:")?await this.fetchJson(Yzw(A)):void 0;if(typeof Q!=="object"||Q===null)return;let w=Q.service;if(!Array.isArray(w))return;let B=w.find(($)=>{return typeof $==="object"&&$!==null&&($.id==="#atproto_pds"||$.type==="AtprotoPersonalDataServer")});return typeof B?.serviceEndpoint==="string"?B.serviceEndpoint:void 0}async fetchJson(A){let Q=await this.fetch(A);if(!Q.ok)return;return Q.json()}fetch(A){return(this.deps.fetch??fetch)(A)}createPdsClient(A){if(this.deps.createPdsClient)return this.deps.createPdsClient({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A});return new To({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A})}resolveAppPassword(){return this.config.appPassword}}function Bzw(A){let Q=A.replace(/[^A-Za-z0-9._~:-]/g,"_").slice(0,512);return Q.length>0?Q:"self"}function $zw(A){return/^at:\/\/([^/]+)/.exec(A)?.[1]}function Yzw(A){let Q=A.slice(8).split(":").map(decodeURIComponent),[w,...B]=Q;if(!w)throw Error(`Invalid did:web value: ${A}`);if(B.length===0)return`https://${w}/.well-known/did.json`;return`https://${w}/${B.join("/")}/did.json`}function oD0(A,Q){return new Tr0(A,Q)}c0();Z0();var sD0={name:"@brains/rover",version:"0.2.0-alpha.135",type:"module",private:!0,main:"./src/index.ts",files:["src","brain.eval.yaml","env.schema.template"],scripts:{"build:web-chat":"turbo run build --filter=@brains/web-chat","start:core":"bun run build:web-chat && cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"bun run build:web-chat && cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"bun run build:web-chat && cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",eval:"brain-eval","eval:core":"brain-eval --suite core","eval:core:coverage":"brain-eval --suite core --tool-coverage","eval:default":"brain-eval --suite default","eval:default:coverage":"brain-eval --suite default --tool-coverage","eval:full":"brain-eval --suite full","eval:full:coverage":"brain-eval --suite full --tool-coverage",lint:"eslint .","lint:fix":"eslint . --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/chat":"workspace:*","@brains/cms":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email-resend":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/playbook":"workspace:*","@brains/playbooks":"workspace:*","@brains/portfolio":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/rover-onboarding":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/theme-default":"workspace:*","@brains/topics":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var Xzw=K.object({}).strict();class dt1 extends IQ{constructor(A={}){super("rover-profile",sD0,A,Xzw)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",xN)}}function nt1(A={}){return new dt1(A)}c0();Z0();IB();_5();c0();var ub=QZ.extend(xN.shape);c0();Vq();Z0();var Hzw=new VU;class aD0{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,w){let B=w.entityService,[$,Y,D,X]=await Promise.all([Zx(B),B.listEntities({entityType:"post",options:{limit:20}}),B.listEntities({entityType:"deck",options:{limit:20}}),qr(B)]),H=Hzw.parseProfileBody($,ub),W=Y.sort(xT).slice(0,3).map(Jr),f=D.sort(xT).slice(0,3).map(Mr);if(!X.cta)throw Error("CTA not configured in site-info");let Z={profile:H,posts:W,decks:f,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:X.cta,sections:X.sections??{}};return Q.parse(Z)}}c0();Vq();var Wzw=new VU;class tD0{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,w){let B=await Zx(w.entityService),Y={profile:Wzw.parseProfileBody(B,ub)};return Q.parse(Y)}}import{jsxDEV as F8,Fragment as Kzw}from"preact/jsx-dev-runtime";var fzw="grid md:grid-cols-[14rem_1px_1fr] gap-y-2 gap-x-0 md:gap-16 items-start",Zzw="border-t md:border-t-0 md:border-l border-rule-strong md:self-stretch",Sr0=({number:A,title:Q,blurb:w,children:B})=>F8("section",{className:"py-20 border-b border-rule px-6 md:px-12",children:F8("div",{className:"max-w-6xl mx-auto",children:F8("div",{className:fzw,children:[F8(iu0,{title:Q,number:A,blurb:w},void 0,!1,void 0,this),F8("div",{className:Zzw,"aria-hidden":"true"},void 0,!1,void 0,this),F8("div",{className:"mt-6 md:mt-0",children: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),mr0=({profile:A,posts:Q,decks:w,postsListUrl:B,decksListUrl:$,cta:Y,sections:D})=>{let X=A.tagline||A.description,H=Q.map((F)=>({id:F.id,url:F.url,title:F.metadata.title,date:F.metadata.publishedAt||F.created,description:F.frontmatter.excerpt,series:F.frontmatter.seriesName&&F.frontmatter.seriesIndex?{name:F.frontmatter.seriesName,index:F.frontmatter.seriesIndex}:void 0})),W=w.map((F)=>({id:F.id,url:F.url,title:F.frontmatter.title||F.id,date:F.frontmatter.publishedAt??F.created,description:F.frontmatter.description})),f=A.name||"Home",Z=A.intro||A.description||X||"Professional site",G=Boolean(A.description)||A.expertise!==void 0&&A.expertise.length>0;return F8(Kzw,{children:[F8(jQ,{title:f,description:Z,ogType:"website"},void 0,!1,void 0,this),F8("div",{className:"homepage-list bg-theme",children:[F8("header",{className:"hero-bg-pattern relative w-full px-6 md:px-12 pt-28 pb-24 md:pt-28 md:pb-24 overflow-hidden border-b border-rule",children:F8("div",{className:"relative z-10 max-w-6xl mx-auto w-full",children:[A.name&&F8("div",{className:"flex items-center gap-[0.6rem] mb-6 font-mono text-[0.7rem] font-medium uppercase tracking-[0.22em] text-accent",children:[F8("span",{className:"w-[18px] h-px bg-accent","aria-hidden":"true"},void 0,!1,void 0,this),F8("span",{children:A.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&F8("h1",{className:"font-heading text-[clamp(2.75rem,6.5vw,5.5rem)] font-normal text-heading leading-[1.02] tracking-[-0.025em] max-w-[18ch] [font-variation-settings:'opsz'_144,'SOFT'_30]",children:S90(X,"italic font-normal text-accent [font-variation-settings:'opsz'_144,'SOFT'_80]")},void 0,!1,void 0,this),A.intro&&F8("p",{className:"font-heading font-light text-[clamp(1.1rem,1.8vw,1.4rem)] leading-[1.5] text-theme-muted max-w-[42ch] mt-8 [font-variation-settings:'opsz'_24]",children:S90(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F8(Sr0,{number:"01",title:"Essays",blurb:D.essays?.blurb,children:F8(T90,{items:H,viewAllUrl:B,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.length>0&&F8(Sr0,{number:"02",title:"Presentations",blurb:D.presentations?.blurb,children:F8(T90,{items:W,viewAllUrl:$,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),G&&F8(Sr0,{number:"03",title:"About",blurb:D.about?.blurb,children:F8("div",{className:"flex flex-col gap-8",children:[A.description&&F8("p",{className:"font-heading font-light text-[1.25rem] leading-[1.55] text-theme max-w-[55ch] [font-variation-settings:'opsz'_24,'SOFT'_50]",children:A.description},void 0,!1,void 0,this),A.expertise&&A.expertise.length>0&&F8(du0,{subjects:A.expertise},void 0,!1,void 0,this),F8("a",{href:"/about",className:"mt-6 inline-flex items-center gap-2 font-mono text-[0.7rem] font-medium uppercase tracking-[0.18em] text-accent pb-1 relative before:content-[''] before:absolute before:left-0 before:right-full before:bottom-0 before:h-px before:bg-accent before:transition-[right] before:duration-300 hover:before:right-0",children:["Learn more",F8("span",{"aria-hidden":"true",children:"\u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F8(xu0,{cta:Y,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 PB,Fragment as Uzw}from"preact/jsx-dev-runtime";var ur0=({profile:A})=>{let Q=`About ${A.name||"Me"}`,w=A.description||A.intro||"About page",B=A.expertise&&A.expertise.length>0||A.currentFocus||A.availability||A.email||A.website||A.socialLinks&&A.socialLinks.length>0;return PB(Uzw,{children:[PB(jQ,{title:Q,description:w,ogType:"profile"},void 0,!1,void 0,this),PB("div",{className:"about-page bg-theme",children:[PB("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:PB("div",{className:"relative z-10 max-w-4xl mx-auto",children:[PB("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&&PB("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),PB("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&PB("section",{className:"content-section-reveal mb-20 md:mb-28",children:PB($9,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),B&&PB("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),PB("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map(($,Y)=>PB("li",{className:Fn({variant:"accent",size:"lg"}),children:$},Y,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),PB("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&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),PB("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)&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),PB("div",{className:"space-y-4",children:[A.email&&PB("p",{className:"text-lg",children:PB("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&&PB("p",{className:"text-lg",children:PB("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&&PB("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map(($,Y)=>PB(B9,{href:$.url,external:!0,variant:"secondary",size:"md",children:$.label||$.platform},Y,!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 x4,Fragment as rt1}from"preact/jsx-dev-runtime";var cr0=()=>{return x4(rt1,{children:[x4(jQ,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),x4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:x4("div",{className:"text-center max-w-md",children:[x4("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),x4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),x4("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),x4(B9,{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)},lr0=()=>{return x4(rt1,{children:[x4(jQ,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),x4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:x4("div",{className:"text-center max-w-md",children:[x4("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),x4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),x4("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),x4(B9,{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)};Z0();var ot1=K.object({label:K.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:K.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')")}),st1=K.object({entityDisplay:K.object({post:ot1,deck:ot1}).describe("Display metadata for post and deck entity types (required for homepage)")});var at1={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.135",description:"Professional site composition package",type:"module",exports:{".":"./src/index.ts"},files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/blog":"workspace:*","@brains/decks":"workspace:*","@brains/identity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/site-info":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class pr0 extends IQ{dependencies=["blog","decks"];constructor(A){super("professional-site",at1,A,st1)}async onRegister(A){let Q=this.config.entityDisplay.post,w=this.config.entityDisplay.deck,B=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,$=`/${w.pluralName??w.label.toLowerCase()+"s"}`,Y=new aD0(B,$);A.entities.registerDataSource(Y);let D=new tD0;A.entities.registerDataSource(D);let X=K.object({profile:ub,posts:K.array(fF),decks:K.array(qP),postsListUrl:K.string(),decksListUrl:K.string(),cta:Kp0,sections:K.record(K.string(),Qe)}),H=K.object({profile:ub}),W=K.object({});A.templates.register({"homepage-list":R1({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:X,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:mr0}}),about:R1({name:"about",description:"About page with full profile information",schema:H,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:ur0}}),"subscribe-thanks":R1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:W,requiredPermission:"public",layout:{component:cr0}}),"subscribe-error":R1({name:"subscribe-error",description:"Newsletter subscription error page",schema:W,requiredPermission:"public",layout:{component:lr0}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function tt1(A){return new pr0(A??{})}var et1=[{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 eD0}from"preact/jsx-dev-runtime";function Ae1({sections:A,siteInfo:Q,slots:w,wordmark:B}){return eD0("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[eD0(Cu0,{title:Q.title,navigation:Q.navigation.primary,showThemeToggle:!0,...Q.logo!==void 0?{logo:Q.logo}:{},...B!==void 0?{wordmark:B}:{}},void 0,!1,void 0,this),eD0("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),eD0(hu0,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,title:Q.title,tagline:Q.description,children:w?.getSlot("footer-top").map(($)=>$.render())},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var zzw={layouts:{default:Ae1},routes:et1,plugin:tt1,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"}}}},mo=zzw;var Qe1=`/*
8611
+ `).map((Q)=>Q.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/)).filter((Q)=>Q!==null).map((Q)=>({name:Q[1]??"",description:Q[2]??"",tags:Q[3]?Q[3].split(",").map((w)=>w.trim()).filter(Boolean):[]}))}var dGw=new pw(lGw,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:pGw,parser:iGw},{key:"notes",label:"Notes",type:"string"}]});class Ct1 extends J2{constructor(){super({entityType:"agent",purpose:"An agent entity used for SWOT evaluation.",schema:uGw,frontmatterSchema:mGw})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=dGw.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 yt1 extends J2{constructor(){super({entityType:"skill",purpose:"A skill entity used for SWOT evaluation.",schema:cGw,frontmatterSchema:NX})}fromMarkdown(A){let Q=this.parseFrontMatter(A,NX);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var n76=new Ct1,r76=new yt1,o76=K.object({skills:K.array(NX),agents:K.array(K.object({id:K.string().optional(),name:K.string(),kind:K.enum(["professional","team","collective"]),organization:K.string().optional(),brainName:K.string(),url:K.string().url(),did:K.string().optional(),status:vr0,discoveredAt:K.string().datetime().optional(),about:K.string(),skills:K.array(vt1),notes:K.string().default("")}))});var nGw=K.object({}).strict();function iD0(A={}){return nGw.parse(A),[hr0()]}c0();Z0();Z0();var Cr0=K.object({enabled:K.boolean().default(!0),pdsEndpoint:K.string().url().default("https://bsky.social").describe("AT Protocol PDS service endpoint"),identifier:K.string().optional().describe("PDS login identifier, usually a handle or account DID"),repoDid:K.string().optional().describe("DID of the PDS repo that owns records"),appPassword:K.string().optional().describe("App password for prototype authentication; supply via ${ENV_VAR} interpolation, never a committed literal"),anchorDid:K.string().optional().describe("Optional human/operator DID referenced from records; defaults to did:web:<site-host>:anchor when omitted"),brainDid:K.string().optional().describe("Optional public brain DID referenced from records; defaults to did:web:<site-host> when omitted")});function rGw(A){return A.replace(/\/+$/,"")}var oGw=(A,Q)=>fetch(A,Q);async function go(A){let Q=await A.json();if(!A.ok){let w=typeof Q==="object"&&Q!==null&&"message"in Q&&typeof Q.message==="string"?Q.message:`AT Protocol request failed with ${A.status}`;throw Error(w)}return Q}class To{pdsEndpoint;identifier;appPassword;fetchFn;session;constructor(A){this.pdsEndpoint=rGw(A.pdsEndpoint),this.identifier=A.identifier,this.appPassword=A.appPassword,this.fetchFn=A.fetch??oGw}async createSession(){let A=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.server.createSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({identifier:this.identifier,password:this.appPassword})}),Q=await go(A);return this.session=Q,Q}async createRecord(A){let Q=await this.getSession(),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.createRecord`,{method:"POST",headers:{Authorization:`Bearer ${Q.accessJwt}`,"Content-Type":"application/json"},body:JSON.stringify({repo:A.repo,collection:A.collection,record:A.record,...A.rkey&&{rkey:A.rkey},...A.validate!==void 0&&{validate:A.validate}})});return go(w)}async putRecord(A){let Q=await this.getSession(),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.putRecord`,{method:"POST",headers:{Authorization:`Bearer ${Q.accessJwt}`,"Content-Type":"application/json"},body:JSON.stringify({repo:A.repo,collection:A.collection,record:A.record,rkey:A.rkey,...A.validate!==void 0&&{validate:A.validate},...A.swapRecord!==void 0&&{swapRecord:A.swapRecord}})});return go(w)}async getRecord(A){let Q=new URLSearchParams({repo:A.repo,collection:A.collection,rkey:A.rkey}),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.getRecord?${Q.toString()}`,{method:"GET"});return go(w)}async uploadBlob(A){let Q=await this.getSession(),w=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.uploadBlob`,{method:"POST",headers:{Authorization:`Bearer ${Q.accessJwt}`,"Content-Type":A.mimeType},body:new Blob([new Uint8Array(A.data)],{type:A.mimeType})});return go(w)}async getSession(){return this.session??=await this.createSession(),this.session}}function EP(A){return A?.startsWith("did:web:")??!1}function dD0(A){if(!EP(A))return;let Q=A.slice(8);if(!Q)return;let[w]=Q.split(":");if(!w)return;try{return decodeURIComponent(w)}catch{return w}}function gt1(A){if(!EP(A))return;let Q=A.slice(8);if(!Q)return;let[,...w]=Q.split(":");if(w.length===0)return"/.well-known/did.json";return`/${w.map(($)=>{try{return decodeURIComponent($)}catch{return $}}).join("/")}/did.json`}function Tt1(A){return A.replace(/\/+$/,"")}function So(A){return`did:web:${encodeURIComponent(A)}`}function nD0(A){return`${So(A)}:anchor`}function yr0(A){return{"@context":["https://www.w3.org/ns/did/v1"],id:A}}function St1(A,Q){let w=A.identifier?.startsWith("did:")?void 0:A.identifier?[`at://${A.identifier}`]:void 0;return{...yr0(Q),...w&&{alsoKnownAs:w},service:[{id:"#atproto_pds",type:"AtprotoPersonalDataServer",serviceEndpoint:Tt1(A.pdsEndpoint)}]}}function mt1(A){if(!EP(A.brainDid))return null;return St1(A,A.brainDid)}function Et1(A,Q){if(!A||!Q)return;let w=dD0(A),B=gt1(A);if(!w||!B)return;return{path:B,hostname:w,document:Q}}function rD0(A){let Q=[],w=Et1(A.brainDid,mt1(A));if(w)Q.push(w);if(EP(A.anchorDid)&&A.anchorDid!==A.brainDid){let B=Et1(A.anchorDid,yr0(A.anchorDid));if(B)Q.push(B)}return Q}function Er0(A,Q){let w=[];if(!A.brainDid){let B=So(Q);w.push({path:"/.well-known/did.json",hostname:Q,document:St1(A,B)})}if(!A.anchorDid){let B=nD0(Q);w.push({path:"/anchor/did.json",hostname:Q,document:yr0(B)})}return w}function sGw(A,Q){if(!A)return;try{return new URL(A,Q).toString()}catch{return}}function aGw(A){let Q=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,200);return Q.length>0?Q:"skill"}function ut1(A,Q){let w=A[Q];return typeof w==="string"&&w.length>0?w:void 0}function ct1(A,Q){let w=A[Q];if(!Array.isArray(w))return;let B=w.filter(($)=>typeof $==="string"&&$.length>0);return B.length>0?B:void 0}function tGw(A){let Q=A.metadata,w=ut1(Q,"name"),B=ut1(Q,"description");if(!w||!B)return;let $=ct1(Q,"tags"),Y=ct1(Q,"examples");return{id:aGw(w),name:w,description:B,...$&&{tags:$},...Y&&{examples:Y}}}async function eGw(A){if(!A.entityService.hasEntityType("skill"))return[];return(await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}})).map((w)=>tGw(w)).filter((w)=>w!==void 0).slice(0,100)}async function gr0(A,Q,w=new Date){let B=A.identity.get(),$=A.identity.getProfile(),Y=await A.identity.getAppInfo(),D=sGw(A.siteUrl??$.website,void 0);if(!D)throw Error("AT Protocol brain card publishing requires siteUrl");let X=new URL(D).hostname,H=Q.brainDid??So(X),W=Q.anchorDid??nD0(X);if(EP(H)){if(dD0(H)!==X)throw Error("AT Protocol brain card did:web host must match siteUrl host")}let f=await eGw(A);return{$type:"ai.rizom.brain.card",siteUrl:D,brain:{did:H,name:B.name,role:B.role,purpose:B.purpose,values:B.values},anchor:{did:W,name:$.name,kind:$.kind},skills:f,model:Y.model,version:Y.version,createdAt:w.toISOString(),updatedAt:w.toISOString()}}var lt1={name:"@brains/atproto",private:!0,version:"0.2.0-alpha.136",description:"AT Protocol integration for identity, publishing, discovery, and feeds",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/atproto-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var pt1=MB["ai.rizom.brain.card"],Qzw="ai.rizom.brain.card",wzw="self",it1=50;class Tr0 extends IQ{deps;projectionRegistry;constructor(A={},Q={}){super("atproto",lt1,A,Cr0);this.deps=Q,this.projectionRegistry=Q.projectionRegistry??U5.getInstance()}getWebRoutes(){if(!this.config.enabled)return[];let A=rD0(this.config),Q=[...!this.config.brainDid?["/.well-known/did.json"]:[],...!this.config.anchorDid?["/anchor/did.json"]:[]];return[...new Set([...A.map((B)=>B.path),...Q])].map((B)=>({path:B,method:"GET",public:!0,handler:($)=>{let Y=new URL($.url).hostname,D=[...rD0(this.config),...Er0(this.config,Y)].filter((H)=>H.path===B),X=D.find((H)=>H.hostname===Y)??D[0];if(!X)return new Response("Not found",{status:404});return new Response(JSON.stringify(X.document),{headers:{"Content-Type":"application/did+json"}})}}))}async publishBrainCard(A,Q={}){let w=await gr0(A,this.config);Lb(pt1,w);let B=this.config.repoDid;if(Q.dryRun)return{record:w,dryRun:!0,...B&&{repo:B}};let $=this.resolveAppPassword();if(!this.config.identifier||!$)throw Error("AT Protocol publishing requires identifier and app password configuration");let Y=this.createPdsClient($),D=await Y.createSession(),X=B??D.did;if(!Y.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let H=await Y.putRecord({repo:X,collection:"ai.rizom.brain.card",rkey:"self",validate:!1,record:w});return{record:w,repo:X,uri:H.uri,cid:H.cid,dryRun:!1}}async publishEntity(A,Q){let w=this.projectionRegistry.get(Q.entityType);if(!w)throw Error(`No AT Protocol projection registered for ${Q.entityType}`);return this.publishProjectedEntity(A,Q,w)}async publishPost(A,Q){let w=this.projectionRegistry.get("post");if(!w)throw Error("No AT Protocol projection registered for post");return this.publishProjectedEntity(A,{entityType:"post",...Q},w)}async discoverBrainCards(A,Q){let w=[...new Set(Q.repos.map((Y)=>Y.trim()))].filter((Y)=>Y.length>0);if(w.length===0)throw Error("AT Protocol discovery requires at least one repo DID or handle");if(w.length>it1)throw Error(`AT Protocol discovery accepts at most ${it1} repos per batch`);let B=new Set,$=[];for(let Y of w)try{let D=await this.resolveRepoPdsEndpoint(Y),X=this.createPublicPdsClient(D.pdsEndpoint);if(!X.getRecord)throw Error("AT Protocol PDS client does not support record reads");let H=await X.getRecord({repo:D.repoDid,collection:Qzw,rkey:wzw});Lb(pt1,H.value);let W=$zw(H.uri)??D.repoDid,f=`${W}:${H.uri}:${H.cid}`;if(B.has(f)){$.push({repo:Y,status:"skipped",repoDid:W,uri:H.uri,cid:H.cid,error:"Duplicate brain card in discovery batch"});continue}B.add(f),await A.messaging.send({type:M40,payload:{repoDid:W,uri:H.uri,cid:H.cid,record:H.value},broadcast:!0}),$.push({repo:Y,status:"discovered",repoDid:W,uri:H.uri,cid:H.cid})}catch(D){$.push({repo:Y,status:"skipped",error:vA(D)})}return{discovered:$.filter((Y)=>Y.status==="discovered").length,skipped:$.filter((Y)=>Y.status==="skipped").length,results:$}}async validatePdsCredentials(){let A=this.resolveAppPassword();if(!this.config.identifier||!A)return!1;try{return await this.createPdsClient(A).createSession(),!0}catch(Q){return this.logger.warn("AT Protocol PDS authentication failed",{error:vA(Q)}),!1}}async getTools(){return[]}async publishProjectedEntity(A,Q,w){let B=await this.findPublishEntity(A,Q),$=Q.entityId??Q.slug;if(!$)throw Error(`${Q.entityType} publish requires entityId or slug`);if(!B)throw Error(`${Q.entityType} not found: ${$}`);if(B.visibility!=="public")throw Error(`Cannot publish non-public ${Q.entityType}: ${$}`);let Y=this.config.repoDid;if(Q.dryRun){let G=await w.buildRecord({entity:B,context:A,config:this.config,...Q.topics&&{topics:Q.topics},dryRun:!0});return Lb(w.lexicon,G),{record:G,dryRun:!0,...Y&&{repo:Y}}}let D=this.resolveAppPassword();if(!this.config.identifier||!D)throw Error("AT Protocol publishing requires identifier and app password configuration");let X=this.createPdsClient(D),H=await X.createSession(),W=Y??H.did,f=await w.buildRecord({entity:B,context:A,config:this.config,client:X,...Q.topics&&{topics:Q.topics}});if(Lb(w.lexicon,f),!X.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let Z=await X.putRecord({repo:W,collection:w.collection,rkey:Bzw(B.id),...w.validate!==void 0&&{validate:w.validate},record:f});return await w.onPublished?.({entity:B,context:A,record:f,uri:Z.uri,cid:Z.cid}),{record:f,repo:W,uri:Z.uri,cid:Z.cid,dryRun:!1}}async findPublishEntity(A,Q){if(Q.entityId)return A.entityService.getEntity({entityType:Q.entityType,id:Q.entityId});if(Q.slug)return(await A.entityService.listEntities({entityType:Q.entityType,options:{filter:{metadata:{slug:Q.slug}}}}))[0]??null;return null}createPublicPdsClient(A){if(this.deps.createPdsClient)return this.deps.createPdsClient({pdsEndpoint:A,identifier:this.config.identifier??"",appPassword:this.config.appPassword??""});return new To({pdsEndpoint:A,identifier:this.config.identifier??"",appPassword:this.config.appPassword??""})}async resolveRepoPdsEndpoint(A){let Q=A.startsWith("did:")?A:await this.resolveHandleToDid(A);if(!Q)throw Error(`Could not resolve AT Protocol repo: ${A}`);let w=await this.resolveDidToPdsEndpoint(Q);if(!w)throw Error(`Could not resolve AT Protocol PDS for repo: ${Q}`);return{repoDid:Q,pdsEndpoint:w}}async resolveHandleToDid(A){let Q=new URL("/xrpc/com.atproto.identity.resolveHandle",this.config.pdsEndpoint);Q.searchParams.set("handle",A);let w=await this.fetch(Q.toString());if(!w.ok)return;let B=await w.json();if(typeof B!=="object"||B===null||!("did"in B))return;return typeof B.did==="string"?B.did:void 0}async resolveDidToPdsEndpoint(A){let Q=A.startsWith("did:plc:")?await this.fetchJson(`https://plc.directory/${encodeURIComponent(A)}`):A.startsWith("did:web:")?await this.fetchJson(Yzw(A)):void 0;if(typeof Q!=="object"||Q===null)return;let w=Q.service;if(!Array.isArray(w))return;let B=w.find(($)=>{return typeof $==="object"&&$!==null&&($.id==="#atproto_pds"||$.type==="AtprotoPersonalDataServer")});return typeof B?.serviceEndpoint==="string"?B.serviceEndpoint:void 0}async fetchJson(A){let Q=await this.fetch(A);if(!Q.ok)return;return Q.json()}fetch(A){return(this.deps.fetch??fetch)(A)}createPdsClient(A){if(this.deps.createPdsClient)return this.deps.createPdsClient({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A});return new To({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A})}resolveAppPassword(){return this.config.appPassword}}function Bzw(A){let Q=A.replace(/[^A-Za-z0-9._~:-]/g,"_").slice(0,512);return Q.length>0?Q:"self"}function $zw(A){return/^at:\/\/([^/]+)/.exec(A)?.[1]}function Yzw(A){let Q=A.slice(8).split(":").map(decodeURIComponent),[w,...B]=Q;if(!w)throw Error(`Invalid did:web value: ${A}`);if(B.length===0)return`https://${w}/.well-known/did.json`;return`https://${w}/${B.join("/")}/did.json`}function oD0(A,Q){return new Tr0(A,Q)}c0();Z0();var sD0={name:"@brains/rover",version:"0.2.0-alpha.136",type:"module",private:!0,main:"./src/index.ts",files:["src","brain.eval.yaml","env.schema.template"],scripts:{"build:web-chat":"turbo run build --filter=@brains/web-chat","start:core":"bun run build:web-chat && cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"bun run build:web-chat && cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"bun run build:web-chat && cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",eval:"brain-eval","eval:core":"brain-eval --suite core","eval:core:coverage":"brain-eval --suite core --tool-coverage","eval:default":"brain-eval --suite default","eval:default:coverage":"brain-eval --suite default --tool-coverage","eval:full":"brain-eval --suite full","eval:full:coverage":"brain-eval --suite full --tool-coverage",lint:"eslint .","lint:fix":"eslint . --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/chat":"workspace:*","@brains/cms":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email-resend":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/playbook":"workspace:*","@brains/playbooks":"workspace:*","@brains/portfolio":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/rover-onboarding":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/theme-default":"workspace:*","@brains/topics":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var Xzw=K.object({}).strict();class dt1 extends IQ{constructor(A={}){super("rover-profile",sD0,A,Xzw)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",xN)}}function nt1(A={}){return new dt1(A)}c0();Z0();IB();_5();c0();var ub=QZ.extend(xN.shape);c0();Vq();Z0();var Hzw=new VU;class aD0{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,w){let B=w.entityService,[$,Y,D,X]=await Promise.all([Zx(B),B.listEntities({entityType:"post",options:{limit:20}}),B.listEntities({entityType:"deck",options:{limit:20}}),qr(B)]),H=Hzw.parseProfileBody($,ub),W=Y.sort(xT).slice(0,3).map(Jr),f=D.sort(xT).slice(0,3).map(Mr);if(!X.cta)throw Error("CTA not configured in site-info");let Z={profile:H,posts:W,decks:f,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:X.cta,sections:X.sections??{}};return Q.parse(Z)}}c0();Vq();var Wzw=new VU;class tD0{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,w){let B=await Zx(w.entityService),Y={profile:Wzw.parseProfileBody(B,ub)};return Q.parse(Y)}}import{jsxDEV as F8,Fragment as Kzw}from"preact/jsx-dev-runtime";var fzw="grid md:grid-cols-[14rem_1px_1fr] gap-y-2 gap-x-0 md:gap-16 items-start",Zzw="border-t md:border-t-0 md:border-l border-rule-strong md:self-stretch",Sr0=({number:A,title:Q,blurb:w,children:B})=>F8("section",{className:"py-20 border-b border-rule px-6 md:px-12",children:F8("div",{className:"max-w-6xl mx-auto",children:F8("div",{className:fzw,children:[F8(iu0,{title:Q,number:A,blurb:w},void 0,!1,void 0,this),F8("div",{className:Zzw,"aria-hidden":"true"},void 0,!1,void 0,this),F8("div",{className:"mt-6 md:mt-0",children: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),mr0=({profile:A,posts:Q,decks:w,postsListUrl:B,decksListUrl:$,cta:Y,sections:D})=>{let X=A.tagline||A.description,H=Q.map((F)=>({id:F.id,url:F.url,title:F.metadata.title,date:F.metadata.publishedAt||F.created,description:F.frontmatter.excerpt,series:F.frontmatter.seriesName&&F.frontmatter.seriesIndex?{name:F.frontmatter.seriesName,index:F.frontmatter.seriesIndex}:void 0})),W=w.map((F)=>({id:F.id,url:F.url,title:F.frontmatter.title||F.id,date:F.frontmatter.publishedAt??F.created,description:F.frontmatter.description})),f=A.name||"Home",Z=A.intro||A.description||X||"Professional site",G=Boolean(A.description)||A.expertise!==void 0&&A.expertise.length>0;return F8(Kzw,{children:[F8(jQ,{title:f,description:Z,ogType:"website"},void 0,!1,void 0,this),F8("div",{className:"homepage-list bg-theme",children:[F8("header",{className:"hero-bg-pattern relative w-full px-6 md:px-12 pt-28 pb-24 md:pt-28 md:pb-24 overflow-hidden border-b border-rule",children:F8("div",{className:"relative z-10 max-w-6xl mx-auto w-full",children:[A.name&&F8("div",{className:"flex items-center gap-[0.6rem] mb-6 font-mono text-[0.7rem] font-medium uppercase tracking-[0.22em] text-accent",children:[F8("span",{className:"w-[18px] h-px bg-accent","aria-hidden":"true"},void 0,!1,void 0,this),F8("span",{children:A.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),X&&F8("h1",{className:"font-heading text-[clamp(2.75rem,6.5vw,5.5rem)] font-normal text-heading leading-[1.02] tracking-[-0.025em] max-w-[18ch] [font-variation-settings:'opsz'_144,'SOFT'_30]",children:S90(X,"italic font-normal text-accent [font-variation-settings:'opsz'_144,'SOFT'_80]")},void 0,!1,void 0,this),A.intro&&F8("p",{className:"font-heading font-light text-[clamp(1.1rem,1.8vw,1.4rem)] leading-[1.5] text-theme-muted max-w-[42ch] mt-8 [font-variation-settings:'opsz'_24]",children:S90(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F8(Sr0,{number:"01",title:"Essays",blurb:D.essays?.blurb,children:F8(T90,{items:H,viewAllUrl:B,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.length>0&&F8(Sr0,{number:"02",title:"Presentations",blurb:D.presentations?.blurb,children:F8(T90,{items:W,viewAllUrl:$,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),G&&F8(Sr0,{number:"03",title:"About",blurb:D.about?.blurb,children:F8("div",{className:"flex flex-col gap-8",children:[A.description&&F8("p",{className:"font-heading font-light text-[1.25rem] leading-[1.55] text-theme max-w-[55ch] [font-variation-settings:'opsz'_24,'SOFT'_50]",children:A.description},void 0,!1,void 0,this),A.expertise&&A.expertise.length>0&&F8(du0,{subjects:A.expertise},void 0,!1,void 0,this),F8("a",{href:"/about",className:"mt-6 inline-flex items-center gap-2 font-mono text-[0.7rem] font-medium uppercase tracking-[0.18em] text-accent pb-1 relative before:content-[''] before:absolute before:left-0 before:right-full before:bottom-0 before:h-px before:bg-accent before:transition-[right] before:duration-300 hover:before:right-0",children:["Learn more",F8("span",{"aria-hidden":"true",children:"\u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F8(xu0,{cta:Y,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 PB,Fragment as Uzw}from"preact/jsx-dev-runtime";var ur0=({profile:A})=>{let Q=`About ${A.name||"Me"}`,w=A.description||A.intro||"About page",B=A.expertise&&A.expertise.length>0||A.currentFocus||A.availability||A.email||A.website||A.socialLinks&&A.socialLinks.length>0;return PB(Uzw,{children:[PB(jQ,{title:Q,description:w,ogType:"profile"},void 0,!1,void 0,this),PB("div",{className:"about-page bg-theme",children:[PB("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:PB("div",{className:"relative z-10 max-w-4xl mx-auto",children:[PB("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&&PB("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),PB("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&PB("section",{className:"content-section-reveal mb-20 md:mb-28",children:PB($9,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),B&&PB("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),PB("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map(($,Y)=>PB("li",{className:Fn({variant:"accent",size:"lg"}),children:$},Y,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),PB("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&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),PB("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)&&PB("section",{children:[PB("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),PB("div",{className:"space-y-4",children:[A.email&&PB("p",{className:"text-lg",children:PB("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&&PB("p",{className:"text-lg",children:PB("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&&PB("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map(($,Y)=>PB(B9,{href:$.url,external:!0,variant:"secondary",size:"md",children:$.label||$.platform},Y,!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 x4,Fragment as rt1}from"preact/jsx-dev-runtime";var cr0=()=>{return x4(rt1,{children:[x4(jQ,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),x4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:x4("div",{className:"text-center max-w-md",children:[x4("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),x4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),x4("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),x4(B9,{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)},lr0=()=>{return x4(rt1,{children:[x4(jQ,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),x4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:x4("div",{className:"text-center max-w-md",children:[x4("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),x4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),x4("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),x4(B9,{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)};Z0();var ot1=K.object({label:K.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:K.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')")}),st1=K.object({entityDisplay:K.object({post:ot1,deck:ot1}).describe("Display metadata for post and deck entity types (required for homepage)")});var at1={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.136",description:"Professional site composition package",type:"module",exports:{".":"./src/index.ts"},files:["src"],scripts:{typecheck:"tsc --noEmit",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/blog":"workspace:*","@brains/decks":"workspace:*","@brains/identity-service":"workspace:*","@brains/plugins":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-engine":"workspace:*","@brains/site-info":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class pr0 extends IQ{dependencies=["blog","decks"];constructor(A){super("professional-site",at1,A,st1)}async onRegister(A){let Q=this.config.entityDisplay.post,w=this.config.entityDisplay.deck,B=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,$=`/${w.pluralName??w.label.toLowerCase()+"s"}`,Y=new aD0(B,$);A.entities.registerDataSource(Y);let D=new tD0;A.entities.registerDataSource(D);let X=K.object({profile:ub,posts:K.array(fF),decks:K.array(qP),postsListUrl:K.string(),decksListUrl:K.string(),cta:Kp0,sections:K.record(K.string(),Qe)}),H=K.object({profile:ub}),W=K.object({});A.templates.register({"homepage-list":R1({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:X,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:mr0}}),about:R1({name:"about",description:"About page with full profile information",schema:H,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:ur0}}),"subscribe-thanks":R1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:W,requiredPermission:"public",layout:{component:cr0}}),"subscribe-error":R1({name:"subscribe-error",description:"Newsletter subscription error page",schema:W,requiredPermission:"public",layout:{component:lr0}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function tt1(A){return new pr0(A??{})}var et1=[{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 eD0}from"preact/jsx-dev-runtime";function Ae1({sections:A,siteInfo:Q,slots:w,wordmark:B}){return eD0("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[eD0(Cu0,{title:Q.title,navigation:Q.navigation.primary,showThemeToggle:!0,...Q.logo!==void 0?{logo:Q.logo}:{},...B!==void 0?{wordmark:B}:{}},void 0,!1,void 0,this),eD0("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),eD0(hu0,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,title:Q.title,tagline:Q.description,children:w?.getSlot("footer-top").map(($)=>$.render())},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var zzw={layouts:{default:Ae1},routes:et1,plugin:tt1,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"}}}},mo=zzw;var Qe1=`/*
8612
8612
  * Default theme \u2014 simplified editorial base inspired by the Rizom family.
8613
8613
  *
8614
8614
  * This theme is intentionally less branded than @brains/theme-rizom. It
@@ -8996,8 +8996,8 @@ ${JSON.stringify(w,null,2)}`}function uD0(A){return A.map((Q)=>Q.detail===null?{
8996
8996
 
8997
8997
  .btn-primary:disabled { opacity: 0.5; }
8998
8998
  }
8999
- `;var gE=Qe1;import{join as Fzw}from"path";var we1=["prompt","rover-profile","image","document","note","link","wishlist","topics","directory-sync","atproto","agents","assessment","auth-service","notifications","playbook","playbooks","rover-onboarding","email-resend","cms","dashboard-root","mcp","webserver","web-chat","discord","a2a"],Be1=[...we1.filter((A)=>A!=="dashboard-root"),"dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],Vzw=[...Be1,"portfolio","topics","content-pipeline","social-media","newsletter","stock-photo"],Jzw=["Rover is a personal professional knowledge and publishing brain for an independent professional. Prioritize personal knowledge management, professional website content, essays, projects, decks, newsletters, and social distribution workflows.","When a user asks for a publishing/content overview, use the available publishing entity types directly instead of treating the request as generic team memory.","Draft blog posts are only post entities with status draft. If the user asks whether draft blog posts exist, call only system_list for entityType post with status draft; do not also list social-post, newsletter, deck, or other draft entity types."],$e1=LJ({name:"rover",version:sD0.version,model:"gpt-5.4-mini",site:mo,theme:gE,presets:{core:we1,default:Be1,full:Vzw},evalDisable:["discord","chat","webserver","web-chat","mcp","atproto","analytics","dashboard","dashboard-root","email-resend"],agentInstructions:Jzw,capabilities:[["prompt",vP,void 0],["rover-profile",nt1,{}],["image",Gc,void 0],["cms",xP,(A)=>({...A.CMS_CONTENT_REPO_PAT?{passkeyLogin:{contentRepoToken:A.CMS_CONTENT_REPO_PAT}}:{}})],["auth-service",Yp,void 0],["notifications",sw0,void 0],["playbook",es1,{}],["playbooks",ln0,{}],["rover-onboarding",ba1,{}],["email-resend",l$0,void 0],["dashboard",Sb,void 0],["dashboard-root",Sb,{routePath:"/"}],["blog",vp0,{}],["series",Sp0,void 0],["decks",_r,void 0],["document",pi0,void 0],["note",LP,{}],["link",jP,{}],["portfolio",Vd0,{}],["topics",lY0,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",Yn0,{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",Wo,{autoGenerateOnBlogPublish:!0}],["newsletter",ys1,{doubleOptIn:!0}],["obsidian-vault",kn0,{autoSync:!0}],["wishlist",VD0,{}],["stock-photo",tn0,{}],["agents",yD0,void 0],["assessment",iD0,void 0],["atproto",oD0,(A)=>({...A.ATPROTO_APP_PASSWORD?{appPassword:A.ATPROTO_APP_PASSWORD}:{}})],["directory-sync",M_,()=>({seedContent:!0,seedContentPath:Fzw(import.meta.dir,"..","seed-content-core"),initialSync:!0})],["analytics",YD0,{}],["rizom-ecosystem",CP,void 0],["site-info",fP,void 0],["site-builder",WP,{cms:{}}]],interfaces:[["mcp",BI,()=>({})],["discord",uI,()=>({})],["chat",F50,()=>({})],["webserver",iI,()=>({})],["web-chat",SC,()=>({})],["a2a",mC,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"public"},{pattern:"discord:*",level:"public"},{pattern:"web-chat:*",level:"anchor"}],entityActions:{"*":{create:"anchor",update:"anchor",delete:"anchor",extract:"anchor"}}},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});MJ();c0();Z0();var Ye1={name:"@brains/atproto-registry",private:!0,version:"0.2.0-alpha.135",description:"Canonical Rizom AT Protocol lexicon registry",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/atproto-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var Xe1=K.object({enabled:K.boolean().default(!0)}),ir0="/atproto/lexicons";function De1(A){return new Response(`${JSON.stringify(A,null,2)}
9000
- `,{headers:{"Content-Type":"application/json"}})}class dr0 extends IQ{constructor(A={}){super("atproto-registry",Ye1,A,Xe1)}getWebRoutes(){if(!this.config.enabled)return[];return[{path:`${ir0}/index.json`,method:"GET",public:!0,handler:()=>De1(this.getIndex())},...ZP().map((A)=>({path:`${ir0}/${A.id}.json`,method:"GET",public:!0,handler:()=>De1(A)}))]}getIndex(){return{lexicons:Fp0().map((A)=>({...A,path:`${ir0}/${A.id}.json`}))}}getLexicon(A){return qp0(A)}async getTools(){return[this.createListLexiconsTool(),this.createValidateLexiconTool(),this.createCheckContractsTool()]}createListLexiconsTool(){return{name:`${this.id}_list_lexicons`,description:"List canonical Rizom AT Protocol lexicons.",inputSchema:{},handler:async()=>({success:!0,data:this.getIndex()})}}createValidateLexiconTool(){return{name:`${this.id}_validate_lexicon`,description:"Validate a record payload against a canonical Rizom AT Protocol lexicon.",inputSchema:{nsid:K.string().describe("Canonical lexicon NSID"),record:K.record(K.unknown()).describe("Record payload to validate")},handler:async(A)=>{let Q=K.object({nsid:K.string(),record:K.record(K.unknown())}).safeParse(A);if(!Q.success)return{success:!1,error:`Invalid input: ${Q.error.message}`};let w=this.getLexicon(Q.data.nsid);if(!w)return{success:!1,error:`Unknown AT Protocol lexicon: ${Q.data.nsid}`};try{return Lb(w,Q.data.record),{success:!0,data:{valid:!0}}}catch(B){return{success:!0,data:{valid:!1,error:B instanceof Error?B.message:"Invalid record"}}}}}}createCheckContractsTool(){return{name:`${this.id}_check_contracts`,description:"Check that canonical Rizom AT Protocol lexicon contracts are available.",inputSchema:{},handler:async()=>({success:!0,data:{lexiconCount:ZP().length,nsids:ZP().map((A)=>A.id),metadata:Fp0()}})}}}function nr0(A={}){return new dr0(A)}c0();Z0();Z0();c0();var AX0=K.object({routeId:K.string(),sectionId:K.string()}),uo=o1.extend({entityType:K.literal("site-content"),template:K.string().optional(),content:K.string(),metadata:AX0});c0();class He1 extends J2{constructor(){super({entityType:"site-content",purpose:"A content section bound to a route on the published site.",schema:uo,frontmatterSchema:AX0})}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 rr0=new He1;Z0();var QX0=K.object({routeId:K.string().optional().describe("Optional: specific route filter"),sectionId:K.string().optional().describe("Optional: specific section filter"),dryRun:K.boolean().optional().default(!1).describe("Optional: preview changes without executing"),force:K.boolean().optional().default(!1).describe("Force regeneration even if content exists")}),tD6=K.object({jobs:K.array(K.object({jobId:K.string(),routeId:K.string(),sectionId:K.string()})),totalSections:K.number(),queuedSections:K.number(),skippedSections:K.number().optional(),batchId:K.string().optional()});class or0{context;constructor(A){this.context=A}createJobOptions(A,Q){if(!A)return;return{source:A.operationType??Q,rootJobId:A.rootJobId??`${Q}-${Date.now()}`,metadata:{operationType:A.operationType??"content_operations",progressToken:A.progressToken,pluginId:A.pluginId??"site-content"}}}async fetchRoutes(){let A=await this.context.messaging.send({type:"site-builder:routes:list",payload:{}});if("noop"in A)throw Error("No handler for site-builder:routes:list \u2014 is site-builder plugin loaded?");if(!A.success||!A.data)throw Error("Failed to fetch routes from site-builder");return A.data}async generate(A,Q,w){let B=this.context.logger.child("SiteContentOperations"),$=await this.fetchRoutes(),Y=$;if(A.routeId){if(Y=$.filter((f)=>f.id===A.routeId),Y.length===0)throw Error(`Route not found: ${A.routeId}`)}let D=[];for(let f of Y)for(let Z of f.sections){if(A.sectionId&&Z.id!==A.sectionId)continue;if(Z.content){B.debug("Section has static content, skipping",{routeId:f.id,sectionId:Z.id});continue}if(Z.template){let G=this.context.templates.getCapabilities(Z.template);if(!G){B.warn("Template not found, skipping section",{routeId:f.id,sectionId:Z.id,templateName:Z.template});continue}if(!G.canGenerate){B.debug("Template doesn't support generation, skipping",{routeId:f.id,sectionId:Z.id,templateName:Z.template,capabilities:G});continue}}else{B.debug("Section has no template, skipping",{routeId:f.id,sectionId:Z.id});continue}if(!A.force&&!A.dryRun){let G=`${f.id}:${Z.id}`;if(await this.context.entityService.getEntity({entityType:"site-content",id:G})){B.debug("Content already exists, skipping",{routeId:f.id,sectionId:Z.id});continue}}D.push({route:f,section:Z})}let X=D.length;if(A.dryRun)return{jobs:[],totalSections:X,queuedSections:X,batchId:`dry-run-${Date.now()}`};let H=[],W=[];for(let{route:f,section:Z}of D){let G=`${f.id}:${Z.id}`,F=Z.template,V={routeId:f.id,sectionId:Z.id,entityId:G,entityType:"site-content",templateName:F,context:{prompt:typeof Z.content==="string"?Z.content:void 0,data:{routeId:f.id,sectionId:Z.id,routeTitle:f.title??Q?.title??"",routeDescription:f.description??Q?.description??"",sectionContent:Z.content},conversationId:"system"},siteConfig:Q};W.push({type:"shell:content-generation",data:V})}if(W.length>0){let f=this.createJobOptions(w,"site:content-generation"),Z=await this.context.jobs.enqueueBatch(W,f);for(let G=0;G<D.length;G++){let F=D[G];if(F)H.push({jobId:`${Z}-${G}`,routeId:F.route.id,sectionId:F.section.id})}return{jobs:H,totalSections:X,queuedSections:H.length,batchId:Z}}return{jobs:[],totalSections:X,queuedSections:0,batchId:`empty-${Date.now()}`}}}class sr0{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new or0(A)}async generateContent(A,Q){let w=QX0.parse(A);return this.operations.generate(w,this.siteConfig,Q)}}l$();Z0();function co(A,Q){return Q?A.optional():A}function tr0(A){switch(A.type){case"string":return co(K.string(),A.optional);case"number":return co(K.number(),A.optional);case"enum":{let Q=[...A.options];return co(K.enum(Q),A.optional)}case"object":{let Q={};for(let[w,B]of Object.entries(A.fields))Q[w]=tr0(B);return co(K.object(Q),A.optional)}case"array":{let Q=K.array(bzw(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return co(Q,A.optional)}}}function bzw(A){let{items:Q}=A;switch(Q.type){case"string":return K.string();case"number":return K.number();case"enum":{let w=[...Q.options];return K.enum(w)}case"object":{let w={};for(let[B,$]of Object.entries(Q.fields))w[B]=tr0($);return K.object(w)}}}function ar0(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(([w,B])=>ar0(w,B))};case"array":{let w={key:A,label:Q.label,type:"array"};switch(Q.items.type){case"string":case"enum":return w.itemType="string",w;case"number":return w.itemType="number",w;case"object":return w.itemType="object",w.itemMappings=Object.entries(Q.items.fields).map(([B,$])=>ar0(B,$)),w}}}}function Lzw(A,Q){let w={};for(let[Y,D]of Object.entries(Q.fields))w[Y]=tr0(D);let B=K.object(w),$=new pw(B,{title:Q.title,mappings:Object.entries(Q.fields).map(([Y,D])=>ar0(Y,D))});return{name:A,description:Q.description,schema:B,formatter:$,requiredPermission:Q.requiredPermission??"public",layout:{component:Q.layout,...Q.fullscreen!==void 0?{fullscreen:Q.fullscreen}:{}},...Q.runtimeScripts?{runtimeScripts:Q.runtimeScripts}:{}}}function er0(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,w])=>[Q,Lzw(Q,w)]))}Z0();var We1=K.object({namespace:K.string(),sections:K.record(K.any())}),fe1=K.object({definitions:K.union([We1,K.array(We1)]).optional()});c0();function Ze1(A,Q){return[Sw(Q,"generate","Generate content for all routes, a specific route, or a specific section",QX0,async(w,B)=>{let $=A();if(!$)return{success:!1,error:"Site content service not initialized"};if(w.sectionId&&!w.routeId)return{success:!1,error:"sectionId requires routeId to be specified"};let Y={rootJobId:`generate-${Date.now()}`,progressToken:B.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:B.interfaceType,channelId:B.channelId},D=await $.generateContent(w,Y);return{success:!0,message:`Generated ${D.queuedSections} of ${D.totalSections} sections. ${D.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:D.batchId,jobsQueued:D.queuedSections,totalSections:D.totalSections,jobs:D.jobs}}})]}var Ke1={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.135",description:"Site content entity and generation orchestration",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Ao0 extends IQ{siteContentService;constructor(A={}){super("site-content",Ke1,A,fe1)}async onRegister(A){A.entities.register("site-content",uo,rr0);for(let Q of XU(this.config.definitions))A.templates.register(er0(Q),Q.namespace);this.siteContentService=new sr0(A)}async getTools(){return Ze1(()=>this.siteContentService,this.id)}}function lo(A={}){return new Ao0(A)}c0();Z0();IB();Z0();c0();var Ue1=K.enum(["available","early access","coming soon","planned"]),Ge1=K.object({title:K.string(),description:K.string()}),hH=K.object({name:K.string(),availability:Ue1,order:K.number(),ogImageId:K.string().optional()}),wX0=K.object({tagline:K.string(),promise:K.string(),role:K.string(),purpose:K.string(),audience:K.string(),values:K.array(K.string()).min(1),features:K.array(Ge1).min(1).max(6),story:K.string()}),jzw=hH.pick({name:!0,availability:!0,order:!0}).extend({slug:K.string()}),TE=o1.extend({entityType:K.literal("product"),metadata:jzw}),BX0=TE.extend({frontmatter:hH,body:wX0,labels:K.record(K.string(),K.string()),ogImageUrl:K.string().optional()}),$X0=BX0.extend({url:K.string().optional(),typeLabel:K.string().optional(),listUrl:K.string().optional(),listLabel:K.string().optional(),ogImageUrl:K.string().optional()});c0();Z0();l$();class SE extends pw{constructor(){super(wX0,{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 Qo0 extends J2{constructor(){super({entityType:"product",purpose:"A product entry in the portfolio.",schema:TE,frontmatterSchema:hH,bodyFormatter:new SE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,hH);return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,hH),w=w1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:w,availability:Q.availability,order:Q.order}}}}var YX0=new Qo0;Z0();c0();var ze1=K.object({title:K.string(),description:K.string()}),qe1=K.object({title:K.string(),description:K.string()}),Mzw=K.object({title:K.string(),description:K.string()}),Fe1=K.object({heading:K.string(),buttonText:K.string(),link:K.string()}),NF=K.object({headline:K.string(),tagline:K.string()}),_zw=K.object({title:K.string(),description:K.string()}),DX0=K.object({vision:K.string(),pillars:K.array(ze1).min(1).max(6),approach:K.array(_zw).min(1).max(6),productsIntro:K.string(),technologies:K.array(Mzw).min(1).max(6),benefits:K.array(qe1).min(1).max(6),cta:Fe1}),Ve1=NF.pick({headline:!0}).extend({slug:K.string()}),mE=o1.extend({entityType:K.literal("products-overview"),metadata:Ve1}),po=mE.extend({frontmatter:NF,body:DX0,labels:K.record(K.string(),K.string())});c0();Z0();l$();class uE extends pw{constructor(){super(DX0,{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 wo0 extends J2{constructor(){super({entityType:"products-overview",purpose:"A high-level overview of the product portfolio.",schema:mE,frontmatterSchema:NF,bodyFormatter:new uE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,NF);return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,NF),w=w1(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:w}}}}var Bo0=new wo0;c0();Z0();var Pzw=K.object({entityType:K.string(),query:K.object({id:K.string().optional()}).optional()});function Je1(A,Q){let w=v2(A.content,hH),B=Q.parse(w.content),$=Q.getLabels();return BX0.parse({...A,frontmatter:w.metadata,body:B,labels:$})}function Ie1(A,Q){let w=v2(A.content,NF),B=Q.parse(w.content),$=Q.getLabels();return po.parse({...A,frontmatter:w.metadata,body:B,labels:$})}class XX0{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new uE;productFormatter=new SE;constructor(A){this.logger=A;this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,w){let B=Pzw.parse(A),$=w.entityService;if(B.entityType==="products-overview"){let W=(await $.listEntities({entityType:"products-overview",options:{limit:1}}))[0];if(!W)throw Error("Products overview entity not found");let f=Ie1(W,this.overviewFormatter);return Q.parse(f)}if(B.query?.id){let W=(await $.listEntities({entityType:"product",options:{filter:{metadata:{slug:B.query.id}},limit:1}}))[0];if(!W)throw Error(`Product not found: ${B.query.id}`);return Q.parse({product:Je1(W,this.productFormatter)})}let[Y,D]=await Promise.all([$.listEntities({entityType:"products-overview",options:{limit:1}}),$.listEntities({entityType:"product",options:{sortFields:[{field:"order",direction:"asc"}]}})]),X=Y[0];if(!X)throw Error("Products overview entity not found");return Q.parse({overview:Ie1(X,this.overviewFormatter),products:D.map((H)=>Je1(H,this.productFormatter))})}}import{jsxDEV as B1,Fragment as xzw}from"preact/jsx-dev-runtime";var be1=({overview:A,products:Q})=>{let{frontmatter:w,body:B,labels:$}=A;return B1(xzw,{children:[B1(jQ,{title:w.headline,description:w.tagline},void 0,!1,void 0,this),B1("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[B1("style",{children:`
8999
+ `;var gE=Qe1;import{join as Fzw}from"path";var we1=["prompt","rover-profile","image","document","note","link","wishlist","topics","directory-sync","atproto","agents","assessment","auth-service","notifications","playbook","playbooks","rover-onboarding","email-resend","cms","dashboard-root","mcp","webserver","web-chat","discord","a2a"],Be1=[...we1.filter((A)=>A!=="dashboard-root"),"dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],Vzw=[...Be1,"portfolio","topics","content-pipeline","social-media","newsletter","stock-photo"],Jzw=["Rover is a personal professional knowledge and publishing brain for an independent professional. Prioritize personal knowledge management, professional website content, essays, projects, decks, newsletters, and social distribution workflows.","When a user asks for a publishing/content overview, use the available publishing entity types directly instead of treating the request as generic team memory.",'Draft blog posts are only post entities with status draft. If the user asks whether draft blog posts exist, call only system_list for entityType post with status draft; do not also list social-post, newsletter, deck, or other draft entity types. After telling the user there are no draft blog posts, treat follow-ups like "make one draft" or "make one a draft" as requests to change an existing published post back to draft: ask which existing published post they want changed; do not offer to create a brand-new post and do not call system_generate to create a fresh draft from that ambiguous follow-up.'],$e1=LJ({name:"rover",version:sD0.version,model:"gpt-5.4-mini",site:mo,theme:gE,presets:{core:we1,default:Be1,full:Vzw},evalDisable:["discord","chat","webserver","web-chat","mcp","atproto","analytics","dashboard","dashboard-root","email-resend"],agentInstructions:Jzw,capabilities:[["prompt",vP,void 0],["rover-profile",nt1,{}],["image",Gc,void 0],["cms",xP,(A)=>({...A.CMS_CONTENT_REPO_PAT?{passkeyLogin:{contentRepoToken:A.CMS_CONTENT_REPO_PAT}}:{}})],["auth-service",Yp,void 0],["notifications",sw0,void 0],["playbook",es1,{}],["playbooks",ln0,{}],["rover-onboarding",ba1,{}],["email-resend",l$0,void 0],["dashboard",Sb,void 0],["dashboard-root",Sb,{routePath:"/"}],["blog",vp0,{}],["series",Sp0,void 0],["decks",_r,void 0],["document",pi0,void 0],["note",LP,{}],["link",jP,{}],["portfolio",Vd0,{}],["topics",lY0,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",Yn0,{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",Wo,{autoGenerateOnBlogPublish:!0}],["newsletter",ys1,{doubleOptIn:!0}],["obsidian-vault",kn0,{autoSync:!0}],["wishlist",VD0,{}],["stock-photo",tn0,{}],["agents",yD0,void 0],["assessment",iD0,void 0],["atproto",oD0,(A)=>({...A.ATPROTO_APP_PASSWORD?{appPassword:A.ATPROTO_APP_PASSWORD}:{}})],["directory-sync",M_,()=>({seedContent:!0,seedContentPath:Fzw(import.meta.dir,"..","seed-content-core"),initialSync:!0})],["analytics",YD0,{}],["rizom-ecosystem",CP,void 0],["site-info",fP,void 0],["site-builder",WP,{cms:{}}]],interfaces:[["mcp",BI,()=>({})],["discord",uI,()=>({})],["chat",F50,()=>({})],["webserver",iI,()=>({})],["web-chat",SC,()=>({})],["a2a",mC,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"public"},{pattern:"discord:*",level:"public"},{pattern:"web-chat:*",level:"anchor"}],entityActions:{"*":{create:"anchor",update:"anchor",delete:"anchor",extract:"anchor"}}},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});MJ();c0();Z0();var Ye1={name:"@brains/atproto-registry",private:!0,version:"0.2.0-alpha.136",description:"Canonical Rizom AT Protocol lexicon registry",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/atproto-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var Xe1=K.object({enabled:K.boolean().default(!0)}),ir0="/atproto/lexicons";function De1(A){return new Response(`${JSON.stringify(A,null,2)}
9000
+ `,{headers:{"Content-Type":"application/json"}})}class dr0 extends IQ{constructor(A={}){super("atproto-registry",Ye1,A,Xe1)}getWebRoutes(){if(!this.config.enabled)return[];return[{path:`${ir0}/index.json`,method:"GET",public:!0,handler:()=>De1(this.getIndex())},...ZP().map((A)=>({path:`${ir0}/${A.id}.json`,method:"GET",public:!0,handler:()=>De1(A)}))]}getIndex(){return{lexicons:Fp0().map((A)=>({...A,path:`${ir0}/${A.id}.json`}))}}getLexicon(A){return qp0(A)}async getTools(){return[this.createListLexiconsTool(),this.createValidateLexiconTool(),this.createCheckContractsTool()]}createListLexiconsTool(){return{name:`${this.id}_list_lexicons`,description:"List canonical Rizom AT Protocol lexicons.",inputSchema:{},handler:async()=>({success:!0,data:this.getIndex()})}}createValidateLexiconTool(){return{name:`${this.id}_validate_lexicon`,description:"Validate a record payload against a canonical Rizom AT Protocol lexicon.",inputSchema:{nsid:K.string().describe("Canonical lexicon NSID"),record:K.record(K.unknown()).describe("Record payload to validate")},handler:async(A)=>{let Q=K.object({nsid:K.string(),record:K.record(K.unknown())}).safeParse(A);if(!Q.success)return{success:!1,error:`Invalid input: ${Q.error.message}`};let w=this.getLexicon(Q.data.nsid);if(!w)return{success:!1,error:`Unknown AT Protocol lexicon: ${Q.data.nsid}`};try{return Lb(w,Q.data.record),{success:!0,data:{valid:!0}}}catch(B){return{success:!0,data:{valid:!1,error:B instanceof Error?B.message:"Invalid record"}}}}}}createCheckContractsTool(){return{name:`${this.id}_check_contracts`,description:"Check that canonical Rizom AT Protocol lexicon contracts are available.",inputSchema:{},handler:async()=>({success:!0,data:{lexiconCount:ZP().length,nsids:ZP().map((A)=>A.id),metadata:Fp0()}})}}}function nr0(A={}){return new dr0(A)}c0();Z0();Z0();c0();var AX0=K.object({routeId:K.string(),sectionId:K.string()}),uo=o1.extend({entityType:K.literal("site-content"),template:K.string().optional(),content:K.string(),metadata:AX0});c0();class He1 extends J2{constructor(){super({entityType:"site-content",purpose:"A content section bound to a route on the published site.",schema:uo,frontmatterSchema:AX0})}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 rr0=new He1;Z0();var QX0=K.object({routeId:K.string().optional().describe("Optional: specific route filter"),sectionId:K.string().optional().describe("Optional: specific section filter"),dryRun:K.boolean().optional().default(!1).describe("Optional: preview changes without executing"),force:K.boolean().optional().default(!1).describe("Force regeneration even if content exists")}),tD6=K.object({jobs:K.array(K.object({jobId:K.string(),routeId:K.string(),sectionId:K.string()})),totalSections:K.number(),queuedSections:K.number(),skippedSections:K.number().optional(),batchId:K.string().optional()});class or0{context;constructor(A){this.context=A}createJobOptions(A,Q){if(!A)return;return{source:A.operationType??Q,rootJobId:A.rootJobId??`${Q}-${Date.now()}`,metadata:{operationType:A.operationType??"content_operations",progressToken:A.progressToken,pluginId:A.pluginId??"site-content"}}}async fetchRoutes(){let A=await this.context.messaging.send({type:"site-builder:routes:list",payload:{}});if("noop"in A)throw Error("No handler for site-builder:routes:list \u2014 is site-builder plugin loaded?");if(!A.success||!A.data)throw Error("Failed to fetch routes from site-builder");return A.data}async generate(A,Q,w){let B=this.context.logger.child("SiteContentOperations"),$=await this.fetchRoutes(),Y=$;if(A.routeId){if(Y=$.filter((f)=>f.id===A.routeId),Y.length===0)throw Error(`Route not found: ${A.routeId}`)}let D=[];for(let f of Y)for(let Z of f.sections){if(A.sectionId&&Z.id!==A.sectionId)continue;if(Z.content){B.debug("Section has static content, skipping",{routeId:f.id,sectionId:Z.id});continue}if(Z.template){let G=this.context.templates.getCapabilities(Z.template);if(!G){B.warn("Template not found, skipping section",{routeId:f.id,sectionId:Z.id,templateName:Z.template});continue}if(!G.canGenerate){B.debug("Template doesn't support generation, skipping",{routeId:f.id,sectionId:Z.id,templateName:Z.template,capabilities:G});continue}}else{B.debug("Section has no template, skipping",{routeId:f.id,sectionId:Z.id});continue}if(!A.force&&!A.dryRun){let G=`${f.id}:${Z.id}`;if(await this.context.entityService.getEntity({entityType:"site-content",id:G})){B.debug("Content already exists, skipping",{routeId:f.id,sectionId:Z.id});continue}}D.push({route:f,section:Z})}let X=D.length;if(A.dryRun)return{jobs:[],totalSections:X,queuedSections:X,batchId:`dry-run-${Date.now()}`};let H=[],W=[];for(let{route:f,section:Z}of D){let G=`${f.id}:${Z.id}`,F=Z.template,V={routeId:f.id,sectionId:Z.id,entityId:G,entityType:"site-content",templateName:F,context:{prompt:typeof Z.content==="string"?Z.content:void 0,data:{routeId:f.id,sectionId:Z.id,routeTitle:f.title??Q?.title??"",routeDescription:f.description??Q?.description??"",sectionContent:Z.content},conversationId:"system"},siteConfig:Q};W.push({type:"shell:content-generation",data:V})}if(W.length>0){let f=this.createJobOptions(w,"site:content-generation"),Z=await this.context.jobs.enqueueBatch(W,f);for(let G=0;G<D.length;G++){let F=D[G];if(F)H.push({jobId:`${Z}-${G}`,routeId:F.route.id,sectionId:F.section.id})}return{jobs:H,totalSections:X,queuedSections:H.length,batchId:Z}}return{jobs:[],totalSections:X,queuedSections:0,batchId:`empty-${Date.now()}`}}}class sr0{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new or0(A)}async generateContent(A,Q){let w=QX0.parse(A);return this.operations.generate(w,this.siteConfig,Q)}}l$();Z0();function co(A,Q){return Q?A.optional():A}function tr0(A){switch(A.type){case"string":return co(K.string(),A.optional);case"number":return co(K.number(),A.optional);case"enum":{let Q=[...A.options];return co(K.enum(Q),A.optional)}case"object":{let Q={};for(let[w,B]of Object.entries(A.fields))Q[w]=tr0(B);return co(K.object(Q),A.optional)}case"array":{let Q=K.array(bzw(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return co(Q,A.optional)}}}function bzw(A){let{items:Q}=A;switch(Q.type){case"string":return K.string();case"number":return K.number();case"enum":{let w=[...Q.options];return K.enum(w)}case"object":{let w={};for(let[B,$]of Object.entries(Q.fields))w[B]=tr0($);return K.object(w)}}}function ar0(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(([w,B])=>ar0(w,B))};case"array":{let w={key:A,label:Q.label,type:"array"};switch(Q.items.type){case"string":case"enum":return w.itemType="string",w;case"number":return w.itemType="number",w;case"object":return w.itemType="object",w.itemMappings=Object.entries(Q.items.fields).map(([B,$])=>ar0(B,$)),w}}}}function Lzw(A,Q){let w={};for(let[Y,D]of Object.entries(Q.fields))w[Y]=tr0(D);let B=K.object(w),$=new pw(B,{title:Q.title,mappings:Object.entries(Q.fields).map(([Y,D])=>ar0(Y,D))});return{name:A,description:Q.description,schema:B,formatter:$,requiredPermission:Q.requiredPermission??"public",layout:{component:Q.layout,...Q.fullscreen!==void 0?{fullscreen:Q.fullscreen}:{}},...Q.runtimeScripts?{runtimeScripts:Q.runtimeScripts}:{}}}function er0(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,w])=>[Q,Lzw(Q,w)]))}Z0();var We1=K.object({namespace:K.string(),sections:K.record(K.any())}),fe1=K.object({definitions:K.union([We1,K.array(We1)]).optional()});c0();function Ze1(A,Q){return[Sw(Q,"generate","Generate content for all routes, a specific route, or a specific section",QX0,async(w,B)=>{let $=A();if(!$)return{success:!1,error:"Site content service not initialized"};if(w.sectionId&&!w.routeId)return{success:!1,error:"sectionId requires routeId to be specified"};let Y={rootJobId:`generate-${Date.now()}`,progressToken:B.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:B.interfaceType,channelId:B.channelId},D=await $.generateContent(w,Y);return{success:!0,message:`Generated ${D.queuedSections} of ${D.totalSections} sections. ${D.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:D.batchId,jobsQueued:D.queuedSections,totalSections:D.totalSections,jobs:D.jobs}}})]}var Ke1={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.136",description:"Site content entity and generation orchestration",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/plugins":"workspace:*","@brains/site-info":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};class Ao0 extends IQ{siteContentService;constructor(A={}){super("site-content",Ke1,A,fe1)}async onRegister(A){A.entities.register("site-content",uo,rr0);for(let Q of XU(this.config.definitions))A.templates.register(er0(Q),Q.namespace);this.siteContentService=new sr0(A)}async getTools(){return Ze1(()=>this.siteContentService,this.id)}}function lo(A={}){return new Ao0(A)}c0();Z0();IB();Z0();c0();var Ue1=K.enum(["available","early access","coming soon","planned"]),Ge1=K.object({title:K.string(),description:K.string()}),hH=K.object({name:K.string(),availability:Ue1,order:K.number(),ogImageId:K.string().optional()}),wX0=K.object({tagline:K.string(),promise:K.string(),role:K.string(),purpose:K.string(),audience:K.string(),values:K.array(K.string()).min(1),features:K.array(Ge1).min(1).max(6),story:K.string()}),jzw=hH.pick({name:!0,availability:!0,order:!0}).extend({slug:K.string()}),TE=o1.extend({entityType:K.literal("product"),metadata:jzw}),BX0=TE.extend({frontmatter:hH,body:wX0,labels:K.record(K.string(),K.string()),ogImageUrl:K.string().optional()}),$X0=BX0.extend({url:K.string().optional(),typeLabel:K.string().optional(),listUrl:K.string().optional(),listLabel:K.string().optional(),ogImageUrl:K.string().optional()});c0();Z0();l$();class SE extends pw{constructor(){super(wX0,{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 Qo0 extends J2{constructor(){super({entityType:"product",purpose:"A product entry in the portfolio.",schema:TE,frontmatterSchema:hH,bodyFormatter:new SE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,hH);return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,hH),w=w1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:w,availability:Q.availability,order:Q.order}}}}var YX0=new Qo0;Z0();c0();var ze1=K.object({title:K.string(),description:K.string()}),qe1=K.object({title:K.string(),description:K.string()}),Mzw=K.object({title:K.string(),description:K.string()}),Fe1=K.object({heading:K.string(),buttonText:K.string(),link:K.string()}),NF=K.object({headline:K.string(),tagline:K.string()}),_zw=K.object({title:K.string(),description:K.string()}),DX0=K.object({vision:K.string(),pillars:K.array(ze1).min(1).max(6),approach:K.array(_zw).min(1).max(6),productsIntro:K.string(),technologies:K.array(Mzw).min(1).max(6),benefits:K.array(qe1).min(1).max(6),cta:Fe1}),Ve1=NF.pick({headline:!0}).extend({slug:K.string()}),mE=o1.extend({entityType:K.literal("products-overview"),metadata:Ve1}),po=mE.extend({frontmatter:NF,body:DX0,labels:K.record(K.string(),K.string())});c0();Z0();l$();class uE extends pw{constructor(){super(DX0,{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 wo0 extends J2{constructor(){super({entityType:"products-overview",purpose:"A high-level overview of the product portfolio.",schema:mE,frontmatterSchema:NF,bodyFormatter:new uE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,NF);return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,NF),w=w1(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:w}}}}var Bo0=new wo0;c0();Z0();var Pzw=K.object({entityType:K.string(),query:K.object({id:K.string().optional()}).optional()});function Je1(A,Q){let w=v2(A.content,hH),B=Q.parse(w.content),$=Q.getLabels();return BX0.parse({...A,frontmatter:w.metadata,body:B,labels:$})}function Ie1(A,Q){let w=v2(A.content,NF),B=Q.parse(w.content),$=Q.getLabels();return po.parse({...A,frontmatter:w.metadata,body:B,labels:$})}class XX0{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new uE;productFormatter=new SE;constructor(A){this.logger=A;this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,w){let B=Pzw.parse(A),$=w.entityService;if(B.entityType==="products-overview"){let W=(await $.listEntities({entityType:"products-overview",options:{limit:1}}))[0];if(!W)throw Error("Products overview entity not found");let f=Ie1(W,this.overviewFormatter);return Q.parse(f)}if(B.query?.id){let W=(await $.listEntities({entityType:"product",options:{filter:{metadata:{slug:B.query.id}},limit:1}}))[0];if(!W)throw Error(`Product not found: ${B.query.id}`);return Q.parse({product:Je1(W,this.productFormatter)})}let[Y,D]=await Promise.all([$.listEntities({entityType:"products-overview",options:{limit:1}}),$.listEntities({entityType:"product",options:{sortFields:[{field:"order",direction:"asc"}]}})]),X=Y[0];if(!X)throw Error("Products overview entity not found");return Q.parse({overview:Ie1(X,this.overviewFormatter),products:D.map((H)=>Je1(H,this.productFormatter))})}}import{jsxDEV as B1,Fragment as xzw}from"preact/jsx-dev-runtime";var be1=({overview:A,products:Q})=>{let{frontmatter:w,body:B,labels:$}=A;return B1(xzw,{children:[B1(jQ,{title:w.headline,description:w.tagline},void 0,!1,void 0,this),B1("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[B1("style",{children:`
9001
9001
  @keyframes wave-drift {
9002
9002
  from { transform: translateX(0); }
9003
9003
  to { transform: translateX(-50%); }
@@ -9192,7 +9192,7 @@ ${JSON.stringify(w,null,2)}`}function uD0(A){return A.map((Q)=>Q.detail===null?{
9192
9192
  font: 10px/1.45 var(--font-mono, "JetBrains Mono", ui-monospace, monospace);
9193
9193
  }
9194
9194
  `}},void 0,!1,void 0,this),vH("section",{className:"product-shell",children:[vH("header",{className:"product-hero",children:[Q.brandLabel&&vH("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),vH("h1",{className:"printable-title",children:Q.name},void 0,!1,void 0,this),Q.availability&&vH("div",{className:"printable-meta",children:vH("span",{children:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),vH("div",{className:"product-body-wrap",children:[vH("aside",{className:"product-rail","aria-hidden":"true",children:vH("p",{className:"product-rail-label",children:"Product brief / capabilities"},void 0,!1,void 0,this)},void 0,!1,void 0,this),vH($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q.brandLabel&&vH("footer",{className:"printable-footer",children:Q.brandLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Tzw=26214400,Szw=60000;class Yo0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??VK}async resolve(A){if(A.sourceEntityType!=="product"||A.attachmentType!==HX0)return;let Q=await this.context.entityService.getEntity({entityType:"product",id:A.sourceEntityId});if(!Q)return;let w=mzw(Q,{brandLabel:this.resolveBrandLabel()}),B=await Czw(gzw(Ezw(),"brain-product-printable-"));try{let $=await jH({outputDir:B,mediaPath:`/_media/printable/product/${Q.id}`,template:je1,format:"pdf",content:w,siteConfig:{title:w.name,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await MH({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:Tzw,timeoutMs:Szw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${uzw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await yzw(B,{recursive:!0,force:!0})}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}}function mzw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=hH.parse(w);return{name:$.name,body:B,availability:$.availability,...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function uzw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.name)}Z0();Z0();import{jsxDEV as pzw}from"preact/jsx-dev-runtime";var WX0="og-image",czw="products:og-image",Me1=K.object({name:K.string().min(1),tagline:K.string().optional(),availability:K.string().optional(),brandLabel:K.string().optional()}),_e1={name:czw,pluginId:"products",schema:Me1,renderers:{image:lzw}};function lzw(A){let Q=Me1.parse(A);return pzw(d3,{cover:!0,brandLabel:Q.brandLabel??Q.name,eyebrow:"Product",title:Q.name,subtitle:Q.tagline,tag:Q.availability},void 0,!1,void 0,this)}class Do0{context;deps;metadata={outputEntityType:"image",targetField:"ogImageId"};constructor(A,Q={}){this.context=A;this.deps=Q}async resolve(A){if(A.sourceEntityType!=="product"||A.attachmentType!==WX0)return;let Q=await this.context.entityService.getEntity({entityType:"product",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w,content:B}=lw(Q.content),$=hH.parse(w),Y=izw(B,"Tagline"),D=this.resolveBrandLabel(),X={name:$.name,availability:$.availability,...Y?{tagline:Y}:{},...D?{brandLabel:D}:{}};return{type:"image",data:await UP({mediaPath:`/_media/og/product/${Q.id}`,template:_e1,content:X,title:X.name,themeMode:"light",themeCSS:this.context.themeCSS,tmpPrefix:"brain-product-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${dzw(Q)}-og.png`}}resolveBrandLabel(){let A=this.context.domain?.trim();if(A&&A.length>0)return A;let Q=this.context.identity.getProfile().name.trim();return Q.length>0?Q:void 0}}function izw(A,Q){let w=A.split(/\r?\n/),B=w.findIndex((D)=>D.trim().toLowerCase()===`## ${Q.toLowerCase()}`);if(B===-1)return;let $=[];for(let D of w.slice(B+1)){if(D.trim().startsWith("## "))break;$.push(D)}let Y=$.join(`
9195
- `).trim();return Y.length>0?Y:void 0}function dzw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.name)}var Pe1={name:"@brains/products",private:!0,version:"0.2.0-alpha.135",description:"Product entity management and overview page for marketing showcase",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var rzw=K.object({overview:po,products:K.array($X0)}),ozw=K.object({product:$X0});class Xo0 extends kQ{entityType=YX0.entityType;schema=TE;adapter=YX0;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("products",Pe1,A,$o0)}getTemplates(){return{"product-list":R1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:rzw,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:be1}}),"product-detail":R1({name:"product-detail",description:"Individual product detail page",schema:ozw,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Le1}})}}getDataSources(){return[new XX0(this.logger.child("ProductsDataSource"))]}async onRegister(A){this.unregisterPrintableAttachmentProvider=A.attachments.register("product",HX0,new Yo0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("product",WX0,new Do0(A)),A.entities.register("products-overview",mE,Bo0)}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0}}function Ho0(A={}){return new Xo0(A)}import{join as Nqw}from"path";import{jsxDEV as fX0,Fragment as szw}from"preact/jsx-dev-runtime";var cE=({children:A})=>fX0(szw,{children:[fX0("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:fX0("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),fX0("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 fW6}from"preact/jsx-dev-runtime";import{jsxDEV as tzw}from"preact/jsx-dev-runtime";var ZX0="px-6 md:px-10 xl:px-20",azw=`${ZX0} relative z-[1]`,cb=({id:A,className:Q,children:w})=>tzw("section",{id:A,className:$2(azw,Q),children:w},void 0,!1,void 0,this);import{jsxDEV as VW6}from"preact/jsx-dev-runtime";import{jsxDEV as bW6}from"preact/jsx-dev-runtime";import{jsxDEV as Bqw}from"preact/jsx-dev-runtime";var ezw="inline-flex items-center justify-center cursor-pointer border border-solid transition-all [gap:var(--rizom-btn-gap)] [border-radius:var(--rizom-btn-radius)] [font-family:var(--rizom-btn-font-family)] [font-style:var(--rizom-btn-font-style)] [letter-spacing:var(--rizom-btn-letter-spacing)] [text-transform:var(--rizom-btn-text-transform)]",Aqw={primary:"[font-weight:var(--rizom-btn-primary-font-weight)] [color:var(--rizom-btn-primary-color)] [background:var(--rizom-btn-primary-bg)] [border-color:var(--rizom-btn-primary-border-color)] [border-width:var(--rizom-btn-primary-border-width)] [box-shadow:var(--rizom-btn-primary-shadow)] hover:[color:var(--rizom-btn-primary-hover-color)] hover:[background:var(--rizom-btn-primary-hover-bg)] hover:[border-color:var(--rizom-btn-primary-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-hover-shadow)] hover:[transform:var(--rizom-btn-primary-hover-transform)]","primary-strong":"duration-400 ease-[cubic-bezier(0.2,0.8,0.2,1)] [font-weight:var(--rizom-btn-primary-strong-font-weight)] [color:var(--rizom-btn-primary-strong-color)] [background:var(--rizom-btn-primary-strong-bg)] [border-color:var(--rizom-btn-primary-strong-border-color)] [border-width:var(--rizom-btn-primary-strong-border-width)] [box-shadow:var(--rizom-btn-primary-strong-shadow)] hover:[color:var(--rizom-btn-primary-strong-hover-color)] hover:[background:var(--rizom-btn-primary-strong-hover-bg)] hover:[border-color:var(--rizom-btn-primary-strong-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-strong-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-strong-hover-shadow)] hover:[transform:var(--rizom-btn-primary-strong-hover-transform)]",secondary:"[font-weight:var(--rizom-btn-secondary-font-weight)] [color:var(--rizom-btn-secondary-color)] [background:var(--rizom-btn-secondary-bg)] [border-color:var(--rizom-btn-secondary-border-color)] [border-width:var(--rizom-btn-secondary-border-width)] [box-shadow:var(--rizom-btn-secondary-shadow)] hover:[color:var(--rizom-btn-secondary-hover-color)] hover:[background:var(--rizom-btn-secondary-hover-bg)] hover:[border-color:var(--rizom-btn-secondary-hover-border-color)] hover:[border-width:var(--rizom-btn-secondary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-secondary-hover-shadow)] hover:[transform:var(--rizom-btn-secondary-hover-transform)]"},Qqw={md:"text-base [padding:var(--rizom-btn-md-padding)]",lg:"text-body-md md:text-body-lg [padding:var(--rizom-btn-lg-padding-mobile)] md:[padding:var(--rizom-btn-lg-padding-desktop)]"},wqw="w-full md:w-auto",gP=({href:A,variant:Q="primary",size:w="md",block:B=!1,className:$,children:Y})=>Bqw("a",{href:A,className:$2("rizom-btn",`rizom-btn-${Q}`,`rizom-btn-${w}`,B&&"rizom-btn-block",ezw,Aqw[Q],Qqw[w],B&&wqw,$),children:Y},void 0,!1,void 0,this);import{jsxDEV as kW6}from"preact/jsx-dev-runtime";import{jsxDEV as hW6}from"preact/jsx-dev-runtime";import{Fragment as yW6}from"preact";import{jsxDEV as gW6}from"preact/jsx-dev-runtime";import{jsxDEV as ke1}from"preact/jsx-dev-runtime";var KX0=({sections:A})=>ke1(cE,{children:ke1("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);c0();Z0();var Oe1=`/*
9195
+ `).trim();return Y.length>0?Y:void 0}function dzw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.name)}var Pe1={name:"@brains/products",private:!0,version:"0.2.0-alpha.136",description:"Product entity management and overview page for marketing showcase",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/media-page-composer":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/app":"workspace:*","@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"latest","bun-types":"latest",eslint:"^8.56.0",typescript:"^5.3.3"}};var rzw=K.object({overview:po,products:K.array($X0)}),ozw=K.object({product:$X0});class Xo0 extends kQ{entityType=YX0.entityType;schema=TE;adapter=YX0;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("products",Pe1,A,$o0)}getTemplates(){return{"product-list":R1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:rzw,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:be1}}),"product-detail":R1({name:"product-detail",description:"Individual product detail page",schema:ozw,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Le1}})}}getDataSources(){return[new XX0(this.logger.child("ProductsDataSource"))]}async onRegister(A){this.unregisterPrintableAttachmentProvider=A.attachments.register("product",HX0,new Yo0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("product",WX0,new Do0(A)),A.entities.register("products-overview",mE,Bo0)}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0}}function Ho0(A={}){return new Xo0(A)}import{join as Nqw}from"path";import{jsxDEV as fX0,Fragment as szw}from"preact/jsx-dev-runtime";var cE=({children:A})=>fX0(szw,{children:[fX0("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:fX0("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),fX0("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 fW6}from"preact/jsx-dev-runtime";import{jsxDEV as tzw}from"preact/jsx-dev-runtime";var ZX0="px-6 md:px-10 xl:px-20",azw=`${ZX0} relative z-[1]`,cb=({id:A,className:Q,children:w})=>tzw("section",{id:A,className:$2(azw,Q),children:w},void 0,!1,void 0,this);import{jsxDEV as VW6}from"preact/jsx-dev-runtime";import{jsxDEV as bW6}from"preact/jsx-dev-runtime";import{jsxDEV as Bqw}from"preact/jsx-dev-runtime";var ezw="inline-flex items-center justify-center cursor-pointer border border-solid transition-all [gap:var(--rizom-btn-gap)] [border-radius:var(--rizom-btn-radius)] [font-family:var(--rizom-btn-font-family)] [font-style:var(--rizom-btn-font-style)] [letter-spacing:var(--rizom-btn-letter-spacing)] [text-transform:var(--rizom-btn-text-transform)]",Aqw={primary:"[font-weight:var(--rizom-btn-primary-font-weight)] [color:var(--rizom-btn-primary-color)] [background:var(--rizom-btn-primary-bg)] [border-color:var(--rizom-btn-primary-border-color)] [border-width:var(--rizom-btn-primary-border-width)] [box-shadow:var(--rizom-btn-primary-shadow)] hover:[color:var(--rizom-btn-primary-hover-color)] hover:[background:var(--rizom-btn-primary-hover-bg)] hover:[border-color:var(--rizom-btn-primary-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-hover-shadow)] hover:[transform:var(--rizom-btn-primary-hover-transform)]","primary-strong":"duration-400 ease-[cubic-bezier(0.2,0.8,0.2,1)] [font-weight:var(--rizom-btn-primary-strong-font-weight)] [color:var(--rizom-btn-primary-strong-color)] [background:var(--rizom-btn-primary-strong-bg)] [border-color:var(--rizom-btn-primary-strong-border-color)] [border-width:var(--rizom-btn-primary-strong-border-width)] [box-shadow:var(--rizom-btn-primary-strong-shadow)] hover:[color:var(--rizom-btn-primary-strong-hover-color)] hover:[background:var(--rizom-btn-primary-strong-hover-bg)] hover:[border-color:var(--rizom-btn-primary-strong-hover-border-color)] hover:[border-width:var(--rizom-btn-primary-strong-hover-border-width)] hover:[box-shadow:var(--rizom-btn-primary-strong-hover-shadow)] hover:[transform:var(--rizom-btn-primary-strong-hover-transform)]",secondary:"[font-weight:var(--rizom-btn-secondary-font-weight)] [color:var(--rizom-btn-secondary-color)] [background:var(--rizom-btn-secondary-bg)] [border-color:var(--rizom-btn-secondary-border-color)] [border-width:var(--rizom-btn-secondary-border-width)] [box-shadow:var(--rizom-btn-secondary-shadow)] hover:[color:var(--rizom-btn-secondary-hover-color)] hover:[background:var(--rizom-btn-secondary-hover-bg)] hover:[border-color:var(--rizom-btn-secondary-hover-border-color)] hover:[border-width:var(--rizom-btn-secondary-hover-border-width)] hover:[box-shadow:var(--rizom-btn-secondary-hover-shadow)] hover:[transform:var(--rizom-btn-secondary-hover-transform)]"},Qqw={md:"text-base [padding:var(--rizom-btn-md-padding)]",lg:"text-body-md md:text-body-lg [padding:var(--rizom-btn-lg-padding-mobile)] md:[padding:var(--rizom-btn-lg-padding-desktop)]"},wqw="w-full md:w-auto",gP=({href:A,variant:Q="primary",size:w="md",block:B=!1,className:$,children:Y})=>Bqw("a",{href:A,className:$2("rizom-btn",`rizom-btn-${Q}`,`rizom-btn-${w}`,B&&"rizom-btn-block",ezw,Aqw[Q],Qqw[w],B&&wqw,$),children:Y},void 0,!1,void 0,this);import{jsxDEV as kW6}from"preact/jsx-dev-runtime";import{jsxDEV as hW6}from"preact/jsx-dev-runtime";import{Fragment as yW6}from"preact";import{jsxDEV as gW6}from"preact/jsx-dev-runtime";import{jsxDEV as ke1}from"preact/jsx-dev-runtime";var KX0=({sections:A})=>ke1(cE,{children:ke1("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);c0();Z0();var Oe1=`/*
9196
9196
  * Shared globals + helpers used by tree / constellation / roots canvas
9197
9197
  * scripts. Loaded as a shared static asset by the Rizom runtime package
9198
9198
  * so the variant canvases
@@ -11682,7 +11682,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});Z0();var y
11682
11682
  `);return this.truncateContent(B||Q||aE(A))}truncateContent(A){if(A.length<=K02)return A;let Q=A.slice(0,K02-1),w=Q.search(/\s\S*$/);return`${(w>0?Q.slice(0,w):Q).trimEnd()}\u2026`}isSummaryEntity(A){return A.entityType===q5}isDecisionEntity(A){return A.entityType===CH}getEntitySpaceId(A){let Q=A.metadata;if("spaceId"in Q&&typeof Q.spaceId==="string")return Q.spaceId;return MK(Q)}}var D3w=5,X3w=3;function Vo0(A){A.messaging.subscribe(XN,async(Q)=>{let w=lT.parse(Q.payload);return{success:!0,data:await MX0(A,w)}})}async function MX0(A,Q){let w=p8(Q.userPermissionLevel);if(!Q.channelId)return U02(A,Q,{visibilityScope:w,reason:"no-channel-context",items:[]}),{items:[]};let B=new tE(A),$=await B.retrieve({query:Q.message,conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,limit:D3w,visibilityScope:w}),Y=$.results.length===0?await B.retrieve({conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,limit:X3w,visibilityScope:w}):void 0,D=$.results.length>0,X=D?$.results:Y?.results??[];return U02(A,Q,{visibilityScope:w,spaceId:$.spaceId??Y?.spaceId,reason:X.length>0?"memory-injected":"no-same-space-memory",items:X.map((H)=>H3w(H,D))}),{items:X.map(W3w)}}function U02(A,Q,w){A.logger.info("Conversation memory agent context audit",{conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,channelName:Q.channelName,userPermissionLevel:Q.userPermissionLevel,visibilityScope:w.visibilityScope,spaceId:w.spaceId,reason:w.reason,itemCount:w.items.length,items:w.items})}function H3w(A,Q){return{id:A.id,entityType:A.entityType,conversationId:A.conversationId,spaceId:A.spaceId,visibility:A.visibility,score:A.score,updated:A.updated,eligibilityReason:Q?"same-space-query-match":"recent-same-space-memory"}}function W3w(A){let Q=A.channelName??A.channelId;return{id:A.id,source:"conversation-memory",title:`${A.entityType} from ${Q}`,content:A.content,provenance:{entityType:A.entityType,entityId:A.id,conversationId:A.conversationId,spaceId:A.spaceId,interfaceType:A.interfaceType,channelId:A.channelId,channelName:A.channelName,updated:A.updated,score:A.score,messageCount:A.messageCount,entryCount:A.entryCount,status:A.status}}}c0();CB();Z0();IX();var Io0=K.object({role:Aq,content:K.string(),timestamp:K.string().datetime().optional(),actor:MN.optional(),source:_N.optional()}),f3w=K.object({conversationId:K.string().default("eval-conversation"),messages:K.array(Io0)}),Z3w=K.object({conversationId:K.string()}),K3w=K.object({conversationId:K.string().default("eval-conversation"),interfaceType:K.string().default("eval"),channelId:K.string().default("eval-channel"),channelName:K.string().optional(),projectionDecision:K.enum(["update","append"]).default("update"),existingSummary:K.string().optional(),existingMessageCount:K.number().int().min(0).default(0),messages:K.array(Io0)}),_X0=K.object({actorId:K.string(),canonicalId:K.string().optional(),displayName:K.string().optional()}),U3w=_X0.extend({roles:K.array(K.enum(["user","assistant","system"])).default(["user"]),sourceActorIds:K.array(K.string()).optional()}),G3w=K.object({actorId:K.string().optional(),canonicalId:K.string().optional(),displayName:K.string()}),q02=K.object({id:K.string(),entityType:K.enum(["summary","decision","action-item"]),content:K.string(),excerpt:K.string().optional(),score:K.number().optional(),conversationId:K.string(),interfaceType:K.string(),channelId:K.string(),channelName:K.string().optional(),updated:K.string().datetime().optional(),visibility:W7,status:K.string().optional(),participants:K.array(U3w).optional(),decidedBy:K.array(_X0).optional(),mentionedBy:K.array(_X0).optional(),assignedTo:K.array(G3w).optional(),requestedBy:K.array(_X0).optional()}),z3w=K.object({query:K.string().optional(),conversationId:K.string().optional(),interfaceType:K.string().optional(),channelId:K.string().optional(),limit:K.number().int().min(1).optional(),includeOtherSpaces:K.boolean().optional(),actorId:K.string().optional(),canonicalId:K.string().optional(),visibilityScope:W7.optional(),memory:K.array(q02).optional()}),q3w=K.object({conversationId:K.string().default("eval-conversation"),message:K.string(),interfaceType:K.string().default("eval"),channelId:K.string().optional(),channelName:K.string().optional(),userPermissionLevel:K.enum(["anchor","trusted","public"]).default("trusted"),memory:K.array(q02).optional()}),F3w=K.object({conversationId:K.string().default("eval-conversation"),existingSummary:K.string().optional(),existingMessageCount:K.number().int().min(0).default(0),messages:K.array(Io0)});function F02(A){let{context:Q,logger:w,config:B}=A;Q.eval.registerHandler("summarizeMessages",async($)=>{let Y=f3w.parse($),D=Jo0(Y.messages,Y.conversationId),H=await new rE(Q,w,B).extract(D);return H.entries.map((W)=>{let f=H.decisions.filter((G)=>G.timeRange.start>=W.timeRange.start).filter((G)=>G.timeRange.end<=W.timeRange.end).map((G)=>G.text),Z=H.actionItems.filter((G)=>G.timeRange.start>=W.timeRange.start).filter((G)=>G.timeRange.end<=W.timeRange.end).map((G)=>G.text);return{...W,decisions:f,actionItems:Z,keyPointsText:W.keyPoints.join(`
11683
11683
  `),decisionsText:f.join(`
11684
11684
  `),actionItemsText:Z.join(`
11685
- `)}})}),Q.eval.registerHandler("decideProjection",async($)=>{let Y=F3w.parse($),D=Jo0(Y.messages,Y.conversationId),X=Y.existingSummary?G02({conversationId:Y.conversationId,content:Y.existingSummary,messageCount:Y.existingMessageCount,projectionVersion:B.projectionVersion,visibility:B.memoryVisibility}):null;return new pb(Q,w,B).decideProjection(D,X)}),Q.eval.registerHandler("retrieveMemory",async($)=>{let Y=z3w.parse($),D=Y.memory?z02(Q,Y.memory):Q;return new tE(D).retrieve(Y)}),Q.eval.registerHandler("buildAgentContext",async($)=>{let Y=q3w.parse($),D=Y.memory?z02(Q,Y.memory):Q;return MX0(D,Y)}),Q.eval.registerHandler("projectMessages",async($)=>{let Y=K3w.parse($),D=Jo0(Y.messages,Y.conversationId),X=V3w({conversationId:Y.conversationId,interfaceType:Y.interfaceType,channelId:Y.channelId,channelName:Y.channelName,messages:D}),H=Y.existingSummary?G02({conversationId:Y.conversationId,content:Y.existingSummary,messageCount:Y.existingMessageCount,projectionVersion:B.projectionVersion,visibility:B.memoryVisibility}):null,W=[],f=[],Z=J3w({context:Q,conversation:X,messages:D,existing:H,upserted:W,deleted:f,projectionDecision:Y.projectionDecision});return{result:await new pb(Z,w,B).projectConversation(Y.conversationId),summaries:W.filter((V)=>V.entityType==="summary"),decisions:W.filter((V)=>V.entityType==="decision"),actionItems:W.filter((V)=>V.entityType==="action-item"),deleted:f}}),Q.eval.registerHandler("projectConversation",async($)=>{let Y=Z3w.parse($);return new pb(Q,w,B).projectConversation(Y.conversationId)})}function G02(A){return{id:A.conversationId,entityType:"summary",content:A.content,contentHash:"eval-existing-summary",visibility:A.visibility,created:"2026-01-01T00:00:00.000Z",updated:"2026-01-01T00:00:00.000Z",metadata:{conversationId:A.conversationId,channelId:"eval-channel",interfaceType:"eval",messageCount:A.messageCount,entryCount:1,sourceHash:"eval-source-hash",projectionVersion:A.projectionVersion}}}function Jo0(A,Q){return A.map((w,B)=>{let $=w.timestamp??new Date(Date.UTC(2026,0,1,0,B)).toISOString();return{id:`eval-message-${B+1}`,conversationId:Q,role:w.role,content:w.content,timestamp:$,metadata:{...w.actor?{actor:w.actor}:{},...w.source?{source:w.source}:{}}}})}function V3w(A){let Q=A.messages[0],w=A.messages[A.messages.length-1],B=Q?.timestamp??"2026-01-01T00:00:00.000Z",$=w?.timestamp??B;return{id:A.conversationId,sessionId:A.conversationId,interfaceType:A.interfaceType,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},startedAt:B,lastActiveAt:$,createdAt:B,updatedAt:$,metadata:{}}}function J3w(A){let Q=MK(A.conversation);return{...A.context,spaces:[Q],conversations:{...A.context.conversations,get:async()=>A.conversation,getMessages:async()=>A.messages},ai:{...A.context.ai,generateObject:async()=>({object:{decision:A.projectionDecision,rationale:"Forced by eval input"}})},entityService:{...A.context.entityService,getEntity:async({entityType:w})=>w==="summary"?A.existing:null,listEntities:async()=>[],deleteEntity:async(w)=>{return A.deleted.push(w),!0},upsertEntity:async({entity:w})=>{return A.upserted.push(w),{entityId:w.id,jobId:"eval-upsert",created:!0,skipped:!1}}}}}function z02(A,Q){let w=Q.map(I3w),B=w.map(($,Y)=>({entity:$,score:Q[Y]?.score??1,excerpt:Q[Y]?.excerpt??aE($)}));return{...A,entityService:{...A.entityService,search:async()=>B,listEntities:async({entityType:$})=>w.filter((Y)=>Y.entityType===$)}}}function I3w(A){if(A.entityType==="summary")return b3w(A);if(A.entityType==="decision")return L3w(A);return N3w(A)}function bo0(A){let Q=A.updated??"2026-01-01T00:00:00.000Z";return{id:A.id,content:A.content,contentHash:xw(A.content),visibility:A.visibility,created:Q,updated:Q}}function b3w(A){return{...bo0(A),entityType:"summary",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,messageCount:3,entryCount:1,sourceHash:`source-${A.id}`,projectionVersion:1,...A.participants?{participants:A.participants}:{}}}}function L3w(A){return{...bo0(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:MK(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:A.status==="superseded"?"superseded":"active",...A.decidedBy?{decidedBy:A.decidedBy}:{},...A.mentionedBy?{mentionedBy:A.mentionedBy}:{}}}}function N3w(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...bo0(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:MK(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:Q,...A.assignedTo?{assignedTo:A.assignedTo}:{},...A.requestedBy?{requestedBy:A.requestedBy}:{}}}}var V02={name:"@brains/conversation-memory",private:!0,version:"0.2.0-alpha.135",description:"Plugin for deriving durable conversation memory",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts,.tsx",eval:"cd evals && bun run brain-eval","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/conversation-service":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};var M3w=new ff,_3w=new iE,P3w=new dE,k3w=K.object({conversationId:K.string()});class Lo0 extends kQ{entityType=q5;schema=no;adapter=M3w;constructor(A={}){super(GX0,V02,A,Ko0)}getConfig(){return this.config}getTemplates(){return{"summary-list":pe1,"summary-detail":ie1,"ai-response":de1}}getDataSources(){return[new Fo0(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:q5,job:{type:ge1,handler:new IX0(A,this.logger,this.config)},initialSync:{shouldEnqueue:async()=>A.spaces.length>0&&!await IN(A,q5,{outputVisibility:this.config.memoryVisibility}),jobData:{mode:"rebuild-all",reason:"initial-sync"},jobOptions:{source:Zo0,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:GX0}}},sourceChange:{sourceKind:NS,sourceTypes:[NS],shouldEnqueue:(Q)=>this.shouldEnqueueConversationProjection(A,Q),events:[eO],jobData:(Q)=>{let{conversationId:w}=this.parseConversationMessagePayload(Q);return{mode:"conversation",conversationId:w,reason:"message-added"}},jobOptions:(Q)=>{let{conversationId:w}=this.parseConversationMessagePayload(Q);return{priority:5,delayMs:this.config.projectionDelayMs,source:Zo0,deduplication:"skip",deduplicationKey:`conversation-memory:${w}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${w}`,pluginId:GX0}}}}}]}parseConversationMessagePayload(A){return k3w.parse(A)}async shouldEnqueueConversationProjection(A,Q){let{conversationId:w}=this.parseConversationMessagePayload(Q),B=await A.conversations.get(w);if(!B)return!1;return mP({conversation:B,spaces:A.spaces}).eligible}async onRegister(A){A.entities.register(CH,ro,_3w),A.entities.register(Wf,oo,P3w),oe1({context:A,pluginId:this.id}),ae1({context:A,pluginId:this.id}),X02({context:A,pluginId:this.id}),f02({context:A,pluginId:this.id,config:this.config}),Vo0(A),F02({context:A,logger:this.logger,config:this.config})}}function No0(A){return new Lo0(A)}c0();Z0();c0();var jF=K.object({title:K.string(),section:K.string(),order:K.number().int(),sourcePath:K.string(),description:K.string().optional(),slug:K.string().optional()}),J02=jF.pick({title:!0,section:!0,order:!0,description:!0}).extend({slug:K.string()}),eE=o1.extend({entityType:K.literal("doc"),metadata:J02}),MF=eE.extend({frontmatter:jF,body:K.string()});c0();Z0();class jo0 extends J2{constructor(){super({entityType:"doc",purpose:"A structured documentation page.",schema:eE,frontmatterSchema:jF})}toMarkdown(A){let Q=this.extractBody(A.content),w=this.parseFrontMatter(A.content,jF);return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,jF),w=Q.slug??w1(Q.title);return{content:A,entityType:"doc",metadata:{title:Q.title,section:Q.section,order:Q.order,slug:w,...Q.description?{description:Q.description}:{}}}}}var PX0=new jo0;c0();function I02(A){return[...A].sort((Q,w)=>{let B=Q.metadata.order-w.metadata.order;if(B!==0)return B;return Q.metadata.title.localeCompare(w.metadata.title)})}function b02(A){let Q=v2(A.content,jF);return MF.parse({...A,frontmatter:Q.metadata,body:Q.content})}class kX0 extends f${id="docs:entities";name="Docs Entity DataSource";description="Fetches and transforms doc entities for rendering";config={entityType:"doc",defaultSort:[{field:"order",direction:"asc"},{field:"section",direction:"asc"},{field:"title",direction:"asc"}],defaultLimit:100,enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return b02(A)}async fetch(A,Q,w){let B=this.parseQuery(A);if(!B.query.id){let f=await this.fetchList({...B.query,limit:1000,page:void 0,pageSize:void 0},w.entityService);return Q.parse(this.buildListResult(f.items,null,B.query))}let[$,Y]=await Promise.all([this.fetchDetail(B.query.id,w.entityService),this.fetchList({limit:1000},w.entityService)]),D=I02(Y.items),X=D.findIndex((f)=>f.id===$.item.id),H=X>0?D[X-1]:null,W=X>=0&&X<D.length-1?D[X+1]:null;return Q.parse({doc:$.item,docs:D,prevDoc:H,nextDoc:W})}buildDetailResult(A,Q){return{doc:A,docs:[A],prevDoc:Q?.prev??null,nextDoc:Q?.next??null}}buildListResult(A,Q,w){return{docs:I02(A),pagination:Q,baseUrl:w.baseUrl}}}c0();IB();Z0();import{jsxDEV as x$}from"preact/jsx-dev-runtime";var O3w=["I","II","III","IV","V","VI","VII","VIII","IX","X"];function to(A){return[...A].sort((Q,w)=>{let B=Q.metadata.order-w.metadata.order;if(B!==0)return B;return Q.metadata.title.localeCompare(w.metadata.title)})}function OX0(A){let Q=new Map;for(let w of to(A)){let B=w.metadata.section;Q.set(B,[...Q.get(B)??[],w])}return[...Q.entries()].map(([w,B])=>({section:w,docs:B}))}function Ag(A){return`/docs/${A.metadata.slug}`}function xX0(A){return`section-${A+1}`}function Qg(A){return O3w[A]??String(A+1)}var j02="text-[var(--docs-text)] font-bold",M02="text-[var(--docs-accent)] font-bold",_02="text-[var(--docs-text-muted)]",x3w="docs-font-label text-xs uppercase tracking-[0.18em] text-[var(--docs-accent)]",R3w="docs-font-display text-[var(--docs-heading)]",L02="inline-flex items-center justify-center rounded-lg border px-[18px] py-2.5 text-sm font-semibold transition-colors duration-150",N02="relative hidden py-1 text-[15px] text-[var(--docs-text-muted)] transition-colors duration-150 after:absolute after:bottom-0 after:left-0 after:h-px after:w-0 after:bg-[var(--docs-accent)] after:transition-[width] after:duration-300 hover:text-[var(--docs-text)] hover:after:w-full min-[861px]:inline-block",Mo0="docs-font-label text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:text-[var(--docs-text)]",Qz={wrap:"mx-auto max-w-6xl px-6 pt-20 md:px-12 md:pt-24",label:x3w,display:R3w,button:`${L02} border-[var(--docs-text)] text-[var(--docs-text)] hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)]`,primaryButton:`${L02} border-[var(--docs-accent)] bg-[var(--docs-accent)] text-white hover:bg-transparent hover:text-[var(--docs-accent)]`},P02=()=>x$("nav",{className:"docs-header fixed inset-x-0 top-0 z-[100] flex items-center justify-between px-6 py-4 md:px-10 md:py-5 xl:px-20",children:[x$("a",{href:"/docs",className:"docs-font-body text-xl font-bold","aria-label":"Brains docs",children:[x$("span",{className:j02,children:"brains"},void 0,!1,void 0,this),x$("span",{className:M02,children:"."},void 0,!1,void 0,this),x$("span",{className:_02,children:"docs"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x$("div",{className:"docs-header__nav flex items-center gap-4 md:gap-8",children:[x$("a",{className:N02,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:N02,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),x$("a",{href:"https://rizom.ai",className:"inline-flex items-center justify-center rounded-lg border border-[var(--docs-text)] px-4 py-2 text-[13px] font-semibold text-[var(--docs-text)] transition-colors duration-150 hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)] md:px-6 md:py-2.5 md:text-[15px]",children:"Get Brains"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),k02=()=>x$("footer",{className:"flex flex-col items-center justify-between gap-4 border-t border-[var(--docs-border-light)] py-8 text-center md:flex-row md:gap-6 md:py-6 md:text-left",children:[x$("a",{href:"https://rizom.ai",className:"docs-font-body text-[15px] font-bold",children:[x$("span",{className:j02,children:"rizom"},void 0,!1,void 0,this),x$("span",{className:M02,children:"."},void 0,!1,void 0,this),x$("span",{className:_02,children:"ai"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x$("div",{className:"flex flex-wrap items-center justify-center gap-6 md:justify-end",children:[x$("a",{className:Mo0,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:Mo0,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),x$("a",{className:Mo0,href:"https://rizom.ai",children:"Rizom"},void 0,!1,void 0,this),x$("button",{id:"themeToggle",className:"docs-font-label cursor-pointer rounded-md border border-[var(--docs-text-light)] bg-transparent px-2.5 py-1.5 text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:border-[var(--docs-text)] hover:text-[var(--docs-text)]",type:"button",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h3w=`
11685
+ `)}})}),Q.eval.registerHandler("decideProjection",async($)=>{let Y=F3w.parse($),D=Jo0(Y.messages,Y.conversationId),X=Y.existingSummary?G02({conversationId:Y.conversationId,content:Y.existingSummary,messageCount:Y.existingMessageCount,projectionVersion:B.projectionVersion,visibility:B.memoryVisibility}):null;return new pb(Q,w,B).decideProjection(D,X)}),Q.eval.registerHandler("retrieveMemory",async($)=>{let Y=z3w.parse($),D=Y.memory?z02(Q,Y.memory):Q;return new tE(D).retrieve(Y)}),Q.eval.registerHandler("buildAgentContext",async($)=>{let Y=q3w.parse($),D=Y.memory?z02(Q,Y.memory):Q;return MX0(D,Y)}),Q.eval.registerHandler("projectMessages",async($)=>{let Y=K3w.parse($),D=Jo0(Y.messages,Y.conversationId),X=V3w({conversationId:Y.conversationId,interfaceType:Y.interfaceType,channelId:Y.channelId,channelName:Y.channelName,messages:D}),H=Y.existingSummary?G02({conversationId:Y.conversationId,content:Y.existingSummary,messageCount:Y.existingMessageCount,projectionVersion:B.projectionVersion,visibility:B.memoryVisibility}):null,W=[],f=[],Z=J3w({context:Q,conversation:X,messages:D,existing:H,upserted:W,deleted:f,projectionDecision:Y.projectionDecision});return{result:await new pb(Z,w,B).projectConversation(Y.conversationId),summaries:W.filter((V)=>V.entityType==="summary"),decisions:W.filter((V)=>V.entityType==="decision"),actionItems:W.filter((V)=>V.entityType==="action-item"),deleted:f}}),Q.eval.registerHandler("projectConversation",async($)=>{let Y=Z3w.parse($);return new pb(Q,w,B).projectConversation(Y.conversationId)})}function G02(A){return{id:A.conversationId,entityType:"summary",content:A.content,contentHash:"eval-existing-summary",visibility:A.visibility,created:"2026-01-01T00:00:00.000Z",updated:"2026-01-01T00:00:00.000Z",metadata:{conversationId:A.conversationId,channelId:"eval-channel",interfaceType:"eval",messageCount:A.messageCount,entryCount:1,sourceHash:"eval-source-hash",projectionVersion:A.projectionVersion}}}function Jo0(A,Q){return A.map((w,B)=>{let $=w.timestamp??new Date(Date.UTC(2026,0,1,0,B)).toISOString();return{id:`eval-message-${B+1}`,conversationId:Q,role:w.role,content:w.content,timestamp:$,metadata:{...w.actor?{actor:w.actor}:{},...w.source?{source:w.source}:{}}}})}function V3w(A){let Q=A.messages[0],w=A.messages[A.messages.length-1],B=Q?.timestamp??"2026-01-01T00:00:00.000Z",$=w?.timestamp??B;return{id:A.conversationId,sessionId:A.conversationId,interfaceType:A.interfaceType,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},startedAt:B,lastActiveAt:$,createdAt:B,updatedAt:$,metadata:{}}}function J3w(A){let Q=MK(A.conversation);return{...A.context,spaces:[Q],conversations:{...A.context.conversations,get:async()=>A.conversation,getMessages:async()=>A.messages},ai:{...A.context.ai,generateObject:async()=>({object:{decision:A.projectionDecision,rationale:"Forced by eval input"}})},entityService:{...A.context.entityService,getEntity:async({entityType:w})=>w==="summary"?A.existing:null,listEntities:async()=>[],deleteEntity:async(w)=>{return A.deleted.push(w),!0},upsertEntity:async({entity:w})=>{return A.upserted.push(w),{entityId:w.id,jobId:"eval-upsert",created:!0,skipped:!1}}}}}function z02(A,Q){let w=Q.map(I3w),B=w.map(($,Y)=>({entity:$,score:Q[Y]?.score??1,excerpt:Q[Y]?.excerpt??aE($)}));return{...A,entityService:{...A.entityService,search:async()=>B,listEntities:async({entityType:$})=>w.filter((Y)=>Y.entityType===$)}}}function I3w(A){if(A.entityType==="summary")return b3w(A);if(A.entityType==="decision")return L3w(A);return N3w(A)}function bo0(A){let Q=A.updated??"2026-01-01T00:00:00.000Z";return{id:A.id,content:A.content,contentHash:xw(A.content),visibility:A.visibility,created:Q,updated:Q}}function b3w(A){return{...bo0(A),entityType:"summary",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,messageCount:3,entryCount:1,sourceHash:`source-${A.id}`,projectionVersion:1,...A.participants?{participants:A.participants}:{}}}}function L3w(A){return{...bo0(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:MK(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:A.status==="superseded"?"superseded":"active",...A.decidedBy?{decidedBy:A.decidedBy}:{},...A.mentionedBy?{mentionedBy:A.mentionedBy}:{}}}}function N3w(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...bo0(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:MK(A),timeRange:{start:"2026-01-01T00:00:00.000Z",end:"2026-01-01T00:01:00.000Z"},sourceSummaryId:A.conversationId,sourceMessageCount:2,projectionVersion:1,status:Q,...A.assignedTo?{assignedTo:A.assignedTo}:{},...A.requestedBy?{requestedBy:A.requestedBy}:{}}}}var V02={name:"@brains/conversation-memory",private:!0,version:"0.2.0-alpha.136",description:"Plugin for deriving durable conversation memory",type:"module",main:"./src/index.ts",exports:{".":"./src/index.ts"},scripts:{test:"bun test",typecheck:"tsc --noEmit",lint:"eslint src test --ext .ts,.tsx",eval:"cd evals && bun run brain-eval","lint:fix":"eslint src test --ext .ts,.tsx --fix"},dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/conversation-service":"workspace:*","@brains/dashboard":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/node":"^20.0.0",eslint:"^8.56.0",typescript:"^5.3.3"}};var M3w=new ff,_3w=new iE,P3w=new dE,k3w=K.object({conversationId:K.string()});class Lo0 extends kQ{entityType=q5;schema=no;adapter=M3w;constructor(A={}){super(GX0,V02,A,Ko0)}getConfig(){return this.config}getTemplates(){return{"summary-list":pe1,"summary-detail":ie1,"ai-response":de1}}getDataSources(){return[new Fo0(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:q5,job:{type:ge1,handler:new IX0(A,this.logger,this.config)},initialSync:{shouldEnqueue:async()=>A.spaces.length>0&&!await IN(A,q5,{outputVisibility:this.config.memoryVisibility}),jobData:{mode:"rebuild-all",reason:"initial-sync"},jobOptions:{source:Zo0,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:GX0}}},sourceChange:{sourceKind:NS,sourceTypes:[NS],shouldEnqueue:(Q)=>this.shouldEnqueueConversationProjection(A,Q),events:[eO],jobData:(Q)=>{let{conversationId:w}=this.parseConversationMessagePayload(Q);return{mode:"conversation",conversationId:w,reason:"message-added"}},jobOptions:(Q)=>{let{conversationId:w}=this.parseConversationMessagePayload(Q);return{priority:5,delayMs:this.config.projectionDelayMs,source:Zo0,deduplication:"skip",deduplicationKey:`conversation-memory:${w}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${w}`,pluginId:GX0}}}}}]}parseConversationMessagePayload(A){return k3w.parse(A)}async shouldEnqueueConversationProjection(A,Q){let{conversationId:w}=this.parseConversationMessagePayload(Q),B=await A.conversations.get(w);if(!B)return!1;return mP({conversation:B,spaces:A.spaces}).eligible}async onRegister(A){A.entities.register(CH,ro,_3w),A.entities.register(Wf,oo,P3w),oe1({context:A,pluginId:this.id}),ae1({context:A,pluginId:this.id}),X02({context:A,pluginId:this.id}),f02({context:A,pluginId:this.id,config:this.config}),Vo0(A),F02({context:A,logger:this.logger,config:this.config})}}function No0(A){return new Lo0(A)}c0();Z0();c0();var jF=K.object({title:K.string(),section:K.string(),order:K.number().int(),sourcePath:K.string(),description:K.string().optional(),slug:K.string().optional()}),J02=jF.pick({title:!0,section:!0,order:!0,description:!0}).extend({slug:K.string()}),eE=o1.extend({entityType:K.literal("doc"),metadata:J02}),MF=eE.extend({frontmatter:jF,body:K.string()});c0();Z0();class jo0 extends J2{constructor(){super({entityType:"doc",purpose:"A structured documentation page.",schema:eE,frontmatterSchema:jF})}toMarkdown(A){let Q=this.extractBody(A.content),w=this.parseFrontMatter(A.content,jF);return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,jF),w=Q.slug??w1(Q.title);return{content:A,entityType:"doc",metadata:{title:Q.title,section:Q.section,order:Q.order,slug:w,...Q.description?{description:Q.description}:{}}}}}var PX0=new jo0;c0();function I02(A){return[...A].sort((Q,w)=>{let B=Q.metadata.order-w.metadata.order;if(B!==0)return B;return Q.metadata.title.localeCompare(w.metadata.title)})}function b02(A){let Q=v2(A.content,jF);return MF.parse({...A,frontmatter:Q.metadata,body:Q.content})}class kX0 extends f${id="docs:entities";name="Docs Entity DataSource";description="Fetches and transforms doc entities for rendering";config={entityType:"doc",defaultSort:[{field:"order",direction:"asc"},{field:"section",direction:"asc"},{field:"title",direction:"asc"}],defaultLimit:100,enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return b02(A)}async fetch(A,Q,w){let B=this.parseQuery(A);if(!B.query.id){let f=await this.fetchList({...B.query,limit:1000,page:void 0,pageSize:void 0},w.entityService);return Q.parse(this.buildListResult(f.items,null,B.query))}let[$,Y]=await Promise.all([this.fetchDetail(B.query.id,w.entityService),this.fetchList({limit:1000},w.entityService)]),D=I02(Y.items),X=D.findIndex((f)=>f.id===$.item.id),H=X>0?D[X-1]:null,W=X>=0&&X<D.length-1?D[X+1]:null;return Q.parse({doc:$.item,docs:D,prevDoc:H,nextDoc:W})}buildDetailResult(A,Q){return{doc:A,docs:[A],prevDoc:Q?.prev??null,nextDoc:Q?.next??null}}buildListResult(A,Q,w){return{docs:I02(A),pagination:Q,baseUrl:w.baseUrl}}}c0();IB();Z0();import{jsxDEV as x$}from"preact/jsx-dev-runtime";var O3w=["I","II","III","IV","V","VI","VII","VIII","IX","X"];function to(A){return[...A].sort((Q,w)=>{let B=Q.metadata.order-w.metadata.order;if(B!==0)return B;return Q.metadata.title.localeCompare(w.metadata.title)})}function OX0(A){let Q=new Map;for(let w of to(A)){let B=w.metadata.section;Q.set(B,[...Q.get(B)??[],w])}return[...Q.entries()].map(([w,B])=>({section:w,docs:B}))}function Ag(A){return`/docs/${A.metadata.slug}`}function xX0(A){return`section-${A+1}`}function Qg(A){return O3w[A]??String(A+1)}var j02="text-[var(--docs-text)] font-bold",M02="text-[var(--docs-accent)] font-bold",_02="text-[var(--docs-text-muted)]",x3w="docs-font-label text-xs uppercase tracking-[0.18em] text-[var(--docs-accent)]",R3w="docs-font-display text-[var(--docs-heading)]",L02="inline-flex items-center justify-center rounded-lg border px-[18px] py-2.5 text-sm font-semibold transition-colors duration-150",N02="relative hidden py-1 text-[15px] text-[var(--docs-text-muted)] transition-colors duration-150 after:absolute after:bottom-0 after:left-0 after:h-px after:w-0 after:bg-[var(--docs-accent)] after:transition-[width] after:duration-300 hover:text-[var(--docs-text)] hover:after:w-full min-[861px]:inline-block",Mo0="docs-font-label text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:text-[var(--docs-text)]",Qz={wrap:"mx-auto max-w-6xl px-6 pt-20 md:px-12 md:pt-24",label:x3w,display:R3w,button:`${L02} border-[var(--docs-text)] text-[var(--docs-text)] hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)]`,primaryButton:`${L02} border-[var(--docs-accent)] bg-[var(--docs-accent)] text-white hover:bg-transparent hover:text-[var(--docs-accent)]`},P02=()=>x$("nav",{className:"docs-header fixed inset-x-0 top-0 z-[100] flex items-center justify-between px-6 py-4 md:px-10 md:py-5 xl:px-20",children:[x$("a",{href:"/docs",className:"docs-font-body text-xl font-bold","aria-label":"Brains docs",children:[x$("span",{className:j02,children:"brains"},void 0,!1,void 0,this),x$("span",{className:M02,children:"."},void 0,!1,void 0,this),x$("span",{className:_02,children:"docs"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x$("div",{className:"docs-header__nav flex items-center gap-4 md:gap-8",children:[x$("a",{className:N02,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:N02,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),x$("a",{href:"https://rizom.ai",className:"inline-flex items-center justify-center rounded-lg border border-[var(--docs-text)] px-4 py-2 text-[13px] font-semibold text-[var(--docs-text)] transition-colors duration-150 hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)] md:px-6 md:py-2.5 md:text-[15px]",children:"Get Brains"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),k02=()=>x$("footer",{className:"flex flex-col items-center justify-between gap-4 border-t border-[var(--docs-border-light)] py-8 text-center md:flex-row md:gap-6 md:py-6 md:text-left",children:[x$("a",{href:"https://rizom.ai",className:"docs-font-body text-[15px] font-bold",children:[x$("span",{className:j02,children:"rizom"},void 0,!1,void 0,this),x$("span",{className:M02,children:"."},void 0,!1,void 0,this),x$("span",{className:_02,children:"ai"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x$("div",{className:"flex flex-wrap items-center justify-center gap-6 md:justify-end",children:[x$("a",{className:Mo0,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:Mo0,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),x$("a",{className:Mo0,href:"https://rizom.ai",children:"Rizom"},void 0,!1,void 0,this),x$("button",{id:"themeToggle",className:"docs-font-label cursor-pointer rounded-md border border-[var(--docs-text-light)] bg-transparent px-2.5 py-1.5 text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:border-[var(--docs-text)] hover:text-[var(--docs-text)]",type:"button",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h3w=`
11686
11686
  .docs-handbook {
11687
11687
  --docs-bg: var(--color-bg, #0d0a1a);
11688
11688
  --docs-bg-card: var(--color-bg-card, #1a0a3e);
@@ -11834,7 +11834,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});Z0();var y
11834
11834
  background: transparent;
11835
11835
  }
11836
11836
 
11837
- `,O02=()=>x$("style",{children:h3w},void 0,!1,void 0,this);import{jsxDEV as F2,Fragment as v3w}from"preact/jsx-dev-runtime";var RX0=({title:A,description:Q,children:w,detail:B=!1,footer:$=!1,contentClassName:Y=""})=>F2(v3w,{children:[F2(jQ,{title:A,description:Q},void 0,!1,void 0,this),F2(O02,{},void 0,!1,void 0,this),F2("div",{className:`docs-handbook${B?" docs-handbook--detail":""}`,children:[F2(P02,{},void 0,!1,void 0,this),F2("div",{className:`${Qz.wrap} ${Y}`.trim(),children:[w,$&&F2(k02,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x02=({docsCount:A,sectionsCount:Q,startDoc:w})=>F2("section",{className:"border-b border-[var(--docs-text)] py-14 md:py-24 md:pb-[72px]",children:[F2("p",{className:`${Qz.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),F2("h1",{className:`${Qz.display} m-0 max-w-[16ch] text-5xl leading-[1.05] tracking-[-0.02em] md:text-7xl`,children:["Build, run, and publish"," ",F2("em",{className:"text-[var(--docs-accent)]",children:"brains."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F2("p",{className:"mt-8 max-w-[52ch] text-lg leading-[1.65] text-[var(--docs-text-muted)]",children:"Documentation for composing brain models, managing markdown entities, wiring interfaces, and shipping generated sites."},void 0,!1,void 0,this),F2("dl",{className:"mt-10 flex flex-wrap gap-7 docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] md:mt-14 md:gap-12",children:[F2("div",{children:[F2("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:A},void 0,!1,void 0,this),"Documents"]},void 0,!0,void 0,this),F2("div",{children:[F2("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:Q},void 0,!1,void 0,this),"Sections"]},void 0,!0,void 0,this),F2("div",{children:[F2("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:"April 2026"},void 0,!1,void 0,this),"Updated"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),F2("div",{className:"mt-9 flex flex-wrap gap-3.5",children:[w&&F2("a",{className:Qz.primaryButton,href:Ag(w),children:"Start reading"},void 0,!1,void 0,this),F2("a",{className:Qz.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),R02=({groups:A})=>F2("aside",{className:"docs-rail sticky top-8 hidden docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] min-[861px]:block","aria-label":"Documentation sections",children:[F2("p",{className:"m-0 mb-3.5 font-medium text-[var(--docs-text)]",children:"Sections"},void 0,!1,void 0,this),F2("ol",{className:"m-0 list-none p-0",children:A.map((Q,w)=>F2("li",{className:"grid grid-cols-[32px_1fr] gap-2 py-1.5",children:[F2("span",{className:"docs-font-display text-[var(--docs-text-light)] italic",children:[Qg(w),"."]},void 0,!0,void 0,this),F2("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:`#${xX0(w)}`,children:Q.section},void 0,!1,void 0,this)]},Q.section,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h02=({group:A,index:Q})=>F2("article",{className:"mb-16 last:mb-0",id:xX0(Q),children:[F2("header",{className:"mb-2 grid grid-cols-[36px_auto_1fr] items-baseline gap-x-3 border-b border-[var(--docs-border)] pb-3.5 md:grid-cols-[48px_auto_1fr] md:gap-x-5",children:[F2("span",{className:"text-right docs-font-display text-3xl leading-[1.1] text-[var(--docs-accent)] italic md:text-4xl",children:[Qg(Q),"."]},void 0,!0,void 0,this),F2("h2",{className:`${Qz.display} m-0 text-3xl leading-[1.1] tracking-[-0.015em] md:text-4xl`,children:A.section},void 0,!1,void 0,this),F2("span",{className:"docs-chapter__leader"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F2("ol",{className:"m-0 list-none p-0",children:A.docs.map((w)=>F2("li",{className:"border-b border-[var(--docs-border-light)] last:border-b-0",children:F2("a",{className:"group block py-[18px] pl-12 md:pl-[68px]",href:Ag(w),children:[F2("p",{className:"m-0 text-[22px] leading-[1.2] tracking-[-0.005em] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:w.metadata.title},void 0,!1,void 0,this),w.metadata.description&&F2("p",{className:"mt-1.5 mb-0 max-w-[70ch] text-sm leading-[1.55] text-[var(--docs-text-muted)]",children:w.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},w.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v02=({title:A})=>F2("nav",{className:"mb-8 flex flex-wrap items-baseline gap-2.5 docs-font-label text-[11px] uppercase tracking-[0.06em] text-[var(--docs-text-light)]","aria-label":"Breadcrumb",children:[F2("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/",children:"Home"},void 0,!1,void 0,this),F2("span",{children:"/"},void 0,!1,void 0,this),F2("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/docs",children:"Docs"},void 0,!1,void 0,this),F2("span",{children:"/"},void 0,!1,void 0,this),F2("span",{children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C02=({groups:A,activeGroupIndex:Q,activeSlug:w})=>F2("aside",{className:"docs-detail-rail sticky top-24 hidden max-h-[calc(100vh-120px)] overflow-auto pr-2 min-[861px]:block","aria-label":"Documentation navigation",children:F2("nav",{className:"docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)]",children:[F2("p",{className:"m-0 mb-4 border-b border-[var(--docs-text)] pb-3 text-[11px] uppercase tracking-[0.08em] text-[var(--docs-text-light)]",children:"Documentation"},void 0,!1,void 0,this),F2("ol",{className:"m-0 list-none p-0",children:A.map((B,$)=>{let Y=$===Q;return F2("li",{className:Y?"mb-[22px]":"mb-3.5",children:[F2("a",{className:`mb-2 flex items-baseline gap-2.5 docs-font-label text-[11px] uppercase leading-[1.4] tracking-[0.06em] transition-colors duration-150 hover:text-[var(--docs-text)] ${Y?"text-[var(--docs-text)]":"text-[var(--docs-text-muted)]"}`,href:`/docs#${xX0($)}`,children:[F2("span",{className:"docs-font-display text-sm text-[var(--docs-accent)] italic",children:[Qg($),"."]},void 0,!0,void 0,this)," ",B.section]},void 0,!0,void 0,this),Y&&F2("ol",{className:"mt-0.5 list-none p-0",children:B.docs.map((D)=>{let X=D.metadata.slug===w;return F2("li",{children:F2("a",{className:`docs-rail__doc relative block py-1.5 docs-font-body text-sm leading-[1.4] tracking-normal transition-[color,padding-left] duration-150 hover:text-[var(--docs-text)] ${X?"pl-3.5 font-medium text-[var(--docs-accent)]":"text-[var(--docs-text-muted)]"}`,href:Ag(D),"aria-current":X?"page":void 0,children:D.metadata.title},void 0,!1,void 0,this)},D.id,!1,void 0,this)})},void 0,!1,void 0,this)]},B.section,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y02=({prevDoc:A,nextDoc:Q})=>{if(!A&&!Q)return null;return F2("nav",{className:"mt-12 grid grid-cols-1 gap-5 border-t border-[var(--docs-border)] pt-7 md:grid-cols-2","aria-label":"Previous and next docs",children:[A?F2("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] transition-colors duration-150 hover:border-[var(--docs-accent)]",href:Ag(A),children:[F2("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Previous"},void 0,!1,void 0,this),F2("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:["\u2190 ",A.metadata.title]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):F2("span",{},void 0,!1,void 0,this),Q&&F2("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] text-left transition-colors duration-150 hover:border-[var(--docs-accent)] md:text-right",href:Ag(Q),children:[F2("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Next"},void 0,!1,void 0,this),F2("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:[Q.metadata.title," \u2192"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as wg}from"preact/jsx-dev-runtime";var _o0=({docs:A})=>{let Q=to(A),w=OX0(Q),$=Q.filter((Y)=>Y.metadata.slug!=="index")[0]??Q[0];return wg(RX0,{title:"Documentation",description:"Brains documentation",children:[wg(x02,{docsCount:A.length,sectionsCount:w.length,startDoc:$},void 0,!1,void 0,this),wg("section",{className:"grid items-start gap-10 py-12 md:grid-cols-[200px_minmax(0,1fr)] md:gap-20 md:py-20 md:pb-[120px]",id:"sections",children:[wg(R02,{groups:w},void 0,!1,void 0,this),wg("div",{children:w.map((Y,D)=>wg(h02,{group:Y,index:D},Y.section,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as yH}from"preact/jsx-dev-runtime";var Po0=({doc:A,docs:Q,prevDoc:w,nextDoc:B})=>{let $=OX0(Q.length>0?Q:[A]),Y=to(Q.length>0?Q:[A]),D=Y.findIndex((H)=>H.metadata.slug===A.metadata.slug),X=Math.max($.findIndex((H)=>H.docs.some((W)=>W.metadata.slug===A.metadata.slug)),0);return yH(RX0,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[yH(v02,{title:A.metadata.title},void 0,!1,void 0,this),yH("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[yH(C02,{groups:$,activeGroupIndex:X,activeSlug:A.metadata.slug},void 0,!1,void 0,this),yH("article",{className:"min-w-0",children:[yH("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[yH("p",{className:`${Qz.label} m-0 mb-6 flex items-baseline gap-3`,children:[yH("span",{className:"docs-font-display text-lg leading-none tracking-normal normal-case text-[var(--docs-accent)] italic",children:[Qg(X),"."]},void 0,!0,void 0,this)," ",A.metadata.section,D>=0?` \xB7 ${D+1}/${Y.length}`:""]},void 0,!0,void 0,this),yH("h1",{className:`${Qz.display} m-0 max-w-[18ch] text-4xl leading-[1.05] tracking-[-0.02em] md:text-6xl`,children:A.metadata.title},void 0,!1,void 0,this),A.metadata.description&&yH("p",{className:"mt-6 max-w-[56ch] docs-font-display text-[22px] font-[350] leading-[1.5] text-[var(--docs-text-muted)]",children:A.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),yH("div",{className:"docs-article__body",children:yH($9,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),yH(y02,{prevDoc:w,nextDoc:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};var C3w=K.object({docs:K.array(MF),pagination:e7.nullable(),baseUrl:K.string().optional()}),y3w=K.object({doc:MF,docs:K.array(MF),prevDoc:MF.nullable(),nextDoc:MF.nullable()});function E02(){return{"doc-list":R1({name:"doc-list",description:"Documentation index template",schema:C3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:_o0}}),"doc-detail":R1({name:"doc-detail",description:"Documentation page template",schema:y3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:Po0}})}}var g02={name:"@brains/doc",private:!0,version:"0.2.0-alpha.135",description:"Documentation entity type \u2014 markdown docs as first-class brain content",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};class ko0 extends kQ{entityType=PX0.entityType;schema=eE;adapter=PX0;constructor(){super("docs",g02,{},void 0)}getTemplates(){return E02()}getDataSources(){return[new kX0(this.logger.child("DocDataSource"))]}}function Oo0(){return new ko0}c0();Z0();Z0();l$();var T02=K.object({label:K.string(),href:K.string()}),S02=K.object({label:K.string(),title:K.string(),detail:K.string()}),g3w=K.object({eyebrow:K.string(),name:K.string(),sub:K.string()}),T3w=K.object({tone:K.enum(["capture","synthesis","share"]),title:K.string(),text:K.string()}),xo0=K.object({captures:K.number(),links:K.number(),topics:K.number(),summaries:K.number(),peers:K.number()}),Bg=K.object({eyebrow:K.string(),headline:K.string(),intro:K.string(),primaryCta:T02,secondaryCta:T02,inputs:K.array(S02).min(1),outputs:K.array(S02).min(1),core:g3w,legend:K.array(T3w).min(1)}),Ro0=Bg.extend({counts:xo0}),m02={eyebrow:"A team brain, diagrammed",headline:"Relay sits between the work and the world, and keeps both honest.",intro:"Capture sources flow into a shared brain; the brain organizes, summarizes, and \u2014 selectively \u2014 exposes a public surface. Everything else stays private and operational.",primaryCta:{label:"See it on a real team",href:"#diagram"},secondaryCta:{label:"Read the model",href:"/about"},inputs:[{label:"Source \xB7 chat",title:"Discord",detail:"Shared decisions and field notes captured in flow."},{label:"Source \xB7 agent",title:"MCP / CLI",detail:"Structured captures from tools and assistants."},{label:"Source \xB7 web",title:"Links & docs",detail:"External material indexed with sourceable metadata."}],outputs:[{label:"Surface \xB7 public",title:"Default site",detail:"A small, durable face onto what the team currently knows."},{label:"Surface \xB7 agents",title:"A2A exchange",detail:"Peer brains coordinate over an approved, signed protocol."},{label:"Surface \xB7 query",title:"Team Q&A",detail:"Ask the brain in chat; answers cite the captures behind them."}],core:{eyebrow:"The relay",name:"brain",sub:"capture \u2192 topics \u2192 summaries"},legend:[{tone:"capture",title:"Capture",text:"Anything the team already does that produces a trace \u2014 chat messages, links, deploys, decisions."},{tone:"synthesis",title:"Synthesis",text:"The work the brain does on its own time \u2014 clustering captures into topics, summaries, and durable memory."},{tone:"share",title:"Share",text:"A small, opinionated public surface and an approved agent-to-agent protocol. Most memory stays private."}]},u02=new pw(Bg,{title:"Home diagram",mappings:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"headline",label:"Headline",type:"string"},{key:"intro",label:"Intro",type:"string"},{key:"primaryCta",label:"Primary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"secondaryCta",label:"Secondary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"inputs",label:"Inputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"outputs",label:"Outputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"core",label:"Core",type:"object",children:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"name",label:"Name",type:"string"},{key:"sub",label:"Sub",type:"string"}]},{key:"legend",label:"Legend",type:"array",itemType:"object",itemMappings:[{key:"tone",label:"Tone",type:"string"},{key:"title",label:"Title",type:"string"},{key:"text",label:"Text",type:"string"}]}]});function hX0(A){return u02.parse(A)}function c02(A){return u02.format(A)}Z0();var S3w=K.object({query:K.object({routeId:K.string().default("home"),sectionId:K.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}).passthrough(),m3w={captures:"note",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class ho0{id="relay-site:home-counts";name="Relay homepage counts";description="Fetches Relay homepage content and live entity counts for the system diagram";async fetch(A,Q,w){let B=S3w.parse(A??{}),$=await this.fetchContent(w,B.query.routeId,B.query.sectionId),Y=await this.fetchCounts(w);return Q.parse({...$,counts:Y})}async fetchContent(A,Q,w){let B=await A.entityService.getEntity({entityType:"site-content",id:`${Q}:${w}`});if(!B?.content)return m02;return Bg.parse(hX0(B.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(m3w).map(async([w,B])=>[w,await this.countOrZero(A,B)]));return xo0.parse(Object.fromEntries(Q))}async countOrZero(A,Q){if(!A.entityService.hasEntityType(Q))return 0;try{return await A.entityService.countEntities({entityType:Q})}catch{return 0}}}import{jsxDEV as $1}from"preact/jsx-dev-runtime";var l02=K.object({label:K.string(),href:K.string()}),u3w=K.object({eyebrow:K.string(),headline:K.string(),intro:K.string(),primaryCta:l02,secondaryCta:l02,signals:K.array(K.object({label:K.string(),value:K.string(),note:K.string()}))}),c3w=K.object({eyebrow:K.string(),title:K.string(),intro:K.string(),steps:K.array(K.object({phase:K.string(),title:K.string(),text:K.string()}))}),l3w=K.object({title:K.string(),intro:K.string(),cards:K.array(K.object({label:K.string(),title:K.string(),text:K.string()}))}),p3w=K.object({title:K.string(),intro:K.string(),points:K.array(K.string())}),i3w={title:"Relay is a collaborative team-memory brain.",intro:"It exists for teams that need to remember together: capturing what happened, summarizing why it matters, and coordinating with trusted peer brains when work crosses boundaries.",points:["Not a personal blog engine or portfolio shell.","Not a marketing automation stack.","A small public face for a larger private knowledge workflow."]},d3w="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function p02({href:A,label:Q}){return $1("a",{href:A,className:d3w,children:Q},void 0,!1,void 0,this)}function n3w({siteInfo:A,children:Q}){let w=[...A.navigation.primary,...A.navigation.secondary],B=A.cta??{buttonText:"Start here",buttonLink:"/about"};return $1(cE,{children:[$1("nav",{className:"fixed left-0 right-0 top-0 z-[100] flex items-center justify-between border-b border-theme-light bg-nav-fade px-6 py-4 backdrop-blur-[12px] md:px-10 xl:px-20",children:[$1("a",{href:"/",className:"font-nav text-[20px]","aria-label":"Relay home",children:[$1("span",{className:"font-bold text-theme",children:"relay"},void 0,!1,void 0,this),$1("span",{className:"font-bold text-accent",children:"."},void 0,!1,void 0,this),$1("span",{className:"text-theme-muted",children:"brain"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"flex items-center gap-5 md:gap-8",children:[$1("div",{className:"hidden items-center gap-6 md:flex",children:w.map(($)=>$1(p02,{...$},`${$.href}-${$.label}`,!1,void 0,this))},void 0,!1,void 0,this),$1("a",{href:B.buttonLink,className:"rounded-[999px] border border-theme px-4 py-2 font-body text-[13px] font-semibold text-theme transition-colors hover:border-accent hover:text-accent md:px-5",children:B.buttonText},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("main",{children:Q},void 0,!1,void 0,this),$1("footer",{className:"relative z-[1] border-t border-theme-light px-6 py-8 md:px-10 xl:px-20",children:$1("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[$1("div",{children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.22em] text-theme-light",children:A.copyright},void 0,!1,void 0,this),$1("p",{className:"mt-2 max-w-[560px] font-body text-body-xs text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"flex flex-wrap items-center gap-5",children:[w.map(($)=>$1(p02,{...$},`footer-${$.href}-${$.label}`,!1,void 0,this)),$1("button",{id:"themeToggle","aria-label":"Toggle light mode",className:"rounded-md border border-theme-light bg-transparent px-2.5 py-1.5 font-body text-label-md text-theme-light transition-colors hover:border-theme hover:text-theme",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var r3w=({sections:A,siteInfo:Q})=>$1(n3w,{siteInfo:Q,children:A},void 0,!1,void 0,this);function o3w({eyebrow:A,headline:Q,intro:w,primaryCta:B,secondaryCta:$,signals:Y}){return $1(cb,{className:"min-h-[92vh] pt-[152px] pb-20 md:pt-[190px]",children:$1("div",{className:"grid gap-10 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-end",children:[$1("div",{children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),$1("h1",{className:"mt-7 max-w-[980px] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),$1("p",{className:"mt-7 max-w-[720px] font-body text-body-lg text-theme-muted",children:w},void 0,!1,void 0,this),$1("div",{className:"mt-10 flex flex-col gap-3 sm:flex-row",children:[$1(gP,{href:B.href,size:"lg",variant:"primary-strong",children:B.label},void 0,!1,void 0,this),$1(gP,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"rounded-[32px] border border-card-relay-border bg-card-relay-bg p-5 shadow-[0_24px_90px_var(--color-glow-relay)] backdrop-blur-sm",children:[$1("p",{className:"font-label text-label-xs uppercase tracking-[0.24em] text-theme-light",children:"Live relay signals"},void 0,!1,void 0,this),$1("div",{className:"mt-5 grid gap-3",children:Y.map((D)=>$1("div",{className:"rounded-[22px] border border-card-divider bg-bg-muted p-5",children:[$1("div",{className:"flex items-center justify-between gap-4",children:[$1("p",{className:"font-label text-label-xs uppercase tracking-[0.18em] text-secondary",children:D.label},void 0,!1,void 0,this),$1("span",{className:"h-2 w-2 rounded-full bg-accent shadow-[0_0_22px_var(--color-accent)]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("p",{className:"mt-4 font-display text-display-sm text-theme",children:D.value},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-body text-body-xs text-theme-muted",children:D.note},void 0,!1,void 0,this)]},D.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function s3w({eyebrow:A,title:Q,intro:w,steps:B}){return $1(cb,{id:"operating-loop",className:"py-section",children:[$1("div",{className:"max-w-[840px]",children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-secondary",children:A},void 0,!1,void 0,this),$1("h2",{className:"mt-5 font-display text-display-md text-theme",children:Q},void 0,!1,void 0,this),$1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:B.map(($)=>$1("article",{className:"min-h-[300px] rounded-[28px] border border-card-panel-border bg-card-panel-bg p-6",children:[$1("p",{className:"font-label text-label-sm text-accent",children:$.phase},void 0,!1,void 0,this),$1("h3",{className:"mt-16 font-display text-display-sm text-theme",children:$.title},void 0,!1,void 0,this),$1("p",{className:"mt-4 font-body text-body-sm text-theme-muted",children:$.text},void 0,!1,void 0,this)]},$.phase,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function a3w({title:A,intro:Q,cards:w}){return $1(cb,{className:"py-section",children:$1("div",{className:"rounded-[36px] border border-theme-light bg-bg-muted p-6 md:p-10",children:$1("div",{className:"grid gap-8 lg:grid-cols-[360px_1fr]",children:[$1("div",{children:[$1("h2",{className:"font-display text-display-md text-theme",children:A},void 0,!1,void 0,this),$1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"grid gap-4",children:w.map((B)=>$1("article",{className:"rounded-[24px] border border-card-divider bg-bg-subtle/70 p-5",children:[$1("p",{className:"font-label text-label-xs uppercase tracking-[0.22em] text-accent",children:B.label},void 0,!1,void 0,this),$1("h3",{className:"mt-3 font-nav text-heading-lg text-theme",children:B.title},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-body text-body-sm text-theme-muted",children:B.text},void 0,!1,void 0,this)]},B.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function t3w({title:A,intro:Q,points:w}){return $1(cb,{className:"min-h-[78vh] pt-[150px] pb-section md:pt-[190px]",children:[$1("div",{className:"max-w-[920px]",children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:"Relay model"},void 0,!1,void 0,this),$1("h1",{className:"mt-6 font-display text-display-lg text-theme",children:A},void 0,!1,void 0,this),$1("p",{className:"mt-7 font-body text-body-lg text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:w.map((B)=>$1("div",{className:"rounded-[24px] border border-card-panel-current-border bg-card-panel-current-bg p-6 font-body text-body-md text-theme",children:B},B,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var e3w=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},AFw=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),eo=(A,Q,w=`${Q}s`)=>`${AFw(A)} ${A===1?Q:w}`;function QFw({eyebrow:A,headline:Q,intro:w,primaryCta:B,secondaryCta:$,inputs:Y,outputs:D,core:X,legend:H,counts:W}){let f=[{key:"captures",className:"top-[-10px] left-1/2 -translate-x-1/2",label:eo(W.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:eo(W.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:eo(W.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:eo(W.summaries,"summary","summaries")}];return $1(cb,{className:"pt-[150px] pb-section md:pt-[190px]",id:"diagram",children:[$1("div",{className:"mx-auto max-w-[1040px] text-center",children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),$1("h1",{className:"mx-auto mt-7 max-w-[22ch] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),$1("p",{className:"mx-auto mt-7 max-w-[64ch] font-body text-body-lg text-theme-muted",children:w},void 0,!1,void 0,this),$1("div",{className:"mt-10 flex flex-col justify-center gap-3 sm:flex-row",children:[$1(gP,{href:B.href,size:"lg",variant:"primary-strong",children:B.label},void 0,!1,void 0,this),$1(gP,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mx-auto mt-20 max-w-[1020px] rounded-[32px] border border-theme-light bg-[radial-gradient(circle_at_1px_1px,rgb(255_255_255_/_0.05)_1px,transparent_0),linear-gradient(180deg,rgb(255_255_255_/_0.02),transparent)] bg-[length:24px_24px,100%_100%] px-6 py-14",children:[$1("div",{className:"grid items-center gap-8 lg:grid-cols-[1fr_1.4fr_1fr]",children:[$1("div",{className:"flex flex-col gap-3.5",children:Y.map((Z)=>$1("div",{className:"rounded-2xl border border-card-panel-border border-l-2 border-l-accent bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[$1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:Z.label},void 0,!1,void 0,this),$1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:Z.title},void 0,!1,void 0,this),$1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:Z.detail},void 0,!1,void 0,this)]},`${Z.label}-${Z.title}`,!0,void 0,this))},void 0,!1,void 0,this),$1("div",{className:"relative mx-auto grid aspect-square w-full max-w-[320px] place-items-center rounded-full bg-[radial-gradient(circle_at_center,rgb(232_119_34_/_0.25),transparent_65%)]",children:[$1("div",{className:"absolute inset-0 rounded-full border border-dashed border-accent/30"},void 0,!1,void 0,this),$1("div",{className:"absolute inset-6 animate-spin rounded-full border border-dashed border-secondary/40 [animation-duration:28s]"},void 0,!1,void 0,this),f.map((Z)=>$1("span",{className:`absolute whitespace-nowrap rounded-full border border-theme bg-bg px-2.5 py-1 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light ${Z.className}`,children:Z.label},Z.key,!1,void 0,this)),$1("div",{className:"relative z-[1] px-6 text-center",children:[$1("p",{className:"font-label text-[10px] uppercase tracking-[0.28em] text-accent",children:X.eyebrow},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-display text-[36px] leading-none text-theme",children:X.name},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-body text-[13px] text-theme-muted",children:X.sub},void 0,!1,void 0,this),$1("p",{className:"mt-4 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light",children:[eo(W.links,"link")," indexed"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"flex flex-col gap-3.5",children:D.map((Z)=>$1("div",{className:"rounded-2xl border border-card-panel-border border-r-2 border-r-secondary bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[$1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:Z.label},void 0,!1,void 0,this),$1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:Z.title},void 0,!1,void 0,this),$1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:Z.detail},void 0,!1,void 0,this)]},`${Z.label}-${Z.title}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mt-14 grid gap-4 border-t border-theme-light pt-8 md:grid-cols-3",children:H.map((Z)=>$1("div",{className:"text-left",children:[$1("h2",{className:"font-display text-[16px] font-medium text-theme",children:[$1("span",{className:`mr-2.5 inline-block h-3 w-3 rounded-[3px] align-middle ${e3w(Z.tone)}`},void 0,!1,void 0,this),Z.title]},void 0,!0,void 0,this),$1("p",{className:"mt-1.5 font-body text-[13px] leading-[1.6] text-theme-muted",children:Z.text},void 0,!1,void 0,this)]},Z.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var wFw=R1({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:Ro0,formatter:{parse:(A)=>Ro0.parse({...hX0(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>c02(Bg.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:QFw}}),BFw=(A)=>o3w(u3w.parse(A)),$Fw=(A)=>s3w(c3w.parse(A)),YFw=(A)=>a3w(l3w.parse(A)),DFw=(A)=>t3w(p3w.parse(A)),i02={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},d02={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:BFw,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...i02,label:"Primary CTA"},secondaryCta:{...i02,label:"Secondary CTA"},signals:{type:"array",label:"Signals",minItems:1,items:{type:"object",label:"Signal",fields:{label:{type:"string",label:"Label"},value:{type:"string",label:"Value"},note:{type:"string",label:"Note"}}}}}},"home-loop":{title:"Home operating loop",description:"Relay capture, synthesis, and sharing loop",layout:$Fw,fields:{eyebrow:{type:"string",label:"Eyebrow"},title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},steps:{type:"array",label:"Steps",minItems:1,items:{type:"object",label:"Step",fields:{phase:{type:"string",label:"Phase"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},"home-surface":{title:"Home surface",description:"Relay default template explanation cards",layout:YFw,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},cards:{type:"array",label:"Cards",minItems:1,items:{type:"object",label:"Card",fields:{label:{type:"string",label:"Label"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},about:{title:"About Relay",description:"Default Relay about page",layout:DFw,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},XFw=[{id:"home",path:"/",title:"Relay",description:"Collaborative team memory and synthesis brain",layout:"default",navigation:{show:!0,label:"Home",slot:"secondary",priority:10},sections:[{id:"diagram",template:"relay-site:home-diagram"}]},{id:"about",path:"/about",title:"About Relay",description:"What Relay is designed to do",layout:"default",navigation:{show:!0,label:"About",slot:"primary",priority:20},sections:[{id:"about",template:"relay-site:about",content:i3w}]}],n02=fo0({packageName:"@brains/relay/site",contentNamespace:"relay-site",themeProfile:"studio",layout:r3w,routes:XFw,templates:{"home-diagram":wFw},dataSources:[new ho0]});var r02={name:"@brains/relay",private:!0,version:"0.2.0-alpha.135",description:"Relay brain model \u2014 collaborative knowledge management",type:"module",files:["src","brain.eval.yaml","env.schema.template"],exports:{".":"./src/index.ts"},scripts:{"build:web-chat":"turbo run build --filter=@brains/web-chat","start:core":"bun run build:web-chat && cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"bun run build:web-chat && cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"bun run build:web-chat && cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:docs":"bun run build:web-chat && cd test-apps/docs && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",test:"bun test",eval:"brain-eval",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/auth-service":"workspace:*","@brains/cms":"workspace:*","@brains/content-formatters":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/doc":"workspace:*","@brains/email-resend":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-info":"workspace:*","@brains/site-rizom":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var o02=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","web-chat","discord","a2a"],s02=[...o02,"image","site-info","site-content","site-builder"],fFw=[...s02,"docs","decks"],ZFw=["Relay is a collaborative team-memory and synthesis brain. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence, and coordinating with peer brains.","Relay is not Rover-for-teams: do not default to personal branding, blog publishing, newsletters, social media, portfolio, or marketing workflows unless the installed plugins and user request explicitly support them."],a02=LJ({name:"relay",version:r02.version,model:"gpt-5.4-mini",site:n02,theme:lE,presets:{core:o02,default:s02,full:fFw},evalDisable:["webserver","web-chat","mcp","discord"],agentInstructions:ZFw,capabilities:[["prompt",vP,void 0],["note",LP,{}],["link",jP,{}],["image",Gc,void 0],["topics",lY0,{includeEntityTypes:["note","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",No0,{memoryVisibility:"shared"}],["docs",Oo0,void 0],["decks",_r,void 0],["agents",yD0,void 0],["assessment",iD0,void 0],["auth-service",Yp,void 0],["notifications",sw0,void 0],["email-resend",l$0,void 0],["cms",xP,{}],["dashboard",Sb,void 0],["directory-sync",M_,{seedContent:!0,seedContentPath:WFw(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",lo,{definitions:d02}],["rizom-ecosystem",CP,void 0],["site-info",fP,void 0],["site-builder",WP,{}]],interfaces:[["mcp",BI,()=>({})],["discord",uI,()=>({captureUrls:!0})],["a2a",mC,()=>({})],["webserver",iI,()=>({})],["web-chat",SC,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"anchor"},{pattern:"discord:*",level:"public"},{pattern:"web-chat:*",level:"anchor"}],entityActions:{note:{create:"trusted",update:"trusted",delete:"anchor"},link:{create:"trusted",update:"trusted",delete:"anchor"},doc:{create:"trusted",update:"trusted",delete:"anchor"},deck:{create:"trusted",update:"trusted",delete:"anchor"},decision:{create:"trusted",update:"trusted",delete:"anchor"},"action-item":{create:"trusted",update:"trusted",delete:"anchor"},image:{create:"trusted",update:"trusted",delete:"anchor"}}},deployment:{cdn:{enabled:!0,provider:"bunny"}}});import{readFileSync as pIw}from"fs";import{join as iIw}from"path";import{execSync as dIw}from"child_process";import{parseArgs as GFw}from"util";var zFw={model:{type:"string"},domain:{type:"string"},"content-repo":{type:"string"},backend:{type:"string"},"push-to":{type:"string"},"ai-api-key":{type:"string"},"no-interactive":{type:"boolean"},preview:{type:"boolean"},deploy:{type:"boolean"},regen:{type:"boolean"},all:{type:"boolean"},only:{type:"string"},"dry-run":{type:"boolean"},"startup-check":{type:"boolean"},"storage-dir":{type:"string"},yes:{type:"boolean"},remote:{type:"string"},token:{type:"string"},outputDir:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};function _K(A,Q){let w=A[Q];return typeof w==="string"?w:void 0}function ib(A,Q){let w=A[Q];return typeof w==="boolean"?w:void 0}function t02(A){let{values:Q,positionals:w}=GFw({args:A,options:zFw,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:w[0]??"help",args:w.slice(1),flags:{model:_K(Q,"model"),domain:_K(Q,"domain"),"content-repo":_K(Q,"content-repo"),backend:_K(Q,"backend"),"push-to":_K(Q,"push-to"),"ai-api-key":_K(Q,"ai-api-key"),"no-interactive":ib(Q,"no-interactive"),preview:ib(Q,"preview"),deploy:ib(Q,"deploy"),regen:ib(Q,"regen"),all:ib(Q,"all"),only:_K(Q,"only"),"dry-run":ib(Q,"dry-run"),"startup-check":ib(Q,"startup-check"),"storage-dir":_K(Q,"storage-dir"),yes:ib(Q,"yes"),remote:_K(Q,"remote"),token:_K(Q,"token"),outputDir:_K(Q,"outputDir")}}}As();import{mkdirSync as CIw}from"fs";import{join as yIw}from"path";import{execSync as EIw}from"child_process";var CX0={name:"@rizom/brain",version:"0.2.0-alpha.135",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun scripts/build.ts","dev:start":"bun scripts/build.ts && bun dist/brain.js start",typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@clack/prompts":"^0.11.0","@modelcontextprotocol/sdk":"^1.24.0","@tailwindcss/postcss":"^4.1.13","@tailwindcss/typography":"^0.5.19",postcss:"^8.5.6",preact:"^10.27.2","preact-render-to-string":"^6.3.1",tailwindcss:"^4.1.11"},optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","playwright-core":"^1.56.0","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"workspace:*","@brains/content-formatters":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"latest",rollup:"^4.60.2","rollup-plugin-dts":"^6.4.1",typescript:"^5.3.3"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",bugs:"https://github.com/rizom-ai/brains/issues",engines:{bun:">=1.3.3"},keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"]};import{mkdirSync as UA2,writeFileSync as ws,chmodSync as Bs,existsSync as co0,readFileSync as lo0}from"fs";import{basename as po0,dirname as io0,join as L6,resolve as oFw}from"path";import{fileURLToPath as sFw}from"url";var e02=`ARG BUN_VERSION=1.3.10
11837
+ `,O02=()=>x$("style",{children:h3w},void 0,!1,void 0,this);import{jsxDEV as F2,Fragment as v3w}from"preact/jsx-dev-runtime";var RX0=({title:A,description:Q,children:w,detail:B=!1,footer:$=!1,contentClassName:Y=""})=>F2(v3w,{children:[F2(jQ,{title:A,description:Q},void 0,!1,void 0,this),F2(O02,{},void 0,!1,void 0,this),F2("div",{className:`docs-handbook${B?" docs-handbook--detail":""}`,children:[F2(P02,{},void 0,!1,void 0,this),F2("div",{className:`${Qz.wrap} ${Y}`.trim(),children:[w,$&&F2(k02,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x02=({docsCount:A,sectionsCount:Q,startDoc:w})=>F2("section",{className:"border-b border-[var(--docs-text)] py-14 md:py-24 md:pb-[72px]",children:[F2("p",{className:`${Qz.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),F2("h1",{className:`${Qz.display} m-0 max-w-[16ch] text-5xl leading-[1.05] tracking-[-0.02em] md:text-7xl`,children:["Build, run, and publish"," ",F2("em",{className:"text-[var(--docs-accent)]",children:"brains."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F2("p",{className:"mt-8 max-w-[52ch] text-lg leading-[1.65] text-[var(--docs-text-muted)]",children:"Documentation for composing brain models, managing markdown entities, wiring interfaces, and shipping generated sites."},void 0,!1,void 0,this),F2("dl",{className:"mt-10 flex flex-wrap gap-7 docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] md:mt-14 md:gap-12",children:[F2("div",{children:[F2("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:A},void 0,!1,void 0,this),"Documents"]},void 0,!0,void 0,this),F2("div",{children:[F2("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:Q},void 0,!1,void 0,this),"Sections"]},void 0,!0,void 0,this),F2("div",{children:[F2("strong",{className:"mb-0.5 block font-medium text-[var(--docs-text)]",children:"April 2026"},void 0,!1,void 0,this),"Updated"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),F2("div",{className:"mt-9 flex flex-wrap gap-3.5",children:[w&&F2("a",{className:Qz.primaryButton,href:Ag(w),children:"Start reading"},void 0,!1,void 0,this),F2("a",{className:Qz.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),R02=({groups:A})=>F2("aside",{className:"docs-rail sticky top-8 hidden docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)] min-[861px]:block","aria-label":"Documentation sections",children:[F2("p",{className:"m-0 mb-3.5 font-medium text-[var(--docs-text)]",children:"Sections"},void 0,!1,void 0,this),F2("ol",{className:"m-0 list-none p-0",children:A.map((Q,w)=>F2("li",{className:"grid grid-cols-[32px_1fr] gap-2 py-1.5",children:[F2("span",{className:"docs-font-display text-[var(--docs-text-light)] italic",children:[Qg(w),"."]},void 0,!0,void 0,this),F2("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:`#${xX0(w)}`,children:Q.section},void 0,!1,void 0,this)]},Q.section,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h02=({group:A,index:Q})=>F2("article",{className:"mb-16 last:mb-0",id:xX0(Q),children:[F2("header",{className:"mb-2 grid grid-cols-[36px_auto_1fr] items-baseline gap-x-3 border-b border-[var(--docs-border)] pb-3.5 md:grid-cols-[48px_auto_1fr] md:gap-x-5",children:[F2("span",{className:"text-right docs-font-display text-3xl leading-[1.1] text-[var(--docs-accent)] italic md:text-4xl",children:[Qg(Q),"."]},void 0,!0,void 0,this),F2("h2",{className:`${Qz.display} m-0 text-3xl leading-[1.1] tracking-[-0.015em] md:text-4xl`,children:A.section},void 0,!1,void 0,this),F2("span",{className:"docs-chapter__leader"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F2("ol",{className:"m-0 list-none p-0",children:A.docs.map((w)=>F2("li",{className:"border-b border-[var(--docs-border-light)] last:border-b-0",children:F2("a",{className:"group block py-[18px] pl-12 md:pl-[68px]",href:Ag(w),children:[F2("p",{className:"m-0 text-[22px] leading-[1.2] tracking-[-0.005em] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:w.metadata.title},void 0,!1,void 0,this),w.metadata.description&&F2("p",{className:"mt-1.5 mb-0 max-w-[70ch] text-sm leading-[1.55] text-[var(--docs-text-muted)]",children:w.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},w.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v02=({title:A})=>F2("nav",{className:"mb-8 flex flex-wrap items-baseline gap-2.5 docs-font-label text-[11px] uppercase tracking-[0.06em] text-[var(--docs-text-light)]","aria-label":"Breadcrumb",children:[F2("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/",children:"Home"},void 0,!1,void 0,this),F2("span",{children:"/"},void 0,!1,void 0,this),F2("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/docs",children:"Docs"},void 0,!1,void 0,this),F2("span",{children:"/"},void 0,!1,void 0,this),F2("span",{children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C02=({groups:A,activeGroupIndex:Q,activeSlug:w})=>F2("aside",{className:"docs-detail-rail sticky top-24 hidden max-h-[calc(100vh-120px)] overflow-auto pr-2 min-[861px]:block","aria-label":"Documentation navigation",children:F2("nav",{className:"docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)]",children:[F2("p",{className:"m-0 mb-4 border-b border-[var(--docs-text)] pb-3 text-[11px] uppercase tracking-[0.08em] text-[var(--docs-text-light)]",children:"Documentation"},void 0,!1,void 0,this),F2("ol",{className:"m-0 list-none p-0",children:A.map((B,$)=>{let Y=$===Q;return F2("li",{className:Y?"mb-[22px]":"mb-3.5",children:[F2("a",{className:`mb-2 flex items-baseline gap-2.5 docs-font-label text-[11px] uppercase leading-[1.4] tracking-[0.06em] transition-colors duration-150 hover:text-[var(--docs-text)] ${Y?"text-[var(--docs-text)]":"text-[var(--docs-text-muted)]"}`,href:`/docs#${xX0($)}`,children:[F2("span",{className:"docs-font-display text-sm text-[var(--docs-accent)] italic",children:[Qg($),"."]},void 0,!0,void 0,this)," ",B.section]},void 0,!0,void 0,this),Y&&F2("ol",{className:"mt-0.5 list-none p-0",children:B.docs.map((D)=>{let X=D.metadata.slug===w;return F2("li",{children:F2("a",{className:`docs-rail__doc relative block py-1.5 docs-font-body text-sm leading-[1.4] tracking-normal transition-[color,padding-left] duration-150 hover:text-[var(--docs-text)] ${X?"pl-3.5 font-medium text-[var(--docs-accent)]":"text-[var(--docs-text-muted)]"}`,href:Ag(D),"aria-current":X?"page":void 0,children:D.metadata.title},void 0,!1,void 0,this)},D.id,!1,void 0,this)})},void 0,!1,void 0,this)]},B.section,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),y02=({prevDoc:A,nextDoc:Q})=>{if(!A&&!Q)return null;return F2("nav",{className:"mt-12 grid grid-cols-1 gap-5 border-t border-[var(--docs-border)] pt-7 md:grid-cols-2","aria-label":"Previous and next docs",children:[A?F2("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] transition-colors duration-150 hover:border-[var(--docs-accent)]",href:Ag(A),children:[F2("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Previous"},void 0,!1,void 0,this),F2("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:["\u2190 ",A.metadata.title]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):F2("span",{},void 0,!1,void 0,this),Q&&F2("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] text-left transition-colors duration-150 hover:border-[var(--docs-accent)] md:text-right",href:Ag(Q),children:[F2("span",{className:"block docs-font-label text-[10.5px] uppercase tracking-[0.22em] text-[var(--docs-text-light)]",children:"Next"},void 0,!1,void 0,this),F2("span",{className:"mt-2 block docs-font-display text-[22px] leading-[1.2] text-[var(--docs-heading)] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:[Q.metadata.title," \u2192"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as wg}from"preact/jsx-dev-runtime";var _o0=({docs:A})=>{let Q=to(A),w=OX0(Q),$=Q.filter((Y)=>Y.metadata.slug!=="index")[0]??Q[0];return wg(RX0,{title:"Documentation",description:"Brains documentation",children:[wg(x02,{docsCount:A.length,sectionsCount:w.length,startDoc:$},void 0,!1,void 0,this),wg("section",{className:"grid items-start gap-10 py-12 md:grid-cols-[200px_minmax(0,1fr)] md:gap-20 md:py-20 md:pb-[120px]",id:"sections",children:[wg(R02,{groups:w},void 0,!1,void 0,this),wg("div",{children:w.map((Y,D)=>wg(h02,{group:Y,index:D},Y.section,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as yH}from"preact/jsx-dev-runtime";var Po0=({doc:A,docs:Q,prevDoc:w,nextDoc:B})=>{let $=OX0(Q.length>0?Q:[A]),Y=to(Q.length>0?Q:[A]),D=Y.findIndex((H)=>H.metadata.slug===A.metadata.slug),X=Math.max($.findIndex((H)=>H.docs.some((W)=>W.metadata.slug===A.metadata.slug)),0);return yH(RX0,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[yH(v02,{title:A.metadata.title},void 0,!1,void 0,this),yH("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[yH(C02,{groups:$,activeGroupIndex:X,activeSlug:A.metadata.slug},void 0,!1,void 0,this),yH("article",{className:"min-w-0",children:[yH("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[yH("p",{className:`${Qz.label} m-0 mb-6 flex items-baseline gap-3`,children:[yH("span",{className:"docs-font-display text-lg leading-none tracking-normal normal-case text-[var(--docs-accent)] italic",children:[Qg(X),"."]},void 0,!0,void 0,this)," ",A.metadata.section,D>=0?` \xB7 ${D+1}/${Y.length}`:""]},void 0,!0,void 0,this),yH("h1",{className:`${Qz.display} m-0 max-w-[18ch] text-4xl leading-[1.05] tracking-[-0.02em] md:text-6xl`,children:A.metadata.title},void 0,!1,void 0,this),A.metadata.description&&yH("p",{className:"mt-6 max-w-[56ch] docs-font-display text-[22px] font-[350] leading-[1.5] text-[var(--docs-text-muted)]",children:A.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),yH("div",{className:"docs-article__body",children:yH($9,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),yH(y02,{prevDoc:w,nextDoc:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};var C3w=K.object({docs:K.array(MF),pagination:e7.nullable(),baseUrl:K.string().optional()}),y3w=K.object({doc:MF,docs:K.array(MF),prevDoc:MF.nullable(),nextDoc:MF.nullable()});function E02(){return{"doc-list":R1({name:"doc-list",description:"Documentation index template",schema:C3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:_o0}}),"doc-detail":R1({name:"doc-detail",description:"Documentation page template",schema:y3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:Po0}})}}var g02={name:"@brains/doc",private:!0,version:"0.2.0-alpha.136",description:"Documentation entity type \u2014 markdown docs as first-class brain content",type:"module",exports:{".":"./src/index.ts"},scripts:{typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix"},dependencies:{"@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"latest",typescript:"^5.3.3"}};class ko0 extends kQ{entityType=PX0.entityType;schema=eE;adapter=PX0;constructor(){super("docs",g02,{},void 0)}getTemplates(){return E02()}getDataSources(){return[new kX0(this.logger.child("DocDataSource"))]}}function Oo0(){return new ko0}c0();Z0();Z0();l$();var T02=K.object({label:K.string(),href:K.string()}),S02=K.object({label:K.string(),title:K.string(),detail:K.string()}),g3w=K.object({eyebrow:K.string(),name:K.string(),sub:K.string()}),T3w=K.object({tone:K.enum(["capture","synthesis","share"]),title:K.string(),text:K.string()}),xo0=K.object({captures:K.number(),links:K.number(),topics:K.number(),summaries:K.number(),peers:K.number()}),Bg=K.object({eyebrow:K.string(),headline:K.string(),intro:K.string(),primaryCta:T02,secondaryCta:T02,inputs:K.array(S02).min(1),outputs:K.array(S02).min(1),core:g3w,legend:K.array(T3w).min(1)}),Ro0=Bg.extend({counts:xo0}),m02={eyebrow:"A team brain, diagrammed",headline:"Relay sits between the work and the world, and keeps both honest.",intro:"Capture sources flow into a shared brain; the brain organizes, summarizes, and \u2014 selectively \u2014 exposes a public surface. Everything else stays private and operational.",primaryCta:{label:"See it on a real team",href:"#diagram"},secondaryCta:{label:"Read the model",href:"/about"},inputs:[{label:"Source \xB7 chat",title:"Discord",detail:"Shared decisions and field notes captured in flow."},{label:"Source \xB7 agent",title:"MCP / CLI",detail:"Structured captures from tools and assistants."},{label:"Source \xB7 web",title:"Links & docs",detail:"External material indexed with sourceable metadata."}],outputs:[{label:"Surface \xB7 public",title:"Default site",detail:"A small, durable face onto what the team currently knows."},{label:"Surface \xB7 agents",title:"A2A exchange",detail:"Peer brains coordinate over an approved, signed protocol."},{label:"Surface \xB7 query",title:"Team Q&A",detail:"Ask the brain in chat; answers cite the captures behind them."}],core:{eyebrow:"The relay",name:"brain",sub:"capture \u2192 topics \u2192 summaries"},legend:[{tone:"capture",title:"Capture",text:"Anything the team already does that produces a trace \u2014 chat messages, links, deploys, decisions."},{tone:"synthesis",title:"Synthesis",text:"The work the brain does on its own time \u2014 clustering captures into topics, summaries, and durable memory."},{tone:"share",title:"Share",text:"A small, opinionated public surface and an approved agent-to-agent protocol. Most memory stays private."}]},u02=new pw(Bg,{title:"Home diagram",mappings:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"headline",label:"Headline",type:"string"},{key:"intro",label:"Intro",type:"string"},{key:"primaryCta",label:"Primary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"secondaryCta",label:"Secondary CTA",type:"object",children:[{key:"label",label:"Label",type:"string"},{key:"href",label:"Href",type:"string"}]},{key:"inputs",label:"Inputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"outputs",label:"Outputs",type:"array",itemType:"object",itemMappings:[{key:"label",label:"Label",type:"string"},{key:"title",label:"Title",type:"string"},{key:"detail",label:"Detail",type:"string"}]},{key:"core",label:"Core",type:"object",children:[{key:"eyebrow",label:"Eyebrow",type:"string"},{key:"name",label:"Name",type:"string"},{key:"sub",label:"Sub",type:"string"}]},{key:"legend",label:"Legend",type:"array",itemType:"object",itemMappings:[{key:"tone",label:"Tone",type:"string"},{key:"title",label:"Title",type:"string"},{key:"text",label:"Text",type:"string"}]}]});function hX0(A){return u02.parse(A)}function c02(A){return u02.format(A)}Z0();var S3w=K.object({query:K.object({routeId:K.string().default("home"),sectionId:K.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}).passthrough(),m3w={captures:"note",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class ho0{id="relay-site:home-counts";name="Relay homepage counts";description="Fetches Relay homepage content and live entity counts for the system diagram";async fetch(A,Q,w){let B=S3w.parse(A??{}),$=await this.fetchContent(w,B.query.routeId,B.query.sectionId),Y=await this.fetchCounts(w);return Q.parse({...$,counts:Y})}async fetchContent(A,Q,w){let B=await A.entityService.getEntity({entityType:"site-content",id:`${Q}:${w}`});if(!B?.content)return m02;return Bg.parse(hX0(B.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(m3w).map(async([w,B])=>[w,await this.countOrZero(A,B)]));return xo0.parse(Object.fromEntries(Q))}async countOrZero(A,Q){if(!A.entityService.hasEntityType(Q))return 0;try{return await A.entityService.countEntities({entityType:Q})}catch{return 0}}}import{jsxDEV as $1}from"preact/jsx-dev-runtime";var l02=K.object({label:K.string(),href:K.string()}),u3w=K.object({eyebrow:K.string(),headline:K.string(),intro:K.string(),primaryCta:l02,secondaryCta:l02,signals:K.array(K.object({label:K.string(),value:K.string(),note:K.string()}))}),c3w=K.object({eyebrow:K.string(),title:K.string(),intro:K.string(),steps:K.array(K.object({phase:K.string(),title:K.string(),text:K.string()}))}),l3w=K.object({title:K.string(),intro:K.string(),cards:K.array(K.object({label:K.string(),title:K.string(),text:K.string()}))}),p3w=K.object({title:K.string(),intro:K.string(),points:K.array(K.string())}),i3w={title:"Relay is a collaborative team-memory brain.",intro:"It exists for teams that need to remember together: capturing what happened, summarizing why it matters, and coordinating with trusted peer brains when work crosses boundaries.",points:["Not a personal blog engine or portfolio shell.","Not a marketing automation stack.","A small public face for a larger private knowledge workflow."]},d3w="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function p02({href:A,label:Q}){return $1("a",{href:A,className:d3w,children:Q},void 0,!1,void 0,this)}function n3w({siteInfo:A,children:Q}){let w=[...A.navigation.primary,...A.navigation.secondary],B=A.cta??{buttonText:"Start here",buttonLink:"/about"};return $1(cE,{children:[$1("nav",{className:"fixed left-0 right-0 top-0 z-[100] flex items-center justify-between border-b border-theme-light bg-nav-fade px-6 py-4 backdrop-blur-[12px] md:px-10 xl:px-20",children:[$1("a",{href:"/",className:"font-nav text-[20px]","aria-label":"Relay home",children:[$1("span",{className:"font-bold text-theme",children:"relay"},void 0,!1,void 0,this),$1("span",{className:"font-bold text-accent",children:"."},void 0,!1,void 0,this),$1("span",{className:"text-theme-muted",children:"brain"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"flex items-center gap-5 md:gap-8",children:[$1("div",{className:"hidden items-center gap-6 md:flex",children:w.map(($)=>$1(p02,{...$},`${$.href}-${$.label}`,!1,void 0,this))},void 0,!1,void 0,this),$1("a",{href:B.buttonLink,className:"rounded-[999px] border border-theme px-4 py-2 font-body text-[13px] font-semibold text-theme transition-colors hover:border-accent hover:text-accent md:px-5",children:B.buttonText},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("main",{children:Q},void 0,!1,void 0,this),$1("footer",{className:"relative z-[1] border-t border-theme-light px-6 py-8 md:px-10 xl:px-20",children:$1("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[$1("div",{children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.22em] text-theme-light",children:A.copyright},void 0,!1,void 0,this),$1("p",{className:"mt-2 max-w-[560px] font-body text-body-xs text-theme-muted",children:A.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"flex flex-wrap items-center gap-5",children:[w.map(($)=>$1(p02,{...$},`footer-${$.href}-${$.label}`,!1,void 0,this)),$1("button",{id:"themeToggle","aria-label":"Toggle light mode",className:"rounded-md border border-theme-light bg-transparent px-2.5 py-1.5 font-body text-label-md text-theme-light transition-colors hover:border-theme hover:text-theme",children:"\u2600 Light"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var r3w=({sections:A,siteInfo:Q})=>$1(n3w,{siteInfo:Q,children:A},void 0,!1,void 0,this);function o3w({eyebrow:A,headline:Q,intro:w,primaryCta:B,secondaryCta:$,signals:Y}){return $1(cb,{className:"min-h-[92vh] pt-[152px] pb-20 md:pt-[190px]",children:$1("div",{className:"grid gap-10 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-end",children:[$1("div",{children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),$1("h1",{className:"mt-7 max-w-[980px] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),$1("p",{className:"mt-7 max-w-[720px] font-body text-body-lg text-theme-muted",children:w},void 0,!1,void 0,this),$1("div",{className:"mt-10 flex flex-col gap-3 sm:flex-row",children:[$1(gP,{href:B.href,size:"lg",variant:"primary-strong",children:B.label},void 0,!1,void 0,this),$1(gP,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"rounded-[32px] border border-card-relay-border bg-card-relay-bg p-5 shadow-[0_24px_90px_var(--color-glow-relay)] backdrop-blur-sm",children:[$1("p",{className:"font-label text-label-xs uppercase tracking-[0.24em] text-theme-light",children:"Live relay signals"},void 0,!1,void 0,this),$1("div",{className:"mt-5 grid gap-3",children:Y.map((D)=>$1("div",{className:"rounded-[22px] border border-card-divider bg-bg-muted p-5",children:[$1("div",{className:"flex items-center justify-between gap-4",children:[$1("p",{className:"font-label text-label-xs uppercase tracking-[0.18em] text-secondary",children:D.label},void 0,!1,void 0,this),$1("span",{className:"h-2 w-2 rounded-full bg-accent shadow-[0_0_22px_var(--color-accent)]"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("p",{className:"mt-4 font-display text-display-sm text-theme",children:D.value},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-body text-body-xs text-theme-muted",children:D.note},void 0,!1,void 0,this)]},D.label,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}function s3w({eyebrow:A,title:Q,intro:w,steps:B}){return $1(cb,{id:"operating-loop",className:"py-section",children:[$1("div",{className:"max-w-[840px]",children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-secondary",children:A},void 0,!1,void 0,this),$1("h2",{className:"mt-5 font-display text-display-md text-theme",children:Q},void 0,!1,void 0,this),$1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:B.map(($)=>$1("article",{className:"min-h-[300px] rounded-[28px] border border-card-panel-border bg-card-panel-bg p-6",children:[$1("p",{className:"font-label text-label-sm text-accent",children:$.phase},void 0,!1,void 0,this),$1("h3",{className:"mt-16 font-display text-display-sm text-theme",children:$.title},void 0,!1,void 0,this),$1("p",{className:"mt-4 font-body text-body-sm text-theme-muted",children:$.text},void 0,!1,void 0,this)]},$.phase,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function a3w({title:A,intro:Q,cards:w}){return $1(cb,{className:"py-section",children:$1("div",{className:"rounded-[36px] border border-theme-light bg-bg-muted p-6 md:p-10",children:$1("div",{className:"grid gap-8 lg:grid-cols-[360px_1fr]",children:[$1("div",{children:[$1("h2",{className:"font-display text-display-md text-theme",children:A},void 0,!1,void 0,this),$1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"grid gap-4",children:w.map((B)=>$1("article",{className:"rounded-[24px] border border-card-divider bg-bg-subtle/70 p-5",children:[$1("p",{className:"font-label text-label-xs uppercase tracking-[0.22em] text-accent",children:B.label},void 0,!1,void 0,this),$1("h3",{className:"mt-3 font-nav text-heading-lg text-theme",children:B.title},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-body text-body-sm text-theme-muted",children:B.text},void 0,!1,void 0,this)]},B.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function t3w({title:A,intro:Q,points:w}){return $1(cb,{className:"min-h-[78vh] pt-[150px] pb-section md:pt-[190px]",children:[$1("div",{className:"max-w-[920px]",children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:"Relay model"},void 0,!1,void 0,this),$1("h1",{className:"mt-6 font-display text-display-lg text-theme",children:A},void 0,!1,void 0,this),$1("p",{className:"mt-7 font-body text-body-lg text-theme-muted",children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:w.map((B)=>$1("div",{className:"rounded-[24px] border border-card-panel-current-border bg-card-panel-current-bg p-6 font-body text-body-md text-theme",children:B},B,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var e3w=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},AFw=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),eo=(A,Q,w=`${Q}s`)=>`${AFw(A)} ${A===1?Q:w}`;function QFw({eyebrow:A,headline:Q,intro:w,primaryCta:B,secondaryCta:$,inputs:Y,outputs:D,core:X,legend:H,counts:W}){let f=[{key:"captures",className:"top-[-10px] left-1/2 -translate-x-1/2",label:eo(W.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:eo(W.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:eo(W.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:eo(W.summaries,"summary","summaries")}];return $1(cb,{className:"pt-[150px] pb-section md:pt-[190px]",id:"diagram",children:[$1("div",{className:"mx-auto max-w-[1040px] text-center",children:[$1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),$1("h1",{className:"mx-auto mt-7 max-w-[22ch] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),$1("p",{className:"mx-auto mt-7 max-w-[64ch] font-body text-body-lg text-theme-muted",children:w},void 0,!1,void 0,this),$1("div",{className:"mt-10 flex flex-col justify-center gap-3 sm:flex-row",children:[$1(gP,{href:B.href,size:"lg",variant:"primary-strong",children:B.label},void 0,!1,void 0,this),$1(gP,{href:$.href,size:"lg",variant:"secondary",children:$.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mx-auto mt-20 max-w-[1020px] rounded-[32px] border border-theme-light bg-[radial-gradient(circle_at_1px_1px,rgb(255_255_255_/_0.05)_1px,transparent_0),linear-gradient(180deg,rgb(255_255_255_/_0.02),transparent)] bg-[length:24px_24px,100%_100%] px-6 py-14",children:[$1("div",{className:"grid items-center gap-8 lg:grid-cols-[1fr_1.4fr_1fr]",children:[$1("div",{className:"flex flex-col gap-3.5",children:Y.map((Z)=>$1("div",{className:"rounded-2xl border border-card-panel-border border-l-2 border-l-accent bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[$1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:Z.label},void 0,!1,void 0,this),$1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:Z.title},void 0,!1,void 0,this),$1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:Z.detail},void 0,!1,void 0,this)]},`${Z.label}-${Z.title}`,!0,void 0,this))},void 0,!1,void 0,this),$1("div",{className:"relative mx-auto grid aspect-square w-full max-w-[320px] place-items-center rounded-full bg-[radial-gradient(circle_at_center,rgb(232_119_34_/_0.25),transparent_65%)]",children:[$1("div",{className:"absolute inset-0 rounded-full border border-dashed border-accent/30"},void 0,!1,void 0,this),$1("div",{className:"absolute inset-6 animate-spin rounded-full border border-dashed border-secondary/40 [animation-duration:28s]"},void 0,!1,void 0,this),f.map((Z)=>$1("span",{className:`absolute whitespace-nowrap rounded-full border border-theme bg-bg px-2.5 py-1 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light ${Z.className}`,children:Z.label},Z.key,!1,void 0,this)),$1("div",{className:"relative z-[1] px-6 text-center",children:[$1("p",{className:"font-label text-[10px] uppercase tracking-[0.28em] text-accent",children:X.eyebrow},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-display text-[36px] leading-none text-theme",children:X.name},void 0,!1,void 0,this),$1("p",{className:"mt-2 font-body text-[13px] text-theme-muted",children:X.sub},void 0,!1,void 0,this),$1("p",{className:"mt-4 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light",children:[eo(W.links,"link")," indexed"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"flex flex-col gap-3.5",children:D.map((Z)=>$1("div",{className:"rounded-2xl border border-card-panel-border border-r-2 border-r-secondary bg-card-panel-bg px-4 py-4 text-left backdrop-blur-sm",children:[$1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:Z.label},void 0,!1,void 0,this),$1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:Z.title},void 0,!1,void 0,this),$1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:Z.detail},void 0,!1,void 0,this)]},`${Z.label}-${Z.title}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$1("div",{className:"mt-14 grid gap-4 border-t border-theme-light pt-8 md:grid-cols-3",children:H.map((Z)=>$1("div",{className:"text-left",children:[$1("h2",{className:"font-display text-[16px] font-medium text-theme",children:[$1("span",{className:`mr-2.5 inline-block h-3 w-3 rounded-[3px] align-middle ${e3w(Z.tone)}`},void 0,!1,void 0,this),Z.title]},void 0,!0,void 0,this),$1("p",{className:"mt-1.5 font-body text-[13px] leading-[1.6] text-theme-muted",children:Z.text},void 0,!1,void 0,this)]},Z.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var wFw=R1({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:Ro0,formatter:{parse:(A)=>Ro0.parse({...hX0(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>c02(Bg.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:QFw}}),BFw=(A)=>o3w(u3w.parse(A)),$Fw=(A)=>s3w(c3w.parse(A)),YFw=(A)=>a3w(l3w.parse(A)),DFw=(A)=>t3w(p3w.parse(A)),i02={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},d02={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:BFw,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...i02,label:"Primary CTA"},secondaryCta:{...i02,label:"Secondary CTA"},signals:{type:"array",label:"Signals",minItems:1,items:{type:"object",label:"Signal",fields:{label:{type:"string",label:"Label"},value:{type:"string",label:"Value"},note:{type:"string",label:"Note"}}}}}},"home-loop":{title:"Home operating loop",description:"Relay capture, synthesis, and sharing loop",layout:$Fw,fields:{eyebrow:{type:"string",label:"Eyebrow"},title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},steps:{type:"array",label:"Steps",minItems:1,items:{type:"object",label:"Step",fields:{phase:{type:"string",label:"Phase"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},"home-surface":{title:"Home surface",description:"Relay default template explanation cards",layout:YFw,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},cards:{type:"array",label:"Cards",minItems:1,items:{type:"object",label:"Card",fields:{label:{type:"string",label:"Label"},title:{type:"string",label:"Title"},text:{type:"string",label:"Text"}}}}}},about:{title:"About Relay",description:"Default Relay about page",layout:DFw,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},XFw=[{id:"home",path:"/",title:"Relay",description:"Collaborative team memory and synthesis brain",layout:"default",navigation:{show:!0,label:"Home",slot:"secondary",priority:10},sections:[{id:"diagram",template:"relay-site:home-diagram"}]},{id:"about",path:"/about",title:"About Relay",description:"What Relay is designed to do",layout:"default",navigation:{show:!0,label:"About",slot:"primary",priority:20},sections:[{id:"about",template:"relay-site:about",content:i3w}]}],n02=fo0({packageName:"@brains/relay/site",contentNamespace:"relay-site",themeProfile:"studio",layout:r3w,routes:XFw,templates:{"home-diagram":wFw},dataSources:[new ho0]});var r02={name:"@brains/relay",private:!0,version:"0.2.0-alpha.136",description:"Relay brain model \u2014 collaborative knowledge management",type:"module",files:["src","brain.eval.yaml","env.schema.template"],exports:{".":"./src/index.ts"},scripts:{"build:web-chat":"turbo run build --filter=@brains/web-chat","start:core":"bun run build:web-chat && cd test-apps/core && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:default":"bun run build:web-chat && cd test-apps/default && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:full":"bun run build:web-chat && cd test-apps/full && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start","start:docs":"bun run build:web-chat && cd test-apps/docs && INIT_CWD=$PWD bun run --filter @rizom/brain dev:start",typecheck:"tsc --noEmit",test:"bun test",eval:"brain-eval",lint:"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/auth-service":"workspace:*","@brains/cms":"workspace:*","@brains/content-formatters":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/directory-sync":"workspace:*","@brains/discord":"workspace:*","@brains/doc":"workspace:*","@brains/email-resend":"workspace:*","@brains/image-plugin":"workspace:*","@brains/link":"workspace:*","@brains/mcp":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/plugins":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-info":"workspace:*","@brains/site-rizom":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^5.3.3"}};var o02=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","web-chat","discord","a2a"],s02=[...o02,"image","site-info","site-content","site-builder"],fFw=[...s02,"docs","decks"],ZFw=["Relay is a collaborative team-memory and synthesis brain. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence, and coordinating with peer brains.","Relay is not Rover-for-teams: do not default to personal branding, blog publishing, newsletters, social media, portfolio, or marketing workflows unless the installed plugins and user request explicitly support them."],a02=LJ({name:"relay",version:r02.version,model:"gpt-5.4-mini",site:n02,theme:lE,presets:{core:o02,default:s02,full:fFw},evalDisable:["webserver","web-chat","mcp","discord"],agentInstructions:ZFw,capabilities:[["prompt",vP,void 0],["note",LP,{}],["link",jP,{}],["image",Gc,void 0],["topics",lY0,{includeEntityTypes:["note","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",No0,{memoryVisibility:"shared"}],["docs",Oo0,void 0],["decks",_r,void 0],["agents",yD0,void 0],["assessment",iD0,void 0],["auth-service",Yp,void 0],["notifications",sw0,void 0],["email-resend",l$0,void 0],["cms",xP,{}],["dashboard",Sb,void 0],["directory-sync",M_,{seedContent:!0,seedContentPath:WFw(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",lo,{definitions:d02}],["rizom-ecosystem",CP,void 0],["site-info",fP,void 0],["site-builder",WP,{}]],interfaces:[["mcp",BI,()=>({})],["discord",uI,()=>({captureUrls:!0})],["a2a",mC,()=>({})],["webserver",iI,()=>({})],["web-chat",SC,()=>({})]],permissions:{rules:[{pattern:"cli:*",level:"anchor"},{pattern:"mcp:stdio",level:"anchor"},{pattern:"mcp:http",level:"anchor"},{pattern:"discord:*",level:"public"},{pattern:"web-chat:*",level:"anchor"}],entityActions:{note:{create:"trusted",update:"trusted",delete:"anchor"},link:{create:"trusted",update:"trusted",delete:"anchor"},doc:{create:"trusted",update:"trusted",delete:"anchor"},deck:{create:"trusted",update:"trusted",delete:"anchor"},decision:{create:"trusted",update:"trusted",delete:"anchor"},"action-item":{create:"trusted",update:"trusted",delete:"anchor"},image:{create:"trusted",update:"trusted",delete:"anchor"}}},deployment:{cdn:{enabled:!0,provider:"bunny"}}});import{readFileSync as pIw}from"fs";import{join as iIw}from"path";import{execSync as dIw}from"child_process";import{parseArgs as GFw}from"util";var zFw={model:{type:"string"},domain:{type:"string"},"content-repo":{type:"string"},backend:{type:"string"},"push-to":{type:"string"},"ai-api-key":{type:"string"},"no-interactive":{type:"boolean"},preview:{type:"boolean"},deploy:{type:"boolean"},regen:{type:"boolean"},all:{type:"boolean"},only:{type:"string"},"dry-run":{type:"boolean"},"startup-check":{type:"boolean"},"storage-dir":{type:"string"},yes:{type:"boolean"},remote:{type:"string"},token:{type:"string"},outputDir:{type:"string"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};function _K(A,Q){let w=A[Q];return typeof w==="string"?w:void 0}function ib(A,Q){let w=A[Q];return typeof w==="boolean"?w:void 0}function t02(A){let{values:Q,positionals:w}=GFw({args:A,options:zFw,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:w[0]??"help",args:w.slice(1),flags:{model:_K(Q,"model"),domain:_K(Q,"domain"),"content-repo":_K(Q,"content-repo"),backend:_K(Q,"backend"),"push-to":_K(Q,"push-to"),"ai-api-key":_K(Q,"ai-api-key"),"no-interactive":ib(Q,"no-interactive"),preview:ib(Q,"preview"),deploy:ib(Q,"deploy"),regen:ib(Q,"regen"),all:ib(Q,"all"),only:_K(Q,"only"),"dry-run":ib(Q,"dry-run"),"startup-check":ib(Q,"startup-check"),"storage-dir":_K(Q,"storage-dir"),yes:ib(Q,"yes"),remote:_K(Q,"remote"),token:_K(Q,"token"),outputDir:_K(Q,"outputDir")}}}As();import{mkdirSync as CIw}from"fs";import{join as yIw}from"path";import{execSync as EIw}from"child_process";var CX0={name:"@rizom/brain",version:"0.2.0-alpha.136",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun scripts/build.ts","dev:start":"bun scripts/build.ts && bun dist/brain.js start",typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@clack/prompts":"^0.11.0","@modelcontextprotocol/sdk":"^1.24.0","@tailwindcss/postcss":"^4.1.13","@tailwindcss/typography":"^0.5.19",postcss:"^8.5.6",preact:"^10.27.2","preact-render-to-string":"^6.3.1",tailwindcss:"^4.1.11"},optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","playwright-core":"^1.56.0","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"workspace:*","@brains/content-formatters":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"latest",rollup:"^4.60.2","rollup-plugin-dts":"^6.4.1",typescript:"^5.3.3"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",bugs:"https://github.com/rizom-ai/brains/issues",engines:{bun:">=1.3.3"},keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"]};import{mkdirSync as UA2,writeFileSync as ws,chmodSync as Bs,existsSync as co0,readFileSync as lo0}from"fs";import{basename as po0,dirname as io0,join as L6,resolve as oFw}from"path";import{fileURLToPath as sFw}from"url";var e02=`ARG BUN_VERSION=1.3.10
11838
11838
  FROM oven/bun:\${BUN_VERSION}-slim AS runtime
11839
11839
 
11840
11840
  WORKDIR /app