@rizom/brain 0.2.0-alpha.138 → 0.2.0-alpha.139
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 +39 -39
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/site.js +4 -4
- package/dist/site.js.map +1 -1
- package/package.json +1 -1
package/dist/brain.js
CHANGED
|
@@ -385,20 +385,20 @@ ${w.join(`
|
|
|
385
385
|
|
|
386
386
|
${Y}`:"")}function qb0(A,Q,w,B){return async($,Y)=>{if(B){let D={toolName:A,args:$,conversationId:w.conversationId,interfaceType:w.interfaceType,...w.channelId!==void 0&&{channelId:w.channelId},...w.channelName!==void 0&&{channelName:w.channelName},...Y?.toolCallId!==void 0&&{toolCallId:Y.toolCallId}};await B.emit("tool:invoking",D)}try{let D=Y?await Q($,Y):await Q($);if(B){let X={toolName:A,conversationId:w.conversationId,interfaceType:w.interfaceType,...w.channelId!==void 0&&{channelId:w.channelId},...w.channelName!==void 0&&{channelName:w.channelName},...Y?.toolCallId!==void 0&&{toolCallId:Y.toolCallId}};await B.emit("tool:completed",X)}return D}catch(D){if(B){let X={toolName:A,error:vA(D),conversationId:w.conversationId,interfaceType:w.interfaceType,...w.channelId!==void 0&&{channelId:w.channelId},...w.channelName!==void 0&&{channelName:w.channelName},...Y?.toolCallId!==void 0&&{toolCallId:Y.toolCallId}};await B.emit("tool:failed",X)}throw D}}}function Fb0(A,Q="brain-agent"){return{emit:async(w,B)=>{await A.send({type:w,payload:B,sender:Q,broadcast:!0}).catch(()=>{return})}}}var _10=i(()=>{Z0()});function zx2(A,Q={}){return Object.fromEntries(Object.entries(A).filter(([w])=>{if(Kx2.has(w))return!1;if(Q.toolName!=="system_create")return!0;return!Ux2.has(w)}))}function qx2(A){let Q=Gx2.safeParse(A);if(!Q.success)return{type:"json",value:J3A(A)};let{attachment:w}=Q.data.data,B={mediaType:w.mediaType,...w.filename!==void 0?{filename:w.filename}:{},...w.sizeBytes!==void 0?{sizeBytes:w.sizeBytes}:{},...w.source!==void 0?{source:w.source}:{}};return{type:"json",value:J3A({...Q.data,data:{...Q.data.data,attachment:B,artifactCard:{rendered:!0,message:"The UI has rendered this artifact as an attachment card with Open and Download controls. Do not print raw attachment URLs in the assistant response."}}})}}function Fx2(A){if(typeof A!=="object"||A===null||Array.isArray(A))return A;if(A.success!==!0)return A;return{...A,cached:!0}}function J3A(A){if(A===void 0)return null;return Vb0.parse(JSON.parse(JSON.stringify(A)))}function Jb0(A,Q,w){let B={},$=new Map;for(let Y of A){let D=qb0(Y.name,async(X,H)=>{let W={interfaceType:Q.interfaceType,userId:"agent-user",conversationId:Q.conversationId,...Q.channelId&&{channelId:Q.channelId},...H?.toolCallId&&{toolCallId:H.toolCallId},...Q.channelName&&{channelName:Q.channelName},...Q.userPermissionLevel&&{userPermissionLevel:Q.userPermissionLevel}};if(Y.sideEffects!=="none"){if(Y.sideEffects==="writes"||Y.sideEffects==="external")$.clear();return Y.handler(X,W)}let f=`${Y.name}:${JSON.stringify(X)}`;if($.has(f))return Fx2($.get(f));let Z=await Y.handler(X,W);return $.set(f,Z),Z},Q,w);B[Y.name]=NV0({description:Y.description,inputSchema:K.object(zx2(Y.inputSchema,{toolName:Y.name,...Q.enableCreateUpload!==void 0&&{enableCreateUpload:Q.enableCreateUpload},...Q.enableCreateTransform!==void 0&&{enableCreateTransform:Q.enableCreateTransform}})),execute:D,toModelOutput:({output:X})=>qx2(X)})}return B}var Kx2,Ux2,Vb0,Gx2;var I3A=i(()=>{cx();Z0();_10();Kx2=new Set(["confirmed","confirmationToken","contentHash"]),Ux2=new Set(["content","prompt","url","from","upload","transform","sourceAttachment"]),Vb0=K.lazy(()=>K.union([K.null(),K.string(),K.number(),K.boolean(),K.array(Vb0),K.record(Vb0)])),Gx2=K.object({success:K.literal(!0),data:K.object({documentId:K.string().min(1).optional(),entityId:K.string().min(1).optional(),attachment:K.object({mediaType:K.string().min(1),url:K.string().min(1),downloadUrl:K.string().min(1).optional(),previewUrl:K.string().min(1).optional(),filename:K.string().min(1).optional(),sizeBytes:K.number().nonnegative().optional(),source:K.object({entityType:K.string().optional(),entityId:K.string().optional(),attachmentType:K.string().optional()}).optional()}).passthrough()}).passthrough()}).passthrough()});function Jx2(A,Q){return A}function Ix2(A){return A.steps.at(-1)?.toolResults?.some((w)=>ZN.safeParse(w.output).success||w.toolName==="playbook_start")??!1}function Ib0(A){let{model:Q,modelId:w,webSearch:B,temperature:$,maxTokens:Y,messageBus:D}=A,X=fUA(w),H=Fb0(D);return function(f){let Z=Jb0(f.tools,{conversationId:"",interfaceType:"agent"},H);return new BUA({model:Q,callOptionsSchema:Vx2,prepareCall:({options:G,...F})=>{let V=G.disableTools?[]:Jx2(f.getToolsForPermission(G.userPermissionLevel),G),L=V.map((N)=>N.name),b=Jb0(V,{conversationId:G.conversationId,channelId:G.channelId,channelName:G.channelName,interfaceType:G.interfaceType,userPermissionLevel:G.userPermissionLevel,enableCreateUpload:G.enableCreateUpload,enableCreateTransform:G.enableCreateTransform},H);return{...F,instructions:V3A(f.identity,G.userPermissionLevel,f.pluginInstructions,f.profile,f.agentInstructions,G.agentContextInstructions),tools:b,activeTools:L,...$!==void 0&&X&&{temperature:$},...Y!==void 0&&{maxTokens:Y},...B&&{providerOptions:{anthropic:{webSearch:!0}}}}},tools:Z,stopWhen:[Ix2,sm(f.stepLimit??10)]})}}var Vx2;var b3A=i(()=>{cx();Z0();k9();px();_10();I3A();Vx2=K.object({userPermissionLevel:K.enum(["anchor","trusted","public"]),conversationId:K.string(),channelId:K.string().optional(),channelName:K.string().optional(),interfaceType:K.string(),agentContextInstructions:K.string().optional(),disableTools:K.boolean().optional(),enableCreateUpload:K.boolean().optional(),enableCreateTransform:K.boolean().optional(),hasPriorResponseCandidate:K.boolean().optional()})});var P10=i(()=>{rzA();px();ozA();F3A();Gb0();b3A();_10()});function j3A(A){return{...A,...A.source!==void 0&&{source:L3A(A.source)},...A.target!==void 0&&{target:L3A(A.target)}}}function L3A(A){if(A instanceof RegExp)return A;if(!A.includes("*"))return A;let Q=A.split("*").map((w)=>w.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`)}function M3A(A,Q){if(!Q)return!0;if(!N3A(A.source,Q.source))return!1;if(!N3A(A.target,Q.target,!0))return!1;if(!bx2(A.metadata,Q.metadata))return!1;return Q.predicate?Q.predicate(A):!0}function N3A(A,Q,w=!1){if(!Q)return!0;if(w&&!A)return!1;return Lx2(A,Q)}function bx2(A,Q){if(!Q)return!0;if(!A)return!1;return Object.entries(Q).every(([w,B])=>A[w]===B)}function Lx2(A,Q){if(!A)return!1;if(Q instanceof RegExp){Q.lastIndex=0;let w=Q.test(A);return Q.lastIndex=0,w}return A===Q}var k10,_3A;var bb0=i(()=>{Z0();k10=K.object({success:K.boolean(),data:K.unknown().optional(),error:K.string().optional()}),_3A=K.object({id:K.string().min(1),timestamp:K.string(),type:K.string().min(1),source:K.string().min(1),target:K.string().optional(),metadata:K.record(K.string(),K.unknown()).optional()})});function P3A(A){let Q=Nx2.safeParse(A);if(!Q.success)throw Error("Invalid message response format");return Q.data}var Nx2;var k3A=i(()=>{Z0();bb0();Nx2=K.union([K.object({noop:K.literal(!0)}),k10])});function x3A(A,Q,w,B,$){return{id:v3A("msg"),type:A,timestamp:C3A(),source:w,target:B,metadata:$,payload:Q}}function R3A(A,Q){let w=P3A(Q);if("noop"in w)return O3A(A,!0);return O3A(A,w.success,w.data,w.error)}function h3A(A,Q){if(Q?.success)return{success:!0,data:Q.data};return{success:!1,error:Q?.error?.message??`No handler found for message type: ${A}`}}function O3A(A,Q,w,B){return{id:v3A("resp"),requestId:A,timestamp:C3A(),success:Q,data:w,error:B?{message:B}:void 0}}function v3A(A){return`${A}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function C3A(){return new Date().toISOString()}var Lb0=i(()=>{k3A()});class Nb0{handlers=new Map;add(A,Q,w){let B=this.createHandlerEntry(Q,w);return this.getOrCreateHandlers(A).add(B),B}remove(A,Q){let w=this.handlers.get(A);if(!w)return!1;let B=w.delete(Q);return this.deleteEmptyHandlerSet(A,w),B}removeHandler(A,Q){let w=this.handlers.get(A);if(!w)return;for(let B of Array.from(w))if(B.originalHandler===Q)w.delete(B);this.deleteEmptyHandlerSet(A,w)}getMatchingHandlers(A,Q){let w=this.handlers.get(A);if(!w||w.size===0)return;return{entries:Array.from(w).filter((B)=>M3A(Q,B.filter)),totalHandlers:w.size}}hasHandlers(A){let Q=this.handlers.get(A);return Q!==void 0&&Q.size>0}clearHandlers(A){return this.handlers.delete(A)}clearAllHandlers(){this.handlers.clear()}getHandlerCount(A){return this.handlers.get(A)?.size??0}getTargetedHandlerCount(A,Q){let w=this.handlers.get(A);if(!w)return 0;return Array.from(w).filter((B)=>B.filter?.target===Q).length}createHandlerEntry(A,Q){let w={handler:this.wrapHandler(A),originalHandler:A};return Q?{...w,filter:j3A(Q)}:w}wrapHandler(A){return async(Q)=>{let B=await A(Q);return R3A(Q.id,B)}}getOrCreateHandlers(A){let Q=this.handlers.get(A);if(!Q)Q=new Set,this.handlers.set(A,Q);return Q}deleteEmptyHandlerSet(A,Q){if(Q.size===0)this.handlers.delete(A)}}var y3A=i(()=>{Lb0()});async function E3A(A,Q,w){for(let B of Q)await T3A(B,A,w);return null}async function g3A(A,Q,w){for(let B of Q){let $=await T3A(B,A,w);if($)return $}return null}async function T3A(A,Q,w){try{return await A.handler(Q)}catch(B){return w.error(`Error in message handler for ${Q.type}`,B),null}}class jb0{registry;logger;constructor(A,Q){this.registry=A;this.logger=Q}async publish(A,Q){if(typeof A!=="object"||!A.type||!A.id)return this.logger.error("Invalid message structure - missing required fields 'id' or 'type'"),null;let{type:w}=A;this.logger.debug(`Publishing message of type: ${w}`,{source:A.source,target:A.target,hasMetadata:!!A.metadata});let B=this.registry.getMatchingHandlers(w,A);if(!B)return this.logger.debug(`No handlers found for message type: ${w}`),null;if(B.entries.length===0)return this.logger.debug(`No matching handlers for message type: ${w}`,{totalHandlers:B.totalHandlers,target:A.target}),null;return Q===!0?E3A(A,B.entries,this.logger):g3A(A,B.entries,this.logger)}}var S3A=()=>{};function m3A(A,Q){try{return{valid:!0,data:Q.parse(A)}}catch(w){if(w instanceof K.ZodError)return{valid:!1,error:w.issues[0]?.message??"Validation failed"};return{valid:!1,error:"Unknown validation error"}}}var u3A=i(()=>{Z0()});class qZ{static instance=null;registry=new Nb0;publisher;logger;static getInstance(A){return qZ.instance??=new qZ(A),qZ.instance}static resetInstance(){qZ.instance=null}static createFresh(A){return new qZ(A)}constructor(A){this.logger=A,this.publisher=new jb0(this.registry,A)}subscribe(A,Q,w){let B=this.registry.add(A,Q,w);return this.logger.debug(`Registered handler for message type: ${A}`,{hasFilter:!!w,filterTarget:w?.target}),()=>{this.registry.remove(A,B)}}async send(A){let{type:Q,payload:w,sender:B,target:$,metadata:Y,broadcast:D}=A,X=x3A(Q,w,B,$,Y),H=await this.publisher.publish(X,D);return h3A(Q,H)}validateMessage(A,Q){return m3A(A,Q)}hasHandlers(A){return this.registry.hasHandlers(A)}unsubscribe(A,Q){this.registry.removeHandler(A,Q)}clearHandlers(A){if(this.registry.clearHandlers(A))this.logger.info(`Cleared all handlers for message type: ${A}`)}clearAllHandlers(){this.registry.clearAllHandlers(),this.logger.info("Cleared all message handlers")}getHandlerCount(A){return this.registry.getHandlerCount(A)}getTargetedHandlerCount(A,Q){return this.registry.getTargetedHandlerCount(A,Q)}}var c3A=i(()=>{y3A();Lb0();S3A();u3A()});var Mx2;var l3A=i(()=>{Z0();bb0();Mx2=K.object({id:K.string().min(1),requestId:K.string().min(1),success:K.boolean(),data:K.unknown().optional(),error:K.object({message:K.string(),code:K.string().optional()}).optional(),timestamp:K.string().datetime()})});var Mb0=i(()=>{c3A();l3A()});var U6;var _b0=i(()=>{pV();U6=KW("runtime_state_records",{namespace:JQ("namespace").notNull(),key:JQ("key").notNull(),value:JQ("value",{mode:"json"}).notNull(),createdAt:x9("created_at").notNull(),updatedAt:x9("updated_at").notNull()},(A)=>({pk:mO({columns:[A.namespace,A.key]}),namespaceUpdatedAtIdx:VX("idx_runtime_state_namespace_updated_at").on(A.namespace,A.updatedAt)}))});import{createClient as p3A}from"@libsql/client";function O10(A){let Q=A.url,w=A.authToken??process.env.RUNTIME_STATE_DATABASE_AUTH_TOKEN,B=w?p3A({url:Q,authToken:w}):p3A({url:Q});return{db:UW(B,{schema:{runtimeStateRecords:U6}}),client:B,url:Q}}async function x10(A,Q){if(Q.startsWith("file:"))await A.execute("PRAGMA journal_mode = WAL"),await A.execute("PRAGMA busy_timeout = 5000")}var Pb0=i(()=>{dO();_b0()});class R10{db;namespace;schema;now;constructor(A,Q,w,B=()=>new Date){this.db=A;this.namespace=Q;this.schema=w;this.now=B;Px2(Q)}async get(A){let Q=Ku(A),B=(await this.db.select().from(U6).where(LB(_2(U6.namespace,this.namespace),_2(U6.key,Q))).limit(1))[0];if(!B)return null;return this.schema.parse(B.value)}async has(A){let Q=Ku(A);return(await this.db.select({key:U6.key}).from(U6).where(LB(_2(U6.namespace,this.namespace),_2(U6.key,Q))).limit(1)).length>0}async set(A,Q){let w=Ku(A),B=this.schema.parse(Q),$=this.now().getTime();await this.db.insert(U6).values({namespace:this.namespace,key:w,value:B,createdAt:$,updatedAt:$}).onConflictDoUpdate({target:[U6.namespace,U6.key],set:{value:B,updatedAt:$}})}async setIfNotExists(A,Q){let w=Ku(A),B=this.schema.parse(Q),$=this.now().getTime(),Y=await this.db.insert(U6).values({namespace:this.namespace,key:w,value:B,createdAt:$,updatedAt:$}).onConflictDoNothing({target:[U6.namespace,U6.key]});return Number(Y.rowsAffected)>0}async delete(A){let Q=Ku(A),w=await this.db.delete(U6).where(LB(_2(U6.namespace,this.namespace),_2(U6.key,Q)));return Number(w.rowsAffected)>0}async list(A={}){let Q=await this.listRows(),w=A.keyPrefix;if(w!==void 0)i3A(w);return Q.filter((B)=>w===void 0||B.key.startsWith(w)).map((B)=>({key:B.key,value:this.schema.parse(B.value),createdAt:new Date(B.createdAt),updatedAt:new Date(B.updatedAt)}))}async clear(A={}){let Q=A.keyPrefix;if(Q===void 0){let B=await this.db.delete(U6).where(_2(U6.namespace,this.namespace));return Number(B.rowsAffected)}i3A(Q);let w=await this.list({keyPrefix:Q});return await Promise.all(w.map((B)=>this.delete(B.key))),w.length}async listRows(){return this.db.select().from(U6).where(_2(U6.namespace,this.namespace))}}function Px2(A){if(!_x2.test(A))throw Error(`Invalid runtime state namespace: ${A}. Use 1-128 alphanumeric, _, ., :, or - characters.`)}function Ku(A){if(A.length===0||A.length>d3A)throw Error("Runtime state keys must be 1-512 characters long");return A}function i3A(A){if(A.length>d3A)throw Error("Runtime state key prefixes must be 512 characters or shorter");return A}var _x2,d3A=512;var kb0=i(()=>{Yq();_b0();_x2=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/});class IW{static instance=null;db;client;logger;static getInstance(A,Q){return IW.instance??=new IW(A,Q??e2.getInstance()),IW.instance}static createFresh(A,Q){return new IW(A,Q??e2.getInstance())}static resetInstance(){IW.instance?.close(),IW.instance=null}constructor(A,Q){let{db:w,client:B,url:$}=O10(A);this.db=w,this.client=B,this.logger=Q.child("RuntimeStateService"),x10(B,$).catch((Y)=>{this.logger.warn("Failed to enable runtime state WAL mode (non-fatal)",Y)})}scoped(A){return new R10(this.db,A.namespace,A.schema)}close(){this.client.close()}}var n3A=i(()=>{Z0();Pb0();kb0()});var Ob0=i(()=>{n3A();kb0()});async function r3A(A,Q){if(A.status==="running"){Q.warn(`Daemon already running: ${A.name}`);return}A.status="starting",delete A.error;try{await A.daemon.start(),A.status="running",A.startedAt=new Date,Q.debug(`Daemon started successfully: ${A.name}`)}catch(w){throw A.status="error",A.error=YW(w),Q.warn(`Daemon ${A.name} failed to start: ${vA(w)}`),w}}async function o3A(A,Q){if(A.status==="stopped"){Q.warn(`Daemon already stopped: ${A.name}`);return}A.status="stopping";try{await A.daemon.stop(),A.status="stopped",A.stoppedAt=new Date,Q.debug(`Daemon stopped successfully: ${A.name}`)}catch(w){throw A.status="error",A.error=YW(w),Q.error(`Failed to stop daemon: ${A.name}`,w),w}}async function s3A(A){if(!A.daemon.healthCheck)return;try{let Q=await A.daemon.healthCheck();return A.health=Q,Q}catch(Q){let w={status:"error",message:vA(Q),lastCheck:new Date};return A.health=w,w}}function a3A(A){return{name:A.name,pluginId:A.pluginId,status:A.status,health:A.health}}var t3A=i(()=>{Z0()});class PU{static instance=null;daemons=new Map;logger;static getInstance(A=e2.getInstance()){return PU.instance??=new PU(A),PU.instance}static resetInstance(){PU.instance=null}static createFresh(A){return new PU(A)}constructor(A){this.logger=A.child("DaemonRegistry")}register(A,Q,w){if(this.daemons.has(A))this.logger.warn(`Daemon already registered: ${A}, overwriting`);let B={name:A,daemon:Q,pluginId:w,status:"stopped"};this.daemons.set(A,B),this.logger.debug(`Registered daemon: ${A} from plugin: ${w}`)}has(A){return this.daemons.has(A)}get(A){return this.daemons.get(A)}async start(A){let Q=this.daemons.get(A);if(!Q)throw Error(`Daemon not registered: ${A}`);await r3A(Q,this.logger)}async stop(A){let Q=this.daemons.get(A);if(!Q)throw Error(`Daemon not registered: ${A}`);await o3A(Q,this.logger)}async checkHealth(A){let Q=this.daemons.get(A);if(!Q)throw Error(`Daemon not registered: ${A}`);return s3A(Q)}getByPlugin(A){return Array.from(this.daemons.values()).filter((Q)=>Q.pluginId===A)}getAll(){return Array.from(this.daemons.keys())}getAllInfo(){return Array.from(this.daemons.values())}async getStatuses(){let A=this.getAllInfo();for(let Q of A)if(Q.daemon.healthCheck)await this.checkHealth(Q.name);return A.map(a3A)}async unregister(A){let Q=this.daemons.get(A);if(!Q){this.logger.warn(`Daemon not registered: ${A}`);return}if(Q.status==="running")await this.stop(A);this.daemons.delete(A),this.logger.debug(`Unregistered daemon: ${A}`)}async startPlugin(A){let Q=this.getByPlugin(A);this.logger.debug(`Starting ${Q.length} daemons for plugin: ${A}`);let w;for(let B of Q)try{await this.start(B.name)}catch($){w??=YW($)}if(w)throw w}async stopPlugin(A){let Q=this.getByPlugin(A);this.logger.debug(`Stopping ${Q.length} daemons for plugin: ${A}`);for(let w of Q)try{await this.stop(w.name)}catch(B){this.logger.error(`Failed to stop daemon: ${w.name}`,B)}}async clear(){this.logger.debug("Clearing all daemons");let A=Array.from(this.daemons.values()).filter((Q)=>Q.status==="running");for(let Q of A)try{await this.stop(Q.name)}catch(w){this.logger.error(`Failed to stop daemon during clear: ${Q.name}`,w)}this.daemons.clear(),this.logger.debug("All daemons cleared")}}var xb0=i(()=>{Z0();t3A()});function Rb0(A,Q,w,B,$){return["entity:created","entity:updated","entity:deleted"].map((D)=>A.subscribe(D,async(X)=>{if(X.payload.entityType===Q&&(w===null||X.payload.entityId===w)){await B();let H=D.replace("entity:","");$.debug(`${Q} entity ${H}, cache refreshed`)}return{success:!0}}))}async function kx2(A,Q,w){let B=Ox2(A.kind);if(!B)return null;try{let $=Q.scoped({namespace:B,refKind:A.kind,routePath:""});return xx2(await $.read(A.id),A)}catch($){return w.debug("Skipped unavailable prior runtime upload",{uploadKind:A.kind,uploadId:A.id,error:$ instanceof Error?$.message:String($)}),null}}function Ox2(A){return A==="upload"?"upload":null}function xx2(A,Q){let{record:w,content:B}=A;if(Rx2(w.mediaType))return{kind:"text",filename:w.filename,mediaType:w.mediaType,content:new TextDecoder("utf-8").decode(B).replace(/^\uFEFF/,""),sizeBytes:w.sizeBytes,source:Q};return{kind:"file",filename:w.filename,mediaType:w.mediaType,data:new Uint8Array(B),sizeBytes:w.sizeBytes,source:Q}}function Rx2(A){let Q=A.toLowerCase();return Q.startsWith("text/")||Q==="application/json"}function e3A(A){let{config:Q,entityService:w,logger:B,messageBus:$,aiService:Y,mcpService:D,conversationService:X,runtimeUploadRegistry:H,disposables:W}=A,f=GW.getInstance(w,B,Q.identity);W.push(...Rb0($,wY.BRAIN_CHARACTER,wY.BRAIN_CHARACTER,()=>f.refreshCache(),B));let Z=QY.getInstance(w,B,Q.profile),G=Fq.getInstance(B),F=Ib0({model:Y.getModel(),modelId:Y.getConfig().model,webSearch:Y.getConfig().webSearch,temperature:Y.getConfig().temperature,maxTokens:Y.getConfig().maxTokens,messageBus:$}),V=Kb0(Q.name),L=v9.getInstance(D,X,f,Z,B,{agentFactory:F,canonicalIdentityResolver:G,indexReadiness:w,uploadAttachmentResolver:(b)=>kx2(b,H,B),agentContextProvider:async(b)=>{let N=await $.send({type:XN,sender:"shell:agent-service",payload:b});if("noop"in N||!N.success)return[];return EZ0(N.data)},...V?{assistantActorId:V}:{},...Q.agentInstructions&&{agentInstructions:Q.agentInstructions}});W.push(...Rb0($,wY.ANCHOR_PROFILE,wY.ANCHOR_PROFILE,()=>Z.refreshCache(),B));for(let b of[wY.BRAIN_CHARACTER,wY.ANCHOR_PROFILE])W.push(...Rb0($,b,b,async()=>L.invalidateAgent(),B));return{identityService:f,profileService:Z,canonicalIdentityService:G,agentService:L}}var AFA=i(()=>{P10();CB();Vq();RN()});function QFA(A){let{dependencies:Q,jobQueueService:w,messageBus:B,logger:$}=A,Y=Q?.batchJobManager??af.getInstance(w,$),D=Q?.jobProgressMonitor??tf.getInstance(w,B,Y,$),X=Q?.jobQueueWorker??sf.getInstance(w,D,$,{pollInterval:100,concurrency:1,autoStart:!1});return{batchJobManager:Y,jobProgressMonitor:D,jobQueueWorker:X}}var wFA=i(()=>{Dq()});function BFA(A,Q){if(Q)return Q;let w={debug:2,info:3,warn:4,error:5}[A.logging.level];return e2.createFresh({level:w,context:A.logging.context,format:A.logging.format==="json"?"json":"text",...A.logging.file?{logFile:A.logging.file}:{}})}function $FA(A){return{apiKey:A.ai.apiKey,model:A.ai.model,temperature:A.ai.temperature,maxTokens:A.ai.maxTokens,webSearch:A.ai.webSearch,...A.ai.imageApiKey?{imageApiKey:A.ai.imageApiKey}:{}}}function ZR(A){return{url:A.url,...A.authToken?{authToken:A.authToken}:{}}}var YFA=i(()=>{Z0()});function DFA(A){let{config:Q,dependencies:w,initializerLogger:B}=A;B.debug("Initializing Shell services");let $=BFA(Q,w?.logger),Y=[],D=w?.embeddingService??GZ.getInstance({apiKey:Q.ai.apiKey,logger:$}),X=w?.aiService??UZ.getInstance($FA(Q),$),H=IX.getInstance($),W=w?.messageBus??qZ.getInstance($),f=w?.templateRegistry??DW.getInstance($),Z=w?.dataSourceRegistry??ef.getInstance($),G=w?.renderService??lf.getInstance(f),F=w?.daemonRegistry??PU.getInstance($),V=w?.pluginManager??zW.getInstance($,F),L=w?.permissionService??new m$(Q.permissions,{spaces:Q.spaces}),b=w?.attachmentRegistry??AZ.getInstance(),N=w?.runtimeUploadRegistry??LS.createFresh({dataDir:Q.dataDir}),_=w?.runtimeStateService??IW.createFresh(ZR(Q.runtimeStateDatabase),$),j=w?.mcpService??XW.getInstance(W,$),g=w?.jobQueueService??JX.getInstance(ZR(Q.jobQueueDatabase),$),E=LX.getInstance({embeddingService:D,entityRegistry:H,logger:$,jobQueueService:g,messageBus:W,dbConfig:ZR(Q.database),embeddingDbConfig:ZR(Q.embeddingDatabase)}),y=w?.conversationService??sY.getInstance($,W,ZR(Q.conversationDatabase)),h=w?.contentService??new P00({logger:$,entityService:E,aiService:X,templateRegistry:f,dataSourceRegistry:Z}),{identityService:T,profileService:S,canonicalIdentityService:c,agentService:m}=e3A({config:Q,entityService:E,entityRegistry:H,logger:$,messageBus:W,aiService:X,mcpService:j,conversationService:y,runtimeUploadRegistry:N,disposables:Y}),{batchJobManager:B0,jobProgressMonitor:a,jobQueueWorker:v}=QFA({dependencies:w,jobQueueService:g,messageBus:W,logger:$});return{logger:$,disposables:Y,entityRegistry:H,messageBus:W,renderService:G,daemonRegistry:F,pluginManager:V,templateRegistry:f,dataSourceRegistry:Z,mcpService:j,embeddingService:D,entityService:E,aiService:X,conversationService:y,contentService:h,jobQueueService:g,jobQueueWorker:v,batchJobManager:B0,jobProgressMonitor:a,permissionService:L,identityService:T,profileService:S,canonicalIdentityService:c,agentService:m,attachmentRegistry:b,runtimeUploadRegistry:N,runtimeStateService:_}}var XFA=i(()=>{P10();O00();PN();aB();aB();Dq();k9();Mb0();c0();Ob0();IB();xb0();AFA();wFA();YFA()});function HFA(A,Q){A.register(lS.name,lS),Q.debug("Shell system templates registered")}function WFA(A,Q){A.register(Gx.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:o1,formatter:new me,requiredPermission:"public"}),Q.debug("Base entity display template registered")}function fFA(A,Q){A.registerEntityType(wY.NOTE,o1,new IS),Q.debug("Fallback base entity adapter registered")}function ZFA(A,Q){let w=new fx;A.registerEntityType(wY.BRAIN_CHARACTER,w.schema,w),Q.debug("Brain character entity support registered")}function KFA(A,Q){let w=new JU;A.registerEntityType(wY.ANCHOR_PROFILE,w.schema,w),Q.debug("Anchor profile entity support registered")}async function UFA(A){let{plugins:Q,pluginManager:w,logger:B,initOptions:$}=A;B.debug(`Found ${Q.length} plugins to register`);for(let Y of Q)B.debug(`Registering plugin: ${Y.id}`),w.registerPlugin(Y);if(await w.initializePlugins($?.registrationContext),!$?.registerOnly){for(let{id:Y,error:D}of w.getFailedPlugins())if(w.getPlugin(Y)?.requiresDaemonStartup?.())throw D}B.debug("Plugin initialization complete")}var GFA=i(()=>{O00();aB();Vq();RN()});function zFA(){LX.resetInstance(),IX.resetInstance(),ef.resetInstance(),GZ.resetInstance(),sY.resetInstance(),zW.resetInstance(),XW.resetInstance(),qZ.resetInstance(),DW.resetInstance(),lf.resetInstance(),PU.resetInstance(),UZ.resetInstance(),v9.resetInstance(),GW.resetInstance(),QY.resetInstance(),JX.resetInstance(),af.resetInstance(),sf.resetInstance(),tf.resetInstance(),AZ.resetInstance(),IW.resetInstance()}var qFA=i(()=>{P10();PN();aB();Vq();Dq();k9();Mb0();c0();Ob0();IB();xb0()});class FZ{static instance=null;logger;config;static getInstance(A,Q){return FZ.instance??=new FZ(A,Q),FZ.instance}static resetInstance(){FZ.instance=null}static createFresh(A,Q){return new FZ(A,Q)}constructor(A,Q){this.logger=A.child("ShellInitializer"),this.config=Q}registerShellTemplates(A){HFA(A,this.logger)}registerBaseEntityDisplayTemplate(A){WFA(A,this.logger)}registerFallbackBaseEntity(A){fFA(A,this.logger)}registerBrainCharacterSupport(A){ZFA(A,this.logger)}registerAnchorProfileSupport(A){KFA(A,this.logger)}async initializePlugins(A,Q){await UFA({plugins:this.config.plugins,pluginManager:A,logger:this.logger,initOptions:Q})}initializeServices(A){return DFA({config:this.config,dependencies:A,initializerLogger:this.logger})}registerJobHandlers(A,Q,w){let B=Jq.createFresh(Q,w);A.registerHandler("shell:content-generation",B,"shell")}wireShell(A,Q){A.pluginManager.setShell(Q)}async initializeAll(A,Q,w,B){this.logger.debug("Starting Shell initialization");try{if(this.registerShellTemplates(A),this.registerBaseEntityDisplayTemplate(A),this.registerBrainCharacterSupport(Q),this.registerAnchorProfileSupport(Q),await this.initializePlugins(w,B),!Q.hasEntityType(wY.NOTE))this.registerFallbackBaseEntity(Q);this.logger.debug("Shell registration phase complete")}catch($){throw this.logger.error("Shell initialization failed",$),$}}}function Uu(){FZ.resetInstance(),zFA()}async function FFA(){let{Shell:A}=await Promise.resolve().then(() => (hb0(),VFA));await A.resetInstance(),Uu()}var h10=i(()=>{O00();RN();XFA();GFA();qFA()});class vb0{config;services;hooks;constructor(A,Q,w){this.config=A;this.services=Q;this.hooks=w}async boot(A){this.services.logger.debug("Starting Shell boot");let Q=FZ.getInstance(this.services.logger,this.config);if(await this.services.entityService.initialize(),await Q.initializeAll(this.services.templateRegistry,this.services.entityRegistry,this.services.pluginManager,{...A?.mode==="register-only"&&{registerOnly:!0},...this.config.entityDisplay!==void 0&&{registrationContext:{entityDisplay:this.config.entityDisplay}}}),Q.registerJobHandlers(this.services.jobQueueService,this.services.contentService,this.services.entityService),this.hooks.registerCoreDataSources(),this.hooks.registerSystemCapabilities(),A?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(A?.mode!=="startup-check"){await this.startEarlyWebserver(),await this.emitPluginsRegistered();let w=await this.services.entityService.backfillMissingEmbeddings();this.services.logger.debug("Queued missing embedding backfill jobs",{queued:w.queued,skipped:w.skipped})}if(await this.prepareReadyState(),await this.services.pluginManager.readyPlugins(),A?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}await this.startRuntimeServices(),this.startIndexReadinessMonitor(),this.services.logger.debug("Shell boot complete")}async startEarlyWebserver(){if(!this.services.daemonRegistry.has("webserver:webserver"))return;await this.services.daemonRegistry.start("webserver:webserver"),this.services.logger.debug("Started webserver before initial sync")}async emitPluginsRegistered(){await this.services.messageBus.send({type:LN.pluginsRegistered,payload:{timestamp:new Date().toISOString(),pluginCount:this.services.pluginManager.getAllPluginIds().length},sender:"shell",broadcast:!0}),this.services.logger.debug("Emitted plugins registered event")}async prepareReadyState(){await Promise.all([this.services.identityService.initialize(),this.services.profileService.initialize(),this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services initialized");let A=await CU0(this.services.templateRegistry,this.services.entityService);if(A>0)this.services.logger.debug(`Materialized ${A} prompt entities`)}async startRuntimeServices(){await this.services.pluginManager.startPluginDaemons(),await this.services.jobQueueWorker.start(),this.services.jobProgressMonitor.start(),this.services.batchJobManager.start()}startIndexReadinessMonitor(){this.runIndexReadinessMonitor()}async runIndexReadinessMonitor(){for(;;){try{let A=await this.services.entityService.awaitIndexReady({timeoutMs:vx2});if(A.ready){if(A.degraded)this.services.logger.warn("Semantic index ready with degraded embeddings",A);else this.services.logger.debug("Semantic index ready",A);return}this.services.logger.warn("Semantic index not ready yet; retrying readiness monitor",A)}catch(A){this.services.logger.warn("Semantic index readiness monitor failed; retrying",A)}await this.delayIndexReadinessRetry()}}async delayIndexReadinessRetry(){await new Promise((A)=>{setTimeout(A,Cx2).unref()})}}var vx2=30000,Cx2=5000;var JFA=i(()=>{c0();h10()});class IFA{handlers=new Map;register(A,Q){this.handlers.set(A,Q)}getTypes(){return Array.from(this.handlers.keys())}async get(A,Q,w){let B=this.handlers.get(A);if(!B)throw Error(`Unknown insight type: ${A}. Available: ${this.getTypes().join(", ")}`);return B(Q,w)}}function bFA(){let A=new IFA;return A.register("overview",yx2),A.register("publishing-cadence",Ex2),A.register("content-health",gx2),A}async function yx2(A,Q){let w=await A.getEntityCounts(Q),B={},$=0;for(let{entityType:F,count:V}of w)B[F]=V,$+=V;let Y=await Cb0(A,Q),D=Date.now(),X=D-604800000,H=D-2592000000,W=0,f=0;for(let F of Y){let V=new Date(F.created).getTime();if(V>=X)W++;if(V>=H)f++}let Z=LFA(Y),G=Y.filter((F)=>F.metadata.status==="published");return{entityCounts:B,totalEntities:$,recentActivity:{last7days:W,last30days:f},contentHealth:{drafts:Z.length,published:G.length}}}async function Ex2(A,Q){let w=await Cb0(A,Q),B=new Map;for(let Y of w){let D=new Date(Y.created);if(isNaN(D.getTime()))continue;let X=`${D.getUTCFullYear()}-${String(D.getUTCMonth()+1).padStart(2,"0")}`,H=B.get(X);if(!H)H={},B.set(X,H);H[Y.entityType]=(H[Y.entityType]??0)+1}return{months:Array.from(B.entries()).sort((Y,D)=>D[0].localeCompare(Y[0])).map(([Y,D])=>{let X=0;for(let H of Object.values(D))X+=H;return{month:Y,counts:D,total:X}})}}async function gx2(A,Q){let w=await Cb0(A,Q),B=LFA(w).map((X)=>({id:X.id,entityType:X.entityType,title:typeof X.metadata.title==="string"?X.metadata.title:X.id,created:X.created})),$=Date.now(),Y=$-7776000000,D=w.filter((X)=>{if(X.entityType==="image")return!1;let H=new Date(X.updated).getTime();return!isNaN(H)&&H<Y}).map((X)=>({id:X.id,entityType:X.entityType,title:typeof X.metadata.title==="string"?X.metadata.title:X.id,updated:X.updated,daysSinceUpdate:Math.floor(($-new Date(X.updated).getTime())/86400000)}));return{drafts:B,stale:D}}function LFA(A){return A.filter((Q)=>Q.metadata.status==="draft")}async function Cb0(A,Q){let w=A.getEntityTypes(),B=[];for(let $ of w){let Y=await A.listEntities({entityType:$,options:{limit:1000,filter:{visibilityScope:Q}}});B.push(...Y)}return B}class Gu{parse;idOf;items=new Map;constructor(A,Q){this.parse=A;this.idOf=Q}register(A){let Q=this.parse(A);this.items.set(this.keyFor(Q.pluginId,this.idOf(Q)),Q)}unregister(A,Q){if(Q!==void 0){this.items.delete(this.keyFor(A,Q));return}let w=`${A}:`;for(let B of this.items.keys())if(B.startsWith(w))this.items.delete(B)}list(){return Array.from(this.items.values()).sort((A,Q)=>A.priority-Q.priority||A.label.localeCompare(Q.label))}keyFor(A,Q){return`${A}:${Q}`}}var yb0;var NFA=i(()=>{c0();yb0=class yb0 extends Gu{constructor(){super((A)=>hO.parse(A),(A)=>A.url)}}});var Eb0;var jFA=i(()=>{c0();Eb0=class Eb0 extends Gu{constructor(){super((A)=>vO.parse(A),(A)=>A.id)}}});function MFA(A,Q){return{enqueueBatch:A.enqueueBatch.bind(A),getActiveBatches:A.getActiveBatches.bind(A),getBatchStatus:A.getBatchStatus.bind(A),getActiveJobs:Q.getActiveJobs.bind(Q),getStatus:Q.getStatus.bind(Q)}}function _FA(A){let Q=[];for(let[w,B]of A.getAllPlugins()){let{plugin:$}=B;if("getApiRoutes"in $&&typeof $.getApiRoutes==="function")for(let Y of $.getApiRoutes())Q.push({pluginId:w,fullPath:`/api/${w}${Y.path}`,definition:Y})}return Q}function PFA(A){let Q=[];for(let[w,B]of A.getAllPlugins()){let{plugin:$}=B;if("getWebRoutes"in $&&typeof $.getWebRoutes==="function")for(let Y of $.getWebRoutes())Q.push({pluginId:w,fullPath:Y.path,definition:Y})}return Q}async function kFA(A){A.batchJobManager.stop(),A.jobProgressMonitor.stop(),await A.jobQueueWorker.stop();for(let[Q]of A.pluginManager.getAllPlugins())await A.pluginManager.disablePlugin(Q);for(let Q of A.disposables.splice(0))try{Q()}catch(w){A.logger.warn("Failed to dispose shell subscription",w)}A.entityService.close(),A.jobQueueService.close(),A.conversationService.close(),A.runtimeStateService.close()}var Tx2,OFA,xFA,RFA,Sx2,mx2,ux2,hFA,vFA,CFA,yFA,EFA,gFA,TFA,h5B,v5B;var Cq=i(()=>{aB();Z0();Tx2=K.discriminatedUnion("kind",[K.object({kind:K.literal("all")}).strict().describe("Search across all entity types"),K.object({kind:K.literal("type"),entityType:K.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),OFA=K.object({query:K.string().describe("Search term"),scope:Tx2.describe("Structured search scope. Use { kind: 'all' } for broad search across all entity types. Use { kind: 'type', entityType } only when the user asks for a specific entity type."),limit:K.number().optional().describe("Maximum number of results"),includeUngenerated:K.boolean().optional().describe("Include queued/failed generation stubs in results")}),xFA=K.object({entityType:K.string().describe("Entity type"),id:K.string().describe("Entity ID, slug, or title")}),RFA=K.object({entityType:K.string().describe("Entity type to list"),status:K.string().optional().describe("Filter by status. Omit unless the user asks for a known status; do not invent generic statuses. For wish statuses: new, planned, in-progress, done, declined."),limit:K.number().optional().describe("Maximum number of results (default: 20)")}),Sx2=K.object({kind:K.literal("upload").describe("Upload ref kind"),id:K.string().min(1).describe("Upload ID")}),mx2=K.discriminatedUnion("kind",[K.object({kind:K.literal("text").describe("Store exact/direct user-provided content without generation"),content:K.string().min(1).describe("Exact markdown/text/content to persist as provided. For direct save requests where the user includes the content in the same message, use that provided content directly.")}).strict(),K.object({kind:K.literal("url").describe("Create URL/domain-backed entities such as links"),url:K.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),K.object({kind:K.literal("upload").describe("Use extract-markdown to import upload text into a note, or preserve only when the user explicitly wants to save the uploaded file/document bytes themselves. Do not use for saving a previous assistant summary about an upload; use prior-response for that."),upload:Sx2.describe("Exact upload candidate object from the current conversation"),transform:K.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response.")}).strict(),K.object({kind:K.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:K.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict()]),ux2=K.discriminatedUnion("kind",[K.object({kind:K.literal("prompt").describe("Generate a new non-image durable entity from a broad prompt with no durable source entity. Use this for general topical social/newsletter/blog/deck generation. This branch has no source field; use prompt-from-source only after resolving a specific existing content entity."),entityType:K.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:K.string().optional().describe("Title for the generated entity"),prompt:K.string().min(1).describe("Prompt for creating new generated content. Do not use for saving/importing existing uploads or prior responses.")}).strict(),K.object({kind:K.literal("prompt-from-source").describe("Generate a new non-image durable entity from a specific resolved existing content entity. Use when the user asks to generate from/based on a source, including requests like 'create a newsletter based on my latest blog post'. After resolving the source with a tool result, call this operation in the same turn; do not merely say you can generate it."),entityType:K.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:K.string().optional().describe("Title for the generated entity"),source:K.object({entityType:K.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:K.string().min(1).describe("Resolved source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder.")}).strict().describe("Existing durable source entity to ground this generation. Use only resolved entity refs, not uploads, filenames, profile/brain-character context, conversation-only context, unknown sources, or guessed sources."),prompt:K.string().min(1).describe("Prompt for creating new generated content from the resolved source. Do not use for saving/importing existing uploads or prior responses.")}).strict(),K.object({kind:K.literal("standalone-image").describe("Generate a standalone image that is not attached to another entity. Do not use this as a cover image substitute; requested covers require cover-image after the target entity exists."),title:K.string().optional().describe("Title for the generated image"),prompt:K.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),K.object({kind:K.literal("cover-image").describe("Generate an image and attach it to an existing entity as coverImageId. Use only after the target entity already exists and its real entityId is known; do not use in the same initial turn as generating that target entity."),target:K.object({entityType:K.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:K.string().min(1).describe("Existing target entity ID copied from a prior tool result or typed entity ref; never a placeholder or guessed future id")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:K.string().optional().describe("Title for the generated image"),prompt:K.string().min(1).describe("Prompt for creating the cover image")}).strict(),K.object({kind:K.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:K.object({entityType:K.string().min(1).describe("Source entity type"),entityId:K.string().min(1).describe("Canonical source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder")}).strict().describe("Existing durable entity whose attachment provider should render the artifact. Use only resolved entity refs, not uploads or conversation-only context."),attachmentType:K.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:K.string().optional().describe("Title for the generated artifact"),replace:K.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),hFA=K.object({entityType:K.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:K.string().optional().describe("Title for a new entity."),source:mx2.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),replace:K.boolean().optional().describe("Create a new copy intentionally"),confirmed:K.literal(!0).optional().describe("Confirm the creation"),confirmationToken:K.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),vFA=K.object({operation:ux2.describe("Generation operation selector. Use prompt for broad non-image AI-generated entities with no source, prompt-from-source for generation from a resolved existing entity, standalone-image for unattached images, cover-image for generated covers on existing entities, and attachment for deterministic source-derived artifacts; for regenerate/replace/refresh artifact requests use attachment with replace:true."),confirmed:K.literal(!0).optional().describe("Confirm generation"),confirmationToken:K.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),CFA=K.object({entityType:K.string().describe("Entity type"),id:K.string().describe("Entity ID, slug, or title"),fields:K.record(K.unknown()).optional().describe("Partial frontmatter fields to update. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, update fields.coverImageId to that image id. To remove or clear a cover image, set fields.coverImageId to null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require full markdown content replacement via content."),content:K.string().optional().describe("Full markdown content replacement only. Do not use this for status/title/frontmatter updates; use fields instead."),confirmed:K.literal(!0).optional().describe("Confirm the update"),contentHash:K.string().optional().describe("Content hash for optimistic concurrency")}),yFA=K.object({entityType:K.string().describe("Entity type"),id:K.string().describe("Entity ID"),confirmed:K.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:K.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),EFA=K.object({entityType:K.string().describe("Entity type to extract"),source:K.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:K.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:K.literal(!0).optional().describe("Confirm destructive rebuild")}),gFA=K.object({batchId:K.string().optional().describe("Specific batch ID to check"),jobTypes:K.array(K.string()).optional().describe("Filter by job types")}),TFA=K.object({type:K.string().describe("Type of insight to retrieve. Built-in: overview, publishing-cadence, content-health. Plugins may register additional types.")}),h5B=K.object({entityId:K.string().optional(),status:K.enum(["created","generating"]),jobId:K.string().optional(),attachment:JU0.optional()}),v5B=K.object({status:K.literal("extracting"),jobId:K.string(),entityType:K.string(),source:K.string().optional(),mode:K.enum(["derive","rebuild"]).optional()})});function bW(A,Q,w,B){try{A.permissionService.assertEntityActionAllowed(Q,w,B.userPermissionLevel);return}catch($){if($ instanceof mT||$ instanceof Error)return{success:!1,error:$.message};throw $}}var KR=i(()=>{IB()});function LW(A,Q,w,B,$={}){let{visibility:Y="anchor",sideEffects:D}=$;return{name:`${cx2}_${A}`,description:Q,inputSchema:w.shape,handler:async(X,H)=>{let W=w.safeParse(X);if(!W.success)return{success:!1,error:`Invalid input: ${W.error.errors.map((f)=>`${f.path.join(".")}: ${f.message}`).join(", ")}`};try{return await B(W.data,H)}catch(f){return{success:!1,error:vA(f)}}},visibility:Y,...D?{sideEffects:D}:{}}}function yq(A,Q){if(A.entityRegistry.hasEntityType(Q))return;let w=A.entityService.getEntityTypes();return{success:!1,error:`Entity type "${Q}" is not available in this brain. Available types: ${w.join(", ")}.`}}function UR(A){let Q={...A.conversationId?{conversationId:A.conversationId}:{},...A.channelId?{channelId:A.channelId}:{},...A.runId?{runId:A.runId}:{},...A.toolCallId?{toolCallId:A.toolCallId}:{}};return Object.keys(Q).length>0?Q:void 0}function gb0(A){if(A.entityType==="image"&&A.content.startsWith("data:"))return{...A,content:"[binary image data \u2014 use metadata for image info]"};return A}function Xj(A){if(A===void 0)return;let Q=A.trim();return Q.length>0?Q:void 0}function mFA(A){if(A.fields)return{fields:A.fields};if(!A.content)return{};try{let Q=JSON.parse(A.content);if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q)){if("fields"in Q&&typeof Q.fields==="object"&&Q.fields!==null&&!Array.isArray(Q.fields))return{fields:Q.fields};return{fields:Q}}}catch{}return{content:A.content}}function uFA(A){return lx2[A]??A.replaceAll("-"," ")}function v10(A){return[A.metadata.title,A.metadata.name,A.metadata.subject,A.metadata.slug].find((B)=>typeof B==="string"&&B.trim().length>0)??A.id}function cFA(A){return!!A&&Object.keys(A.shape).length>0}function SFA(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}async function lFA(A,Q,w){if(!w)return!1;let B=await A.conversationService.getMessages(w,{limit:100});for(let $ of B){let D=ne($.metadata)?.attachments;if(!Array.isArray(D))continue;for(let X of D){if(!SFA(X))continue;let H=X.source;if(!SFA(H))continue;if(H.kind===Q.kind&&H.id===Q.id)return!0}}return!1}var cx2="system",lx2;var HJ=i(()=>{PN();Z0();lx2={base:"note"}});function ix2(A){return{summary:`Save uploaded file${A.title?` as "${A.title}"`:""}?`,preview:[`Filename: ${A.filename}`,`Media type: ${A.mediaType}`,`Entity type: ${A.entityType}`,...A.title?[`Title: ${A.title}`]:[]].join(`
|
|
387
387
|
`)}}function dx2(A){let{entityType:Q,title:w,prompt:B,content:$,url:Y,from:D}=A,X=w?` "${w}"`:` ${Q}`,H=`${B?"Generate":"Create"}${X}?`,W=D?.kind==="entity-attachment"?D:void 0,f=[`Entity type: ${Q}`,...w?[`Title: ${w}`]:[],...Y?[`URL: ${Y}`]:[],...D?.kind==="upload"?["Upload: uploaded file"]:[],...W?[`Source attachment: ${W.sourceEntityType}/${W.sourceEntityId} (${W.attachmentType})`]:[],...B?[`Prompt: ${B}`]:[],...$?[`Content preview: ${$.slice(0,500)}`]:[]];return{summary:H,preview:f.join(`
|
|
388
|
-
`)}}async function nx2(A,Q,w){if(!w)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let B=await A.conversationService.getMessages(w,{limit:100}),$=Q.messageId?B.find((Y)=>Y.id===Q.messageId&&Y.role==="assistant"):[...B].reverse().find(re);if(!$||!re($))return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};return{success:!0,messageId:$.id,content:$.content}}function rx2(A){switch(A.kind){case"text":return{success:!0,source:{content:A.content}};case"url":return{success:!0,source:{url:A.url}};case"upload":return{success:!0,source:{from:A.upload,uploadRef:A.upload,transform:A.transform}};case"prior-response":return{success:!0,source:{conversationMessageRef:{kind:"conversation-message",...A.messageId?{messageId:A.messageId}:{}}}}}}function ox2(A){if(A.source.kind==="prior-response"){let Q=A.source.messageId??A.resolvedMessageId;return{kind:"prior-response",...Q?{messageId:Q}:{}}}return A.source}async function sx2(A,Q,w,B){let $={interfaceType:B.interfaceType,userId:B.userId,...B.channelId&&{channelId:B.channelId},...B.channelName&&{channelName:B.channelName}},Y=await Q(w,$);if(Y.kind==="handled")return{kind:"handled",result:Y.result};let D=Y.input,X=bW(A,D.entityType,"create",B);if(X)return{kind:"error",result:X};return{kind:"continue",createInput:D}}async function ax2(A,Q){let w={interfaceType:Q.interfaceType,userId:Q.userId,...Q.channelId&&{channelId:Q.channelId},...Q.channelName&&{channelName:Q.channelName}};return A.handler({upload:A.upload,...A.title&&{title:A.title}},w)}async function tx2(A,Q,w){let{entityService:B,entityRegistry:$}=A,Y=w1(Q.title??`${Q.entityType}-${Date.now()}`),D=$.getEffectiveFrontmatterSchema(Q.entityType);try{let X={deduplicateId:!0,...w?{eventContext:w}:{}};return{success:!0,data:{entityId:(Q.content&&cFA(D)?await B.createEntityFromMarkdown({input:{entityType:Q.entityType,id:Y,markdown:Q.content},options:X}):await B.createEntity({entity:{id:Y,entityType:Q.entityType,content:Q.content??"",metadata:{title:Q.title??Y},created:new Date().toISOString(),updated:new Date().toISOString()},options:X})).entityId,status:"created"}}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Failed to create entity"}}}async function ex2(A,Q,w){if(!(Q.source.kind==="upload"&&Q.source.transform==="preserve")){let y=yq(A,Q.entityType);if(y)return{kind:"error",result:y}}let $=rx2(Q.source),{content:Y,url:D,from:X,uploadRef:H,conversationMessageRef:W,transform:f}=$.source,Z=W?await nx2(A,W,w.conversationId??w.channelId):void 0;if(Z&&!Z.success)return{kind:"error",result:Z};let G=Z?.success===!0?Z.content:Y,F=Xj(Q.title);if(f==="extract-markdown"&&(!H||Q.entityType!=="note"))return{kind:"error",result:{success:!1,error:'Transform "extract-markdown" requires entityType "note" and an upload ref. Omit transform for raw file promotion to document/image.'}};let V=Q.replace===!0;if(!G&&!D&&!X)return{kind:"error",result:{success:!1,error:'Provide `source` with kind "text", "url", "prior-response", or "upload". Use system_generate for generated content or artifacts.'}};let L,b=Q.entityType;if(H){if(!await lFA(A,H,w.conversationId??w.channelId))return{kind:"error",result:{success:!1,error:"Upload ref is not accessible in this conversation or no longer exists."}};if(f==="preserve"){let h;try{h=await A.runtimeUploads.scoped(px2).readRecord(H.id)}catch{return{kind:"error",result:{success:!1,error:"Upload ref not found"}}}let T=A.entityRegistry.getUploadSaveHandler(h.mediaType);if(!T)return{kind:"error",result:{success:!1,error:`No installed plugin can save uploads with media type "${h.mediaType}".`}};b=T.entityType,L={upload:H,filename:h.filename,mediaType:h.mediaType,handler:T.handler}}}let N=yq(A,b);if(N)return{kind:"error",result:N};if(G&&Te(G)){let y=VN(G);if(!nO(w.userPermissionLevel,y))return{kind:"error",result:{success:!1,error:`Cannot create entity with visibility "${y}" \u2014 caller permission "${w.userPermissionLevel??"public"}" is not allowed to write at that level.`}}}let _=UR(w),j={entityType:b,...F&&{title:F},...G&&{content:G},...D&&{url:D},...X&&{from:X},...f&&{transform:f},...V&&{replace:V}},g=bW(A,j.entityType,"create",w);if(g)return{kind:"error",result:g};let E=A.entityRegistry.getCreateInterceptor(j.entityType);if(!j.content&&!E&&!L)return{kind:"error",result:{success:!1,error:'URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.'}};if(!E&&!V){let y=j.title?w1(j.title):void 0;if(y){if(await A.entityService.getEntity({entityType:j.entityType,id:y}))return{kind:"error",result:{success:!1,error:`A ${j.entityType} already exists for "${y}". To change its fields or status, use system_update; pass replace:true to create a new copy intentionally.`}}}}return{kind:"ok",prepared:{createInput:j,resolvedMessageId:Z?.success===!0?Z.messageId:void 0,interceptor:E,eventContext:_,...L&&{uploadPreserve:L}}}}function pFA(A){let Q=new pf;return LW("create","Create a new entity from existing material. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use source to choose exactly one concrete source: text for exact user-provided content, url for URL-first flows, prior-response for saving a previous assistant response, or upload with transform extract-markdown to import text into a note or transform preserve to save raw uploaded bytes as their durable file entity. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind text with that content instead of asking them to paste it again; for example, 'Save this as a note: ...' already supplies the content, even when it is only a short sentence or fragment. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Use entityType wish for explicitly saved or tracked unmet requested capabilities or outcomes. On the initial create request, do not pass confirmed; the tool will return confirmation args after the user confirms.",hFA,async(w,B)=>{let $=await ex2(A,w,B);if($.kind==="error")return $.result;let{createInput:Y}=$.prepared,{resolvedMessageId:D,interceptor:X,eventContext:H,uploadPreserve:W}=$.prepared;if(w.confirmed){let f=w.confirmationToken,Z=Q.validate(f,w);if(Z.status==="missing")return{success:!1,error:"No pending create confirmation found. Please request creation again and confirm the new approval."};if(Z.status==="mismatch")return{success:!1,error:"Confirmed create arguments do not match the pending approval. Please request creation again and confirm the new approval."}}else{let f=W?ix2({...Y.title&&{title:Y.title},filename:W.filename,mediaType:W.mediaType,entityType:Y.entityType}):dx2(Y),Z=ox2({source:w.source,...D&&{resolvedMessageId:D}}),G=Q.create((F)=>({entityType:Y.entityType,...Y.title&&{title:Y.title},source:Z,...Y.replace&&{replace:Y.replace},confirmed:!0,confirmationToken:F}));return{needsConfirmation:!0,toolName:"system_create",summary:f.summary,preview:f.preview,args:G}}if(W)return ax2({upload:W.upload,...Y.title&&{title:Y.title},handler:W.handler},B);if(X){let f=await sx2(A,X,Y,B);if(f.kind==="handled"||f.kind==="error")return f.result;Y=f.createInput}if(!Y.content)return{success:!1,error:'URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.'};return tx2(A,Y,H)},{visibility:"trusted",sideEffects:"writes"})}var px2;var iFA=i(()=>{PN();aB();k9();Z0();Cq();KR();HJ();px2={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"}});function AR2(A){let Q=A.title?` "${A.title}"`:` ${A.entityType}`,w=A.from?.kind==="entity-attachment"?A.from:void 0,B=[`Entity type: ${A.entityType}`,...A.title?[`Title: ${A.title}`]:[],...A.prompt?[`Prompt: ${A.prompt}`]:[],...w?[`Source attachment: ${w.sourceEntityType}/${w.sourceEntityId} (${w.attachmentType})`]:[],...A.targetEntityType&&A.targetEntityId?[`Target: ${A.targetEntityType}/${A.targetEntityId}`]:[]];return{summary:`Generate${Q}?`,preview:B.join(`
|
|
388
|
+
`)}}async function nx2(A,Q,w){if(!w)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let B=await A.conversationService.getMessages(w,{limit:100}),$=Q.messageId?B.find((Y)=>Y.id===Q.messageId&&Y.role==="assistant"):[...B].reverse().find(re);if(!$||!re($))return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};return{success:!0,messageId:$.id,content:$.content}}function rx2(A){switch(A.kind){case"text":return{success:!0,source:{content:A.content}};case"url":return{success:!0,source:{url:A.url}};case"upload":return{success:!0,source:{from:A.upload,uploadRef:A.upload,transform:A.transform}};case"prior-response":return{success:!0,source:{conversationMessageRef:{kind:"conversation-message",...A.messageId?{messageId:A.messageId}:{}}}}}}function ox2(A){if(A.source.kind==="prior-response"){let Q=A.source.messageId??A.resolvedMessageId;return{kind:"prior-response",...Q?{messageId:Q}:{}}}return A.source}async function sx2(A,Q,w,B){let $={interfaceType:B.interfaceType,userId:B.userId,...B.channelId&&{channelId:B.channelId},...B.channelName&&{channelName:B.channelName}},Y=await Q(w,$);if(Y.kind==="handled")return{kind:"handled",result:Y.result};let D=Y.input,X=bW(A,D.entityType,"create",B);if(X)return{kind:"error",result:X};return{kind:"continue",createInput:D}}async function ax2(A,Q){let w={interfaceType:Q.interfaceType,userId:Q.userId,...Q.channelId&&{channelId:Q.channelId},...Q.channelName&&{channelName:Q.channelName}};return A.handler({upload:A.upload,...A.title&&{title:A.title}},w)}async function tx2(A,Q,w){let{entityService:B,entityRegistry:$}=A,Y=w1(Q.title??`${Q.entityType}-${Date.now()}`),D=$.getEffectiveFrontmatterSchema(Q.entityType);try{let X={deduplicateId:!0,...w?{eventContext:w}:{}};return{success:!0,data:{entityId:(Q.content&&cFA(D)?await B.createEntityFromMarkdown({input:{entityType:Q.entityType,id:Y,markdown:Q.content},options:X}):await B.createEntity({entity:{id:Y,entityType:Q.entityType,content:Q.content??"",metadata:{title:Q.title??Y},created:new Date().toISOString(),updated:new Date().toISOString()},options:X})).entityId,status:"created"}}}catch(X){return{success:!1,error:X instanceof Error?X.message:"Failed to create entity"}}}async function ex2(A,Q,w){if(!(Q.source.kind==="upload"&&Q.source.transform==="preserve")){let y=yq(A,Q.entityType);if(y)return{kind:"error",result:y}}let $=rx2(Q.source),{content:Y,url:D,from:X,uploadRef:H,conversationMessageRef:W,transform:f}=$.source,Z=W?await nx2(A,W,w.conversationId??w.channelId):void 0;if(Z&&!Z.success)return{kind:"error",result:Z};let G=Z?.success===!0?Z.content:Y,F=Xj(Q.title);if(f==="extract-markdown"&&(!H||Q.entityType!=="note"))return{kind:"error",result:{success:!1,error:'Transform "extract-markdown" requires entityType "note" and an upload ref. Omit transform for raw file promotion to document/image.'}};let V=Q.replace===!0;if(!G&&!D&&!X)return{kind:"error",result:{success:!1,error:'Provide `source` with kind "text", "url", "prior-response", or "upload". Use system_generate for generated content or artifacts.'}};let L,b=Q.entityType;if(H){if(!await lFA(A,H,w.conversationId??w.channelId))return{kind:"error",result:{success:!1,error:"Upload ref is not accessible in this conversation or no longer exists."}};if(f==="preserve"){let h;try{h=await A.runtimeUploads.scoped(px2).readRecord(H.id)}catch{return{kind:"error",result:{success:!1,error:"Upload ref not found"}}}let T=A.entityRegistry.getUploadSaveHandler(h.mediaType);if(!T)return{kind:"error",result:{success:!1,error:`No installed plugin can save uploads with media type "${h.mediaType}".`}};b=T.entityType,L={upload:H,filename:h.filename,mediaType:h.mediaType,handler:T.handler}}}let N=yq(A,b);if(N)return{kind:"error",result:N};if(G&&Te(G)){let y=VN(G);if(!nO(w.userPermissionLevel,y))return{kind:"error",result:{success:!1,error:`Cannot create entity with visibility "${y}" \u2014 caller permission "${w.userPermissionLevel??"public"}" is not allowed to write at that level.`}}}let _=UR(w),j={entityType:b,...F&&{title:F},...G&&{content:G},...D&&{url:D},...X&&{from:X},...f&&{transform:f},...V&&{replace:V}},g=bW(A,j.entityType,"create",w);if(g)return{kind:"error",result:g};let E=A.entityRegistry.getCreateInterceptor(j.entityType);if(!j.content&&!E&&!L)return{kind:"error",result:{success:!1,error:'URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.'}};if(!E&&!V){let y=j.title?w1(j.title):void 0;if(y){if(await A.entityService.getEntity({entityType:j.entityType,id:y}))return{kind:"error",result:{success:!1,error:`A ${j.entityType} already exists for "${y}". To change its fields or status, use system_update; pass replace:true to create a new copy intentionally.`}}}}return{kind:"ok",prepared:{createInput:j,resolvedMessageId:Z?.success===!0?Z.messageId:void 0,interceptor:E,eventContext:_,...L&&{uploadPreserve:L}}}}function pFA(A){let Q=new pf;return LW("create","Create a new entity from existing material. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use source to choose exactly one concrete source: text for exact user-provided content, url for URL-first flows, prior-response for saving a previous assistant response, or upload with transform extract-markdown to import text into a note or transform preserve to save raw uploaded bytes as their durable file entity. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind text with that content instead of asking them to paste it again; for example, 'Save this as a note: ...' or 'Save this memo about the launch timeline' already supplies the content, even when it is only a short sentence or fragment. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Only use source.kind upload when the runtime supplies an actual upload reference/attachment; if the user message merely contains a pasted uploaded-file transcript with readable content, use source.kind text for that visible content. Use entityType wish for explicitly saved or tracked unmet requested capabilities or outcomes. On the initial create request, do not pass confirmed; the tool will return confirmation args after the user confirms.",hFA,async(w,B)=>{let $=await ex2(A,w,B);if($.kind==="error")return $.result;let{createInput:Y}=$.prepared,{resolvedMessageId:D,interceptor:X,eventContext:H,uploadPreserve:W}=$.prepared;if(w.confirmed){let f=w.confirmationToken,Z=Q.validate(f,w);if(Z.status==="missing")return{success:!1,error:"No pending create confirmation found. Please request creation again and confirm the new approval."};if(Z.status==="mismatch")return{success:!1,error:"Confirmed create arguments do not match the pending approval. Please request creation again and confirm the new approval."}}else{let f=W?ix2({...Y.title&&{title:Y.title},filename:W.filename,mediaType:W.mediaType,entityType:Y.entityType}):dx2(Y),Z=ox2({source:w.source,...D&&{resolvedMessageId:D}}),G=Q.create((F)=>({entityType:Y.entityType,...Y.title&&{title:Y.title},source:Z,...Y.replace&&{replace:Y.replace},confirmed:!0,confirmationToken:F}));return{needsConfirmation:!0,toolName:"system_create",summary:f.summary,preview:f.preview,args:G}}if(W)return ax2({upload:W.upload,...Y.title&&{title:Y.title},handler:W.handler},B);if(X){let f=await sx2(A,X,Y,B);if(f.kind==="handled"||f.kind==="error")return f.result;Y=f.createInput}if(!Y.content)return{success:!1,error:'URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.'};return tx2(A,Y,H)},{visibility:"trusted",sideEffects:"writes"})}var px2;var iFA=i(()=>{PN();aB();k9();Z0();Cq();KR();HJ();px2={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"}});function AR2(A){let Q=A.title?` "${A.title}"`:` ${A.entityType}`,w=A.from?.kind==="entity-attachment"?A.from:void 0,B=[`Entity type: ${A.entityType}`,...A.title?[`Title: ${A.title}`]:[],...A.prompt?[`Prompt: ${A.prompt}`]:[],...w?[`Source attachment: ${w.sourceEntityType}/${w.sourceEntityId} (${w.attachmentType})`]:[],...A.targetEntityType&&A.targetEntityId?[`Target: ${A.targetEntityType}/${A.targetEntityId}`]:[]];return{summary:`Generate${Q}?`,preview:B.join(`
|
|
389
389
|
`)}}async function QR2(A,Q,w){if(!Q)return{kind:"ok",sourceAttachment:void 0};let B=await Q4(A.entityService,Q.sourceEntityType,Q.sourceEntityId,A.logger,void 0,w);if(!B.ok)return{kind:"error",result:{success:!1,error:B.error,code:"source-not-found"}};let $={...Q,sourceEntityId:B.entity.id};if(!A.attachments.hasProvider($.sourceEntityType,$.attachmentType))return{kind:"error",result:{success:!1,error:`No attachment provider found for ${$.sourceEntityType}/${$.attachmentType}.`,code:"no-provider"}};let Y=A.attachments.getProviderMetadata($.sourceEntityType,$.attachmentType);if(!Y)return{kind:"error",result:{success:!1,error:`Attachment provider for ${$.sourceEntityType}/${$.attachmentType} is missing output metadata.`,code:"provider-missing-metadata"}};return{kind:"ok",sourceAttachment:$,metadata:Y}}async function wR2(A,Q,w){if(!Q)return{kind:"ok",source:void 0};let B=await Q4(A.entityService,Q.entityType,Q.entityId,A.logger,void 0,w);if(!B.ok)return{kind:"error",result:{success:!1,error:B.error,code:"source-not-found"}};return{kind:"ok",source:{...Q,entityId:B.entity.id}}}async function BR2(A,Q,w){if(!Q)return{kind:"ok",target:void 0};let B=await Q4(A.entityService,Q.entityType,Q.entityId,A.logger,void 0,w);if(!B.ok)return{kind:"error",result:{success:!1,error:B.error}};return{kind:"ok",target:{...Q,entityId:B.entity.id}}}async function $R2(A,Q,w,B){let $={interfaceType:B.interfaceType,userId:B.userId,...B.channelId&&{channelId:B.channelId},...B.channelName&&{channelName:B.channelName}},Y=await Q(w,$);if(Y.kind==="handled")return{kind:"handled",result:Y.result};let D=Y.input,X=bW(A,D.entityType,"create",B);if(X)return{kind:"error",result:X};return{kind:"continue",createInput:D}}async function YR2(A,Q,w,B,$){let{entityService:Y,jobs:D}=A,X=w1(Q.title??w).slice(0,100);if(!X)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let H=Q.title??X,W=RU0(A.entityRegistry,{entityType:Q.entityType,id:X,title:H});if(!W)return{success:!1,error:`Entity type '${Q.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let f;try{f=(await Y.createEntity({entity:W,options:{deduplicateId:!0,...B?{eventContext:B}:{}}})).entityId}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Failed to persist generation stub"}}try{let Z=await D.enqueue({type:`${Q.entityType}:generation`,data:{entityId:f,prompt:w,...Q.title&&{title:Q.title},...Q.sourceEntityType&&{sourceEntityType:Q.sourceEntityType},...Q.sourceEntityId&&{sourceEntityId:Q.sourceEntityId},...Q.sourceEntityIds&&{sourceEntityIds:Q.sourceEntityIds},...Q.targetEntityType&&{targetEntityType:Q.targetEntityType},...Q.targetEntityId&&{targetEntityId:Q.targetEntityId}},toolContext:$});return{success:!0,data:{entityId:f,status:"generating",jobId:Z}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Failed to queue generation job"}}}async function DR2(A,Q,w){let B=Q.operation,$=p8(w.userPermissionLevel),Y,D,X=B.kind==="attachment"&&B.replace===!0;if(B.kind==="prompt"||B.kind==="prompt-from-source"){if(B.entityType==="image")return{kind:"error",result:{success:!1,error:"Use operation.kind 'standalone-image' or 'cover-image' for image generation.",code:"unsupported-generation"}};let Z=B.kind==="prompt-from-source"?await wR2(A,B.source,$):{kind:"ok",source:void 0};if(Z.kind==="error")return Z;let G=Xj(B.title);Y={entityType:B.entityType,...G?{title:G}:{},prompt:B.prompt,...Z.source?.entityType&&{sourceEntityType:Z.source.entityType},...Z.source?.entityId&&{sourceEntityId:Z.source.entityId,sourceEntityIds:[Z.source.entityId]}}}else if(B.kind==="standalone-image"){let Z=Xj(B.title);Y={entityType:"image",...Z?{title:Z}:{},prompt:B.prompt}}else if(B.kind==="cover-image"){let Z=await BR2(A,B.target,$);if(Z.kind==="error"){let F=Z.result;return{kind:"error",result:"success"in F&&F.success===!1?{...F,code:"target-not-found"}:F}}let G=Xj(B.title);Y={entityType:"image",...G?{title:G}:{},prompt:B.prompt,...Z.target?.entityType&&{targetEntityType:Z.target.entityType},...Z.target?.entityId&&{targetEntityId:Z.target.entityId}}}else{let Z=await QR2(A,{sourceEntityType:B.source.entityType,sourceEntityId:B.source.entityId,attachmentType:B.attachmentType},$);if(Z.kind==="error")return Z;D=Z.sourceAttachment;let G=Z.metadata;if(!G||!D)return{kind:"error",result:{success:!1,error:"Attachment generation requires provider metadata.",code:"provider-missing-metadata"}};let F=Xj(B.title);Y={entityType:G.outputEntityType,...F?{title:F}:{},from:{kind:"entity-attachment",...D},...X&&{replace:X},...G.targetField&&{targetEntityType:D.sourceEntityType,targetEntityId:D.sourceEntityId}}}let H=yq(A,Y.entityType);if(H)return{kind:"error",result:H};let W=bW(A,Y.entityType,"create",w);if(W)return{kind:"error",result:W};let f=A.entityRegistry.getCreateInterceptor(Y.entityType);if(!Y.prompt&&!Y.from)return{kind:"error",result:{success:!1,error:"Provide a generation source."}};if(Y.from&&!f)return{kind:"error",result:{success:!1,error:`Entity type '${Y.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,code:"unsupported-generation"}};if(!f&&!X){let Z=Y.prompt?w1(Y.title??Y.prompt).slice(0,100):Y.title?w1(Y.title):void 0;if(Z){if(await A.entityService.getEntity({entityType:Y.entityType,id:Z}))return{kind:"error",result:{success:!1,error:`A ${Y.entityType} already exists for "${Z}". To change its fields or status, use system_update; pass replace:true to generate a new copy intentionally.`}}}}return{kind:"ok",prepared:{createInput:Y,operation:XR2(B,Y,D),sourceAttachment:D,interceptor:f,eventContext:UR(w)}}}function XR2(A,Q,w){if(A.kind==="attachment"){let B=w??{sourceEntityType:A.source.entityType,sourceEntityId:A.source.entityId,attachmentType:A.attachmentType};return{kind:"attachment",source:{entityType:B.sourceEntityType,entityId:B.sourceEntityId},attachmentType:B.attachmentType,...Q.title&&{title:Q.title},...Q.replace&&{replace:Q.replace}}}if(A.kind==="cover-image")return{kind:"cover-image",target:{entityType:Q.targetEntityType??A.target.entityType,entityId:Q.targetEntityId??A.target.entityId},...Q.title&&{title:Q.title},prompt:A.prompt};if(A.kind==="standalone-image")return{kind:"standalone-image",...Q.title&&{title:Q.title},prompt:A.prompt};if(A.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:Q.entityType,...Q.title&&{title:Q.title},source:{entityType:Q.sourceEntityType??A.source.entityType,entityId:Q.sourceEntityId??A.source.entityId},prompt:A.prompt};return{kind:"prompt",entityType:Q.entityType,...Q.title&&{title:Q.title},prompt:A.prompt}}function dFA(A){let Q=new pf;return LW("generate","Generate durable content or artifacts. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; do not call standalone-image or cover-image until the target entity exists after confirmation. Critical: broad topical prompt generation uses operation.kind prompt and has no source field. Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Critical: when the user asks to generate from a source such as 'my latest blog post', resolve the source, then call operation.kind prompt-from-source in the same turn; for latest blog/published source requests, use system_list metadata to compare publishedAt and do not rely on semantic search order. If dated candidates such as publishedAt are visible, choose the newest candidate by publishedAt (not updated/created order) and do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Requires confirmation. Calling this tool without confirmed is how you request that confirmation; do not respond with separate prose such as 'I can generate it if you want' or 'I need to queue it first.' Use operation.kind prompt for broad non-image AI-generated entities with no source. Use operation.kind prompt-from-source only when generating from a resolved existing durable source entity, for example a newsletter from a resolved post: { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. Use standalone-image only for unattached generated images, cover-image with operation.target only for generated covers on existing entities, and attachment with operation.source for source-derived artifacts such as carousel/printable PDFs or OG/social preview images. When a cover-image request for an existing entity resolves a clear target via search/get, call this tool in the same turn; do not stop after saying you found the entity. For regenerate/replace/refresh source-derived artifact requests, call attachment with replace:true immediately; do not say you can queue it later. When the user asks to create/write/draft/generate new durable content, call this tool without confirmed to request confirmation instead of asking for separate prose approval. If you first resolve a clear source entity for the requested generation, still call this tool in the same turn using prompt-from-source. Use system_create instead for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded file preservation with upload transform preserve. On the initial generation request, do not pass confirmed; the tool returns confirmation args.",vFA,async(w,B)=>{let $=await DR2(A,w,B);if($.kind==="error")return $.result;let{createInput:Y}=$.prepared,{operation:D,interceptor:X,eventContext:H}=$.prepared;if(w.confirmed){let W=Q.validate(w.confirmationToken,w);if(W.status==="missing")return{success:!1,error:"No pending generate confirmation found. Please request generation again and confirm the new approval."};if(W.status==="mismatch")return{success:!1,error:"Confirmed generate arguments do not match the pending approval. Please request generation again and confirm the new approval."}}else{let W=AR2(Y),f=Q.create((Z)=>({operation:D,confirmed:!0,confirmationToken:Z}));return{needsConfirmation:!0,toolName:"system_generate",summary:W.summary,preview:W.preview,args:f}}if(X){let W=await $R2(A,X,Y,B);if(W.kind==="handled"||W.kind==="error")return W.result;Y=W.createInput}if(!Y.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return YR2(A,Y,Y.prompt,H,B)},{visibility:"trusted",sideEffects:"writes"})}var nFA=i(()=>{aB();k9();Z0();Cq();KR();HJ()});function rFA(A){let{entityService:Q,entityRegistry:w,logger:B}=A,$=new pf;return LW("delete","Request entity deletion by id. Unauthorized callers get a permission error; authorized callers get confirmation first. Do not pass confirmed on the initial request.",yFA,async(Y,D)=>{if((D.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let X=bW(A,Y.entityType,"delete",D);if(X)return X;let H=yq(A,Y.entityType);if(H)return H;if(w.getAdapter(Y.entityType).isSingleton===!0)return{success:!1,error:`${Y.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let W=p8(D.userPermissionLevel),f=await Q4(Q,Y.entityType,Y.id,B,void 0,W);if(!f.ok)return{success:!1,error:f.error};let{entity:Z}=f;if(Y.confirmed){let V=$.validate(Y.confirmationToken,Y);if(V.status==="missing")return{success:!1,error:"No pending delete confirmation found. Please request deletion again and confirm the new approval."};if(V.status==="mismatch")return{success:!1,error:"Confirmed delete arguments do not match the pending approval. Please request deletion again and confirm the new approval."};try{await Q.deleteEntity({entityType:Y.entityType,id:Z.id})}catch(L){return{success:!1,error:L instanceof Error?L.message:"Failed to delete entity"}}return{success:!0,data:{deleted:Z.id}}}let G=v10(Z),F=$.create((V)=>({...Y,id:Z.id,confirmed:!0,confirmationToken:V}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${G}"?`,preview:Z.content.slice(0,200),args:F}},{visibility:"anchor",sideEffects:"writes"})}var oFA=i(()=>{aB();k9();Cq();KR();HJ()});function sFA(A){let{entityService:Q,jobs:w}=A;return LW("extract",'Generate derived entities (e.g. topics) from existing content. Use this for explicit requests like "generate topics for me", "extract topics", "derive topics from my notes" \u2014 call once with `entityType` (typically `"topic"`); do not preflight with search/list. After a successful non-confirmation extract call, report that extraction started or was queued and do not append optional follow-up offers like "If you want...". Do not call this for vague continuations such as "go ahead", "continue", or "do that" unless the operator clearly chose extraction or topic derivation. Provide `source` to derive from a single entity, omit for a batch over all sources. `mode: "rebuild"` is currently only supported for `entityType: "topic"` and requires confirmation; other entity types fall back to normal projection mode.',EFA,async(B,$)=>{let{entityType:Y,source:D}=B,H=(B.mode??"derive")==="rebuild",W=Y==="topic"&&!D,f=H&&W?"rebuild":"derive",Z=yq(A,Y);if(Z)return Z;let G=bW(A,Y,"extract",$);if(G)return G;if(H&&W&&!B.confirmed)return{needsConfirmation:!0,toolName:"system_extract",summary:"Rebuild all derived topic entities from current source content?",preview:"This will delete existing topics and regenerate them from scratch.",args:{...B,confirmed:!0}};try{let F={mode:f};if(D){let L=p8($.userPermissionLevel);for(let b of Q.getEntityTypes()){let N=await Q.getEntity({entityType:b,id:D,visibilityScope:L});if(N){F.mode="source",F.entityId=N.id,F.entityType=N.entityType;break}}if(!F.entityId)return{success:!1,error:`Source entity not found: ${D}`}}return{success:!0,data:{status:"extracting",jobId:await w.enqueue({type:`${Y}:project`,data:F,toolContext:$}),entityType:Y,mode:f,...D&&{source:D}},...H&&!W?{message:D||Y!=="topic"?`Rebuild is currently only supported for batch topic extraction. Ran normal projection mode for ${Y} instead.`:void 0}:{}}}catch(F){return{success:!1,error:F instanceof Error?F.message:"Failed to queue extraction job"}}},{visibility:"trusted",sideEffects:"writes"})}var aFA=i(()=>{aB();Cq();KR();HJ()});var tFA,eFA,AVA,zu,HR2;var Tb0=i(()=>{Z0();aB();tFA=K.enum(["png","jpg","jpeg","webp","gif","svg"]),eFA=K.enum(["pending","draft","failed"]),AVA=K.object({title:K.string().optional(),alt:K.string().optional(),format:tFA,width:K.number(),height:K.number(),status:eFA.optional(),processingJobId:K.string().optional(),processingError:K.string().optional(),sourceUrl:K.string().url().optional(),sourceEntityType:K.string().optional(),sourceEntityId:K.string().optional(),sourceUploadId:K.string().optional(),sourceFilename:K.string().optional(),sourceMediaType:K.string().optional(),attachmentType:K.string().optional(),dedupKey:K.string().optional()}),zu=o1.extend({entityType:K.literal("image"),metadata:AVA}),HR2=K.object({url:K.string(),alt:K.string(),title:K.string(),width:K.number(),height:K.number()})});function WJ(A){let Q=A.trim().match(/^data:image\/([a-z+]+);base64,(.+)$/i);if(!Q?.[1]||!Q[2])throw Error("Invalid image data URL");return{format:Q[1].toLowerCase(),base64:Q[2]}}function Sb0(A,Q){return`data:image/${Q==="jpg"?"jpeg":Q};base64,${A}`}function Hj(A){for(let[Q,w]of Object.entries(WR2))if(A.startsWith(w))return Q;return null}async function NW(A){return Mt(A,"image/")}function fJ(A){let Q=Buffer.from(A,"base64");if(Q[0]===137&&Q[1]===80&&Q[2]===78&&Q[3]===71){let w=Q.readUInt32BE(16),B=Q.readUInt32BE(20);return{width:w,height:B}}if(Q[0]===255&&Q[1]===216){let w=2;while(w<Q.length-8){if(Q[w]!==255){w++;continue}let B=Q[w+1];if(B===192||B===194){let Y=Q.readUInt16BE(w+5);return{width:Q.readUInt16BE(w+7),height:Y}}let $=Q.readUInt16BE(w+2);w+=2+$}}if(Q[0]===71&&Q[1]===73&&Q[2]===70){let w=Q.readUInt16LE(6),B=Q.readUInt16LE(8);return{width:w,height:B}}if(Q.length>=30&&Q[0]===82&&Q[1]===73&&Q[2]===70&&Q[3]===70){if(Q[12]===86&&Q[13]===80&&Q[14]===56){if(Q[15]===32){let w=Q[26]??0,B=Q[27]??0,$=Q[28]??0,Y=Q[29]??0,D=(w|B<<8)&16383,X=($|Y<<8)&16383;return{width:D,height:X}}if(Q[15]===76&&Q.length>=25){let w=Q.readUInt32LE(21),B=(w&16383)+1,$=(w>>14&16383)+1;return{width:B,height:$}}}}return null}var WR2;var mb0=i(()=>{Z0();WR2={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"}});class ub0{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=zu;toMarkdown(A){return A.content}fromMarkdown(A){let{format:Q,base64:w}=WJ(A),B=fJ(w);return{entityType:"image",content:A,metadata:{format:Q,width:B?.width??0,height:B?.height??0}}}extractMetadata(A){return A.metadata}parseFrontMatter(A,Q){return Q.parse({})}generateFrontMatter(A){return""}getBodyTemplate(){return""}createImageEntity(A){let{dataUrl:Q,title:w,alt:B}=A,{format:$,base64:Y}=WJ(Q),D=fJ(Y),H=Hj(Y)??$;return{entityType:"image",content:Q,metadata:{title:w,alt:B??w,format:H,width:D?.width??0,height:D?.height??0,...A.status&&{status:A.status},...A.sourceUrl&&{sourceUrl:A.sourceUrl},...A.sourceEntityType&&{sourceEntityType:A.sourceEntityType},...A.sourceEntityId&&{sourceEntityId:A.sourceEntityId},...A.sourceUploadId&&{sourceUploadId:A.sourceUploadId},...A.sourceFilename&&{sourceFilename:A.sourceFilename},...A.sourceMediaType&&{sourceMediaType:A.sourceMediaType},...A.attachmentType&&{attachmentType:A.attachmentType},...A.dedupKey&&{dedupKey:A.dedupKey}}}}}var vX;var QVA=i(()=>{Tb0();mb0();vX=new ub0});async function wVA(A,Q){let w=await Q.getEntity({entityType:"image",id:A});if(!w)return;return{url:w.content,alt:w.metadata.alt??"",title:w.metadata.title??"",width:w.metadata.width,height:w.metadata.height}}function BVA(A,Q){let w=fR2.exec(A.content);if(!w?.[1])return;try{let B=Jt(w[1]);if(B&&typeof B==="object"&&!Array.isArray(B)){let $=B[Q];return typeof $==="string"?$:void 0}}catch{return}return}function qu(A){return BVA(A,"coverImageId")}function C10(A){return BVA(A,"ogImageId")}function Wj(A,Q){return{...A,content:a4(A.content,"coverImageId",Q)}}function Fu(A,Q){return{...A,content:a4(A.content,"ogImageId",Q)}}async function cb0(A,Q){let w=qu(A);if(!w)return;return wVA(w,Q)}var fR2;var $VA=i(()=>{Z0();fR2=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/});function lb0(A){let Q=[],w=ZR2.parse(A);return LT(w,"image",(B)=>{Q.push({url:B.url,alt:B.alt??"",title:B.title??void 0})}),Q}var ZR2;var YVA=i(()=>{Wt();Sf0();ZR2=QO()});var H4=i(()=>{Tb0();QVA();$VA();YVA();mb0()});function DVA(A,Q,w,B){let $=B.getEntityTypeConfig(A).publish?.publishStatuses;if(!$?.length)return"non-publish";if(typeof w!=="string")return"non-publish";let Y=typeof Q==="string"&&$.includes(Q);if(!$.includes(w))return"non-publish";return Y?"within-publish-set":"boundary"}function KR2(A,Q){return Q==="visibility"?A.visibility:A.metadata[Q]}function UR2(A,Q){let{visibility:w,coverImageId:B,ogImageId:$,...Y}=Q,D=w===void 0?A.visibility:f7.parse(w),X=Object.hasOwn(Q,"coverImageId")?Wj(A,typeof B==="string"?B:null):A,H=Object.hasOwn(Q,"ogImageId")?Fu(X,typeof $==="string"?$:null):X,W={...A.metadata};for(let[Z,G]of Object.entries(Y))if(G===null)delete W[Z];else W[Z]=G;let f={...H,visibility:D,metadata:W};for(let[Z,G]of Object.entries(Y))if(G===null)delete f[Z];else f[Z]=G;return f}function GR2(A,Q){if(A!=="anchor-profile")return;if(Q.fields)return{success:!1,error:"anchor-profile updates require full markdown content replacement, not fields-only updates."};return}function zR2(A,Q,w){if(Q.content===void 0)return;let B=Q.content.trim(),$=w.getEffectiveFrontmatterSchema(A);if(!$)return;if(!B)return{success:!1,error:"Full content replacement cannot be empty for this entity type. Use 'fields' for partial updates."};try{w.getAdapter(A).parseFrontMatter(Q.content,$)}catch{return{success:!1,error:"Invalid content replacement for this entity type. Provide full markdown with valid frontmatter, or use 'fields' for partial updates."}}return}function qR2(A,Q,w){if(!Q.fields||!("coverImageId"in Q.fields))return;let B=Q.fields.coverImageId;if(B!==null&&B!==void 0&&typeof B!=="string")return{success:!1,error:"coverImageId must be a string or null"};if(B==="__PENDING__"||typeof B==="string"&&B.startsWith("upload-"))return{success:!1,error:"coverImageId must reference an existing image id or be null"};if(w.getAdapter(A).supportsCoverImage)return;return{success:!1,error:`Entity type '${A}' doesn't support cover images`}}function FR2(A,Q,w){if(Q.fields&&"status"in Q.fields)return Q.fields.status;if(Q.content!==void 0){let B=w.getEffectiveFrontmatterSchema(A.entityType);if(!B)return A.metadata.status;try{return w.getAdapter(A.entityType).parseFrontMatter(Q.content,B).status}catch{return A.metadata.status}}return A.metadata.status}function VR2(A,Q){if(Q.fields)return Object.entries(Q.fields).map(([Y,D])=>`${Y}: ${String(KR2(A,Y)??"(empty)")} \u2192 ${String(D)}`).join(`
|
|
390
390
|
`);let w=A.content.split(`
|
|
391
391
|
`),B=(Q.content??"").split(`
|
|
392
392
|
`),$=[];for(let Y=0;Y<Math.max(w.length,B.length);Y++)if((w[Y]??"")!==(B[Y]??"")){if(w[Y])$.push(`- ${w[Y]}`);if(B[Y])$.push(`+ ${B[Y]}`)}return $.join(`
|
|
393
393
|
`)}function XVA(A){let{entityService:Q,logger:w,entityRegistry:B}=A;return LW("update","Update an entity's fields or content. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. For direct requests that provide exact IDs to set an existing image as an entity cover, call this tool on the target entity with fields.coverImageId set to the image ID; do not stop after lookup.",CFA,async($,Y)=>{let D=p8(Y.userPermissionLevel),X=await Q4(Q,$.entityType,$.id,w,void 0,D);if(!X.ok)return{success:!1,error:X.error};let{entity:H}=X,W=mFA({...$.fields!==void 0?{fields:$.fields}:{},...$.content!==void 0?{content:$.content}:{}}),f=W.content?.trim().length===0&&W.fields===void 0,Z=H.metadata.status;if($.confirmed&&H.entityType==="agent"&&(Z==="discovered"||Z==="approved")&&(!W.content&&!W.fields||f))W={fields:{status:"approved"}};if(W.content&&W.fields)return{success:!1,error:"Provide either 'content' or 'fields', not both"};if(!W.content&&!W.fields)return{success:!1,error:"Provide 'content' (full replacement) or 'fields' (partial update)"};let G=GR2(H.entityType,W);if(G)return G;let F=zR2(H.entityType,W,B);if(F)return F;let V=qR2(H.entityType,W,B);if(V)return V;let L=H.metadata.status,b=FR2(H,W,B),_=DVA(H.entityType,L,b,B)==="non-publish"?"update":"publish",j=bW(A,$.entityType,_,Y);if(j)return j;if($.confirmed){if($.contentHash&&H.contentHash!==$.contentHash)return{success:!1,error:"Entity was modified since you reviewed the changes. Please try again."};let y=W.content!==void 0?{...H,content:W.content,visibility:VN(W.content)}:UR2(H,W.fields??{});if(y.visibility!==H.visibility&&!nO(Y.userPermissionLevel,y.visibility))return{success:!1,error:`Cannot set entity visibility to "${y.visibility}" \u2014 caller permission "${Y.userPermissionLevel??"public"}" is not allowed to write at that level.`};try{let h=UR(Y);await Q.updateEntity({entity:y,...h?{options:{eventContext:h}}:{}})}catch(h){return{success:!1,error:h instanceof Error?h.message:"Failed to update entity"}}return{success:!0,data:{updated:H.id}}}let g=v10(H),E=VR2(H,W);return{needsConfirmation:!0,toolName:"system_update",summary:`Update "${g}"?`,completionSummary:`Updated ${uFA(H.entityType)}.`,preview:E,args:{...$,...W,id:H.id,confirmed:!0,contentHash:H.contentHash}}},{visibility:"trusted",sideEffects:"writes"})}var HVA=i(()=>{aB();H4();Cq();KR();HJ()});function WVA(A){return[pFA(A),dFA(A),rFA(A),XVA(A),sFA(A)]}var fVA=i(()=>{iFA();nFA();oFA();aFA();HVA()});function ZVA(A){let{entityService:Q,logger:w}=A;return[Sw("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. Search results are candidates; do not present weak or unrelated candidates as exact matches.",OFA,async(B,$)=>{let Y=p8($.userPermissionLevel);return{success:!0,data:{guidance:"Search results are semantic candidates, not guaranteed exact matches. If the results do not clearly answer the requested item/category, say no clear matching content was found instead of presenting weak candidates as matches.",results:(await Q.search({query:B.query,options:{limit:B.limit??A.searchLimit,...B.scope.kind==="type"&&{types:[B.scope.entityType]},...B.includeUngenerated!==void 0&&{includeUngenerated:B.includeUngenerated},visibilityScope:Y}})).map((D)=>({...D,entity:gb0(D.entity)}))}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),Sw("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). If retrieval fails, report the entity as not found rather than describing related generation work as pending.",xFA,async(B,$)=>{if(!Q.getEntityTypes().includes(B.entityType))return{success:!1,error:`Unknown entity type: ${B.entityType}. Available: ${Q.getEntityTypes().join(", ")}`};let Y=p8($.userPermissionLevel),D=await Q4(Q,B.entityType,B.id,w,void 0,Y);if(!D.ok)return{success:!1,error:D.error};return{success:!0,data:{entity:gb0(D.entity)}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),Sw("system","list","List entities by a known entity type. Returns metadata only \u2014 use system_get for full content. Use system_search, not system_list, for broad or vague lookup requests. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",RFA,async(B,$)=>{if(!Q.getEntityTypes().includes(B.entityType))return{success:!1,error:`Unknown entity type: ${B.entityType}. Available: ${Q.getEntityTypes().join(", ")}`};let D={visibilityScope:p8($.userPermissionLevel)};if(B.status&&B.status!=="any")D.metadata={status:B.status};let H=(await Q.listEntities({entityType:B.entityType,options:{limit:B.limit??20,filter:D}})).map(({content:W,contentHash:f,...Z})=>Z);if(B.entityType==="post"&&B.status==="published")H.sort((W,f)=>{let Z=W.metadata.publishedAt,G=f.metadata.publishedAt,F=typeof Z==="string"?Date.parse(Z):0;return(typeof G==="string"?Date.parse(G):0)-F});return{success:!0,data:{entities:H,count:H.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}var KVA=i(()=>{k9();aB();Cq();HJ()});function UVA(A){let{entityService:Q}=A;return[Sw("system","insights",`Get aggregate content insights and analytics only. For a general overview of actual content, use system_list instead. Available types: ${A.insights.getTypes().join(", ")}.`,TFA,async(w,B)=>{let $=p8(B.userPermissionLevel);return{success:!0,data:await A.insights.get(w.type,Q,$)}},{visibility:"public",sideEffects:"none"})]}var GVA=i(()=>{k9();aB();Cq()});function zVA(A){let{jobs:Q}=A;return[LW("job_status","Get status for background operations. Use this for ready checks, follow-up questions about queued/background work, and status disputes where the operator says logs or runtime state disagree with the conversation. Inspect runtime job status before answering. Do not argue from the transcript alone when job status is available.",gFA,async(w)=>{if(w.batchId){let Y=await Q.getBatchStatus(w.batchId);if(!Y)return{success:!1,error:`No batch found with ID: ${w.batchId}`};let D=Y.totalOperations>0?Math.round(Y.completedOperations/Y.totalOperations*100):0;return{success:!0,data:{batchId:w.batchId,status:Y.status,progress:{total:Y.totalOperations,completed:Y.completedOperations,failed:Y.failedOperations,percentComplete:D},currentOperation:Y.currentOperation,errors:Y.errors}}}let B=await Q.getActiveJobs(w.jobTypes),$=await Q.getActiveBatches();return{success:!0,data:{summary:{activeJobs:B.length,activeBatches:$.length},jobs:B.map((Y)=>({id:Y.id,type:Y.type,status:Y.status,priority:Y.priority,retryCount:Y.retryCount,createdAt:new Date(Y.createdAt).toISOString(),startedAt:Y.startedAt?new Date(Y.startedAt).toISOString():null})),batches:$.map((Y)=>({batchId:Y.batchId,status:Y.status.status,totalOperations:Y.status.totalOperations,completedOperations:Y.status.completedOperations,failedOperations:Y.status.failedOperations,currentOperation:Y.status.currentOperation,pluginId:Y.metadata.metadata.pluginId,errors:Y.status.errors}))}}},{visibility:"public",sideEffects:"none"})]}var qVA=i(()=>{Cq();HJ()});function JR2(A){let{entityCounts:Q,daemons:w,endpoints:B,interactions:$,...Y}=A;return Y}function FVA(A){return[Sw("system","status","Get system status including model, version, interfaces, and tools",K.object({}),async()=>({success:!0,data:JR2(await A.getAppInfo())}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}var VVA=i(()=>{k9();Z0()});function JVA(A){return[...ZVA(A),...zVA(A),...FVA(A),...WVA(A),...UVA(A)]}var IVA=i(()=>{fVA();KVA();GVA();qVA();VVA()});function bVA(A){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:A.entityService.getEntityTypes().join(`
|
|
394
|
-
`)}]})},{uri:"brain://identity",name:"Brain Identity",description:"Brain character \u2014 name, role, purpose, values",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://identity",mimeType:"application/json",text:JSON.stringify(A.getIdentity(),null,2)}]})},{uri:"brain://profile",name:"Anchor Profile",description:"Brain owner profile \u2014 name, bio, expertise",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://profile",mimeType:"application/json",text:JSON.stringify(A.getProfile(),null,2)}]})},{uri:"brain://status",name:"Brain Status",description:"System status \u2014 version, model, interfaces, tools",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://status",mimeType:"application/json",text:JSON.stringify(await A.getAppInfo(),null,2)}]})}]}function LVA(A){let{entityService:Q}=A;return[{name:"entity-list",uriTemplate:"entity://{type}",description:"List entities of a given type",mimeType:"application/json",list:async()=>{return Q.getEntityTypes().map((B)=>({uri:`entity://${B}`,name:`${B} entities`}))},complete:{type:async()=>Q.getEntityTypes()},handler:async({type:w})=>{let B=Q.getEntityTypes();if(!B.includes(w))throw Error(`Unknown entity type: ${w}. Available: ${B.join(", ")}`);let Y=(await Q.listEntities({entityType:w})).map((D)=>({id:D.id,entityType:D.entityType,...D.metadata,updated:D.updated}));return{contents:[{uri:`entity://${w}`,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(w)=>{let B=Q.getEntityTypes();return w?B.filter(($)=>$.startsWith(w)):B},id:async()=>[]},handler:async({type:w,id:B})=>{let $=await Q.getEntity({entityType:w,id:B});if(!$)throw Error(`Entity not found: ${w}/${B}`);return{contents:[{uri:`entity://${w}/${B}`,mimeType:"text/markdown",text:$.content}]}}}]}function NVA(A){return[{name:"create",description:"Create new content of any type",args:{type:{description:"Entity type (e.g. post, deck, note)",required:!0},topic:{description:"Topic or title for the content"}},handler:async({topic:w,type:B})=>({messages:[{role:"user",content:{type:"text",text:w?`Create a new ${B} about: ${w}`:`Create a new ${B}. Ask me what it should be about.`}}]})},{name:"generate",description:"AI-generate content with a prompt",args:{type:{description:`Entity type (${(()=>A.entityService.getEntityTypes().join(", "))()})`,required:!0},topic:{description:"What to generate",required:!0}},handler:async({type:w,topic:B})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${w} about: ${B}`}}]})},{name:"review",description:"Review and improve existing content",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:w,id:B})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${w} "${B}". Read it first, then give me specific feedback on structure, clarity, and impact. Suggest concrete improvements.`}}]})},{name:"publish",description:"Publish content \u2014 preview, confirm, and publish",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:w,id:B})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${w} "${B}". Show me a preview first, then publish it.`}}]})},{name:"brainstorm",description:"Brainstorm ideas using brain context and expertise",args:{topic:{description:"Topic to brainstorm about",required:!0}},handler:async({topic:w})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${w}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function jVA(A){let Q=A.entityService.getEntityTypes(),w=Q.map((B)=>`- ${B}: ${A.entityRegistry.getAdapter(B).purpose}`);return["## Entity CRUD","","Use these system tools for ALL entity operations:","",`- **system_create**: Create an entity from existing/concrete material. Requires confirmation before persisting; call system_create without \`confirmed\` to request that confirmation, and never pass \`confirmed: true\` on the initial user request. Required \`source\` union: \`{ kind: "text", content }\` stores exact/direct content; \`{ kind: "url", url }\` creates URL/domain-backed records such as links (preserve bare domains as bare domains); \`{ kind: "upload", upload, transform: "extract-markdown" }\` imports extractable upload bytes as a markdown note; \`{ kind: "upload", upload, transform: "preserve" }\` preserves raw uploaded bytes as their durable file entity; \`{ kind: "prior-response", messageId? }\` saves a previous assistant answer/summary by reference without copying or paraphrasing it. If a direct save request includes the content in the same message, that content is sufficient, even if it is a short sentence or fragment after a colon; call system_create instead of asking the user to paste it again. If the immediate context is an assistant summary/answer about an upload and the user asks to save it/that/this/summary, create a note with \`source.kind: "prior-response"\`; do this even when the prior answer says there was limited readable content. Do not ask whether they meant the summary or the file after you just summarized/answered about the upload: save the visible prior response as a note. Do not treat a bare upload receipt like "I got filename. What would you like me to do?" as a summary/answer; if the user then says "save it", preserve the latest uploaded file itself with upload \`preserve\` (image uploads as entityType image, PDFs/documents as their file entity type). Only use upload \`preserve\` otherwise when they explicitly want to save the uploaded file/document itself. Use system_generate, not system_create, for AI generation, generated images, cover images, and source-derived artifacts. Available entity types: ${Q.join(", ")}.`,'- **system_generate**: Generate a new durable entity or deterministic artifact. Requires confirmation before queueing generation; call system_generate without `confirmed` to request that confirmation, and never pass `confirmed: true` on the initial user request. When the user asks you to create, write, draft, or generate new durable content and has not supplied final exact content to store, call system_generate instead of drafting the content in chat or asking for separate prose approval first. If generation depends on an existing source entity (for example, a newsletter from a blog post), resolve the source with read/search/list tools first unless the user gives an exact entity id in quotes, then call system_generate with `operation.kind: "prompt-from-source"` in the same turn when a clear source is found. If you identify the latest source entity, do not stop after saying you found it or can generate from it; call system_generate immediately. If no existing durable source entity is resolved, use `operation.kind: "prompt"`, which has no source field; never invent source IDs, use upload IDs/filenames as entity refs, use profile/brain-character as a generic source, or create placeholder source refs. For broad topical prompts like \'about AI\' or \'about continuous learning\', use `operation.kind: "prompt"`. If the user asks for the latest published/blog source, use system_list for that entity type (for blog posts, entityType post) to inspect publishedAt dates; do not rely on semantic search result order. Choose the newest matching candidate by publishedAt (not updated/created order) and proceed with system_generate rather than asking for separate prose approval; do not say \'if that is the one you mean\' when a newest dated candidate is visible. Do not say \'I can generate it if you want\' or \'I need to queue it first\'; calling system_generate without `confirmed` is the confirmation request. Required `operation` union: `{ kind: "prompt", entityType, prompt }` generates a new non-image durable entity from a broad prompt with no source; `{ kind: "prompt-from-source", entityType, source: { entityType, entityId }, prompt }` generates from an existing resolved entity, such as a newsletter from a blog post. `{ kind: "standalone-image", prompt }` generates an unattached image; `{ kind: "cover-image", target: { entityType, entityId }, prompt }` generates an image and attaches it to an existing canonical entity as `coverImageId`; `{ kind: "attachment", source: { entityType, entityId }, attachmentType }` renders a deterministic artifact from an existing entity attachment provider. For save/render/regenerate/replace requests for source-derived artifacts, call `system_generate` with `operation.kind: "attachment"` immediately; do not say you can queue it later. Use `replace: true` when the user says regenerate, replace, refresh, or update an existing artifact. For OG/social preview renders, use `attachmentType: "og-image"`; the provider derives the output image and updates `ogImageId`. For deck carousel PDFs use `attachmentType: "carousel"`; for printable post/project/product PDFs use `attachmentType: "printable"`. If the user asks to attach a generated artifact to another entity, generate the artifact first in the same turn; do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer`. Update the target only after the real artifact ID exists. To create an entity and a cover image, first create/generate only the entity, then after confirmation and after the real canonical entity ID is known call system_generate with operation.kind cover-image. When the user asks to create/regenerate a cover for an existing entity and search/get resolves a clear target, call system_generate with operation.kind cover-image in the same turn; do not stop after saying you found it. In a single initial request for \'a post with a cover image\', do not also call standalone-image; never guess a future target ID, and do not generate a standalone image as a substitute for a requested cover image.','- **system_update**: Modify an entity\'s fields or content. Use `fields` for title, status, coverImageId, ogImageId, and other frontmatter/metadata changes. To remove or clear a cover image, set `fields.coverImageId` to null, not an empty string. Use system_update for coverImageId when an existing image entity id is known; if the user says to set an existing image as a cover, update `coverImageId` even when `ogImageId` already points at that image. To generate a new cover image for an existing entity, use system_generate with operation.kind cover-image. Agent approval/archive is a status field update on `entityType: "agent"`. Cover images use `coverImageId`; OG/social previews use `ogImageId`; do not treat them as interchangeable. Requires confirmation before applying changes; call system_update without `confirmed` to request that confirmation, rather than asking for prose approval. For explicit publish requests, use the publishing tool if available instead of changing status with system_update; follow-up pronouns like \'publish it\' should target the entity just read or updated in the conversation.',"- **system_delete**: Owner/anchor-only entity removal. Requires confirmation before deleting. Never pass `confirmed: true` on the initial user request; call without `confirmed` so the confirmation flow can ask the owner first. If system_delete is not available in the current tool surface, say deletion requires owner access; do not imply a confirmation flow is available. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.","- **system_get**: Retrieve a specific entity by type and ID/slug/title.","- **system_list**: List entities by type with optional filters. For simple list/show-all/summary requests that name or browse a known type or synonym (for example essays/articles/blog posts => post), use system_list with that entity type instead of semantic search. For 'summarize my blog posts' or similar whole-type summaries, first call system_list for entityType post, then summarize those returned entities. For 'latest' requests, use system_list metadata dates such as publishedAt to choose the newest candidate.","- **system_search**: Semantic search across all entities. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn search results or memory; this includes analysis phrasing such as 'How do I discuss X in my writing?' even if prior turns searched related topics.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content.","","Entity types \u2014 select `entityType` by what the type is for:",...w].join(`
|
|
394
|
+
`)}]})},{uri:"brain://identity",name:"Brain Identity",description:"Brain character \u2014 name, role, purpose, values",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://identity",mimeType:"application/json",text:JSON.stringify(A.getIdentity(),null,2)}]})},{uri:"brain://profile",name:"Anchor Profile",description:"Brain owner profile \u2014 name, bio, expertise",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://profile",mimeType:"application/json",text:JSON.stringify(A.getProfile(),null,2)}]})},{uri:"brain://status",name:"Brain Status",description:"System status \u2014 version, model, interfaces, tools",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://status",mimeType:"application/json",text:JSON.stringify(await A.getAppInfo(),null,2)}]})}]}function LVA(A){let{entityService:Q}=A;return[{name:"entity-list",uriTemplate:"entity://{type}",description:"List entities of a given type",mimeType:"application/json",list:async()=>{return Q.getEntityTypes().map((B)=>({uri:`entity://${B}`,name:`${B} entities`}))},complete:{type:async()=>Q.getEntityTypes()},handler:async({type:w})=>{let B=Q.getEntityTypes();if(!B.includes(w))throw Error(`Unknown entity type: ${w}. Available: ${B.join(", ")}`);let Y=(await Q.listEntities({entityType:w})).map((D)=>({id:D.id,entityType:D.entityType,...D.metadata,updated:D.updated}));return{contents:[{uri:`entity://${w}`,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(w)=>{let B=Q.getEntityTypes();return w?B.filter(($)=>$.startsWith(w)):B},id:async()=>[]},handler:async({type:w,id:B})=>{let $=await Q.getEntity({entityType:w,id:B});if(!$)throw Error(`Entity not found: ${w}/${B}`);return{contents:[{uri:`entity://${w}/${B}`,mimeType:"text/markdown",text:$.content}]}}}]}function NVA(A){return[{name:"create",description:"Create new content of any type",args:{type:{description:"Entity type (e.g. post, deck, note)",required:!0},topic:{description:"Topic or title for the content"}},handler:async({topic:w,type:B})=>({messages:[{role:"user",content:{type:"text",text:w?`Create a new ${B} about: ${w}`:`Create a new ${B}. Ask me what it should be about.`}}]})},{name:"generate",description:"AI-generate content with a prompt",args:{type:{description:`Entity type (${(()=>A.entityService.getEntityTypes().join(", "))()})`,required:!0},topic:{description:"What to generate",required:!0}},handler:async({type:w,topic:B})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${w} about: ${B}`}}]})},{name:"review",description:"Review and improve existing content",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:w,id:B})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${w} "${B}". Read it first, then give me specific feedback on structure, clarity, and impact. Suggest concrete improvements.`}}]})},{name:"publish",description:"Publish content \u2014 preview, confirm, and publish",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:w,id:B})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${w} "${B}". Show me a preview first, then publish it.`}}]})},{name:"brainstorm",description:"Brainstorm ideas using brain context and expertise",args:{topic:{description:"Topic to brainstorm about",required:!0}},handler:async({topic:w})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${w}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function jVA(A){let Q=A.entityService.getEntityTypes(),w=Q.map((B)=>`- ${B}: ${A.entityRegistry.getAdapter(B).purpose}`);return["## Entity CRUD","","Use these system tools for ALL entity operations:","",`- **system_create**: Create an entity from existing/concrete material. Requires confirmation before persisting; call system_create without \`confirmed\` to request that confirmation, and never pass \`confirmed: true\` on the initial user request. Required \`source\` union: \`{ kind: "text", content }\` stores exact/direct content; \`{ kind: "url", url }\` creates URL/domain-backed records such as links (preserve bare domains as bare domains); \`{ kind: "upload", upload, transform: "extract-markdown" }\` imports extractable upload bytes as a markdown note; \`{ kind: "upload", upload, transform: "preserve" }\` preserves raw uploaded bytes as their durable file entity; \`{ kind: "prior-response", messageId? }\` saves a previous assistant answer/summary by reference without copying or paraphrasing it. If a direct save request includes the content in the same message, that content is sufficient, even if it is a short sentence or fragment after a colon or embedded in the request phrase (for example, "Save this memo about the launch timeline"); call system_create instead of asking the user to paste it again. If the immediate context is an assistant summary/answer about an upload and the user asks to save it/that/this/summary, create a note with \`source.kind: "prior-response"\`; do this even when the prior answer says there was limited readable content. Do not ask whether they meant the summary or the file after you just summarized/answered about the upload: save the visible prior response as a note. Do not treat a bare upload receipt like "I got filename. What would you like me to do?" as a summary/answer; if the user then says "save it", preserve the latest uploaded file itself with upload \`preserve\` (image uploads as entityType image, PDFs/documents as their file entity type). Only use \`source.kind: "upload"\` when the runtime supplies an actual upload reference/attachment; if the message contains a pasted uploaded-file transcript with readable content (for example, \`User uploaded a file "name.md": ...\`), save the visible transcript content as \`source.kind: "text"\`. Only use upload \`preserve\` otherwise when they explicitly want to save the uploaded file/document itself. Use system_generate, not system_create, for AI generation, generated images, cover images, and source-derived artifacts. Available entity types: ${Q.join(", ")}.`,'- **system_generate**: Generate a new durable entity or deterministic artifact. Requires confirmation before queueing generation; call system_generate without `confirmed` to request that confirmation, and never pass `confirmed: true` on the initial user request. When the user asks you to create, write, draft, or generate new durable content and has not supplied final exact content to store, call system_generate instead of drafting the content in chat or asking for separate prose approval first. If generation depends on an existing source entity (for example, a newsletter from a blog post), resolve the source with read/search/list tools first unless the user gives an exact entity id in quotes, then call system_generate with `operation.kind: "prompt-from-source"` in the same turn when a clear source is found. If you identify the latest source entity, do not stop after saying you found it or can generate from it; call system_generate immediately. If no existing durable source entity is resolved, use `operation.kind: "prompt"`, which has no source field; never invent source IDs, use upload IDs/filenames as entity refs, use profile/brain-character as a generic source, or create placeholder source refs. For broad topical prompts like \'about AI\' or \'about continuous learning\', use `operation.kind: "prompt"`. If the user asks for the latest published/blog source, use system_list for that entity type (for blog posts, entityType post) to inspect publishedAt dates; do not rely on semantic search result order. Choose the newest matching candidate by publishedAt (not updated/created order) and proceed with system_generate rather than asking for separate prose approval; do not say \'if that is the one you mean\' when a newest dated candidate is visible. Do not say \'I can generate it if you want\' or \'I need to queue it first\'; calling system_generate without `confirmed` is the confirmation request. Required `operation` union: `{ kind: "prompt", entityType, prompt }` generates a new non-image durable entity from a broad prompt with no source; `{ kind: "prompt-from-source", entityType, source: { entityType, entityId }, prompt }` generates from an existing resolved entity, such as a newsletter from a blog post. `{ kind: "standalone-image", prompt }` generates an unattached image; `{ kind: "cover-image", target: { entityType, entityId }, prompt }` generates an image and attaches it to an existing canonical entity as `coverImageId`; `{ kind: "attachment", source: { entityType, entityId }, attachmentType }` renders a deterministic artifact from an existing entity attachment provider. For save/render/regenerate/replace requests for source-derived artifacts, call `system_generate` with `operation.kind: "attachment"` immediately; do not say you can queue it later. Use `replace: true` when the user says regenerate, replace, refresh, or update an existing artifact. For OG/social preview renders, use `attachmentType: "og-image"`; the provider derives the output image and updates `ogImageId`. For deck carousel PDFs use `attachmentType: "carousel"`; for printable post/project/product PDFs use `attachmentType: "printable"`. If the user asks to attach a generated artifact to another entity, generate the artifact first in the same turn; do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer`. Update the target only after the real artifact ID exists. To create an entity and a cover image, first create/generate only the entity, then after confirmation and after the real canonical entity ID is known call system_generate with operation.kind cover-image. When the user asks to create/regenerate a cover for an existing entity and search/get resolves a clear target, call system_generate with operation.kind cover-image in the same turn; do not stop after saying you found it. In a single initial request for \'a post with a cover image\', do not also call standalone-image; never guess a future target ID, and do not generate a standalone image as a substitute for a requested cover image.','- **system_update**: Modify an entity\'s fields or content. Use `fields` for title, status, coverImageId, ogImageId, and other frontmatter/metadata changes. To remove or clear a cover image, set `fields.coverImageId` to null, not an empty string. Use system_update for coverImageId when an existing image entity id is known; if the user says to set an existing image as a cover, update `coverImageId` even when `ogImageId` already points at that image. To generate a new cover image for an existing entity, use system_generate with operation.kind cover-image. Agent approval/archive is a status field update on `entityType: "agent"`. Cover images use `coverImageId`; OG/social previews use `ogImageId`; do not treat them as interchangeable. Requires confirmation before applying changes; call system_update without `confirmed` to request that confirmation, rather than asking for prose approval. For explicit publish requests, use the publishing tool if available instead of changing status with system_update; follow-up pronouns like \'publish it\' should target the entity just read or updated in the conversation.',"- **system_delete**: Owner/anchor-only entity removal. Requires confirmation before deleting. Never pass `confirmed: true` on the initial user request; call without `confirmed` so the confirmation flow can ask the owner first. If system_delete is not available in the current tool surface, say deletion requires owner access; do not imply a confirmation flow is available. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.","- **system_get**: Retrieve a specific entity by type and ID/slug/title.","- **system_list**: List entities by type with optional filters. For simple list/show-all/summary requests that name or browse a known type or synonym (for example essays/articles/blog posts => post), use system_list with that entity type instead of semantic search. For 'summarize my blog posts' or similar whole-type summaries, first call system_list for entityType post, then summarize those returned entities. For 'latest' requests, use system_list metadata dates such as publishedAt to choose the newest candidate.","- **system_search**: Semantic search across all entities. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn search results or memory; this includes analysis phrasing such as 'How do I discuss X in my writing?' even if prior turns searched related topics.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content.","","Entity types \u2014 select `entityType` by what the type is for:",...w].join(`
|
|
395
395
|
`)}function y10(A,Q,w,B,$){for(let Y of A)try{Q(Y)}catch{$.debug(`System ${B} ${w(Y)} already registered, skipping`)}}function MVA(A,Q,w,B){let $=JVA(A);y10($,(f)=>Q.registerTool(GR,f),(f)=>f.name,"tool",B);let Y=w.subscribe(`plugin:${GR}:tool:execute`,async(f)=>{let Z=IR2.safeParse(f.payload);if(!Z.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:G,args:F,interfaceType:V,userId:L,conversationId:b,channelId:N,userPermissionLevel:_}=Z.data,j=$.find((y)=>y.name===G);if(!j)return{success:!1,error:`System tool not found: ${G}`};let g={interfaceType:V??"system",userId:L??"system"};if(b)g.conversationId=b;if(N)g.channelId=N;if(_)g.userPermissionLevel=_;return{success:!0,data:await j.handler(F,g)}});B.debug(`Registered ${$.length} system tools`);let D=bVA(A);y10(D,(f)=>Q.registerResource(GR,f),(f)=>f.uri,"resource",B),B.debug(`Registered ${D.length} system resources`);let X=LVA(A);y10(X,(f)=>Q.registerResourceTemplate(GR,f),(f)=>f.uriTemplate,"resource template",B),B.debug(`Registered ${X.length} system resource templates`);let H=NVA(A);y10(H,(f)=>Q.registerPrompt(GR,f),(f)=>f.name,"prompt",B),B.debug(`Registered ${H.length} system prompts`);let W=jVA(A);try{Q.registerInstructions(GR,W)}catch{B.debug("System instructions already registered, skipping")}return B.debug("Registered system instructions"),Y}var GR="system",IR2;var _VA=i(()=>{k9();Z0();IVA();IR2=K.object({toolName:K.string(),args:K.unknown()}).extend(WN.partial().shape)});function PVA(A){let{services:Q,jobs:w,insights:B,query:$,getAppInfo:Y}=A,D=Q.jobQueueService,X=Q.logger.child("system"),H=MVA({entityService:Q.entityService,entityRegistry:Q.entityRegistry,jobs:{...w,enqueue:KS(D,"system",!1),enqueueBatch:US(w,"system"),registerHandler:GS(D,"system")},conversationService:Q.conversationService,runtimeUploads:Q.runtimeUploadRegistry,attachments:bS(Q.attachmentRegistry),logger:X,query:$,getIdentity:()=>Q.identityService.getCharacter(),getProfile:()=>Q.profileService.getProfile(),getAppInfo:Y,searchLimit:10,insights:B,permissionService:Q.permissionService},Q.mcpService,Q.messageBus,X);Q.disposables.push(H)}var kVA=i(()=>{Dq();c0();_VA()});var VFA={};sw(VFA,{Shell:()=>CX});class CX{config;static instance=null;services;bootloader;initialized=!1;insightsRegistry;bootTime=Date.now();endpointRegistry=new yb0;interactionRegistry=new Eb0;jobs;static getInstance(A){return CX.instance??=new CX(Ux(A??{})),CX.instance}static async resetInstance(){if(CX.instance)await CX.instance.shutdown(),CX.instance=null}static createFresh(A,Q){Uu();let w=Ux(A);return new CX(w,Q)}constructor(A,Q){this.config=A;let w=FZ.getInstance(Q?.logger??e2.getInstance(),this.config);this.services=w.initializeServices(Q),this.jobs=MFA(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=bFA(),this.bootloader=new vb0(this.config,this.services,{registerCoreDataSources:()=>Q7A(this.services,this.config),registerSystemCapabilities:()=>PVA({services:this.services,jobs:this.jobs,insights:this.insightsRegistry,query:(B,$)=>this.query(B,$),getAppInfo:()=>this.getAppInfo()})}),w.wireShell(this.services,this)}getInsightsRegistry(){return this.insightsRegistry}async initialize(A){if(this.services.logger.debug("Shell.initialize() called"),this.initialized){this.services.logger.warn("Shell already initialized");return}try{await this.bootloader.boot(A),this.initialized=!0}catch(Q){throw this.services.logger.error("Failed to initialize Shell",Q),Q}}registerTemplates(A,Q){this.services.logger.debug("Registering templates",{pluginId:Q,count:Object.keys(A).length});for(let[w,B]of Object.entries(A))this.registerTemplate(w,B,Q)}async shutdown(){this.services.logger.debug("Shutting down Shell"),await kFA(this.services),this.initialized=!1,this.services.logger.debug("Shell shutdown complete")}async generateContent(A){return this.requireInitialized("Shell content generation"),B7A(this.services,A)}async query(A,Q){this.requireInitialized("Shell query");let w=await this.getAppInfo(),B={...Q,appInfo:w,timestamp:new Date().toISOString()},{conversationHistory:$,...Y}=B;return this.generateContent({prompt:A,templateName:Gx.KNOWLEDGE_QUERY,...$&&{conversationHistory:$},data:Y,interfacePermissionGrant:"public"})}registerPlugin(A){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(A)}isInitialized(){return this.initialized}requireInitialized(A){if(!this.initialized)throw Error(`${A} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(A,Q){this.requireInitialized("Shell generateObject");let{object:w}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",A,Q);return{object:w}}async judge(A){return this.requireInitialized("Shell judge"),this.services.aiService.judge(A)}getAIService(){return this.services.aiService}generateImage(A,Q){return this.services.aiService.generateImage(A,Q)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return bS(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return dU0(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(A){return this.services.mcpService.listToolsForPermissionLevel(A).map(({pluginId:Q,tool:w})=>({name:w.name,description:w.description,pluginId:Q}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(A,Q){for(let w of Q)try{this.services.mcpService.registerTool(A,w)}catch(B){this.services.logger.error(`Failed to register tool ${w.name} from ${A}:`,B)}}registerResources(A,Q){for(let w of Q)try{this.services.mcpService.registerResource(A,w)}catch(B){this.services.logger.error(`Failed to register resource ${w.name} from ${A}:`,B)}}registerResourceTemplate(A,Q){this.services.mcpService.registerResourceTemplate(A,Q)}registerPrompt(A,Q){this.services.mcpService.registerPrompt(A,Q)}registerInstructions(A,Q){if(this.services.mcpService.registerInstructions(A,Q),this.initialized)this.services.agentService.invalidateAgent()}getPluginPackageName(A){return this.services.pluginManager.getPluginPackageName(A)}hasPlugin(A){return this.services.pluginManager.hasPlugin(A)}getPluginApiRoutes(){return _FA(this.services.pluginManager)}getPluginWebRoutes(){return PFA(this.services.pluginManager)}registerDaemon(A,Q,w){this.services.daemonRegistry.register(A,Q,w)}registerEndpoint(A){this.endpointRegistry.register(A)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(A){this.interactionRegistry.register(A)}listInteractions(){return this.interactionRegistry.list()}getPublicContext(){return{entityService:this.services.entityService,generateContent:(A)=>this.generateContent(A),getBatchStatus:(A)=>this.services.batchJobManager.getBatchStatus(A)}}registerTemplate(A,Q,w){let B=w?`${w}:${A}`:`shell:${A}`;this.services.templateRegistry.register(B,Q),this.services.logger.debug(`Registered template: ${B}`)}getTemplate(A){return this.services.templateRegistry.get(A)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}getThemeCSS(){return this.config.themeCSS}getSpaces(){return this.config.spaces}getDataDir(){return this.config.dataDir}registerEvalHandler(A,Q,w){this.config.evalHandlerRegistry?.register(A,Q,w)}async getAppInfo(){return n9A({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}}var hb0=i(()=>{c0();Z0();r9A();OG0();RN();w7A();h10();JFA();NFA();jFA();kVA()});var OVA={};sw(OVA,{shellConfigSchema:()=>N00,resetServiceSingletons:()=>Uu,resetAllSingletons:()=>FFA,getStandardConfigWithDirectories:()=>uS,getStandardConfig:()=>mS,createShellConfig:()=>Ux,Shell:()=>CX,STANDARD_PATHS:()=>tV,SHELL_TEMPLATE_NAMES:()=>Gx,SHELL_ENTITY_TYPES:()=>wY,SHELL_DATASOURCE_IDS:()=>j00});var E10=i(()=>{hb0();OG0();RN();h10()});var ZJ,pb0,g10;var zR=i(()=>{Z0();c0();Vq();ZJ=K.enum(["debug","info","warn","error"]),pb0=K.object({provider:K.enum(["hetzner","docker"]).default("hetzner"),serverSize:K.string().default("cx33"),location:K.string().default("fsn1"),domain:K.string().optional(),docker:K.object({enabled:K.boolean().default(!0),image:K.string().optional()}).default({}),ports:K.object({default:K.number().default(3333),preview:K.number().default(4321),production:K.number().default(8080)}).default({}),cdn:K.object({enabled:K.boolean().default(!1),provider:K.enum(["bunny","none"]).default("none")}).default({}),dns:K.object({enabled:K.boolean().default(!1),provider:K.enum(["bunny","none"]).default("none")}).default({}),paths:K.object({install:K.string().optional(),data:K.string().optional()}).default({})}),g10=K.object({name:K.string().default("brain-app"),version:K.string().default("1.0.0"),database:K.string().optional(),aiApiKey:K.string().optional(),aiImageKey:K.string().optional(),aiModel:K.string().optional(),logLevel:ZJ.optional(),logFile:K.string().optional(),plugins:K.array(nT).default([]),spaces:K.array(K.string()).default([]),identity:Wx.optional(),agentInstructions:K.array(K.string()).optional(),deployment:pb0.default({})})});import bR2 from"crypto";import ib0 from"fs";function xVA(A){let Q=A.migrationsFolder,w=[],B=`${Q}/meta/_journal.json`;if(!ib0.existsSync(B))throw Error("Can't find meta/_journal.json file");let $=ib0.readFileSync(`${Q}/meta/_journal.json`).toString(),Y=JSON.parse($);for(let D of Y.entries){let X=`${Q}/${D.tag}.sql`;try{let H=ib0.readFileSync(`${Q}/${D.tag}.sql`).toString(),W=H.split("--> statement-breakpoint").map((f)=>{return f});w.push({sql:W,bps:D.breakpoints,folderMillis:D.when,hash:bR2.createHash("sha256").update(H).digest("hex")})}catch{throw Error(`No file ${X} found in ${Q} folder`)}}return w}var RVA=()=>{};async function KJ(A,Q){let w=xVA(Q),B=Q.migrationsTable??"__drizzle_migrations",$=g0`
|
|
396
396
|
CREATE TABLE IF NOT EXISTS ${g0.identifier(B)} (
|
|
397
397
|
id SERIAL PRIMARY KEY,
|
|
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 Vu=i(()=>{RVA();c$()});async function hVA(A,Q){let w=Q?.child("entity-migrate")??e2.getInstance().child("entity-migrate"),{db:B,client:$,url:Y}=he(A);w.debug("Running entity database migrations...");try{await ve($,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 Ce($),w.debug("Entity database migrations completed successfully")}catch(D){throw w.error("Entity database migration failed:",D),D}finally{$.close()}}var vVA=i(()=>{Vu();fU0();Z0()});async function CVA(A,Q){let w=Q?.child("job-queue-migrate")??e2.getInstance().child("job-queue-migrate"),{db:B,client:$,url:Y}=Oe(A);w.debug("Running job queue migrations...");try{await xe($,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 yVA=i(()=>{Vu();AU0();Z0()});async function EVA(A,Q){let w=Q?.child("conversation-migrate")??e2.getInstance().child("conversation-migrate"),{db:B,client:$,url:Y}=de(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 gVA=i(()=>{Vu();sU0();Z0()});async function TVA(A,Q){let w=Q?.child("runtime-state-migrate")??e2.getInstance().child("runtime-state-migrate"),{db:B,client:$,url:Y}=O10(A);w.debug("Running runtime state migrations...");try{await x10($,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 SVA=i(()=>{Vu();Z0();Pb0()});class Ju{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:uS,migrateEntities:hVA,migrateJobQueue:CVA,migrateConversations:EVA,migrateRuntimeState:TVA}}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 db0=i(()=>{E10();vVA();yVA();gVA();SVA()});function NR2(){return process.env[LR2]}function mVA(){return NR2()!=="production"}var LR2="NODE_ENV";var T10;var nb0=i(()=>{Z0();T10=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 cVA;var uVA=i(()=>{cVA={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.138",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((MR2,S10)=>{(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 L(){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 b(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:L}):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=b(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 Vu=i(()=>{RVA();c$()});async function hVA(A,Q){let w=Q?.child("entity-migrate")??e2.getInstance().child("entity-migrate"),{db:B,client:$,url:Y}=he(A);w.debug("Running entity database migrations...");try{await ve($,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 Ce($),w.debug("Entity database migrations completed successfully")}catch(D){throw w.error("Entity database migration failed:",D),D}finally{$.close()}}var vVA=i(()=>{Vu();fU0();Z0()});async function CVA(A,Q){let w=Q?.child("job-queue-migrate")??e2.getInstance().child("job-queue-migrate"),{db:B,client:$,url:Y}=Oe(A);w.debug("Running job queue migrations...");try{await xe($,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 yVA=i(()=>{Vu();AU0();Z0()});async function EVA(A,Q){let w=Q?.child("conversation-migrate")??e2.getInstance().child("conversation-migrate"),{db:B,client:$,url:Y}=de(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 gVA=i(()=>{Vu();sU0();Z0()});async function TVA(A,Q){let w=Q?.child("runtime-state-migrate")??e2.getInstance().child("runtime-state-migrate"),{db:B,client:$,url:Y}=O10(A);w.debug("Running runtime state migrations...");try{await x10($,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 SVA=i(()=>{Vu();Z0();Pb0()});class Ju{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:uS,migrateEntities:hVA,migrateJobQueue:CVA,migrateConversations:EVA,migrateRuntimeState:TVA}}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 db0=i(()=>{E10();vVA();yVA();gVA();SVA()});function NR2(){return process.env[LR2]}function mVA(){return NR2()!=="production"}var LR2="NODE_ENV";var T10;var nb0=i(()=>{Z0();T10=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 cVA;var uVA=i(()=>{cVA={name:"@brains/chat-repl",private:!0,version:"0.2.0-alpha.139",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((MR2,S10)=>{(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 L(){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 b(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:L}):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=b(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}`,wT2);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=UjA(Z,G)+W,L;try{L=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 b=vX.createImageEntity({dataUrl:L.dataUrl,title:X,status:"draft",attachmentType:"generated",...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}});if(await NX({entityService:this.context.entityService,entity:{...b,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 GU({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();H4();var $T2=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 Wj0 extends _w{context;constructor(A,Q){super(Q,{schema:$T2,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=vX.createImageEntity({dataUrl:Sb0(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 NX({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 GU({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"?Fu(w,Q):Wj(w,Q);await this.context.entities.update($)}}c0();Z0();CB();H4();Z0();var rR={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function DQ0(A){return["image/png","image/jpeg","image/webp","image/gif"].includes(A.toLowerCase())}function XQ0(A){let Q=YT2(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 GjA(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function YT2(A,Q){let w=A?.trim();if(w)return w;return Q.replace(/\.[^.]+$/,"").trim()||Q}var DT2=K.object({uploadId:K.string().min(1),imageId:K.string().min(1).optional(),title:K.string().optional()});class fj0 extends _w{context;constructor(A,Q){super(A,{schema:DT2,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(!DQ0(B.record.mediaType))throw Error("Only image uploads can be promoted to image entities");let $=XQ0({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=vX.createImageEntity({dataUrl:GjA(B.record.mediaType,B.content),title:$.title,status:"draft",sourceUploadId:A.uploadId,sourceFilename:B.record.filename,sourceMediaType:B.record.mediaType,attachmentType:"uploaded"}),H=await NX({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 GU({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 zjA={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.138",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 HT2="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",WT2=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 jZ(A){let Q=A?.trim();if(!Q)return;return Q}function fT2(A){let Q=jZ(A.prompt);if(Q)return Q;let w=jZ(A.content);if(w&&!Hj0(w))return w;return}function ZT2(A){let Q=A.attachmentType==="og-image"?"og":A.attachmentType;return w1(`${Q}-${A.sourceEntityType}-${A.sourceEntityId}`)}function qjA(A){let Q=jZ(A.title)??(A.targetEntityId?`cover-${A.targetEntityId}`:A.prompt.slice(0,60).trim());return w1(Q)}async function KT2(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 Zj0(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 UT2(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 Kj0 extends kQ{entityType=vX.entityType;schema=zu;adapter=vX;constructor(A={}){super("image",zjA,A,WT2)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,w){if(A.from?.kind===rR.refKind)return this.promoteUpload(A,w);let B=fT2(A),$=jZ(A.targetEntityType),Y=jZ(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=jZ(A.title)??D,F=qjA({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:Zj0(F)}}}}let H=await Q4(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=$Q0(H.entity.content),f=qjA({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:Zj0(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(!DQ0($.mediaType))return{kind:"handled",result:{success:!1,error:"Only image uploads can be promoted to image entities"}};let Y;try{Y=XQ0({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:UT2({mediaType:$.mediaType,entityId:Y.id,filename:$.filename})}}}}async enqueueSourceImageRender(A,Q){let w=jZ(A.from.sourceEntityType),B=jZ(A.from.sourceEntityId),$=jZ(A.from.attachmentType);if(!w||!B||!$)return{kind:"handled",result:{success:!1,error:"Image source requires sourceEntityType, sourceEntityId, and attachmentType"}};let Y=await Q4(Q.entityService,w,B,this.logger,"Source entity");if(!Y.ok)return{kind:"handled",result:{success:!1,error:Y.error}};let D=jZ(A.targetEntityType),X=jZ(A.targetEntityId),H;if(D&&X){let F=await Q4(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 KT2(Q,W),Z=ZT2(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:Zj0(Z,$)}}}}async createPendingImage(A,Q){let w=new Date().toISOString(),B=vX.createImageEntity({dataUrl:HT2,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 YQ0(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 YQ0(A,this.logger);A.jobs.registerHandler("image-generate",Q),A.jobs.registerHandler("image-render-source",new Wj0(A,this.logger)),A.jobs.registerHandler("upload-promote",new fj0(this.logger.child("UploadPromotionJobHandler"),A))}}function zc(A){return new Kj0(A)}c0();import{StdioServerTransport as GT2}from"@modelcontextprotocol/sdk/server/stdio.js";function FjA(){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 Uj0(){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 HQ0(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 Uj0()}class MZ{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return MZ.instance??=new MZ(A),MZ.instance}static resetInstance(){if(MZ.instance)MZ.instance.stop(),MZ.instance=null}static createFresh(A){return new MZ(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?HQ0(this.config.logger):FjA()}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 GT2,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 VjA}from"crypto";import{WebStandardStreamableHTTPServerTransport as zT2}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as qT2}from"@modelcontextprotocol/sdk/types.js";c0();var FT2={"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 VT2(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?HQ0(this.config.logger):Uj0(),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(FT2))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:`${VT2(A)}/.well-known/oauth-protected-resource`,...Q};return`Bearer ${Object.entries(B).map(([Y,D])=>`${Y}="${JT2(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&&qT2(w))B=new zT2({sessionIdGenerator:()=>VjA(),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??VjA();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=wG0.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 JT2(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}import{randomUUID as bT2}from"crypto";import{mkdir as LT2,readFile as NT2,writeFile as jT2,chmod as MT2}from"fs/promises";import{dirname as _T2,join as PT2}from"path";function JjA(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function IjA(A){try{return new URL(A)}catch{return}}function Gj0(A,Q){if(A===Q)return!0;let w=IjA(A),B=IjA(Q);if(!w||!B)return!1;if(!JjA(w.hostname)||!JjA(B.hostname))return!1;return w.protocol===B.protocol&&w.port===B.port&&IT2(w.pathname,B.pathname)&&w.search===B.search&&w.hash===B.hash}function IT2(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function zj0(A,Q){return A.some((w)=>Gj0(w,Q))}var kT2="oauth-auth-codes.json",OT2=600;function bjA(){return Math.floor(Date.now()/1000)}function xT2(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 RT2(A){if(!A||typeof A!=="object")return{codes:[]};let Q=A.codes;if(!Array.isArray(Q))return{codes:[]};return{codes:Q.filter(xT2)}}async function hT2(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class WQ0{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=PT2(A.storageDir,A.storeFile??kT2)}async createCode(A){let Q=bjA(),w={code:`ocd_${bT2()}`,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+OT2};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=bjA(),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 _Z("Authorization code not found");if(Y.consumed_at!==void 0)throw new _Z("Authorization code already consumed");if(Y.expires_at<=Q)throw new _Z("Authorization code expired");if(Y.client_id!==A.clientId)throw new _Z("Authorization code client mismatch");if(!Gj0(Y.redirect_uri,A.redirectUri))throw new _Z("Authorization code redirect URI mismatch");let D=await hT2(A.codeVerifier);if(Y.code_challenge!==D)throw new _Z("PKCE verification failed");w={...Y,consumed_at:Q},B.codes[$]=w,await this.writeStore(B)}),!w)throw new _Z("Authorization code not consumed");return w}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return RT2(JSON.parse(await NT2(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{codes:[]};throw A}}async writeStore(A){await LT2(_T2(this.storeFile),{recursive:!0,mode:448}),await jT2(this.storeFile,`${JSON.stringify(A,null,2)}
|
|
1698
|
+
${f}`,wT2);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=UjA(Z,G)+W,L;try{L=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 b=vX.createImageEntity({dataUrl:L.dataUrl,title:X,status:"draft",attachmentType:"generated",...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}});if(await NX({entityService:this.context.entityService,entity:{...b,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 GU({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();H4();var $T2=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 Wj0 extends _w{context;constructor(A,Q){super(Q,{schema:$T2,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=vX.createImageEntity({dataUrl:Sb0(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 NX({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 GU({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"?Fu(w,Q):Wj(w,Q);await this.context.entities.update($)}}c0();Z0();CB();H4();Z0();var rR={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function DQ0(A){return["image/png","image/jpeg","image/webp","image/gif"].includes(A.toLowerCase())}function XQ0(A){let Q=YT2(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 GjA(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function YT2(A,Q){let w=A?.trim();if(w)return w;return Q.replace(/\.[^.]+$/,"").trim()||Q}var DT2=K.object({uploadId:K.string().min(1),imageId:K.string().min(1).optional(),title:K.string().optional()});class fj0 extends _w{context;constructor(A,Q){super(A,{schema:DT2,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(!DQ0(B.record.mediaType))throw Error("Only image uploads can be promoted to image entities");let $=XQ0({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=vX.createImageEntity({dataUrl:GjA(B.record.mediaType,B.content),title:$.title,status:"draft",sourceUploadId:A.uploadId,sourceFilename:B.record.filename,sourceMediaType:B.record.mediaType,attachmentType:"uploaded"}),H=await NX({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 GU({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 zjA={name:"@brains/image-plugin",private:!0,version:"0.2.0-alpha.139",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 HT2="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",WT2=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 jZ(A){let Q=A?.trim();if(!Q)return;return Q}function fT2(A){let Q=jZ(A.prompt);if(Q)return Q;let w=jZ(A.content);if(w&&!Hj0(w))return w;return}function ZT2(A){let Q=A.attachmentType==="og-image"?"og":A.attachmentType;return w1(`${Q}-${A.sourceEntityType}-${A.sourceEntityId}`)}function qjA(A){let Q=jZ(A.title)??(A.targetEntityId?`cover-${A.targetEntityId}`:A.prompt.slice(0,60).trim());return w1(Q)}async function KT2(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 Zj0(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 UT2(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 Kj0 extends kQ{entityType=vX.entityType;schema=zu;adapter=vX;constructor(A={}){super("image",zjA,A,WT2)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,w){if(A.from?.kind===rR.refKind)return this.promoteUpload(A,w);let B=fT2(A),$=jZ(A.targetEntityType),Y=jZ(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=jZ(A.title)??D,F=qjA({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:Zj0(F)}}}}let H=await Q4(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=$Q0(H.entity.content),f=qjA({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:Zj0(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(!DQ0($.mediaType))return{kind:"handled",result:{success:!1,error:"Only image uploads can be promoted to image entities"}};let Y;try{Y=XQ0({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:UT2({mediaType:$.mediaType,entityId:Y.id,filename:$.filename})}}}}async enqueueSourceImageRender(A,Q){let w=jZ(A.from.sourceEntityType),B=jZ(A.from.sourceEntityId),$=jZ(A.from.attachmentType);if(!w||!B||!$)return{kind:"handled",result:{success:!1,error:"Image source requires sourceEntityType, sourceEntityId, and attachmentType"}};let Y=await Q4(Q.entityService,w,B,this.logger,"Source entity");if(!Y.ok)return{kind:"handled",result:{success:!1,error:Y.error}};let D=jZ(A.targetEntityType),X=jZ(A.targetEntityId),H;if(D&&X){let F=await Q4(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 KT2(Q,W),Z=ZT2(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:Zj0(Z,$)}}}}async createPendingImage(A,Q){let w=new Date().toISOString(),B=vX.createImageEntity({dataUrl:HT2,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 YQ0(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 YQ0(A,this.logger);A.jobs.registerHandler("image-generate",Q),A.jobs.registerHandler("image-render-source",new Wj0(A,this.logger)),A.jobs.registerHandler("upload-promote",new fj0(this.logger.child("UploadPromotionJobHandler"),A))}}function zc(A){return new Kj0(A)}c0();import{StdioServerTransport as GT2}from"@modelcontextprotocol/sdk/server/stdio.js";function FjA(){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 Uj0(){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 HQ0(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 Uj0()}class MZ{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return MZ.instance??=new MZ(A),MZ.instance}static resetInstance(){if(MZ.instance)MZ.instance.stop(),MZ.instance=null}static createFresh(A){return new MZ(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?HQ0(this.config.logger):FjA()}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 GT2,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 VjA}from"crypto";import{WebStandardStreamableHTTPServerTransport as zT2}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as qT2}from"@modelcontextprotocol/sdk/types.js";c0();var FT2={"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 VT2(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?HQ0(this.config.logger):Uj0(),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(FT2))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:`${VT2(A)}/.well-known/oauth-protected-resource`,...Q};return`Bearer ${Object.entries(B).map(([Y,D])=>`${Y}="${JT2(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&&qT2(w))B=new zT2({sessionIdGenerator:()=>VjA(),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??VjA();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=wG0.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 JT2(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}import{randomUUID as bT2}from"crypto";import{mkdir as LT2,readFile as NT2,writeFile as jT2,chmod as MT2}from"fs/promises";import{dirname as _T2,join as PT2}from"path";function JjA(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function IjA(A){try{return new URL(A)}catch{return}}function Gj0(A,Q){if(A===Q)return!0;let w=IjA(A),B=IjA(Q);if(!w||!B)return!1;if(!JjA(w.hostname)||!JjA(B.hostname))return!1;return w.protocol===B.protocol&&w.port===B.port&&IT2(w.pathname,B.pathname)&&w.search===B.search&&w.hash===B.hash}function IT2(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function zj0(A,Q){return A.some((w)=>Gj0(w,Q))}var kT2="oauth-auth-codes.json",OT2=600;function bjA(){return Math.floor(Date.now()/1000)}function xT2(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 RT2(A){if(!A||typeof A!=="object")return{codes:[]};let Q=A.codes;if(!Array.isArray(Q))return{codes:[]};return{codes:Q.filter(xT2)}}async function hT2(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class WQ0{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=PT2(A.storageDir,A.storeFile??kT2)}async createCode(A){let Q=bjA(),w={code:`ocd_${bT2()}`,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+OT2};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=bjA(),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 _Z("Authorization code not found");if(Y.consumed_at!==void 0)throw new _Z("Authorization code already consumed");if(Y.expires_at<=Q)throw new _Z("Authorization code expired");if(Y.client_id!==A.clientId)throw new _Z("Authorization code client mismatch");if(!Gj0(Y.redirect_uri,A.redirectUri))throw new _Z("Authorization code redirect URI mismatch");let D=await hT2(A.codeVerifier);if(Y.code_challenge!==D)throw new _Z("PKCE verification failed");w={...Y,consumed_at:Q},B.codes[$]=w,await this.writeStore(B)}),!w)throw new _Z("Authorization code not consumed");return w}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async readStore(){try{return RT2(JSON.parse(await NT2(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{codes:[]};throw A}}async writeStore(A){await LT2(_T2(this.storeFile),{recursive:!0,mode:448}),await jT2(this.storeFile,`${JSON.stringify(A,null,2)}
|
|
1699
1699
|
`,{mode:384}),await MT2(this.storeFile,384)}}class _Z extends Error{constructor(A){super(A);this.name="InvalidGrantError"}}Z0();import{randomUUID as LjA}from"crypto";import{mkdir as vT2,readFile as CT2,writeFile as yT2,chmod as ET2}from"fs/promises";import{dirname as gT2,join as TT2}from"path";var ST2="oauth-clients.json",mT2=K.enum(["none","client_secret_basic","client_secret_post"]),uT2=K.object({redirect_uris:K.array(K.string().url()).min(1),token_endpoint_auth_method:mT2.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 cT2(){return Math.floor(Date.now()/1000)}function lT2(){return`ocs_${LjA().replaceAll("-","")}`}function pT2(A){if(!A||typeof A!=="object")return{clients:[]};let Q=A.clients;if(!Array.isArray(Q))return{clients:[]};return{clients:Q.filter(iT2)}}function iT2(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 fQ0{storeFile;writeQueue=Promise.resolve();constructor(A){this.storeFile=TT2(A.storageDir,A.storeFile??ST2)}async registerClient(A){let Q=uT2.safeParse(A);if(!Q.success)throw new qc(Q.error.message);let w=Q.data,B=cT2(),$=`oc_${LjA()}`,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:lT2(),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 pT2(JSON.parse(await CT2(this.storeFile,"utf8")))}catch(A){if(A.code==="ENOENT")return{clients:[]};throw A}}async writeStore(A){await vT2(gT2(this.storeFile),{recursive:!0,mode:448}),await yT2(this.storeFile,`${JSON.stringify(A,null,2)}
|
|
1700
1700
|
`,{mode:384}),await ET2(this.storeFile,384)}}class qc extends Error{constructor(A){super(A);this.name="InvalidClientMetadataError"}}import{createHash as dT2}from"crypto";import{mkdir as nT2,readFile as rT2,writeFile as oT2,chmod as sT2}from"fs/promises";import{dirname as aT2,join as tT2}from"path";var eT2="oauth-signing-key.jwk";function NjA(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 jjA(A){let Q=JSON.stringify({crv:A.crv,kty:A.kty,x:A.x,y:A.y});return dT2("sha256").update(Q).digest("base64url")}function AS2(A){return{kty:"EC",crv:"P-256",x:A.x,y:A.y,kid:A.kid,use:"sig",alg:"ES256"}}async function QS2(){let A=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),Q=await crypto.subtle.exportKey("jwk",A.privateKey);if(!NjA(Q))throw Error("Generated OAuth signing key is not a P-256 private JWK");let w=jjA(Q);return{...Q,kid:w,use:"sig",alg:"ES256"}}class ZQ0{keyFile;cachedKey;loadPromise;constructor(A){this.keyFile=tT2(A.storageDir,A.keyFile??eT2)}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 QS2();return await nT2(aT2(this.keyFile),{recursive:!0,mode:448}),await oT2(this.keyFile,`${JSON.stringify(Q,null,2)}
|
|
1701
1701
|
`,{mode:384}),await sT2(this.keyFile,384),Q}async getPublicJwk(){return AS2(await this.getPrivateJwk())}async readExistingKey(){try{let A=JSON.parse(await rT2(this.keyFile,"utf8"));if(!NjA(A))throw Error(`OAuth signing key at ${this.keyFile} is not a private P-256 JWK`);let Q=typeof A.kid==="string"?A.kid:jjA(A);return{...A,kid:Q,use:"sig",alg:"ES256"}}catch(A){if(A.code==="ENOENT")return;throw A}}}var $Q={};sw($Q,{trimPadding:()=>_jA,toUTF8String:()=>fS2,toBuffer:()=>DS2,toBase64:()=>HS2,isBase64URL:()=>KS2,isBase64:()=>ZS2,fromUTF8String:()=>WS2,fromBuffer:()=>XS2});var MjA=(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},wS2=MjA("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),BS2=MjA("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),$S2=/^[-A-Za-z0-9\-_]*$/,YS2=/^[-A-Za-z0-9+/]*={0,3}$/,EU={};EU.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?BS2:wS2;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};EU.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 $};EU.toString=(A,Q)=>{return new TextDecoder().decode(EU.toArrayBuffer(A,Q))};EU.fromString=(A,Q)=>{return EU.fromArrayBuffer(new TextEncoder().encode(A),Q)};EU.validate=(A,Q)=>{if(!(typeof A==="string"||A instanceof String))return!1;try{return Q?$S2.test(A):YS2.test(A)}catch(w){return!1}};EU.base64=EU;var uq=EU;function DS2(A,Q="base64url"){let w=uq.toArrayBuffer(A,Q==="base64url");return new Uint8Array(w)}function XS2(A,Q="base64url"){let w=new Uint8Array(A);return uq.fromArrayBuffer(w.buffer,Q==="base64url")}function HS2(A){let Q=uq.toArrayBuffer(A,!0);return uq.fromArrayBuffer(Q)}function WS2(A){return uq.fromString(A,!0)}function fS2(A){return uq.toString(A,!0)}function ZS2(A){return uq.validate(A,!1)}function KS2(A){return A=_jA(A),uq.validate(A,!0)}function _jA(A){return A.replace(/=/g,"")}var HY={};sw(HY,{encode:()=>vS2,decodeFirst:()=>hS2});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 KQ0=0,Fc=1,qj0=2,Fj0=3,Vj0=4,Jj0=5,Ij0=6,PjA=7;function gU(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==Fc){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 GQ0{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 kjA(A,Q,w){return oR(A,Q,w)}function US2(A,Q,w){let[B,$]=kjA(A,Q,w);return[-B-1,$]}function OjA(A,Q,w){let[B,$]=oR(A,Q,w),Y=w+$;return[new Uint8Array(A.buffer.slice(Y,Y+B)),$+B]}var GS2=new TextDecoder;function zS2(A,Q,w){let[B,$]=OjA(A,Q,w);return[GS2.decode(B),$]}function qS2(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 UQ0="Map is not supported or well formed";function FS2(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(UQ0);let[W,f]=Pj(A,w+Y);if(Y+=f,H-=f,H<=0)throw Error(UQ0);if(typeof W!=="string"&&typeof W!=="number")throw Error(UQ0);if(D.has(W))throw Error(UQ0);let[Z,G]=Pj(A,w+Y);Y+=G,D.set(W,Z)}return[D,Y]}function VS2(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 JS2(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 IS2(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 bS2(A,Q,w){let[B,$]=oR(A,Q,w),[Y,D]=Pj(A,w+$);return[new GQ0(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 KQ0:return kjA(A,$,Q);case Fc:return US2(A,$,Q);case qj0:return OjA(A,$,Q);case Fj0:return zS2(A,$,Q);case Vj0:return qS2(A,$,Q);case Jj0:return FS2(A,$,Q);case Ij0:return bS2(A,$,Q);case PjA: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 VS2(A,Q);case 26:return JS2(A,Q);case 27:return IS2(A,Q)}}throw Error(`Unsupported or not well formed at ${Q}`)}function LS2(A){if(A===!0)return 245;else if(A===!1)return 244;else if(A===null)return 246;return 247}function NS2(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 gU(Fc,Math.abs(A));else return gU(KQ0,A);return[NS2(A)]}else if(A<0n)return gU(Fc,A*-1n);else return gU(KQ0,A)}var MS2=new TextEncoder;function _S2(A,Q){Q.push(...gU(Fj0,A.length)),Q.push(MS2.encode(A))}function PS2(A,Q){Q.push(...gU(qj0,A.length)),Q.push(A)}function kS2(A,Q){Q.push(...gU(Vj0,A.length));for(let w of A)Vc(w,Q)}function OS2(A,Q){Q.push(new Uint8Array(gU(Jj0,A.size)));for(let[w,B]of A.entries())Vc(w,Q),Vc(B,Q)}function xS2(A,Q){Q.push(...gU(Ij0,A.tag)),Vc(A.value,Q)}function Vc(A,Q){if(typeof A=="boolean"||A===null||A==null){Q.push(LS2(A));return}if(typeof A=="number"||typeof A=="bigint"){Q.push(...jS2(A));return}if(typeof A=="string"){_S2(A,Q);return}if(A instanceof Uint8Array){PS2(A,Q);return}if(Array.isArray(A)){kS2(A,Q);return}if(A instanceof Map){OS2(A,Q);return}if(A instanceof GQ0){xS2(A,Q);return}throw Error("Not implemented")}function bj0(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 Lj0(A){let Q=[];Vc(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 hS2(A){let Q=new Uint8Array(A),w=bj0(Q,0),[B]=w;return B}function vS2(A){return Lj0(A)}var SU={};sw(SU,{verify:()=>fOA,getRandomValues:()=>CjA,digest:()=>vjA});function xjA(A){let Q=A.get(QQ.kty);return Nj0(Q)&&Q===EX.OKP}function _J(A){let Q=A.get(QQ.kty);return Nj0(Q)&&Q===EX.EC2}function sR(A){let Q=A.get(QQ.kty);return Nj0(Q)&&Q===EX.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 EX;(function(A){A[A.OKP=1]="OKP",A[A.EC2=2]="EC2",A[A.RSA=3]="RSA"})(EX||(EX={}));function Nj0(A){return Object.values(EX).indexOf(A)>=0}var f4;(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"})(f4||(f4={}));function RjA(A){return Object.values(f4).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 TU(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 Jc=void 0;function $D(){return new Promise((Q,w)=>{if(Jc)return Q(Jc);let B=yS2.stubThisGlobalThisCrypto();if(B)return Jc=B,Q(Jc);return w(new hjA)})}class hjA extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}}var yS2={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(A)=>{Jc=A}};async function vjA(A,Q){let w=await $D(),B=PJ(Q),$=await w.subtle.digest(B,A);return new Uint8Array($)}async function CjA(A){return(await $D()).getRandomValues(A),A}async function aR(A){let Q=await $D(),{keyData:w,algorithm:B}=A;return Q.subtle.importKey("jwk",w,B,!1,["verify"])}async function zQ0(A){let{cosePublicKey:Q,signature:w,data:B,shaHashOverride:$}=A,Y=await $D(),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===f4.P256)f="P-256";else if(X===f4.P384)f="P-384";else if(X===f4.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 L={name:"ECDSA",hash:{name:V}};return Y.subtle.verify(L,F,w,B)}function jj0(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 qQ0(A){let{cosePublicKey:Q,signature:w,data:B,shaHashOverride:$}=A,Y=await $D(),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(!TU(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:jj0(D),hash:{name:PJ(D)}},Z={name:jj0(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 FQ0(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 b=Y.algorithms.map((N)=>N.alg)
|
|
|
2274
2274
|
</form>
|
|
2275
2275
|
</main>
|
|
2276
2276
|
</body>
|
|
2277
|
-
</html>`}function $p(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(SP0(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function AG(A){return A.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}import{randomUUID as Ul2}from"crypto";function NxA(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function Kl2(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([...jxA(Y),...jxA(H)])}function jxA(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 uP0(A,Q){let w={typ:"JWT",alg:"ES256",kid:A.kid},B=`${NxA(w)}.${NxA(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(Kl2(Y)).toString("base64url")}`}var Gl2=600;class cP0{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 $p(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(LxA(w.params,B))}async handleAuthorizeApproval(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return $p(A);let w=await A.formData(),B=await this.validateAuthorizationRequest(new URLSearchParams(yP0(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_${Ul2()}`;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)+Gl2}),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(!zj0(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 pX(w,201)}catch(w){if(w instanceof qc)return y6("invalid_client_metadata",w.message);throw w}}async handleTokenRequest(A,Q){let w=await CP0(A),B=w.get("grant_type"),$=gP0(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=EP0(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||!zj0(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 _Z)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 uP0(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 pX({access_token:B,token_type:"Bearer",expires_in:900,...A.scope?{scope:A.scope}:{},refresh_token:$})}async handleRevokeRequest(A){let Q=await CP0(A),w=gP0(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=EP0(Y,w);if(D)return y6("invalid_client",D)}return await this.refreshTokenStore.revokeToken($,B),new Response(null,{status:200})}}class lP0{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(ow0(A));return pX(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(),ow0(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:Ap(A)});return pX({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(ow0(A));return pX(Q)}async handleAuthenticationVerify(A){let Q=await this.passkeyService.verifyAuthenticationResponse(await A.json(),ow0(A));if(!Q.verified)return y6("access_denied","Passkey authentication failed");let w=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:Ap(A)});return pX({verified:!0},200,{"Set-Cookie":w.cookie})}}function ow0(A){let Q=fv(A),w=new URL(Q);return{origin:w.origin,rpID:w.hostname}}import{randomUUID as zl2}from"crypto";var Yp=86400;class pP0{setupStateStore;passkeyService;setupTokenTtlSeconds;setupToken;constructor(A){this.setupStateStore=A.setupStateStore,this.passkeyService=A.passkeyService,this.setupTokenTtlSeconds=A.setupTokenTtlSeconds??Yp}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_${zl2()}`,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 eU(A,`/setup?token=${encodeURIComponent(Q.token)}`)}async getOperatorSetupRequired(A){if(await this.passkeyService.hasCredentials())return;let Q=this.getValidSetupToken();if(!Q)return;return{setupUrl:eU(A,`/setup?token=${encodeURIComponent(Q.token)}`),expiresAt:Q.expiresAt,setupTokenId:UP0(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(IxA(Q))}async hasSetupEmailDelivery(A,Q){return this.setupStateStore.hasDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,w={}){await this.setupStateStore.recordDelivery(A,Q,w)}}class sw0{issuer;trustedIssuers;allowLocalhostIssuers;keyStore;clientStore;authCodeStore;sessionStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;logger;constructor(A){this.issuer=gZ(A.issuer),this.trustedIssuers=new Set([this.issuer,...(A.trustedIssuers??[]).map((Q)=>gZ(Q))]),this.allowLocalhostIssuers=A.allowLocalhostIssuers??Wv(this.issuer),this.keyStore=new ZQ0({storageDir:A.storageDir}),this.clientStore=new fQ0({storageDir:A.storageDir}),this.authCodeStore=new WQ0({storageDir:A.storageDir}),this.sessionStore=new pw0({storageDir:A.storageDir}),this.passkeyService=new Sw0({storageDir:A.storageDir,...A.logger?{logger:A.logger}:{}}),this.setupFlow=new pP0({setupStateStore:new GP0({storageDir:A.storageDir}),passkeyService:this.passkeyService,setupTokenTtlSeconds:A.setupTokenTtlSeconds??Yp}),this.oauthEndpoints=new cP0({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:new uw0({storageDir:A.storageDir}),sessionStore:this.sessionStore,keyStore:this.keyStore}),this.webauthnEndpoints=new lP0({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=gZ(A);return{issuer:Q,authorization_endpoint:eU(Q,"/authorize"),token_endpoint:eU(Q,"/token"),registration_endpoint:eU(Q,"/register"),revocation_endpoint:eU(Q,"/revoke"),jwks_uri:eU(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:[gZ(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 $p(A)}async verifyBearerToken(A,Q={}){let w=vP0(A);if(!w)return;let B=Q.issuer?gZ(Q.issuer):this.resolveRequestIssuer(A);return hP0(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"&&FxA(w))return VxA();if(A.method==="GET"){if(w==="/.well-known/oauth-authorization-server")return wI(pX(this.getAuthorizationServerMetadata(Q)));if(w==="/.well-known/jwks.json")return wI(pX(await this.getJwks()));if(w==="/.well-known/oauth-protected-resource")return wI(pX(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=TP0(new URL(A.url).searchParams.get("return_to"));return Fv(SP0(Q))}async handleLogout(A){await this.sessionStore.revokeSessionFromRequest(A);let Q=TP0(new URL(A.url).searchParams.get("return_to"));return new Response(null,{status:302,headers:{Location:Q,"Set-Cookie":FP0(Ap(A)),"Cache-Control":"no-store"}})}}Z0();var aw0="email:send",MxA=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 _xA={name:"@brains/notifications",private:!0,version:"0.2.0-alpha.138",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 iP0="notifications:send",Fl2=K.object({}),Vl2=K.discriminatedUnion("type",[K.object({type:K.literal("email"),address:K.string().email()}).strict()]),Jl2=K.object({recipient:Vl2,title:K.string().min(1),body:K.string().min(1),html:K.string().min(1).optional(),sensitivity:K.enum(["normal","secret"]).default("normal")}).strict(),PxA=K.discriminatedUnion("status",[K.object({status:K.literal("sent"),deliveryId:K.string().optional()}).strict(),K.object({status:K.literal("failed")}).strict()]);class kxA extends IQ{constructor(A={}){super("notifications",_xA,A,Fl2)}async onRegister(A){A.messaging.subscribe(iP0,async(Q)=>{let w=Jl2.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:aw0,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 tw0(A={}){return new kxA(A)}c0();Z0();var OxA={name:"@brains/auth-service",private:!0,version:"0.2.0-alpha.138",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 bl2=K.union([K.string().email(),K.object({to:K.string().email(),subject:K.string().min(1),body:K.string().min(1)}).strict()]),Ll2=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(Yp),setupEmail:bl2.optional()}),Nl2=K.object({}),ew0;function gW(){return ew0}class dP0 extends IQ{service;constructor(A={}){super("auth-service",OxA,A,Ll2)}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 sw0({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(),ew0=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(ew0===this.service)ew0=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.",Nl2,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:iP0,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=PxA.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:xxA(A.subject,Q),body:xxA(A.body,Q)}}function xxA(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 Dp(A){return new dP0(A)}Z0();var nP0=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 RxA(A,Q){return[]}c0();function rP0(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 hxA={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.138",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 zU{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",hxA,Q,nP0)}async getTools(){return RxA(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"});rP0(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=gW();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||gW()))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=MZ.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(){MZ.resetInstance(),mq.resetInstance()}}c0();Z0();var AH=X1(By0(),1);Z0();c0();var $y0=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 RW1={name:"@brains/discord",private:!0,version:"0.2.0-alpha.138",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 pi=2000,dbQ=8388608,nbQ=8000,rbQ=100;function B50(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class uI extends QZ{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",RW1,A,$y0);this.fetchText=Q.fetchText??_t}async onRegister(A){await super.onRegister(A),this.client=new AH.Client({intents:[AH.GatewayIntentBits.Guilds,AH.GatewayIntentBits.GuildMessages,AH.GatewayIntentBits.MessageContent,AH.GatewayIntentBits.DirectMessages],partials:[AH.Partials.Channel]}),this.client.on(AH.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.on(AH.Events.InteractionCreate,(Q)=>{this.handleInteraction(Q)}),this.client.once(AH.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(!B50(w))return;let B=AN(Q,pi);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(!B50(w))return;if(typeof Q!=="string")return(await w.send(Q)).id;let B=AN(Q,pi),$;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(!B50(B))return!1;try{return await(await B.messages.fetch(Q)).edit(w.slice(0,pi)),!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,L=F.contentType??void 0,b=F.size;if(!this.isUploadableTextFile(V,L))continue;if(!this.isFileSizeAllowed(b))continue;try{let N=await this.fetchText(F.url);W+=`
|
|
2277
|
+
</html>`}function $p(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(SP0(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function AG(A){return A.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}import{randomUUID as Ul2}from"crypto";function NxA(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function Kl2(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([...jxA(Y),...jxA(H)])}function jxA(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 uP0(A,Q){let w={typ:"JWT",alg:"ES256",kid:A.kid},B=`${NxA(w)}.${NxA(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(Kl2(Y)).toString("base64url")}`}var Gl2=600;class cP0{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 $p(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(LxA(w.params,B))}async handleAuthorizeApproval(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return $p(A);let w=await A.formData(),B=await this.validateAuthorizationRequest(new URLSearchParams(yP0(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_${Ul2()}`;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)+Gl2}),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(!zj0(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 pX(w,201)}catch(w){if(w instanceof qc)return y6("invalid_client_metadata",w.message);throw w}}async handleTokenRequest(A,Q){let w=await CP0(A),B=w.get("grant_type"),$=gP0(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=EP0(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||!zj0(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 _Z)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 uP0(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 pX({access_token:B,token_type:"Bearer",expires_in:900,...A.scope?{scope:A.scope}:{},refresh_token:$})}async handleRevokeRequest(A){let Q=await CP0(A),w=gP0(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=EP0(Y,w);if(D)return y6("invalid_client",D)}return await this.refreshTokenStore.revokeToken($,B),new Response(null,{status:200})}}class lP0{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(ow0(A));return pX(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(),ow0(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:Ap(A)});return pX({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(ow0(A));return pX(Q)}async handleAuthenticationVerify(A){let Q=await this.passkeyService.verifyAuthenticationResponse(await A.json(),ow0(A));if(!Q.verified)return y6("access_denied","Passkey authentication failed");let w=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:Ap(A)});return pX({verified:!0},200,{"Set-Cookie":w.cookie})}}function ow0(A){let Q=fv(A),w=new URL(Q);return{origin:w.origin,rpID:w.hostname}}import{randomUUID as zl2}from"crypto";var Yp=86400;class pP0{setupStateStore;passkeyService;setupTokenTtlSeconds;setupToken;constructor(A){this.setupStateStore=A.setupStateStore,this.passkeyService=A.passkeyService,this.setupTokenTtlSeconds=A.setupTokenTtlSeconds??Yp}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_${zl2()}`,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 eU(A,`/setup?token=${encodeURIComponent(Q.token)}`)}async getOperatorSetupRequired(A){if(await this.passkeyService.hasCredentials())return;let Q=this.getValidSetupToken();if(!Q)return;return{setupUrl:eU(A,`/setup?token=${encodeURIComponent(Q.token)}`),expiresAt:Q.expiresAt,setupTokenId:UP0(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(IxA(Q))}async hasSetupEmailDelivery(A,Q){return this.setupStateStore.hasDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,w={}){await this.setupStateStore.recordDelivery(A,Q,w)}}class sw0{issuer;trustedIssuers;allowLocalhostIssuers;keyStore;clientStore;authCodeStore;sessionStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;logger;constructor(A){this.issuer=gZ(A.issuer),this.trustedIssuers=new Set([this.issuer,...(A.trustedIssuers??[]).map((Q)=>gZ(Q))]),this.allowLocalhostIssuers=A.allowLocalhostIssuers??Wv(this.issuer),this.keyStore=new ZQ0({storageDir:A.storageDir}),this.clientStore=new fQ0({storageDir:A.storageDir}),this.authCodeStore=new WQ0({storageDir:A.storageDir}),this.sessionStore=new pw0({storageDir:A.storageDir}),this.passkeyService=new Sw0({storageDir:A.storageDir,...A.logger?{logger:A.logger}:{}}),this.setupFlow=new pP0({setupStateStore:new GP0({storageDir:A.storageDir}),passkeyService:this.passkeyService,setupTokenTtlSeconds:A.setupTokenTtlSeconds??Yp}),this.oauthEndpoints=new cP0({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:new uw0({storageDir:A.storageDir}),sessionStore:this.sessionStore,keyStore:this.keyStore}),this.webauthnEndpoints=new lP0({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=gZ(A);return{issuer:Q,authorization_endpoint:eU(Q,"/authorize"),token_endpoint:eU(Q,"/token"),registration_endpoint:eU(Q,"/register"),revocation_endpoint:eU(Q,"/revoke"),jwks_uri:eU(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:[gZ(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 $p(A)}async verifyBearerToken(A,Q={}){let w=vP0(A);if(!w)return;let B=Q.issuer?gZ(Q.issuer):this.resolveRequestIssuer(A);return hP0(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"&&FxA(w))return VxA();if(A.method==="GET"){if(w==="/.well-known/oauth-authorization-server")return wI(pX(this.getAuthorizationServerMetadata(Q)));if(w==="/.well-known/jwks.json")return wI(pX(await this.getJwks()));if(w==="/.well-known/oauth-protected-resource")return wI(pX(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=TP0(new URL(A.url).searchParams.get("return_to"));return Fv(SP0(Q))}async handleLogout(A){await this.sessionStore.revokeSessionFromRequest(A);let Q=TP0(new URL(A.url).searchParams.get("return_to"));return new Response(null,{status:302,headers:{Location:Q,"Set-Cookie":FP0(Ap(A)),"Cache-Control":"no-store"}})}}Z0();var aw0="email:send",MxA=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 _xA={name:"@brains/notifications",private:!0,version:"0.2.0-alpha.139",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 iP0="notifications:send",Fl2=K.object({}),Vl2=K.discriminatedUnion("type",[K.object({type:K.literal("email"),address:K.string().email()}).strict()]),Jl2=K.object({recipient:Vl2,title:K.string().min(1),body:K.string().min(1),html:K.string().min(1).optional(),sensitivity:K.enum(["normal","secret"]).default("normal")}).strict(),PxA=K.discriminatedUnion("status",[K.object({status:K.literal("sent"),deliveryId:K.string().optional()}).strict(),K.object({status:K.literal("failed")}).strict()]);class kxA extends IQ{constructor(A={}){super("notifications",_xA,A,Fl2)}async onRegister(A){A.messaging.subscribe(iP0,async(Q)=>{let w=Jl2.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:aw0,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 tw0(A={}){return new kxA(A)}c0();Z0();var OxA={name:"@brains/auth-service",private:!0,version:"0.2.0-alpha.139",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 bl2=K.union([K.string().email(),K.object({to:K.string().email(),subject:K.string().min(1),body:K.string().min(1)}).strict()]),Ll2=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(Yp),setupEmail:bl2.optional()}),Nl2=K.object({}),ew0;function gW(){return ew0}class dP0 extends IQ{service;constructor(A={}){super("auth-service",OxA,A,Ll2)}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 sw0({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(),ew0=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(ew0===this.service)ew0=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.",Nl2,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:iP0,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=PxA.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:xxA(A.subject,Q),body:xxA(A.body,Q)}}function xxA(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 Dp(A){return new dP0(A)}Z0();var nP0=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 RxA(A,Q){return[]}c0();function rP0(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 hxA={name:"@brains/mcp",private:!0,version:"0.2.0-alpha.139",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 zU{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",hxA,Q,nP0)}async getTools(){return RxA(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"});rP0(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=gW();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||gW()))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=MZ.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(){MZ.resetInstance(),mq.resetInstance()}}c0();Z0();var AH=X1(By0(),1);Z0();c0();var $y0=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 RW1={name:"@brains/discord",private:!0,version:"0.2.0-alpha.139",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 pi=2000,dbQ=8388608,nbQ=8000,rbQ=100;function B50(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class uI extends QZ{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",RW1,A,$y0);this.fetchText=Q.fetchText??_t}async onRegister(A){await super.onRegister(A),this.client=new AH.Client({intents:[AH.GatewayIntentBits.Guilds,AH.GatewayIntentBits.GuildMessages,AH.GatewayIntentBits.MessageContent,AH.GatewayIntentBits.DirectMessages],partials:[AH.Partials.Channel]}),this.client.on(AH.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.on(AH.Events.InteractionCreate,(Q)=>{this.handleInteraction(Q)}),this.client.once(AH.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(!B50(w))return;let B=AN(Q,pi);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(!B50(w))return;if(typeof Q!=="string")return(await w.send(Q)).id;let B=AN(Q,pi),$;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(!B50(B))return!1;try{return await(await B.messages.fetch(Q)).edit(w.slice(0,pi)),!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,L=F.contentType??void 0,b=F.size;if(!this.isUploadableTextFile(V,L))continue;if(!this.isFileSizeAllowed(b))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:H7(A,rbQ),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(B50(W))this.startTypingIndicator(W);if(this.pendingConfirmations.has(D)){if(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)));else this.pendingConfirmations.delete(D);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:H7(A.trim().length>0?`${A}
|
|
2281
2281
|
|
|
@@ -2343,7 +2343,7 @@ ${A.value}
|
|
|
2343
2343
|
`);if(X50(A))return this.renderList(A,0,(Q)=>this.nodeToDiscordMarkdown(Q));if(A.type==="break")return`
|
|
2344
2344
|
`;if(A.type==="thematicBreak")return"---";if(GE0(A))return`\`\`\`
|
|
2345
2345
|
${zE0(A)}
|
|
2346
|
-
\`\`\``;return this.defaultNodeToText(A,(Q)=>this.nodeToDiscordMarkdown(Q))}},pJ1={DeferredChannelMessageWithSource:5,DeferredUpdateMessage:6},F50="https://discord.com/api/v10",iJ1=2000,jOQ=/^[0-9a-f]{64}$/,MOQ=/^[0-9a-f]+$/,_OQ=class A{name="discord";userName;botUserId;apiBaseUrl;botToken;publicKey;applicationId;mentionRoleIds;chat=null;logger;formatConverter=new NOQ;requestContext=new UOQ;threadParentCache=new Map;static THREAD_PARENT_CACHE_TTL=300000;constructor(Q={}){let w=Q.botToken??process.env.DISCORD_BOT_TOKEN;if(!w)throw new rW("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 rW("discord","publicKey is required. Set DISCORD_PUBLIC_KEY or provide it in config.");let $=Q.applicationId??process.env.DISCORD_APPLICATION_ID;if(!$)throw new rW("discord","applicationId is required. Set DISCORD_APPLICATION_ID or provide it in config.");if(this.apiBaseUrl=Q.apiUrl??process.env.DISCORD_API_URL??F50,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 G50("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:MOQ.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:wd.InteractionResponseType.PONG});return this.logger.info("Discord PING received, responding with PONG",{responseBody:Z,responseType:wd.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:pJ1.DeferredUpdateMessage});if(f.type===RC.ApplicationCommand)return this.handleApplicationCommandInteraction(f,w),this.respondToInteraction({type:pJ1.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 wd.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=zOQ(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 L=await(await this.discordFetch(`/channels/${Y}`,"GET")).json();if(L.parent_id)D=Y,X=L.parent_id,this.threadParentCache.set(Y,{parentId:L.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=q50(w);if(W){let V=tE0(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=RE0(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<=iJ1)return Q;return`${Q.slice(0,iJ1-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 hE0(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(`${F50}/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(`${F50}${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 hE0(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(`${F50}${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=q50(B);if(f){let F=tE0(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=ai.toDiscord?ai.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 rW("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===cz1.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 m9.Client({intents:[m9.GatewayIntentBits.Guilds,m9.GatewayIntentBits.GuildMessages,m9.GatewayIntentBits.MessageContent,m9.GatewayIntentBits.DirectMessages,m9.GatewayIntentBits.GuildMessageReactions,m9.GatewayIntentBits.DirectMessageReactions],partials:[m9.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(m9.Events.ClientReady,()=>{this.logger.info("Discord Gateway connected",{username:$.user?.username,id:$.user?.id})}),$.on(m9.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(m9.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(m9.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(m9.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(m9.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 rW("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 rW("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((b)=>b.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((b)=>{if(Z.has(b.id))return!1;return Z.add(b.id),!0}),F=w.limit||50,V=G.slice(0,F),L=[];for(let b of V){let N=this.encodeThreadId({guildId:$,channelId:Y,threadId:b.id});try{let g=(await(await this.discordFetch(`/channels/${b.id}/messages?limit=1&after=0`,"GET")).json())[0];if(g)L.push({id:N,rootMessage:this.parseDiscordMessage(g,N),replyCount:b.total_message_sent??b.message_count,lastReplyAt:b.thread_metadata?.archive_timestamp?new Date(b.thread_metadata.archive_timestamp):void 0})}catch{L.push({id:N,rootMessage:new x5({id:b.id,threadId:N,text:b.name,formatted:this.formatConverter.toAst(b.name),raw:b,author:{userId:"unknown",userName:"unknown",fullName:"unknown",isBot:!1,isMe:!1},metadata:{dateSent:new Date,edited:!1},attachments:[]}),replyCount:b.total_message_sent??b.message_count})}}return this.logger.debug("Discord API: listThreads result",{threadCount:L.length}),{threads:L,nextCursor:G.length>F?String(F):void 0}}async fetchChannelInfo(Q){let B=Q.split(":")[2];if(!B)throw new rW("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 rW("discord",`Invalid Discord channel ID: ${Q}`);let Y={},D=[],X=[],H=q50(w);if(H){let F=tE0(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=RE0(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 rJ1(A){return new _OQ(A??{})}var POQ=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:kOQ(),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 kOQ(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function V50(A){return new POQ}Z0();var OOQ=K.object({subscribedAt:K.string().datetime(),routingMode:K.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:K.boolean().optional()}),xOQ="chat.discord.subscriptions";function eE0(A){return A.scoped({namespace:xOQ,schema:OOQ})}function oJ1(A,Q=V50()){let w=eE0(A);return new sJ1(Q,w)}class sJ1{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 aJ1(A){let{discord:Q}=A;if(!Q)return new OE0({userName:A.userName,adapters:{},state:V50()});let w=rJ1({botToken:Q.botToken,publicKey:Q.publicKey,applicationId:Q.applicationId,mentionRoleIds:Q.mentionRoleIds});return A.gatewayLoop.setAdapter(w),new OE0({userName:A.userName,adapters:{discord:w},concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"},state:oJ1(A.runtimeState)})}class Ag0{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 Qg0{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=K00(W,f);if(!G){$.notices.push(`Unsupported file upload type: ${W}`);continue}if(!U00(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 L=await D.save({filename:V.filename,mediaType:V.mediaType,content:F,metadata:this.buildMetadata(A,Q,w)});$.attachments.push(eJ1(L.filename,L.mediaType,F,L.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 tJ1(A,Q,w,B){return eJ1(A,Q,w,B,aV(A,Q))}function eJ1(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 Bd(){return{namespace:"discord-chat",refKind:"discord-chat-upload",routePath:"/api/webhooks/chat/discord/uploads"}}var AI1={name:"@brains/chat",private:!0,version:"0.2.0-alpha.138",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 hOQ=/https?:\/\/\S+/i,vOQ=/[\s\S]+/,COQ="https://discord.com/api/v10",yOQ=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(),EOQ=K.object({card:K.custom((A)=>yOQ.safeParse(A).success),fallbackText:K.string().optional()});class J50 extends QZ{threadRegistry=new $50;pendingApprovals;uploadContinuity;promptActions=new Map;toolStatusMessenger=new Dy0(this.threadRegistry);cardBuilder=new fy0({getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),registerPromptAction:(A,Q)=>this.registerPromptAction(A,Q)});artifactDelivery=new Ky0({getContext:()=>this.context,getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),logger:this.logger});approvalCards=new Uy0({cardBuilder:this.cardBuilder,clearMessageComponents:(A,Q)=>this.clearDiscordMessageComponents(A,Q)});subscriptionRouter=new Ag0({getSubscriptions:()=>this.discordSubscriptions,getPlatform:(A)=>this.getPlatform(A),isBotCreatedThread:(A,Q)=>this.isBotCreatedDiscordThread(A,Q),logger:this.logger});chatInputBuilder=new Qg0({getUploadStore:()=>this.context?.uploads.scoped(Bd()),getThreadIdParts:(A)=>this.getThreadIdParts(A),logger:this.logger});gatewayLoop;discordApp;discordSubscriptions;constructor(A={}){super("chat",AI1,A,Yy0);this.gatewayLoop=new Gy0({getApp:()=>this.discordApp.instance,gatewayRunMs:this.config.gatewayRunMs,gatewayRestartDelayMs:this.config.gatewayRestartDelayMs,logger:this.logger}),this.discordApp=new zy0({discord:this.config.adapters.discord,getUploadStore:()=>this.context?.uploads.scoped(Bd()),buildApp:(Q)=>aJ1({userName:this.config.userName,discord:this.config.adapters.discord,gatewayLoop:this.gatewayLoop,runtimeState:Q})}),this.pendingApprovals=new RS({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 gS({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(Bd());if(!w)throw Error("Chat upload store unavailable");let B=await w.read(Q);return tJ1(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=eE0(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 ii(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 ii(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=EOQ.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 Wy0(A)}formatCompletionOutput(A){return Wy0(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 yW1(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(vOQ,async(Q,w,B)=>{await this.handleRoutedMessage(Q,w,B)});A.onNewMessage(hOQ,async(Q,w)=>{await this.handlePassiveUrlCapture(Q,w)}),A.onAction([Y50,Xy0],async(Q)=>{await this.handleApprovalAction(Q)}),A.onAction(Hy0,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===Y50,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 ii(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){if(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 H00(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){if(!PS(A,B))return!1;let D=se({message:A,approvalIds:B});if(D.kind==="not-confirmation")return this.pendingApprovals.deleteConversation(Q),await w.post(this.formatNoticePayload("No pending approval to resolve.")),!0;if(D.kind==="notice")return await w.post(this.formatNoticePayload(D.message)),!0;return await this.confirmApproval({thread:w,conversationId:Q,approvalId:D.approvalId,confirmed:D.confirmed,userPermissionLevel:$,...Y?{metadata:Y}:{}}),!0}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 $00({text:A,cards:Q,pendingConfirmations:w,deniedCardIds:B,formatCard:($)=>this.cardBuilder.formatStructuredCard($,B)}).join(`
|
|
2346
|
+
\`\`\``;return this.defaultNodeToText(A,(Q)=>this.nodeToDiscordMarkdown(Q))}},pJ1={DeferredChannelMessageWithSource:5,DeferredUpdateMessage:6},F50="https://discord.com/api/v10",iJ1=2000,jOQ=/^[0-9a-f]{64}$/,MOQ=/^[0-9a-f]+$/,_OQ=class A{name="discord";userName;botUserId;apiBaseUrl;botToken;publicKey;applicationId;mentionRoleIds;chat=null;logger;formatConverter=new NOQ;requestContext=new UOQ;threadParentCache=new Map;static THREAD_PARENT_CACHE_TTL=300000;constructor(Q={}){let w=Q.botToken??process.env.DISCORD_BOT_TOKEN;if(!w)throw new rW("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 rW("discord","publicKey is required. Set DISCORD_PUBLIC_KEY or provide it in config.");let $=Q.applicationId??process.env.DISCORD_APPLICATION_ID;if(!$)throw new rW("discord","applicationId is required. Set DISCORD_APPLICATION_ID or provide it in config.");if(this.apiBaseUrl=Q.apiUrl??process.env.DISCORD_API_URL??F50,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 G50("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:MOQ.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:wd.InteractionResponseType.PONG});return this.logger.info("Discord PING received, responding with PONG",{responseBody:Z,responseType:wd.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:pJ1.DeferredUpdateMessage});if(f.type===RC.ApplicationCommand)return this.handleApplicationCommandInteraction(f,w),this.respondToInteraction({type:pJ1.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 wd.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=zOQ(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 L=await(await this.discordFetch(`/channels/${Y}`,"GET")).json();if(L.parent_id)D=Y,X=L.parent_id,this.threadParentCache.set(Y,{parentId:L.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=q50(w);if(W){let V=tE0(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=RE0(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<=iJ1)return Q;return`${Q.slice(0,iJ1-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 hE0(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(`${F50}/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(`${F50}${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 hE0(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(`${F50}${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=q50(B);if(f){let F=tE0(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=ai.toDiscord?ai.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 rW("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===cz1.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 m9.Client({intents:[m9.GatewayIntentBits.Guilds,m9.GatewayIntentBits.GuildMessages,m9.GatewayIntentBits.MessageContent,m9.GatewayIntentBits.DirectMessages,m9.GatewayIntentBits.GuildMessageReactions,m9.GatewayIntentBits.DirectMessageReactions],partials:[m9.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(m9.Events.ClientReady,()=>{this.logger.info("Discord Gateway connected",{username:$.user?.username,id:$.user?.id})}),$.on(m9.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(m9.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(m9.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(m9.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(m9.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 rW("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 rW("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((b)=>b.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((b)=>{if(Z.has(b.id))return!1;return Z.add(b.id),!0}),F=w.limit||50,V=G.slice(0,F),L=[];for(let b of V){let N=this.encodeThreadId({guildId:$,channelId:Y,threadId:b.id});try{let g=(await(await this.discordFetch(`/channels/${b.id}/messages?limit=1&after=0`,"GET")).json())[0];if(g)L.push({id:N,rootMessage:this.parseDiscordMessage(g,N),replyCount:b.total_message_sent??b.message_count,lastReplyAt:b.thread_metadata?.archive_timestamp?new Date(b.thread_metadata.archive_timestamp):void 0})}catch{L.push({id:N,rootMessage:new x5({id:b.id,threadId:N,text:b.name,formatted:this.formatConverter.toAst(b.name),raw:b,author:{userId:"unknown",userName:"unknown",fullName:"unknown",isBot:!1,isMe:!1},metadata:{dateSent:new Date,edited:!1},attachments:[]}),replyCount:b.total_message_sent??b.message_count})}}return this.logger.debug("Discord API: listThreads result",{threadCount:L.length}),{threads:L,nextCursor:G.length>F?String(F):void 0}}async fetchChannelInfo(Q){let B=Q.split(":")[2];if(!B)throw new rW("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 rW("discord",`Invalid Discord channel ID: ${Q}`);let Y={},D=[],X=[],H=q50(w);if(H){let F=tE0(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=RE0(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 rJ1(A){return new _OQ(A??{})}var POQ=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:kOQ(),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 kOQ(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function V50(A){return new POQ}Z0();var OOQ=K.object({subscribedAt:K.string().datetime(),routingMode:K.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:K.boolean().optional()}),xOQ="chat.discord.subscriptions";function eE0(A){return A.scoped({namespace:xOQ,schema:OOQ})}function oJ1(A,Q=V50()){let w=eE0(A);return new sJ1(Q,w)}class sJ1{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 aJ1(A){let{discord:Q}=A;if(!Q)return new OE0({userName:A.userName,adapters:{},state:V50()});let w=rJ1({botToken:Q.botToken,publicKey:Q.publicKey,applicationId:Q.applicationId,mentionRoleIds:Q.mentionRoleIds});return A.gatewayLoop.setAdapter(w),new OE0({userName:A.userName,adapters:{discord:w},concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"},state:oJ1(A.runtimeState)})}class Ag0{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 Qg0{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=K00(W,f);if(!G){$.notices.push(`Unsupported file upload type: ${W}`);continue}if(!U00(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 L=await D.save({filename:V.filename,mediaType:V.mediaType,content:F,metadata:this.buildMetadata(A,Q,w)});$.attachments.push(eJ1(L.filename,L.mediaType,F,L.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 tJ1(A,Q,w,B){return eJ1(A,Q,w,B,aV(A,Q))}function eJ1(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 Bd(){return{namespace:"discord-chat",refKind:"discord-chat-upload",routePath:"/api/webhooks/chat/discord/uploads"}}var AI1={name:"@brains/chat",private:!0,version:"0.2.0-alpha.139",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 hOQ=/https?:\/\/\S+/i,vOQ=/[\s\S]+/,COQ="https://discord.com/api/v10",yOQ=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(),EOQ=K.object({card:K.custom((A)=>yOQ.safeParse(A).success),fallbackText:K.string().optional()});class J50 extends QZ{threadRegistry=new $50;pendingApprovals;uploadContinuity;promptActions=new Map;toolStatusMessenger=new Dy0(this.threadRegistry);cardBuilder=new fy0({getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),registerPromptAction:(A,Q)=>this.registerPromptAction(A,Q)});artifactDelivery=new Ky0({getContext:()=>this.context,getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),logger:this.logger});approvalCards=new Uy0({cardBuilder:this.cardBuilder,clearMessageComponents:(A,Q)=>this.clearDiscordMessageComponents(A,Q)});subscriptionRouter=new Ag0({getSubscriptions:()=>this.discordSubscriptions,getPlatform:(A)=>this.getPlatform(A),isBotCreatedThread:(A,Q)=>this.isBotCreatedDiscordThread(A,Q),logger:this.logger});chatInputBuilder=new Qg0({getUploadStore:()=>this.context?.uploads.scoped(Bd()),getThreadIdParts:(A)=>this.getThreadIdParts(A),logger:this.logger});gatewayLoop;discordApp;discordSubscriptions;constructor(A={}){super("chat",AI1,A,Yy0);this.gatewayLoop=new Gy0({getApp:()=>this.discordApp.instance,gatewayRunMs:this.config.gatewayRunMs,gatewayRestartDelayMs:this.config.gatewayRestartDelayMs,logger:this.logger}),this.discordApp=new zy0({discord:this.config.adapters.discord,getUploadStore:()=>this.context?.uploads.scoped(Bd()),buildApp:(Q)=>aJ1({userName:this.config.userName,discord:this.config.adapters.discord,gatewayLoop:this.gatewayLoop,runtimeState:Q})}),this.pendingApprovals=new RS({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 gS({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(Bd());if(!w)throw Error("Chat upload store unavailable");let B=await w.read(Q);return tJ1(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=eE0(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 ii(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 ii(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=EOQ.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 Wy0(A)}formatCompletionOutput(A){return Wy0(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 yW1(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(vOQ,async(Q,w,B)=>{await this.handleRoutedMessage(Q,w,B)});A.onNewMessage(hOQ,async(Q,w)=>{await this.handlePassiveUrlCapture(Q,w)}),A.onAction([Y50,Xy0],async(Q)=>{await this.handleApprovalAction(Q)}),A.onAction(Hy0,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===Y50,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 ii(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){if(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 H00(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){if(!PS(A,B))return!1;let D=se({message:A,approvalIds:B});if(D.kind==="not-confirmation")return this.pendingApprovals.deleteConversation(Q),await w.post(this.formatNoticePayload("No pending approval to resolve.")),!0;if(D.kind==="notice")return await w.post(this.formatNoticePayload(D.message)),!0;return await this.confirmApproval({thread:w,conversationId:Q,approvalId:D.approvalId,confirmed:D.confirmed,userPermissionLevel:$,...Y?{metadata:Y}:{}}),!0}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 $00({text:A,cards:Q,pendingConfirmations:w,deniedCardIds:B,formatCard:($)=>this.cardBuilder.formatStructuredCard($,B)}).join(`
|
|
2347
2347
|
|
|
2348
2348
|
`)}formatConfirmationResponsePayload(A,Q,w,B){let $=Y00({response:A,confirmed:Q,remainingApprovalHelp:w,deniedCardIds:B,formatCard:(Y)=>this.cardBuilder.formatStructuredCard(Y,B),formatPendingConfirmationHelp:Yx});return{card:{type:"card",title:B00($.variant),children:$.parts.map((Y)=>({type:"text",content:Y}))},fallbackText:$.parts.join(`
|
|
2349
2349
|
|
|
@@ -2415,7 +2415,7 @@ ${zE0(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 vI1={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.
|
|
2418
|
+
</html>`;var vI1={name:"@brains/webserver",private:!0,version:"0.2.0-alpha.139",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 zU{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",vI1,A,qg0)}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 R50({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&&!CI1(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(yI1(this.config.previewDistDir,"index.html"),Fg0),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!CI1(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(yI1(this.config.productionDistDir,"index.html"),Fg0),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}CB();c0();Z0();var fb1="vercel.ai.error",MxQ=Symbol.for(fb1),EI1,gI1,mw=class A extends(gI1=Error,EI1=MxQ,gI1){constructor({name:Q,message:w,cause:B}){super(w);this[EI1]=!0,this.name=Q,this.cause=B}static isInstance(Q){return A.hasMarker(Q,fb1)}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}},Zb1="AI_APICallError",Kb1=`vercel.ai.error.${Zb1}`,_xQ=Symbol.for(Kb1),TI1,SI1,sG8=class extends(SI1=mw,TI1=_xQ,SI1){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:Zb1,message:A,cause:D});this[TI1]=!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,Kb1)}},Ub1="AI_EmptyResponseBodyError",Gb1=`vercel.ai.error.${Ub1}`,PxQ=Symbol.for(Gb1),mI1,uI1,aG8=class extends(uI1=mw,mI1=PxQ,uI1){constructor({message:A="Empty response body"}={}){super({name:Ub1,message:A});this[mI1]=!0}static isInstance(A){return mw.hasMarker(A,Gb1)}};function zb1(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 qb1="AI_InvalidArgumentError",Fb1=`vercel.ai.error.${qb1}`,kxQ=Symbol.for(Fb1),cI1,lI1,Vb1=class extends(lI1=mw,cI1=kxQ,lI1){constructor({message:A,cause:Q,argument:w}){super({name:qb1,message:A,cause:Q});this[cI1]=!0,this.argument=w}static isInstance(A){return mw.hasMarker(A,Fb1)}},Jb1="AI_InvalidPromptError",Ib1=`vercel.ai.error.${Jb1}`,OxQ=Symbol.for(Ib1),pI1,iI1,tG8=class extends(iI1=mw,pI1=OxQ,iI1){constructor({prompt:A,message:Q,cause:w}){super({name:Jb1,message:`Invalid prompt: ${Q}`,cause:w});this[pI1]=!0,this.prompt=A}static isInstance(A){return mw.hasMarker(A,Ib1)}},bb1="AI_InvalidResponseDataError",Lb1=`vercel.ai.error.${bb1}`,xxQ=Symbol.for(Lb1),dI1,nI1,eG8=class extends(nI1=mw,dI1=xxQ,nI1){constructor({data:A,message:Q=`Invalid response data: ${JSON.stringify(A)}.`}){super({name:bb1,message:Q});this[dI1]=!0,this.data=A}static isInstance(A){return mw.hasMarker(A,Lb1)}},Nb1="AI_JSONParseError",jb1=`vercel.ai.error.${Nb1}`,RxQ=Symbol.for(jb1),rI1,oI1,Vg0=class extends(oI1=mw,rI1=RxQ,oI1){constructor({text:A,cause:Q}){super({name:Nb1,message:`JSON parsing failed: Text: ${A}.
|
|
2419
2419
|
Error message: ${zb1(Q)}`,cause:Q});this[rI1]=!0,this.text=A}static isInstance(A){return mw.hasMarker(A,jb1)}},Mb1="AI_LoadAPIKeyError",_b1=`vercel.ai.error.${Mb1}`,hxQ=Symbol.for(_b1),sI1,aI1,Az8=class extends(aI1=mw,sI1=hxQ,aI1){constructor({message:A}){super({name:Mb1,message:A});this[sI1]=!0}static isInstance(A){return mw.hasMarker(A,_b1)}},Pb1="AI_LoadSettingError",kb1=`vercel.ai.error.${Pb1}`,vxQ=Symbol.for(kb1),tI1,eI1,Qz8=class extends(eI1=mw,tI1=vxQ,eI1){constructor({message:A}){super({name:Pb1,message:A});this[tI1]=!0}static isInstance(A){return mw.hasMarker(A,kb1)}},Ob1="AI_NoContentGeneratedError",xb1=`vercel.ai.error.${Ob1}`,CxQ=Symbol.for(xb1),Ab1,Qb1,wz8=class extends(Qb1=mw,Ab1=CxQ,Qb1){constructor({message:A="No content generated."}={}){super({name:Ob1,message:A});this[Ab1]=!0}static isInstance(A){return mw.hasMarker(A,xb1)}},Rb1="AI_NoSuchModelError",hb1=`vercel.ai.error.${Rb1}`,yxQ=Symbol.for(hb1),wb1,Bb1,Bz8=class extends(Bb1=mw,wb1=yxQ,Bb1){constructor({errorName:A=Rb1,modelId:Q,modelType:w,message:B=`No such ${w}: ${Q}`}){super({name:A,message:B});this[wb1]=!0,this.modelId=Q,this.modelType=w}static isInstance(A){return mw.hasMarker(A,hb1)}},vb1="AI_TooManyEmbeddingValuesForCallError",Cb1=`vercel.ai.error.${vb1}`,ExQ=Symbol.for(Cb1),$b1,Yb1,$z8=class extends(Yb1=mw,$b1=ExQ,Yb1){constructor(A){super({name:vb1,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[$b1]=!0,this.provider=A.provider,this.modelId=A.modelId,this.maxEmbeddingsPerCall=A.maxEmbeddingsPerCall,this.values=A.values}static isInstance(A){return mw.hasMarker(A,Cb1)}},yb1="AI_TypeValidationError",Eb1=`vercel.ai.error.${yb1}`,gxQ=Symbol.for(Eb1),Db1,Xb1,VG=class A extends(Xb1=mw,Db1=gxQ,Xb1){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:yb1,message:`${$}: Value: ${JSON.stringify(Q)}.
|
|
2420
2420
|
Error message: ${zb1(w)}`,cause:w});this[Db1]=!0,this.value=Q,this.context=B}static isInstance(Q){return mw.hasMarker(Q,Eb1)}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})}},gb1="AI_UnsupportedFunctionalityError",Tb1=`vercel.ai.error.${gb1}`,TxQ=Symbol.for(Tb1),Hb1,Wb1,Yz8=class extends(Wb1=mw,Hb1=TxQ,Wb1){constructor({functionality:A,message:Q=`'${A}' functionality not supported.`}){super({name:gb1,message:Q});this[Hb1]=!0,this.functionality=A}static isInstance(A){return mw.hasMarker(A,Tb1)}};F1();bU();bU();bU();var pb1="AI_DownloadError",ib1=`vercel.ai.error.${pb1}`,SxQ=Symbol.for(ib1),Sb1,mb1,oW=class extends(mb1=mw,Sb1=SxQ,mb1){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:pb1,message:$,cause:B});this[Sb1]=!0,this.url=A,this.statusCode=Q,this.statusText=w}static isInstance(A){return mw.hasMarker(A,ib1)}},jg0=2147483648;async function db1({response:A,url:Q,maxBytes:w=jg0}){let B=A.headers.get("content-length");if(B!=null){let f=parseInt(B,10);if(!isNaN(f)&&f>w)throw new oW({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 oW({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 Mg0(A){let Q;try{Q=new URL(A)}catch(B){throw new oW({url:A,message:`Invalid URL: ${A}`})}if(Q.protocol==="data:")return;if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw new oW({url:A,message:`URL scheme must be http, https, or data, got ${Q.protocol}`});let w=Q.hostname;if(!w)throw new oW({url:A,message:"URL must have a hostname"});if(w==="localhost"||w.endsWith(".local")||w.endsWith(".localhost"))throw new oW({url:A,message:`URL with hostname ${w} is not allowed`});if(w.startsWith("[")&&w.endsWith("]")){let B=w.slice(1,-1);if(mxQ(B))throw new oW({url:A,message:`URL with IPv6 address ${w} is not allowed`});return}if(nb1(w)){if(bg0(w))throw new oW({url:A,message:`URL with IP address ${w} is not allowed`});return}}function nb1(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 bg0(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 mxQ(A){let Q=A.toLowerCase();if(Q==="::1")return!0;if(Q==="::")return!0;if(Q.startsWith("::ffff:")){let w=Q.slice(7);if(nb1(w))return bg0(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 bg0(`${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 Vb1({argument:"separator",message:`The separator "${B}" must not be part of the alphabet "${w}".`});return()=>`${A}${B}${$()}`},rb1=h3();function _g0(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 ob1(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 uxQ(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 h50(A,...Q){let w=new Headers(uxQ(A)),B=w.get("user-agent")||"";return w.set("user-agent",[B,...Q].filter(Boolean).join(" ")),Object.fromEntries(w.entries())}var cxQ=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,lxQ=/"(?: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 ub1(A){let Q=JSON.parse(A);if(Q===null||typeof Q!=="object")return Q;if(cxQ.test(A)===!1&&lxQ.test(A)===!1)return Q;return pxQ(Q)}function pxQ(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 ixQ(A){let{stackTraceLimit:Q}=Error;try{Error.stackTraceLimit=0}catch(w){return ub1(A)}try{return ub1(A)}finally{Error.stackTraceLimit=Q}}function Pg0(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 Pg0(A)}var dxQ=Symbol("Let zodToJsonSchema decide on which parser to use"),cb1={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"},nxQ=(A)=>typeof A==="string"?{...cb1,name:A}:{...cb1,...A};function HH(){return{}}function rxQ(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 oxQ(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 sxQ(){return{type:"boolean"}}function sb1(A,Q){return lB(A.type._def,Q)}var axQ=(A,Q)=>{return lB(A.innerType._def,Q)};function ab1(A,Q,w){let B=w!=null?w:Q.dateStrategy;if(Array.isArray(B))return{anyOf:B.map(($,Y)=>ab1(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 txQ(A)}}var txQ=(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 exQ(A,Q){return{...lB(A.innerType._def,Q),default:A.defaultValue()}}function ARQ(A,Q){return Q.effectStrategy==="input"?lB(A.schema._def,Q):HH()}function QRQ(A){return{type:"string",enum:Array.from(A.values)}}var wRQ=(A)=>{if("type"in A&&A.type==="string")return!1;return"allOf"in A};function BRQ(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(wRQ($))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 $RQ(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 Jg0=void 0,aZ={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(Jg0===void 0)Jg0=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Jg0},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 tb1(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":tZ(w,"email",B.message,Q);break;case"format:idn-email":tZ(w,"idn-email",B.message,Q);break;case"pattern:zod":_Y(w,aZ.email,B.message,Q);break}break;case"url":tZ(w,"uri",B.message,Q);break;case"uuid":tZ(w,"uuid",B.message,Q);break;case"regex":_Y(w,B.regex,B.message,Q);break;case"cuid":_Y(w,aZ.cuid,B.message,Q);break;case"cuid2":_Y(w,aZ.cuid2,B.message,Q);break;case"startsWith":_Y(w,RegExp(`^${Ig0(B.value,Q)}`),B.message,Q);break;case"endsWith":_Y(w,RegExp(`${Ig0(B.value,Q)}$`),B.message,Q);break;case"datetime":tZ(w,"date-time",B.message,Q);break;case"date":tZ(w,"date",B.message,Q);break;case"time":tZ(w,"time",B.message,Q);break;case"duration":tZ(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":{_Y(w,RegExp(Ig0(B.value,Q)),B.message,Q);break}case"ip":{if(B.version!=="v6")tZ(w,"ipv4",B.message,Q);if(B.version!=="v4")tZ(w,"ipv6",B.message,Q);break}case"base64url":_Y(w,aZ.base64url,B.message,Q);break;case"jwt":_Y(w,aZ.jwt,B.message,Q);break;case"cidr":{if(B.version!=="v6")_Y(w,aZ.ipv4Cidr,B.message,Q);if(B.version!=="v4")_Y(w,aZ.ipv6Cidr,B.message,Q);break}case"emoji":_Y(w,aZ.emoji(),B.message,Q);break;case"ulid":{_Y(w,aZ.ulid,B.message,Q);break}case"base64":{switch(Q.base64Strategy){case"format:binary":{tZ(w,"binary",B.message,Q);break}case"contentEncoding:base64":{w.contentEncoding="base64";break}case"pattern:zod":{_Y(w,aZ.base64,B.message,Q);break}}break}case"nanoid":_Y(w,aZ.nanoid,B.message,Q);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return w}function Ig0(A,Q){return Q.patternStrategy==="escape"?DRQ(A):A}var YRQ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function DRQ(A){let Q="";for(let w=0;w<A.length;w++){if(!YRQ.has(A[w]))Q+="\\";Q+=A[w]}return Q}function tZ(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 _Y(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:lb1(Q,B),...w&&B.errorMessages&&{errorMessage:{pattern:w}}})}else A.pattern=lb1(Q,B)}function lb1(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: ${zb1(w)}`,cause:w});this[Db1]=!0,this.value=Q,this.context=B}sta
|
|
|
2425
2425
|
|
|
2426
2426
|
`)},flush(A){A.enqueue(`data: [DONE]
|
|
2427
2427
|
|
|
2428
|
-
`)}})}},NvQ={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function UL1({status:A,statusText:Q,headers:w,stream:B,consumeSseStream:$}){let Y=B.pipeThrough(new LvQ);if($){let[D,X]=Y.tee();Y=D,$({stream:X})}return new Response(Y.pipeThrough(new TextEncoderStream),{status:A,statusText:Q,headers:bvQ(w,NvQ)})}var fd=z.record(z.string(),q_.optional()),rz8=v50(()=>Wd(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:fd.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:fd.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:fd.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:fd.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:fd.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 Og0(A){return A.type.startsWith("tool-")}function MvQ(A){return A.type==="dynamic-tool"}function AL1(A){return Og0(A)||MvQ(A)}function QL1(A){return A.type.split("-").slice(1).join("-")}function _vQ({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 PvQ({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 L(j){let E=W.message.parts.filter(AL1).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 b(j){var g;let E=W.message.parts.find((T)=>Og0(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?KL1(W.message.metadata,j):j;if(Q!=null)await E50({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(Og0);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 b({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 Zd(j.text);if(j.dynamic)N({toolCallId:X.toolCallId,toolName:j.toolName,state:"input-streaming",input:g,title:j.title,toolMetadata:j.toolMetadata});else b({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 b({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(AL1).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 b({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=L(X.toolCallId);j.state="approval-requested",j.approval={id:X.approvalId},f();break}case"tool-output-denied":{let j=L(X.toolCallId);j.state="output-denied",f();break}case"tool-output-available":{let j=L(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 b({toolCallId:X.toolCallId,toolName:QL1(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=L(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 b({toolCallId:X.toolCallId,toolName:QL1(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 E50({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 kvQ({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,L){if(V.type==="start"){let b=V;if(b.messageId==null&&A!=null)b.messageId=A}if(V.type==="abort")X=!0;L.enqueue(V)}}));if(B==null&&w==null)return H;let W=_vQ({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(L){$(L)}};return PvQ({stream:H,runUpdateMessageJob:f,onError:$}).pipeThrough(new TransformStream({async transform(V,L){if(V.type==="finish-step")await F();L.enqueue(V)},async cancel(){await G()},async flush(){await G()}}))}var oz8=h3({prefix:"aitxt",size:24});function GL1({execute:A,onError:Q=_g0,originalMessages:w,onStepFinish:B,onFinish:$,generateId:Y=rb1}){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:L}=await F.read();if(V)break;W(L)}})().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){}}),kvQ({stream:H,messageId:Y(),originalMessages:w,onStepFinish:B,onFinish:$,onError:Q})}var kD=z.record(z.string(),q_.optional()),ez8=v50(()=>Wd(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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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 Qq8=h3({prefix:"aiobj",size:24});function zL1(A){return({url:Q,abortSignal:w})=>BvQ({url:Q,maxBytes:A==null?void 0:A.maxBytes,abortSignal:w})}var Bq8=h3({prefix:"aiobj",size:24});var $q8=zL1();var OvQ="AI_NoSuchProviderError",xvQ=`vercel.ai.error.${OvQ}`,RvQ=Symbol.for(xvQ),hvQ;hvQ=RvQ;var Yq8=zL1();var qL1={name:"@brains/web-chat",private:!0,version:"0.2.0-alpha.138",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/contracts":"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 FL1(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 JL1({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=fq("document",Y.content);if(!D)return new Response("Document content is not a PDF",{status:415});let X=Zq(Y.metadata,$,"document",D.mimeType);return IL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function VL1(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 JL1({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=fq("image",Y.content);if(!D)return new Response("Image content is not an image",{status:415});let X=Zq(Y.metadata,$,"image",D.mimeType);return IL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function JL1(A){let Q={entityType:A.entityType,id:A.id},w=await Kq({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 IL1(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 Kd="upload",bL1=tO;var CvQ={namespace:"upload",refKind:Kd,routePath:"/api/chat/uploads"};function g50(){return CvQ}c0();FG0();var LL1=f00;var NL1=Z00;var yvQ="file",EvQ=16384;async function jL1(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>NL1+EvQ)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(yvQ);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 ML1(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 kL1(w,Q.getUploadStore());if(B instanceof Response)return B;let{record:$,content:Y}=B,D=OL1($,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 _L1(A){let Q=Gq(A.filename??LL1),w=TvQ(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 xL1(B,w.buffer)}async function PL1(A,Q){let w=await kL1(A,Q);if(w instanceof Response)return w;let{record:B,content:$}=w,Y=OL1(B,$);if(Y instanceof Response)return Y;return xL1(Y,$,{kind:Kd,id:A})}async function kL1(A,Q){try{return await Q.read(A)}catch(w){if(w instanceof qU)return gvQ(w);throw w}}function OL1(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 xL1(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 gvQ(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 TvQ(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 SvQ=K.object({type:K.literal("text"),text:K.string()}),mvQ=K.object({type:K.literal("file"),mediaType:K.string().optional(),filename:K.string().optional(),url:K.string()}),uvQ=K.object({state:K.literal("approval-responded"),approval:K.object({id:K.string(),approved:K.boolean()})}).passthrough(),cvQ=K.object({id:K.string().optional(),role:K.string(),parts:K.array(K.unknown()).optional(),content:K.string().optional()}),RL1=K.object({id:K.string().optional(),messages:K.array(cvQ).min(1),trigger:K.string().optional()}),lvQ=K.object({kind:K.literal(Kd),id:K.string().regex(bL1)}),pvQ=K.object({type:K.literal("data-upload"),data:K.object({ref:lvQ})});async function hL1(A,Q){let w=ivQ(A);if(!w)return{message:"",attachments:[]};let B=[],$=[];for(let D of w.parts??[]){let X=SvQ.safeParse(D);if(X.success){if(X.data.text.length>0)B.push(X.data.text);continue}let H=mvQ.safeParse(D);if(H.success){let f=_L1(H.data);if(f instanceof Response)return f;$.push(f);continue}let W=pvQ.safeParse(D);if(W.success){let f=await PL1(W.data.data.ref.id,Q.uploadStore);if(f instanceof Response)return f;$.push(f);continue}if(dvQ(D)==="data-upload")return new Response("Invalid upload ref",{status:400})}return{message:B.length>0?B.join(`
|
|
2428
|
+
`)}})}},NvQ={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function UL1({status:A,statusText:Q,headers:w,stream:B,consumeSseStream:$}){let Y=B.pipeThrough(new LvQ);if($){let[D,X]=Y.tee();Y=D,$({stream:X})}return new Response(Y.pipeThrough(new TextEncoderStream),{status:A,statusText:Q,headers:bvQ(w,NvQ)})}var fd=z.record(z.string(),q_.optional()),rz8=v50(()=>Wd(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:fd.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:fd.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:fd.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:fd.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:fd.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 Og0(A){return A.type.startsWith("tool-")}function MvQ(A){return A.type==="dynamic-tool"}function AL1(A){return Og0(A)||MvQ(A)}function QL1(A){return A.type.split("-").slice(1).join("-")}function _vQ({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 PvQ({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 L(j){let E=W.message.parts.filter(AL1).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 b(j){var g;let E=W.message.parts.find((T)=>Og0(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?KL1(W.message.metadata,j):j;if(Q!=null)await E50({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(Og0);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 b({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 Zd(j.text);if(j.dynamic)N({toolCallId:X.toolCallId,toolName:j.toolName,state:"input-streaming",input:g,title:j.title,toolMetadata:j.toolMetadata});else b({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 b({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(AL1).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 b({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=L(X.toolCallId);j.state="approval-requested",j.approval={id:X.approvalId},f();break}case"tool-output-denied":{let j=L(X.toolCallId);j.state="output-denied",f();break}case"tool-output-available":{let j=L(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 b({toolCallId:X.toolCallId,toolName:QL1(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=L(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 b({toolCallId:X.toolCallId,toolName:QL1(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 E50({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 kvQ({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,L){if(V.type==="start"){let b=V;if(b.messageId==null&&A!=null)b.messageId=A}if(V.type==="abort")X=!0;L.enqueue(V)}}));if(B==null&&w==null)return H;let W=_vQ({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(L){$(L)}};return PvQ({stream:H,runUpdateMessageJob:f,onError:$}).pipeThrough(new TransformStream({async transform(V,L){if(V.type==="finish-step")await F();L.enqueue(V)},async cancel(){await G()},async flush(){await G()}}))}var oz8=h3({prefix:"aitxt",size:24});function GL1({execute:A,onError:Q=_g0,originalMessages:w,onStepFinish:B,onFinish:$,generateId:Y=rb1}){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:L}=await F.read();if(V)break;W(L)}})().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){}}),kvQ({stream:H,messageId:Y(),originalMessages:w,onStepFinish:B,onFinish:$,onError:Q})}var kD=z.record(z.string(),q_.optional()),ez8=v50(()=>Wd(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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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:kD.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 Qq8=h3({prefix:"aiobj",size:24});function zL1(A){return({url:Q,abortSignal:w})=>BvQ({url:Q,maxBytes:A==null?void 0:A.maxBytes,abortSignal:w})}var Bq8=h3({prefix:"aiobj",size:24});var $q8=zL1();var OvQ="AI_NoSuchProviderError",xvQ=`vercel.ai.error.${OvQ}`,RvQ=Symbol.for(xvQ),hvQ;hvQ=RvQ;var Yq8=zL1();var qL1={name:"@brains/web-chat",private:!0,version:"0.2.0-alpha.139",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/contracts":"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 FL1(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 JL1({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=fq("document",Y.content);if(!D)return new Response("Document content is not a PDF",{status:415});let X=Zq(Y.metadata,$,"document",D.mimeType);return IL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function VL1(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 JL1({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=fq("image",Y.content);if(!D)return new Response("Image content is not an image",{status:415});let X=Zq(Y.metadata,$,"image",D.mimeType);return IL1({requestUrl:B,data:D.data,mediaType:D.mimeType,filename:X})}async function JL1(A){let Q={entityType:A.entityType,id:A.id},w=await Kq({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 IL1(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 Kd="upload",bL1=tO;var CvQ={namespace:"upload",refKind:Kd,routePath:"/api/chat/uploads"};function g50(){return CvQ}c0();FG0();var LL1=f00;var NL1=Z00;var yvQ="file",EvQ=16384;async function jL1(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>NL1+EvQ)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(yvQ);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 ML1(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 kL1(w,Q.getUploadStore());if(B instanceof Response)return B;let{record:$,content:Y}=B,D=OL1($,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 _L1(A){let Q=Gq(A.filename??LL1),w=TvQ(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 xL1(B,w.buffer)}async function PL1(A,Q){let w=await kL1(A,Q);if(w instanceof Response)return w;let{record:B,content:$}=w,Y=OL1(B,$);if(Y instanceof Response)return Y;return xL1(Y,$,{kind:Kd,id:A})}async function kL1(A,Q){try{return await Q.read(A)}catch(w){if(w instanceof qU)return gvQ(w);throw w}}function OL1(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 xL1(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 gvQ(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 TvQ(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 SvQ=K.object({type:K.literal("text"),text:K.string()}),mvQ=K.object({type:K.literal("file"),mediaType:K.string().optional(),filename:K.string().optional(),url:K.string()}),uvQ=K.object({state:K.literal("approval-responded"),approval:K.object({id:K.string(),approved:K.boolean()})}).passthrough(),cvQ=K.object({id:K.string().optional(),role:K.string(),parts:K.array(K.unknown()).optional(),content:K.string().optional()}),RL1=K.object({id:K.string().optional(),messages:K.array(cvQ).min(1),trigger:K.string().optional()}),lvQ=K.object({kind:K.literal(Kd),id:K.string().regex(bL1)}),pvQ=K.object({type:K.literal("data-upload"),data:K.object({ref:lvQ})});async function hL1(A,Q){let w=ivQ(A);if(!w)return{message:"",attachments:[]};let B=[],$=[];for(let D of w.parts??[]){let X=SvQ.safeParse(D);if(X.success){if(X.data.text.length>0)B.push(X.data.text);continue}let H=mvQ.safeParse(D);if(H.success){let f=_L1(H.data);if(f instanceof Response)return f;$.push(f);continue}let W=pvQ.safeParse(D);if(W.success){let f=await PL1(W.data.data.ref.id,Q.uploadStore);if(f instanceof Response)return f;$.push(f);continue}if(dvQ(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 vL1(A){let Q=A.messages.at(-1);if(!Q||Q.role==="user")return[];return(Q.parts??[]).map((w)=>uvQ.safeParse(w)).filter((w)=>w.success).map((w)=>w.data.approval)}function ivQ(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 dvQ(A){if(typeof A!=="object"||A===null||!("type"in A))return;let Q=A.type;return typeof Q==="string"?Q:void 0}c0();var nvQ=/\n{0,2}\[Entities affected this turn: [\s\S]*? Reference these IDs directly in follow-ups instead of searching for them\.\]\s*$/;function T50(A){return A.replace(nvQ,"").trimEnd()}c0();function CL1(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 xg0(A,Q,w=new Set){for(let B of Q){if(B.kind==="attachment"&&w.has(B.id))continue;let $=F00(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((b)=>b.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",L=(G?.message?.parts??[]).filter((b)=>b.kind==="text"&&typeof b.text==="string").map((b)=>b.text).join(`
|
|
4729
|
-
`)||"No response text";return{success:!0,data:{state:F,response:L}}}Y=await WN1(w,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class Ud extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A;this.name="A2ARequestTimeoutError"}}class Gd extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A;this.name="A2AStreamIdleTimeoutError"}}async function ICQ(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 Ud(B))},B)})])}catch(D){if(D instanceof Ud)throw D;if($.signal.aborted)throw new Ud(B);throw D}finally{if(Y)clearTimeout(Y)}}async function WN1(A,Q){let w;try{return await Promise.race([A.read(),new Promise((B,$)=>{w=setTimeout(()=>$(new Gd(Q)),Q)})])}catch(B){if(B instanceof Gd)A.cancel().catch(()=>{});throw B}finally{if(w)clearTimeout(w)}}function bCQ(A){if(A instanceof Ud||A instanceof Gd)return!0;return A instanceof Error}function LCQ(A,Q){let w=Q>1?` after ${Q} attempts`:"";if(A instanceof Gd)return`${A.message}${w}`;let B=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${w}: ${B}`}function ZN1(A={}){let Q=A.fetch??globalThis.fetch,w={requestTimeoutMs:A.requestTimeoutMs??GCQ,streamIdleTimeoutMs:A.streamIdleTimeoutMs??zCQ,maxNetworkAttempts:A.maxNetworkAttempts??qCQ};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:DN1,visibility:"trusted",sideEffects:"external",handler:async(B)=>{let $=K.object(DN1).safeParse(B);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};let{agent:Y,message:D}=$.data,X=FCQ(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(!VCQ(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}`,L=await XN1(V,Q);if(!L)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 b=await HN1(L.url,D,Q,void 0,w);if("success"in b&&b.success===!0){let N=typeof b.data==="object"&&b.data!==null?b.data:{};return{...b,data:{...N,agentCall:{mode:"one-shot",agent:H},agentContactCandidate:{source:{kind:"url",url:X.sourceUrl??H}}}}}return b}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 XN1(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 HN1(G,D,Q,F,w)}}}var Tg0={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.138",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 zU{agentCard;taskManager=new Eg0;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",Tg0,A,tL1)}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)=>jX.safeParse(X.metadata)).filter((X)=>X.success).map((X)=>X.data)}catch{}this.agentCard=eL1({character:Q,profile:w,version:Tg0.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=wN1.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=$N1.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}=YN1(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 BN1(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[ZN1({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 Sg0{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 OM1=X1(_M1(),1);import{extname as LSQ}from"path";var Y$0=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function I_(A){let Q=LSQ(A).toLowerCase();return Y$0.includes(Q)}function PM1(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 TT0(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as NSQ,relative as jSQ,sep as kM1,join as MSQ}from"path";function sW(A,Q){return NSQ(Q)?Q:MSQ(A,Q)}function nC(A,Q){let w=sW(A,Q),B=jSQ(A,w);return kM1==="/"?B:B.split(kM1).join("/")}function _SQ(A,Q){if(!nC(Q,A).startsWith("image/"))return!1;return I_(A)}function PSQ(A,Q){if(nC(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return _SQ(A,Q)}class ST0{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=OM1.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(!PSQ(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=sW(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 xM1(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return kSQ(Q)}function RM1(A){if(A)A.stop();return}function hM1(A,Q){if(A)A.setCallback(Q)}async function kSQ(A){let{logger:Q,syncPath:w,watchInterval:B,importEntities:$,jobQueueCallback:Y,fileOperations:D,deleteOnFileRemoval:X}=A,H=new Sg0(Q,$,Y,D,X),W=new ST0({syncPath:w,watchInterval:B,logger:Q,onFileChange:async(f,Z)=>{await H.handleFileChange(f,Z)}});return await W.start(),W}async function vM1(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 mT0{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 uT0{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new mT0({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 cT0{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 CSQ,dirname as ySQ,extname as ESQ}from"path";import{extname as OSQ}from"path";var D$0=[".pdf"],CM1=".meta.json";function b_(A){let Q=OSQ(A).toLowerCase();return D$0.includes(Q)}function yM1(A){return A.toLowerCase().endsWith(CM1)}function lT0(A){return`${A}${CM1}`}function EM1(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as xSQ,join as X$0}from"path";function H$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]=gM1(X);D=Y.join(":")}else D=gM1(Y[0]??"");return{entityType:$,id:D}}function TM1(A,Q,w,B=".md"){let $=Q.split(":").filter((W)=>W.length>0),Y=w==="note";if($.length===1)return Y?X$0(A,`${$[0]}${B}`):X$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 X$0(A,...H,`${X}${B}`);return X$0(A,w,...H,`${X}${B}`)}function SM1(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return TT0(Q);let w=A.content.match(/^data:image\/([a-z+]+);base64,/i);return w?.[1]?TT0(w[1]):".md"}function gM1(A){let Q=xSQ(A).toLowerCase();return Q===".md"||Y$0.includes(Q)||D$0.includes(Q)?A.slice(0,-Q.length):A}bX();import{mkdir as gSQ,readFile as rC,writeFile as iT0,stat as TSQ,utimes as SSQ}from"fs/promises";import{join as W$0}from"path";import{mkdir as mM1,readdir as hSQ,stat as vSQ}from"fs/promises";import{access as RSQ}from"fs/promises";async function y5(A){try{return await RSQ(A),!0}catch{return!1}}async function pT0(A,Q){return pM1(A,Q,{includeDocuments:!1,includeImages:!1})}async function uM1(A,Q){return pM1(A,Q,{includeDocuments:!0,includeImages:!0})}async function cM1(A,Q){if(!await y5(A))await mM1(A,{recursive:!0});for(let w of Q)if(w!=="note")await mM1(W$0(A,w),{recursive:!0})}async function lM1(A,Q){let w=[],B={totalFiles:0,byEntityType:{}};if(!await y5(A))return{files:w,stats:B};let $=await pT0(A,Q);for(let Y of $)try{let D=W$0(A,Y),X=await vSQ(D),{entityType:H}=H$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 pM1(A,Q,w){let B=[];if(!await y5(A))return B;let $=async(Y,D="",X=!1,H=!1)=>{let W=await hSQ(Y,{withFileTypes:!0});for(let f of W){let Z=D?W$0(D,f.name):f.name;if(f.isFile()&&!f.name.endsWith(".invalid")&&!yM1(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=W$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 mSQ(A){return typeof A==="object"&&A!==null}class dT0{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return H$0(this.syncPath,A)}async readEntity(A){let Q=sW(this.syncPath,A),w=await TSQ(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=ESQ(A);if(X=`data:${b_(A)?EM1(G):PM1(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:CSQ(Q)},B=lT0(A);if(!await y5(B))return w;try{let $=await rC(B,"utf-8"),Y=JSON.parse($),D=mSQ(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 iT0(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 iT0(Q,Y,"utf-8")}let $=new Date(A.updated);await SSQ(Q,$,$)}async ensureEntityDirectory(A,Q){if(A.entityType!=="note")await gSQ(ySQ(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 $=lT0(Q),Y=`${JSON.stringify(B,null,2)}
|
|
4729
|
+
`)||"No response text";return{success:!0,data:{state:F,response:L}}}Y=await WN1(w,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class Ud extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A;this.name="A2ARequestTimeoutError"}}class Gd extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A;this.name="A2AStreamIdleTimeoutError"}}async function ICQ(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 Ud(B))},B)})])}catch(D){if(D instanceof Ud)throw D;if($.signal.aborted)throw new Ud(B);throw D}finally{if(Y)clearTimeout(Y)}}async function WN1(A,Q){let w;try{return await Promise.race([A.read(),new Promise((B,$)=>{w=setTimeout(()=>$(new Gd(Q)),Q)})])}catch(B){if(B instanceof Gd)A.cancel().catch(()=>{});throw B}finally{if(w)clearTimeout(w)}}function bCQ(A){if(A instanceof Ud||A instanceof Gd)return!0;return A instanceof Error}function LCQ(A,Q){let w=Q>1?` after ${Q} attempts`:"";if(A instanceof Gd)return`${A.message}${w}`;let B=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${w}: ${B}`}function ZN1(A={}){let Q=A.fetch??globalThis.fetch,w={requestTimeoutMs:A.requestTimeoutMs??GCQ,streamIdleTimeoutMs:A.streamIdleTimeoutMs??zCQ,maxNetworkAttempts:A.maxNetworkAttempts??qCQ};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:DN1,visibility:"trusted",sideEffects:"external",handler:async(B)=>{let $=K.object(DN1).safeParse(B);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};let{agent:Y,message:D}=$.data,X=FCQ(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(!VCQ(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}`,L=await XN1(V,Q);if(!L)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 b=await HN1(L.url,D,Q,void 0,w);if("success"in b&&b.success===!0){let N=typeof b.data==="object"&&b.data!==null?b.data:{};return{...b,data:{...N,agentCall:{mode:"one-shot",agent:H},agentContactCandidate:{source:{kind:"url",url:X.sourceUrl??H}}}}}return b}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 XN1(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 HN1(G,D,Q,F,w)}}}var Tg0={name:"@brains/a2a",private:!0,version:"0.2.0-alpha.139",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 zU{agentCard;taskManager=new Eg0;agentService;permissionContext;app;hasWebserver=!1;constructor(A={}){super("a2a",Tg0,A,tL1)}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)=>jX.safeParse(X.metadata)).filter((X)=>X.success).map((X)=>X.data)}catch{}this.agentCard=eL1({character:Q,profile:w,version:Tg0.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=wN1.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=$N1.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}=YN1(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 BN1(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[ZN1({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 Sg0{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 OM1=X1(_M1(),1);import{extname as LSQ}from"path";var Y$0=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function I_(A){let Q=LSQ(A).toLowerCase();return Y$0.includes(Q)}function PM1(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 TT0(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as NSQ,relative as jSQ,sep as kM1,join as MSQ}from"path";function sW(A,Q){return NSQ(Q)?Q:MSQ(A,Q)}function nC(A,Q){let w=sW(A,Q),B=jSQ(A,w);return kM1==="/"?B:B.split(kM1).join("/")}function _SQ(A,Q){if(!nC(Q,A).startsWith("image/"))return!1;return I_(A)}function PSQ(A,Q){if(nC(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return _SQ(A,Q)}class ST0{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=OM1.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(!PSQ(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=sW(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 xM1(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return kSQ(Q)}function RM1(A){if(A)A.stop();return}function hM1(A,Q){if(A)A.setCallback(Q)}async function kSQ(A){let{logger:Q,syncPath:w,watchInterval:B,importEntities:$,jobQueueCallback:Y,fileOperations:D,deleteOnFileRemoval:X}=A,H=new Sg0(Q,$,Y,D,X),W=new ST0({syncPath:w,watchInterval:B,logger:Q,onFileChange:async(f,Z)=>{await H.handleFileChange(f,Z)}});return await W.start(),W}async function vM1(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 mT0{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 uT0{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new mT0({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 cT0{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 CSQ,dirname as ySQ,extname as ESQ}from"path";import{extname as OSQ}from"path";var D$0=[".pdf"],CM1=".meta.json";function b_(A){let Q=OSQ(A).toLowerCase();return D$0.includes(Q)}function yM1(A){return A.toLowerCase().endsWith(CM1)}function lT0(A){return`${A}${CM1}`}function EM1(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as xSQ,join as X$0}from"path";function H$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]=gM1(X);D=Y.join(":")}else D=gM1(Y[0]??"");return{entityType:$,id:D}}function TM1(A,Q,w,B=".md"){let $=Q.split(":").filter((W)=>W.length>0),Y=w==="note";if($.length===1)return Y?X$0(A,`${$[0]}${B}`):X$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 X$0(A,...H,`${X}${B}`);return X$0(A,w,...H,`${X}${B}`)}function SM1(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return TT0(Q);let w=A.content.match(/^data:image\/([a-z+]+);base64,/i);return w?.[1]?TT0(w[1]):".md"}function gM1(A){let Q=xSQ(A).toLowerCase();return Q===".md"||Y$0.includes(Q)||D$0.includes(Q)?A.slice(0,-Q.length):A}bX();import{mkdir as gSQ,readFile as rC,writeFile as iT0,stat as TSQ,utimes as SSQ}from"fs/promises";import{join as W$0}from"path";import{mkdir as mM1,readdir as hSQ,stat as vSQ}from"fs/promises";import{access as RSQ}from"fs/promises";async function y5(A){try{return await RSQ(A),!0}catch{return!1}}async function pT0(A,Q){return pM1(A,Q,{includeDocuments:!1,includeImages:!1})}async function uM1(A,Q){return pM1(A,Q,{includeDocuments:!0,includeImages:!0})}async function cM1(A,Q){if(!await y5(A))await mM1(A,{recursive:!0});for(let w of Q)if(w!=="note")await mM1(W$0(A,w),{recursive:!0})}async function lM1(A,Q){let w=[],B={totalFiles:0,byEntityType:{}};if(!await y5(A))return{files:w,stats:B};let $=await pT0(A,Q);for(let Y of $)try{let D=W$0(A,Y),X=await vSQ(D),{entityType:H}=H$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 pM1(A,Q,w){let B=[];if(!await y5(A))return B;let $=async(Y,D="",X=!1,H=!1)=>{let W=await hSQ(Y,{withFileTypes:!0});for(let f of W){let Z=D?W$0(D,f.name):f.name;if(f.isFile()&&!f.name.endsWith(".invalid")&&!yM1(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=W$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 mSQ(A){return typeof A==="object"&&A!==null}class dT0{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return H$0(this.syncPath,A)}async readEntity(A){let Q=sW(this.syncPath,A),w=await TSQ(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=ESQ(A);if(X=`data:${b_(A)?EM1(G):PM1(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:CSQ(Q)},B=lT0(A);if(!await y5(B))return w;try{let $=await rC(B,"utf-8"),Y=JSON.parse($),D=mSQ(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 iT0(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 iT0(Q,Y,"utf-8")}let $=new Date(A.updated);await SSQ(Q,$,$)}async ensureEntityDirectory(A,Q){if(A.entityType!=="note")await gSQ(ySQ(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 $=lT0(Q),Y=`${JSON.stringify(B,null,2)}
|
|
4730
4730
|
`;if(await y5($)){if(await rC($,"utf-8")===Y)return}await this.ensureEntityDirectory(A,$),await iT0($,Y,"utf-8")}getFilePath(A,Q,w=".md"){return TM1(this.syncPath,A,Q,w)}getEntityFilePath(A){return this.getFilePath(A.id,A.entityType,SM1(A))}async getAllMarkdownFiles(){return pT0(this.syncPath,this.entityService)}async getAllSyncFiles(){return uM1(this.syncPath,this.entityService)}async ensureDirectoryStructure(A){await cM1(this.syncPath,A)}shouldUpdateEntity(A,Q){let w=xw(Q.content);return A.contentHash!==w}async gatherFileStatus(){return lM1(this.syncPath,this.entityService)}async syncDirectoryExists(){return y5(this.syncPath)}async fileExists(A){return y5(A)}}H4();Z0();H4();async function f$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 iM1=K.object({title:K.string(),slug:K.string().optional(),coverImageUrl:K.string().url(),coverImageId:K.string().optional(),coverImageAlt:K.string().optional()});class nT0{entityService;fetcher;logger;constructor(A,Q,w=NW){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=iM1.safeParse(w);if(!B.success)return null;if(B.data.coverImageId)return null;let{title:$,slug:Y,coverImageUrl:D,coverImageAlt:X}=B.data;if(!oz(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=iM1.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(!oz(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:dz(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 f$0({id:`${w}-cover`,title:Y,alt:$??Y,sourceUrl:B},this.entityService,this.fetcher,this.logger)}}H4();Z0();class kd{entityService;fetcher;logger;constructor(A,Q,w=NW){this.entityService=A;this.fetcher=w;this.logger=Q.child("MarkdownImageConverter")}detectInlineImages(A,Q){let w=[],B=lb0(A);for(let $ of B){if(!oz($.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``;return``}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=``;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 f$0({id:`${$}-inline-${Q}`,title:B||`Inline image ${Q+1} for ${$}`,alt:B||"",sourceUrl:w},this.entityService,this.fetcher,this.logger)}}class rT0{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 uSQ,appendFile as cSQ,readFile as lSQ,writeFile as pSQ,access as iSQ}from"fs/promises";import{join as dM1}from"path";class oT0{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 uSQ($,Y),w.quarantined++,w.quarantinedFiles.push(A);let D=dM1(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 g$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:oS0,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 T$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:rS0,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 S$0 extends _w{directorySync;context;constructor(A,Q,w){super(A,{schema:dS0,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 m$0 extends _w{context;directorySync;gitSync;constructor(A,Q,w,B){super(A,{schema:nS0,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`}),mlQ(B)}summarizeDataForLog(A){return{source:A.source,interfaceType:A.interfaceType,channelId:A.channelId}}}function mlQ(A){return{gitPulled:!0,batchQueued:!0,batchId:A.batchId,importOperations:A.importOperationsCount,totalFiles:A.totalFiles}}c0();class u$0 extends _w{context;constructor(A,Q,w){super(A,{schema:y$0,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,w){let B=y$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 ulQ=K.object({});class c$0 extends _w{directorySync;constructor(A,Q){super(A,{schema:ulQ,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();H4();Z0();CB();H4();import{readFile as clQ,writeFile as llQ}from"fs/promises";var plQ=sS0;class l$0 extends _w{context;fetcher;constructor(A,Q,w=NW){super(Q,{schema:plQ,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 clQ(B,"utf-8")}catch(L){return this.logger.error("Failed to read file",{filePath:B,error:vA(L)}),x6.failure(L)}let W;try{W=lw(H)}catch(L){return this.logger.warn("Failed to parse markdown",{filePath:B,error:vA(L)}),x6.failure(L)}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 L;try{L=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:b}=WJ(L),N=Hj(b),_=fJ(b);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:L,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=dz(F,W.content);try{await llQ(B,V,"utf-8")}catch(L){return this.logger.error("Failed to write file",{filePath:B,error:vA(L)}),x6.failure(L)}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();H4();Z0();CB();import{readFile as ilQ,writeFile as dlQ}from"fs/promises";class p$0 extends _w{converter;constructor(A,Q,w=NW){super(Q,{schema:aS0,jobTypeName:"inline-image-convert"});this.converter=new kd(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 ilQ(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 dlQ(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 jO1(A,Q,w){let B=($)=>w.child($);A.jobs.registerHandler("directory-sync",new S$0(B("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new g$0(B("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new T$0(B("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new u$0(B("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new c$0(B("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new l$0(A,B("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new p$0(A,B("InlineImageConversionJobHandler"))),w.debug("Registered async job handlers")}c0();import{unlink as nlQ,access as rlQ}from"fs/promises";function MO1(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 rlQ(W).then(()=>!0,()=>!1))await nlQ(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 _O1(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 OO1,mkdir as slQ,copyFile as alQ}from"fs/promises";import{join as kO1,resolve as tS0}from"path";import{join as olQ}from"path";async function PO1(A){if(!await y5(olQ(A,".git")))return!1;try{return await QK(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function tlQ(A,Q){if(!await y5(A))return!0;if((await OO1(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await PO1(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function xO1(A,Q){let w=await OO1(A,{withFileTypes:!0});for(let B of w){let $=kO1(A,B.name),Y=kO1(Q,B.name);if(B.isDirectory()){if(!await y5(Y))await slQ(Y,{recursive:!0});await xO1($,Y)}else await alQ($,Y)}}async function RO1(A,Q,w){let B=tS0(process.cwd(),A);w=w?tS0(w):tS0(process.cwd(),"seed-content");let $=await tlQ(B,Q);if($&&await y5(w))Q.debug("Copying seed content to brain-data directory"),await xO1(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 hO1(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 RO1(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 vO1(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 CO1(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 EO1}from"child_process";import{cpSync as elQ,existsSync as yO1,mkdirSync as ApQ,mkdtempSync as QpQ,rmSync as wpQ}from"fs";import{tmpdir as BpQ}from"os";import{fileURLToPath as $pQ}from"url";import{join as YpQ,resolve as DpQ}from"path";function sI(A,Q){let w=EO1("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 XpQ(A){return A.startsWith("file://")}function HpQ(A){return $pQ(A)}function WpQ(A,Q){return EO1("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function gO1(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!XpQ(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",w=HpQ(A.gitUrl),B=DpQ(A.seedContentPath);if(!yO1(B))throw Error(`Seed content path not found: ${B}`);if(!yO1(w))A.logger.debug("Creating local bare content remote",{remotePath:w,branch:Q}),ApQ(w,{recursive:!0}),sI(process.cwd(),["init","--bare",`--initial-branch=${Q}`,w]);if(WpQ(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 $=QpQ(YpQ(BpQ(),"directory-sync-seed-"));try{sI($,["init",`--initial-branch=${Q}`]),sI($,["config","user.name",A.authorName??"Brain"]),sI($,["config","user.email",A.authorEmail??"brain@localhost"]),elQ(B,$,{recursive:!0}),sI($,["add","."]),sI($,["commit","-m","seed content remote"]),sI($,["remote","add","origin",A.gitUrl]),sI($,["push","-u","origin",Q])}finally{wpQ($,{recursive:!0,force:!0})}}function TO1(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 SO1(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 mO1(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(SO1(w,B));return $}var uO1={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.138",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 eS0 extends IQ{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",uO1,A,ud)}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:cd,basePrompt:"",formatter:new E$0,requiredPermission:"anchor"}});let B=this.config.syncPath??A.dataDir;this.directorySync=new Od({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(MO1(A,$,this.logger,this.config.entityTypes),this.config.autoSync)_O1(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 gO1({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 iS0({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 m$0(this.logger.child("DirectorySyncRequestJobHandler"),A,this.requireDirectorySync(),this.gitSync)),this.gitCleanups.push(vO1(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(CO1(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)hO1(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);TO1(A,()=>this.requireDirectorySync(),(D)=>this.configure(D),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return mO1(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 Od({...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){jO1(A,this.requireDirectorySync(),this.logger)}}function M_(A={}){return new eS0(A)}c0();Z0();var cO1={name:"@brains/email-resend",private:!0,version:"0.2.0-alpha.138",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 KpQ=K.object({apiKey:K.string().min(1).optional(),from:K.string().min(1).optional()});class lO1 extends IQ{fetchImpl;constructor(A={},Q={}){super("email-resend",cO1,A,KpQ);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(aw0,async(w)=>{let B=MxA.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 i$0(A={}){return new lO1(A)}c0();import{render as wp1}from"preact-render-to-string";import{h as HP}from"preact";function pO1(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=pO1(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=pO1(A))&&(B&&(B+=" "),B+=Q);return B}var UpQ=(A)=>{let Q=zpQ(A),{conflictingClassGroups:w,conflictingClassGroupModifiers:B}=A;return{getClassGroupId:(D)=>{let X=D.split("-");if(X[0]===""&&X.length!==1)X.shift();return oO1(X,Q)||GpQ(D)},getConflictingClassGroupIds:(D,X)=>{let H=w[D]||[];if(X&&B[D])return[...H,...B[D]];return H}}},oO1=(A,Q)=>{if(A.length===0)return Q.classGroupId;let w=A[0],B=Q.nextPart.get(w),$=B?oO1(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},iO1=/^\[(.+)\]$/,GpQ=(A)=>{if(iO1.test(A)){let Q=iO1.exec(A)[1],w=Q?.substring(0,Q.indexOf(":"));if(w)return"arbitrary.."+w}},zpQ=(A)=>{let{theme:Q,prefix:w}=A,B={nextPart:new Map,validators:[]};return FpQ(Object.entries(A.classGroups),w).forEach(([Y,D])=>{Qm0(D,B,Y,Q)}),B},Qm0=(A,Q,w,B)=>{A.forEach(($)=>{if(typeof $==="string"){let Y=$===""?Q:dO1(Q,$);Y.classGroupId=w;return}if(typeof $==="function"){if(qpQ($)){Qm0($(B),Q,w,B);return}Q.validators.push({validator:$,classGroupId:w});return}Object.entries($).forEach(([Y,D])=>{Qm0(D,dO1(Q,Y),w,B)})})},dO1=(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},qpQ=(A)=>A.isThemeGetter,FpQ=(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,$]})},VpQ=(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 JpQ=(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 b=0;b<X.length;b++){let N=X[b];if(W===0){if(N===$&&(B||X.slice(b,b+Y)===Q)){H.push(X.slice(f,b)),f=b+Y;continue}if(N==="/"){Z=b;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,L=Z&&Z>f?Z-f:void 0;return{modifiers:H,hasImportantModifier:F,baseClassName:V,maybePostfixModifierPosition:L}};if(w)return(X)=>w({className:X,parseClassName:D});return D},IpQ=(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},bpQ=(A)=>({cache:VpQ(A.cacheSize),parseClassName:JpQ(A),...UpQ(A)}),LpQ=/\s+/,NpQ=(A,Q)=>{let{parseClassName:w,getClassGroupId:B,getConflictingClassGroupIds:$}=Q,Y=[],D=A.trim().split(LpQ),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),L=B(V?G.substring(0,F):G);if(!L){if(!V){X=W+(X.length>0?" "+X:X);continue}if(L=B(G),!L){X=W+(X.length>0?" "+X:X);continue}V=!1}let b=IpQ(f).join(":"),N=Z?b+"!":b,_=N+L;if(Y.includes(_))continue;Y.push(_);let j=$(L,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=sO1(Q))B&&(B+=" "),B+=w}return B}var sO1=(A)=>{if(typeof A==="string")return A;let Q,w="";for(let B=0;B<A.length;B++)if(A[B]){if(Q=sO1(A[B]))w&&(w+=" "),w+=Q}return w};function nO1(A,...Q){let w,B,$,Y=D;function D(H){let W=Q.reduce((f,Z)=>Z(f),A());return w=bpQ(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=NpQ(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},aO1=/^\[(?:([a-z-]+):)?(.+)\]$/i,MpQ=/^\d+\/\d+$/,_pQ=new Set(["px","full","screen"]),PpQ=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,kpQ=/\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$/,OpQ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,xpQ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,RpQ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,E3=(A)=>wy(A)||_pQ.has(A)||MpQ.test(A),aI=(A)=>By(A,"length",SpQ),wy=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),Am0=(A)=>By(A,"number",wy),ld=(A)=>Boolean(A)&&Number.isInteger(Number(A)),hpQ=(A)=>A.endsWith("%")&&wy(A.slice(0,-1)),tQ=(A)=>aO1.test(A),tI=(A)=>PpQ.test(A),vpQ=new Set(["length","size","percentage"]),CpQ=(A)=>By(A,vpQ,tO1),ypQ=(A)=>By(A,"position",tO1),EpQ=new Set(["image","url"]),gpQ=(A)=>By(A,EpQ,upQ),TpQ=(A)=>By(A,"",mpQ),pd=()=>!0,By=(A,Q,w)=>{let B=aO1.exec(A);if(B){if(B[1])return typeof Q==="string"?B[1]===Q:Q.has(B[1]);return w(B[2])}return!1},SpQ=(A)=>kpQ.test(A)&&!OpQ.test(A),tO1=()=>!1,mpQ=(A)=>xpQ.test(A),upQ=(A)=>RpQ.test(A);var rO1=()=>{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"),L=a8("inset"),b=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:[pd],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:[hpQ,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:[L]}],"inset-x":[{"inset-x":[L]}],"inset-y":[{"inset-y":[L]}],start:[{start:[L]}],end:[{end:[L]}],top:[{top:[L]}],right:[{right:[L]}],bottom:[{bottom:[L]}],left:[{left:[L]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",ld,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",ld,tQ]}],"grid-cols":[{"grid-cols":[pd]}],"col-start-end":[{col:["auto",{span:["full",ld,tQ]},tQ]}],"col-start":[{"col-start":v()}],"col-end":[{"col-end":v()}],"grid-rows":[{"grid-rows":[pd]}],"row-start-end":[{row:["auto",{span:[ld,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:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"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",Am0]}],"font-family":[{font:[pd]}],"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,Am0]}],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(),ypQ]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",CpQ]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},gpQ]}],"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,TpQ]}],"shadow-color":[{shadow:[pd]}],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:[ld,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,Am0]}],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"]}}},cpQ=(A,{cacheSize:Q,prefix:w,separator:B,experimentalParseClassName:$,extend:Y={},override:D={}})=>{id(A,"cacheSize",Q),id(A,"prefix",w),id(A,"separator",B),id(A,"experimentalParseClassName",$);for(let X in D)lpQ(A[X],D[X]);for(let X in Y)ppQ(A[X],Y[X]);return A},id=(A,Q,w)=>{if(w!==void 0)A[Q]=w},lpQ=(A,Q)=>{if(Q)for(let w in Q)id(A,w,Q[w])},ppQ=(A,Q)=>{if(Q)for(let w in Q){let B=Q[w];if(B!==void 0)A[w]=(A[w]||[]).concat(B)}},d$0=(A,...Q)=>typeof A==="function"?nO1(rO1,A,...Q):nO1(()=>cpQ(rO1(),A),...Q);var ipQ=d$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 ipQ(Qy(A))}var eO1=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,Ax1=Qy,D8=(A,Q)=>(w)=>{var B;if((Q===null||Q===void 0?void 0:Q.variants)==null)return Ax1(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=eO1(f)||eO1(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[L,b]=V;return Array.isArray(b)?b.includes({...Y,...X}[L]):{...Y,...X}[L]===b})?[...W,Z,G]:W},[]);return Ax1(A,D,H,w===null||w===void 0?void 0:w.class,w===null||w===void 0?void 0:w.className)};import{jsxDEV as wm0}from"preact/jsx-dev-runtime";var Qx1=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 Bm0({variant:A,title:Q,children:w,className:B}){return wm0("div",{className:$2(Qx1({variant:A}),B),role:"alert",children:[Q&&wm0("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),wm0("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 dpQ}from"preact/jsx-dev-runtime";var wx1=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 dpQ("button",{type:Y,className:$2(wx1({variant:A,size:Q}),w),...D,...$&&{onclick:$},children:B},void 0,!1,void 0,this)}import{jsxDEV as npQ}from"preact/jsx-dev-runtime";var Bx1=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 npQ("a",{href:A,className:$2(Bx1({variant:w,size:B}),Y),"aria-label":D,...X,children:Q},void 0,!1,void 0,this)}import{jsxDEV as n$0}from"preact/jsx-dev-runtime";var $x1=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"}}),rpQ={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=rpQ[Q??"md"];return n$0("button",{onclick:"toggleTheme()",type:"button",className:$2($x1({variant:A,size:Q}),w),"aria-label":"Toggle dark mode",children:n$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:[n$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),n$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 $m0}from"preact/jsx-dev-runtime";var Yx1=D8("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function r$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 $m0("ul",{className:$2(Yx1({orientation:B}),Q),children:[Y.map((D)=>$m0("li",{children:$m0("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 rN8}from"preact/jsx-dev-runtime";import{jsxDEV as aN8}from"preact/jsx-dev-runtime";import{createContext as opQ,h as spQ}from"preact";import{useContext as apQ}from"preact/hooks";var Ym0=opQ(null);function Yy({headCollector:A,children:Q}){return spQ(Ym0.Provider,{value:A},Q)}function Dx1(){return apQ(Ym0)}function jQ(A){let Q=Dx1();if(Q)Q.setHeadProps(A);return null}import{createContext as _aQ,h as PaQ}from"preact";import{useContext as kaQ}from"preact/hooks";cN0();var qC1=X1(zC1(),1),jaQ=new Wc({gfm:!0,breaks:!0}),MaQ={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 ku0(A,Q){let{imageRenderer:w}=Q??{},$=(w?new Wc({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 g$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:oS0,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 T$0 extends _w{directorySync;constructor(A,Q,w){super(A,{schema:rS0,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 S$0 extends _w{directorySync;context;constructor(A,Q,w){super(A,{schema:dS0,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 m$0 extends _w{context;directorySync;gitSync;constructor(A,Q,w,B){super(A,{schema:nS0,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`}),mlQ(B)}summarizeDataForLog(A){return{source:A.source,interfaceType:A.interfaceType,channelId:A.channelId}}}function mlQ(A){return{gitPulled:!0,batchQueued:!0,batchId:A.batchId,importOperations:A.importOperationsCount,totalFiles:A.totalFiles}}c0();class u$0 extends _w{context;constructor(A,Q,w){super(A,{schema:y$0,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,w){let B=y$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 ulQ=K.object({});class c$0 extends _w{directorySync;constructor(A,Q){super(A,{schema:ulQ,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();H4();Z0();CB();H4();import{readFile as clQ,writeFile as llQ}from"fs/promises";var plQ=sS0;class l$0 extends _w{context;fetcher;constructor(A,Q,w=NW){super(Q,{schema:plQ,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 clQ(B,"utf-8")}catch(L){return this.logger.error("Failed to read file",{filePath:B,error:vA(L)}),x6.failure(L)}let W;try{W=lw(H)}catch(L){return this.logger.warn("Failed to parse markdown",{filePath:B,error:vA(L)}),x6.failure(L)}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 L;try{L=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:b}=WJ(L),N=Hj(b),_=fJ(b);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:L,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=dz(F,W.content);try{await llQ(B,V,"utf-8")}catch(L){return this.logger.error("Failed to write file",{filePath:B,error:vA(L)}),x6.failure(L)}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();H4();Z0();CB();import{readFile as ilQ,writeFile as dlQ}from"fs/promises";class p$0 extends _w{converter;constructor(A,Q,w=NW){super(Q,{schema:aS0,jobTypeName:"inline-image-convert"});this.converter=new kd(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 ilQ(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 dlQ(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 jO1(A,Q,w){let B=($)=>w.child($);A.jobs.registerHandler("directory-sync",new S$0(B("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new g$0(B("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new T$0(B("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new u$0(B("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new c$0(B("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new l$0(A,B("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new p$0(A,B("InlineImageConversionJobHandler"))),w.debug("Registered async job handlers")}c0();import{unlink as nlQ,access as rlQ}from"fs/promises";function MO1(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 rlQ(W).then(()=>!0,()=>!1))await nlQ(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 _O1(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 OO1,mkdir as slQ,copyFile as alQ}from"fs/promises";import{join as kO1,resolve as tS0}from"path";import{join as olQ}from"path";async function PO1(A){if(!await y5(olQ(A,".git")))return!1;try{return await QK(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function tlQ(A,Q){if(!await y5(A))return!0;if((await OO1(A)).filter(($)=>!$.startsWith(".")&&!$.startsWith("_")).length>0)return!1;if(await PO1(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function xO1(A,Q){let w=await OO1(A,{withFileTypes:!0});for(let B of w){let $=kO1(A,B.name),Y=kO1(Q,B.name);if(B.isDirectory()){if(!await y5(Y))await slQ(Y,{recursive:!0});await xO1($,Y)}else await alQ($,Y)}}async function RO1(A,Q,w){let B=tS0(process.cwd(),A);w=w?tS0(w):tS0(process.cwd(),"seed-content");let $=await tlQ(B,Q);if($&&await y5(w))Q.debug("Copying seed content to brain-data directory"),await xO1(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 hO1(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 RO1(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 vO1(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 CO1(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 EO1}from"child_process";import{cpSync as elQ,existsSync as yO1,mkdirSync as ApQ,mkdtempSync as QpQ,rmSync as wpQ}from"fs";import{tmpdir as BpQ}from"os";import{fileURLToPath as $pQ}from"url";import{join as YpQ,resolve as DpQ}from"path";function sI(A,Q){let w=EO1("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 XpQ(A){return A.startsWith("file://")}function HpQ(A){return $pQ(A)}function WpQ(A,Q){return EO1("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function gO1(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!XpQ(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",w=HpQ(A.gitUrl),B=DpQ(A.seedContentPath);if(!yO1(B))throw Error(`Seed content path not found: ${B}`);if(!yO1(w))A.logger.debug("Creating local bare content remote",{remotePath:w,branch:Q}),ApQ(w,{recursive:!0}),sI(process.cwd(),["init","--bare",`--initial-branch=${Q}`,w]);if(WpQ(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 $=QpQ(YpQ(BpQ(),"directory-sync-seed-"));try{sI($,["init",`--initial-branch=${Q}`]),sI($,["config","user.name",A.authorName??"Brain"]),sI($,["config","user.email",A.authorEmail??"brain@localhost"]),elQ(B,$,{recursive:!0}),sI($,["add","."]),sI($,["commit","-m","seed content remote"]),sI($,["remote","add","origin",A.gitUrl]),sI($,["push","-u","origin",Q])}finally{wpQ($,{recursive:!0,force:!0})}}function TO1(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 SO1(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 mO1(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(SO1(w,B));return $}var uO1={name:"@brains/directory-sync",private:!0,version:"0.2.0-alpha.139",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 eS0 extends IQ{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",uO1,A,ud)}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:cd,basePrompt:"",formatter:new E$0,requiredPermission:"anchor"}});let B=this.config.syncPath??A.dataDir;this.directorySync=new Od({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(MO1(A,$,this.logger,this.config.entityTypes),this.config.autoSync)_O1(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 gO1({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 iS0({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 m$0(this.logger.child("DirectorySyncRequestJobHandler"),A,this.requireDirectorySync(),this.gitSync)),this.gitCleanups.push(vO1(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(CO1(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)hO1(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);TO1(A,()=>this.requireDirectorySync(),(D)=>this.configure(D),this.logger,this.config.git)}async getTools(){let A=this.requireDirectorySync();return mO1(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 Od({...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){jO1(A,this.requireDirectorySync(),this.logger)}}function M_(A={}){return new eS0(A)}c0();Z0();var cO1={name:"@brains/email-resend",private:!0,version:"0.2.0-alpha.139",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 KpQ=K.object({apiKey:K.string().min(1).optional(),from:K.string().min(1).optional()});class lO1 extends IQ{fetchImpl;constructor(A={},Q={}){super("email-resend",cO1,A,KpQ);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(aw0,async(w)=>{let B=MxA.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 i$0(A={}){return new lO1(A)}c0();import{render as wp1}from"preact-render-to-string";import{h as HP}from"preact";function pO1(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=pO1(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=pO1(A))&&(B&&(B+=" "),B+=Q);return B}var UpQ=(A)=>{let Q=zpQ(A),{conflictingClassGroups:w,conflictingClassGroupModifiers:B}=A;return{getClassGroupId:(D)=>{let X=D.split("-");if(X[0]===""&&X.length!==1)X.shift();return oO1(X,Q)||GpQ(D)},getConflictingClassGroupIds:(D,X)=>{let H=w[D]||[];if(X&&B[D])return[...H,...B[D]];return H}}},oO1=(A,Q)=>{if(A.length===0)return Q.classGroupId;let w=A[0],B=Q.nextPart.get(w),$=B?oO1(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},iO1=/^\[(.+)\]$/,GpQ=(A)=>{if(iO1.test(A)){let Q=iO1.exec(A)[1],w=Q?.substring(0,Q.indexOf(":"));if(w)return"arbitrary.."+w}},zpQ=(A)=>{let{theme:Q,prefix:w}=A,B={nextPart:new Map,validators:[]};return FpQ(Object.entries(A.classGroups),w).forEach(([Y,D])=>{Qm0(D,B,Y,Q)}),B},Qm0=(A,Q,w,B)=>{A.forEach(($)=>{if(typeof $==="string"){let Y=$===""?Q:dO1(Q,$);Y.classGroupId=w;return}if(typeof $==="function"){if(qpQ($)){Qm0($(B),Q,w,B);return}Q.validators.push({validator:$,classGroupId:w});return}Object.entries($).forEach(([Y,D])=>{Qm0(D,dO1(Q,Y),w,B)})})},dO1=(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},qpQ=(A)=>A.isThemeGetter,FpQ=(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,$]})},VpQ=(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 JpQ=(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 b=0;b<X.length;b++){let N=X[b];if(W===0){if(N===$&&(B||X.slice(b,b+Y)===Q)){H.push(X.slice(f,b)),f=b+Y;continue}if(N==="/"){Z=b;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,L=Z&&Z>f?Z-f:void 0;return{modifiers:H,hasImportantModifier:F,baseClassName:V,maybePostfixModifierPosition:L}};if(w)return(X)=>w({className:X,parseClassName:D});return D},IpQ=(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},bpQ=(A)=>({cache:VpQ(A.cacheSize),parseClassName:JpQ(A),...UpQ(A)}),LpQ=/\s+/,NpQ=(A,Q)=>{let{parseClassName:w,getClassGroupId:B,getConflictingClassGroupIds:$}=Q,Y=[],D=A.trim().split(LpQ),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),L=B(V?G.substring(0,F):G);if(!L){if(!V){X=W+(X.length>0?" "+X:X);continue}if(L=B(G),!L){X=W+(X.length>0?" "+X:X);continue}V=!1}let b=IpQ(f).join(":"),N=Z?b+"!":b,_=N+L;if(Y.includes(_))continue;Y.push(_);let j=$(L,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=sO1(Q))B&&(B+=" "),B+=w}return B}var sO1=(A)=>{if(typeof A==="string")return A;let Q,w="";for(let B=0;B<A.length;B++)if(A[B]){if(Q=sO1(A[B]))w&&(w+=" "),w+=Q}return w};function nO1(A,...Q){let w,B,$,Y=D;function D(H){let W=Q.reduce((f,Z)=>Z(f),A());return w=bpQ(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=NpQ(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},aO1=/^\[(?:([a-z-]+):)?(.+)\]$/i,MpQ=/^\d+\/\d+$/,_pQ=new Set(["px","full","screen"]),PpQ=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,kpQ=/\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$/,OpQ=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,xpQ=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,RpQ=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,E3=(A)=>wy(A)||_pQ.has(A)||MpQ.test(A),aI=(A)=>By(A,"length",SpQ),wy=(A)=>Boolean(A)&&!Number.isNaN(Number(A)),Am0=(A)=>By(A,"number",wy),ld=(A)=>Boolean(A)&&Number.isInteger(Number(A)),hpQ=(A)=>A.endsWith("%")&&wy(A.slice(0,-1)),tQ=(A)=>aO1.test(A),tI=(A)=>PpQ.test(A),vpQ=new Set(["length","size","percentage"]),CpQ=(A)=>By(A,vpQ,tO1),ypQ=(A)=>By(A,"position",tO1),EpQ=new Set(["image","url"]),gpQ=(A)=>By(A,EpQ,upQ),TpQ=(A)=>By(A,"",mpQ),pd=()=>!0,By=(A,Q,w)=>{let B=aO1.exec(A);if(B){if(B[1])return typeof Q==="string"?B[1]===Q:Q.has(B[1]);return w(B[2])}return!1},SpQ=(A)=>kpQ.test(A)&&!OpQ.test(A),tO1=()=>!1,mpQ=(A)=>xpQ.test(A),upQ=(A)=>RpQ.test(A);var rO1=()=>{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"),L=a8("inset"),b=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:[pd],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:[hpQ,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:[L]}],"inset-x":[{"inset-x":[L]}],"inset-y":[{"inset-y":[L]}],start:[{start:[L]}],end:[{end:[L]}],top:[{top:[L]}],right:[{right:[L]}],bottom:[{bottom:[L]}],left:[{left:[L]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",ld,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",ld,tQ]}],"grid-cols":[{"grid-cols":[pd]}],"col-start-end":[{col:["auto",{span:["full",ld,tQ]},tQ]}],"col-start":[{"col-start":v()}],"col-end":[{"col-end":v()}],"grid-rows":[{"grid-rows":[pd]}],"row-start-end":[{row:["auto",{span:[ld,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:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"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",Am0]}],"font-family":[{font:[pd]}],"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,Am0]}],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(),ypQ]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",CpQ]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},gpQ]}],"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,TpQ]}],"shadow-color":[{shadow:[pd]}],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:[ld,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,Am0]}],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"]}}},cpQ=(A,{cacheSize:Q,prefix:w,separator:B,experimentalParseClassName:$,extend:Y={},override:D={}})=>{id(A,"cacheSize",Q),id(A,"prefix",w),id(A,"separator",B),id(A,"experimentalParseClassName",$);for(let X in D)lpQ(A[X],D[X]);for(let X in Y)ppQ(A[X],Y[X]);return A},id=(A,Q,w)=>{if(w!==void 0)A[Q]=w},lpQ=(A,Q)=>{if(Q)for(let w in Q)id(A,w,Q[w])},ppQ=(A,Q)=>{if(Q)for(let w in Q){let B=Q[w];if(B!==void 0)A[w]=(A[w]||[]).concat(B)}},d$0=(A,...Q)=>typeof A==="function"?nO1(rO1,A,...Q):nO1(()=>cpQ(rO1(),A),...Q);var ipQ=d$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 ipQ(Qy(A))}var eO1=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,Ax1=Qy,D8=(A,Q)=>(w)=>{var B;if((Q===null||Q===void 0?void 0:Q.variants)==null)return Ax1(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=eO1(f)||eO1(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[L,b]=V;return Array.isArray(b)?b.includes({...Y,...X}[L]):{...Y,...X}[L]===b})?[...W,Z,G]:W},[]);return Ax1(A,D,H,w===null||w===void 0?void 0:w.class,w===null||w===void 0?void 0:w.className)};import{jsxDEV as wm0}from"preact/jsx-dev-runtime";var Qx1=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 Bm0({variant:A,title:Q,children:w,className:B}){return wm0("div",{className:$2(Qx1({variant:A}),B),role:"alert",children:[Q&&wm0("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),wm0("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 dpQ}from"preact/jsx-dev-runtime";var wx1=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 dpQ("button",{type:Y,className:$2(wx1({variant:A,size:Q}),w),...D,...$&&{onclick:$},children:B},void 0,!1,void 0,this)}import{jsxDEV as npQ}from"preact/jsx-dev-runtime";var Bx1=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 npQ("a",{href:A,className:$2(Bx1({variant:w,size:B}),Y),"aria-label":D,...X,children:Q},void 0,!1,void 0,this)}import{jsxDEV as n$0}from"preact/jsx-dev-runtime";var $x1=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"}}),rpQ={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=rpQ[Q??"md"];return n$0("button",{onclick:"toggleTheme()",type:"button",className:$2($x1({variant:A,size:Q}),w),"aria-label":"Toggle dark mode",children:n$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:[n$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),n$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 $m0}from"preact/jsx-dev-runtime";var Yx1=D8("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function r$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 $m0("ul",{className:$2(Yx1({orientation:B}),Q),children:[Y.map((D)=>$m0("li",{children:$m0("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 rN8}from"preact/jsx-dev-runtime";import{jsxDEV as aN8}from"preact/jsx-dev-runtime";import{createContext as opQ,h as spQ}from"preact";import{useContext as apQ}from"preact/hooks";var Ym0=opQ(null);function Yy({headCollector:A,children:Q}){return spQ(Ym0.Provider,{value:A},Q)}function Dx1(){return apQ(Ym0)}function jQ(A){let Q=Dx1();if(Q)Q.setHeadProps(A);return null}import{createContext as _aQ,h as PaQ}from"preact";import{useContext as kaQ}from"preact/hooks";cN0();var qC1=X1(zC1(),1),jaQ=new Wc({gfm:!0,breaks:!0}),MaQ={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 ku0(A,Q){let{imageRenderer:w}=Q??{},$=(w?new Wc({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>`),qC1.default($,MaQ)}var FC1=_aQ(null);function Ly({imageRenderer:A,children:Q}){return PaQ(FC1.Provider,{value:A??null},Q)}function VC1(){return kaQ(FC1)}function i3(){let A=VC1();return(Q)=>ku0(Q,A?{imageRenderer:A}:void 0)}var OaQ=/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,xaQ={"&":"&","<":"<",">":">",""":'"',"'":"'"},RaQ=/&(?:amp|lt|gt|quot|#39);/g;function haQ(A){return A.replace(RaQ,(Q)=>xaQ[Q]??Q)}function Ou0(A){return A.replace(OaQ,(Q,w)=>{return`<div class="mermaid">${haQ(w)}</div>`})}var JC1=/<!--\s*\.slide:\s*(.*?)\s*-->/g;function IC1(A){let Q={};for(let B of A.matchAll(JC1)){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(JC1,"").replace(/^\n+/,"").replace(/\n{3,}/g,`
|
|
4759
4759
|
|
|
4760
4760
|
`).trim();return{attributes:Q,markdown:w}}var vaQ=/<!--\s*\.break\s*-->/;function bC1(A){let Q=A.split(vaQ);return Q.length>1?Q:null}import{jsxDEV as _G}from"preact/jsx-dev-runtime";var xu0=({markdown:A,deck:Q})=>{let w=i3(),$=A.split(/^---$/gm).map((f)=>f.trim()).map((f)=>{let{attributes:Z,markdown:G}=IC1(f),F=bC1(G),V;if(F)V=`<div class="slide-columns">${F.map((b)=>`<div class="slide-column">${Ou0(w(b.trim()))}</div>`).join("")}</div>`;else V=Ou0(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)=>_G("section",{...f,dangerouslySetInnerHTML:{__html:Z}},G,!1,void 0,this));return _G("section",{className:"presentation-section",children:[D&&_G(jQ,{title:D,...X?{description:X}:{},...H?{ogImage:H}:{},ogType:"article"},void 0,!1,void 0,this),_G("link",{rel:"stylesheet",href:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.css"},void 0,!1,void 0,this),_G("div",{className:"reveal",children:_G("div",{className:"slides",children:W},void 0,!1,void 0,this)},void 0,!1,void 0,this),_G("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&&_G("script",{src:"https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js",defer:!0},void 0,!1,void 0,this),_G("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=TG(this.outputDir,"styles","main.css");await this.cssProcessor.process(Y,D,this.workingDir,this.outputDir,this.logger);let X=await x7.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 x7.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=TG(process.cwd(),"public");try{await x7.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await x7.readdir(A,{withFileTypes:!0});for(let w of Q){let B=TG(A,w.name),$=TG(this.outputDir,w.name);if(w.isDirectory())await this.copyDirectory(B,$);else await x7.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=TG(this.outputDir,$);await x7.mkdir(g7w(Y),{recursive:!0}),await x7.writeFile(Y,B,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await x7.mkdir(Q,{recursive:!0});let w=await x7.readdir(A,{withFileTypes:!0});for(let B of w){let $=TG(A,B.name),Y=TG(Q,B.name);if(B.isDirectory())await this.copyDirectory($,Y);else await x7.copyFile($,Y)}}}function Wp0(A){return new Bp1(A)}_5();Z0();Z0();_5();var $p1=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:zX,layouts:K.record(K.any()),themeCSS:K.string().optional()}),ay8=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 Yp1(A){let Q=A.list(),w=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:w}}function Dp1(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();H4();_5();Z0();var T7w=K.object({id:K.string(),entityType:K.string(),content:K.string(),metadata:K.object({slug:K.string()}).passthrough()}).passthrough(),S7w=K.object({content:K.string(),metadata:K.object({width:K.number().optional(),height:K.number().optional()}).passthrough()});async function j40(A,Q){let w=Q.urlGenerator??a7.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((g)=>j40(g,{...Q,urlGenerator:w})));if(typeof A!=="object")return A;let B={},$=Object.entries(A),Y=await Promise.all($.map(([,g])=>j40(g,{...Q,urlGenerator:w})));for(let g=0;g<$.length;g++){let E=$[g];if(E)B[E[0]]=Y[g]}let D=T7w.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":UX(H),F=`/${G}`,V=G.charAt(0).toUpperCase()+G.slice(1),L=qu(X),b=await m7w(L,Q),N=C10(X)??L,_=await u7w(N,Q);return{...B,...X,url:w.generateUrl(H,W),typeLabel:Z,listUrl:F,listLabel:V,...b,..._&&{ogImageUrl:_}}}async function m7w(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 Hp1(A,Q.pipelineContext.services.entityService);if(!B)return{};return{coverImageUrl:B.url,...B.width&&{coverImageWidth:B.width},...B.height&&{coverImageHeight:B.height}}}async function u7w(A,Q){if(!A)return;let w=Q.imageBuildService?.get(A);if(w)return Xp1(w.src,Q.siteUrl);let B=await Hp1(A,Q.pipelineContext.services.entityService);if(!B)return;if(B.url.startsWith("data:"))return;return Xp1(B.url,Q.siteUrl)}function Xp1(A,Q){if(/^https?:\/\//i.test(A)||A.startsWith("data:"))return A;if(!Q)return A;return`${Q.replace(/\/$/,"")}/${A.replace(/^\//,"")}`}async function Hp1(A,Q){if(!A)return;let w=await Q.getEntity({entityType:"image",id:A}),B=S7w.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 Wp1(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=qu(D);if(X)w.add(X);let H=C10(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 fp1(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 j40(X,{pipelineContext:$.pipelineContext,imageBuildService:$.imageBuildService,siteUrl:$.siteUrl,urlGenerator:a7.getInstance()})}function Zp1(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 fp1(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 Dp1(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 c7w}from"path";async function Kp1(A){let Q=A.parsedOptions.workingDir??c7w(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 Up1(A){await new L40({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 Gp1(A){let Q=new b40(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),w=await Wp1(A.pipelineContext.services.entityService,A.pipelineContext.logger);if(w.length>0)await Q.resolveAll(w);return Q}async function zp1(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,(w)=>{Q?.report(w).catch(()=>{})})}function qp1(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function Fp1(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function Vp1(A){let Q=$p1.parse(A.buildOptions),w=X7.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 Up1({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let $=await Kp1({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),Y=Yp1(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 Gp1({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),H=Zp1({routes:D,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:X,siteMetadata:Q.siteConfig});return await zp1({staticSiteBuilder:$,buildContext:H,reporter:w}),await w?.report({message:"Site build complete",progress:100,total:100}),qp1({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:$}),Fp1({outputDir:Q.outputDir,errorMessage:Y.message})}}class LH{static instance=null;static defaultStaticSiteBuilderFactory=Wp0;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){LH.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,w,B,$=void 0){return LH.instance??=new LH(A,LH.defaultStaticSiteBuilderFactory,Q,w,B,$),LH.instance}static resetInstance(){LH.instance=null}static createFresh(A,Q,w,B,$,Y=void 0){return new LH(A,$??LH.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,a7.getInstance().configure(Y)}async build(A,Q){return Vp1({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}Z0();class fp0{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 l7w(A,Q){return A.map((w)=>({...w,template:w.template.includes(":")?w.template:`${Q}:${w.template}`}))}function M40(A,Q,w){for(let B of A)w.register({...B,pluginId:Q,sections:B.sections?l7w(B.sections,Q):[]})}function Jp1(A,Q,w){A.messaging.subscribe("plugin:site-builder:route:register",async(B)=>{try{let $=at.parse(B.payload),{routes:Y,pluginId:D}=$;return M40(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 $=tt.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 $=et.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 $=Ae.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 Ip1}from"fs";import{join as bp1}from"path";async function p7w(A,Q,w){let B=A.siteConfig.url??"https://example.com",$=Q.list(),Y=Xp0(B,A.environment);await Ip1.writeFile(bp1(A.outputDir,"robots.txt"),Y,"utf-8"),w.info(`Generated robots.txt for ${A.environment} environment`);let D=Hp0($,B);await Ip1.writeFile(bp1(A.outputDir,"sitemap.xml"),D,"utf-8"),w.info(`Generated sitemap.xml with ${$.length} URLs`)}function Lp1(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 p7w(Y,w,B),{success:!0}}catch(Y){return B.error("Failed to generate SEO files",Y),{success:!1}}})}c0();Z0();_5();var Np1=K.object({environment:K.enum(["preview","production"]).optional(),outputDir:K.string(),workingDir:K.string().optional(),enableContentGeneration:K.boolean().optional(),siteConfig:zX.optional()});_5();_5();async function zr(A,Q){try{let w=await A({type:rT,payload:void 0});if("success"in w&&w.success&&w.data){let B=zX.safeParse(w.data);if(B.success)return zX.parse({...Q,...B.data})}}catch{}return Q}class Zp0 extends _w{sendMessage;cfg;constructor(A,Q,w){super(A,{schema:Np1,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 zr(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)=>a7.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 i7w=K.object({slot:K.enum(UN).optional().default("primary"),limit:K.number().optional()});class Kp0{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=i7w.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 d7w=K.object({environment:K.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function jp1(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'.",d7w,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 Mp1=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:zX.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 _p1={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.138",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 Up0 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",_p1,{...A,layouts:Q},Mp1);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new N40(A.logger),this._slotRegistry=new w40,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 Kp0(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=QY.getInstance(A.entityService,A.logger),Jp1(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)M40(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=LH.getInstance(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new Zp0(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 fp0(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}}),Lp1({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 jp1(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 zr(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 zr(A.messaging.send,this.config.siteInfo);return`## Your Site
|
|
5744
|
+
`+X;await x7.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=TG(process.cwd(),"public");try{await x7.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await x7.readdir(A,{withFileTypes:!0});for(let w of Q){let B=TG(A,w.name),$=TG(this.outputDir,w.name);if(w.isDirectory())await this.copyDirectory(B,$);else await x7.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=TG(this.outputDir,$);await x7.mkdir(g7w(Y),{recursive:!0}),await x7.writeFile(Y,B,"utf-8"),this.logger.debug(`Wrote inline static asset: ${$}`)}))}async copyDirectory(A,Q){await x7.mkdir(Q,{recursive:!0});let w=await x7.readdir(A,{withFileTypes:!0});for(let B of w){let $=TG(A,B.name),Y=TG(Q,B.name);if(B.isDirectory())await this.copyDirectory($,Y);else await x7.copyFile($,Y)}}}function Wp0(A){return new Bp1(A)}_5();Z0();Z0();_5();var $p1=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:zX,layouts:K.record(K.any()),themeCSS:K.string().optional()}),ay8=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 Yp1(A){let Q=A.list(),w=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:w}}function Dp1(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();H4();_5();Z0();var T7w=K.object({id:K.string(),entityType:K.string(),content:K.string(),metadata:K.object({slug:K.string()}).passthrough()}).passthrough(),S7w=K.object({content:K.string(),metadata:K.object({width:K.number().optional(),height:K.number().optional()}).passthrough()});async function j40(A,Q){let w=Q.urlGenerator??a7.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((g)=>j40(g,{...Q,urlGenerator:w})));if(typeof A!=="object")return A;let B={},$=Object.entries(A),Y=await Promise.all($.map(([,g])=>j40(g,{...Q,urlGenerator:w})));for(let g=0;g<$.length;g++){let E=$[g];if(E)B[E[0]]=Y[g]}let D=T7w.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":UX(H),F=`/${G}`,V=G.charAt(0).toUpperCase()+G.slice(1),L=qu(X),b=await m7w(L,Q),N=C10(X)??L,_=await u7w(N,Q);return{...B,...X,url:w.generateUrl(H,W),typeLabel:Z,listUrl:F,listLabel:V,...b,..._&&{ogImageUrl:_}}}async function m7w(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 Hp1(A,Q.pipelineContext.services.entityService);if(!B)return{};return{coverImageUrl:B.url,...B.width&&{coverImageWidth:B.width},...B.height&&{coverImageHeight:B.height}}}async function u7w(A,Q){if(!A)return;let w=Q.imageBuildService?.get(A);if(w)return Xp1(w.src,Q.siteUrl);let B=await Hp1(A,Q.pipelineContext.services.entityService);if(!B)return;if(B.url.startsWith("data:"))return;return Xp1(B.url,Q.siteUrl)}function Xp1(A,Q){if(/^https?:\/\//i.test(A)||A.startsWith("data:"))return A;if(!Q)return A;return`${Q.replace(/\/$/,"")}/${A.replace(/^\//,"")}`}async function Hp1(A,Q){if(!A)return;let w=await Q.getEntity({entityType:"image",id:A}),B=S7w.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 Wp1(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=qu(D);if(X)w.add(X);let H=C10(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 fp1(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 j40(X,{pipelineContext:$.pipelineContext,imageBuildService:$.imageBuildService,siteUrl:$.siteUrl,urlGenerator:a7.getInstance()})}function Zp1(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 fp1(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 Dp1(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 c7w}from"path";async function Kp1(A){let Q=A.parsedOptions.workingDir??c7w(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 Up1(A){await new L40({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 Gp1(A){let Q=new b40(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),w=await Wp1(A.pipelineContext.services.entityService,A.pipelineContext.logger);if(w.length>0)await Q.resolveAll(w);return Q}async function zp1(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,(w)=>{Q?.report(w).catch(()=>{})})}function qp1(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function Fp1(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function Vp1(A){let Q=$p1.parse(A.buildOptions),w=X7.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 Up1({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let $=await Kp1({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),Y=Yp1(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 Gp1({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),H=Zp1({routes:D,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:X,siteMetadata:Q.siteConfig});return await zp1({staticSiteBuilder:$,buildContext:H,reporter:w}),await w?.report({message:"Site build complete",progress:100,total:100}),qp1({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:$}),Fp1({outputDir:Q.outputDir,errorMessage:Y.message})}}class LH{static instance=null;static defaultStaticSiteBuilderFactory=Wp0;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){LH.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,w,B,$=void 0){return LH.instance??=new LH(A,LH.defaultStaticSiteBuilderFactory,Q,w,B,$),LH.instance}static resetInstance(){LH.instance=null}static createFresh(A,Q,w,B,$,Y=void 0){return new LH(A,$??LH.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,a7.getInstance().configure(Y)}async build(A,Q){return Vp1({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}Z0();class fp0{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 l7w(A,Q){return A.map((w)=>({...w,template:w.template.includes(":")?w.template:`${Q}:${w.template}`}))}function M40(A,Q,w){for(let B of A)w.register({...B,pluginId:Q,sections:B.sections?l7w(B.sections,Q):[]})}function Jp1(A,Q,w){A.messaging.subscribe("plugin:site-builder:route:register",async(B)=>{try{let $=at.parse(B.payload),{routes:Y,pluginId:D}=$;return M40(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 $=tt.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 $=et.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 $=Ae.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 Ip1}from"fs";import{join as bp1}from"path";async function p7w(A,Q,w){let B=A.siteConfig.url??"https://example.com",$=Q.list(),Y=Xp0(B,A.environment);await Ip1.writeFile(bp1(A.outputDir,"robots.txt"),Y,"utf-8"),w.info(`Generated robots.txt for ${A.environment} environment`);let D=Hp0($,B);await Ip1.writeFile(bp1(A.outputDir,"sitemap.xml"),D,"utf-8"),w.info(`Generated sitemap.xml with ${$.length} URLs`)}function Lp1(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 p7w(Y,w,B),{success:!0}}catch(Y){return B.error("Failed to generate SEO files",Y),{success:!1}}})}c0();Z0();_5();var Np1=K.object({environment:K.enum(["preview","production"]).optional(),outputDir:K.string(),workingDir:K.string().optional(),enableContentGeneration:K.boolean().optional(),siteConfig:zX.optional()});_5();_5();async function zr(A,Q){try{let w=await A({type:rT,payload:void 0});if("success"in w&&w.success&&w.data){let B=zX.safeParse(w.data);if(B.success)return zX.parse({...Q,...B.data})}}catch{}return Q}class Zp0 extends _w{sendMessage;cfg;constructor(A,Q,w){super(A,{schema:Np1,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 zr(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)=>a7.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 i7w=K.object({slot:K.enum(UN).optional().default("primary"),limit:K.number().optional()});class Kp0{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=i7w.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 d7w=K.object({environment:K.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function jp1(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'.",d7w,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 Mp1=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:zX.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 _p1={name:"@brains/site-builder-plugin",private:!0,version:"0.2.0-alpha.139",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 Up0 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",_p1,{...A,layouts:Q},Mp1);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new N40(A.logger),this._slotRegistry=new w40,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 Kp0(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService=QY.getInstance(A.entityService,A.logger),Jp1(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)M40(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=LH.getInstance(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,this.config.entityDisplay),A.jobs.registerHandler("site-build",new Zp0(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 fp0(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}}),Lp1({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 jp1(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 zr(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 zr(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(),LH.resetInstance(),this.logger.debug("Cleaned up all event subscriptions")}}function WP(A={}){return new Up0(A)}c0();_5();Z0();c0();_5();var Pp1=K.object({}),qr=o1.extend({id:K.literal("site-info"),entityType:K.literal("site-info"),metadata:Pp1}),Gp0=we,ty=zX.omit({url:!0,analyticsScript:!0});c0();class SG extends J2{constructor(){super({entityType:"site-info",purpose:"Singleton configuration describing the published site.",schema:qr,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 mG{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,w){return mG.instance??=new mG(A,Q,w),mG.instance}static resetInstance(){mG.instance=null}static createFresh(A,Q,w){return new mG(A,Q,w)}constructor(A,Q,w){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new SG;let B=mG.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 r7w=new SG;class _40{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?r7w.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 kp1={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.138",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 s7w=new SG;class zp0 extends kQ{entityType="site-info";schema=qr;adapter=s7w;defaultSiteInfo;constructor(A){super("site-info",kp1);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new _40(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=mG.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 zp0(A)}var a7w=new SG;async function Fr(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 a7w.parseSiteInfoBody(w.content)}Z0();var t7w=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 Op1={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 xp1={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 Rp1={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 hp1={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 vp1={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 Cp1={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 yp1={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 Ep1={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 gp1={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 H4w=K.object({type:K.string()}).catchall(K.unknown()),W4w=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(H4w)})})})});function uG(A){return W4w.parse(A)}var MB={"ai.rizom.brain.card":uG(Op1),"ai.rizom.brain.deck":uG(xp1),"ai.rizom.brain.link":uG(Rp1),"ai.rizom.brain.note":uG(hp1),"ai.rizom.brain.post":uG(vp1),"ai.rizom.brain.project":uG(Cp1),"ai.rizom.brain.series":uG(yp1),"ai.rizom.brain.socialPost":uG(Ep1),"ai.rizom.brain.topic":uG(gp1)},f4w="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:f4w}}var Z4w={"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 Vp0(A){return MB[A]}function Jp0(){return Object.entries(Z4w).map(([A,Q])=>({id:A,...Q}))}function Fp0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var K4w=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function U4w(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)=>K4w.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 Tp1(A){switch(A.type){case"string":return U4w(A);case"integer":return K.number().int();case"boolean":return K.boolean();case"array":{let Q=A.items?Tp1(A.items):K.unknown(),w=K.array(Q);if(A.maxLength!==void 0)w=w.max(A.maxLength);return w}case"object":return G4w(A);case"blob":return K.custom(Fp0,{message:"expected blob"});default:return K.unknown()}}function Sp1(A){let Q=new Set(A.required??[]),w={};for(let[B,$]of Object.entries(A.properties??{})){let Y=Tp1($);w[B]=Q.has(B)?Y:Y.optional()}return w}function G4w(A){return K.object(Sp1(A)).passthrough()}function qp0(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 z4w(A,Q){if(qp0(A,new Set(["$type","siteUrl","brain","anchor","skills","model","version","createdAt","updatedAt"]),Q),Fp0(A.brain))qp0(A.brain,new Set(["did","name","role","purpose","values"]),Q,["brain"]);if(Fp0(A.anchor))qp0(A.anchor,new Set(["did","name","kind"]),Q,["anchor"])}function cG(A){let Q=K.object({...Sp1(A.defs.main.record),$type:K.literal(A.id).optional()}).passthrough();return A.id==="ai.rizom.brain.card"?Q.superRefine(z4w):Q}var q4w={"ai.rizom.brain.card":cG(MB["ai.rizom.brain.card"]),"ai.rizom.brain.deck":cG(MB["ai.rizom.brain.deck"]),"ai.rizom.brain.link":cG(MB["ai.rizom.brain.link"]),"ai.rizom.brain.note":cG(MB["ai.rizom.brain.note"]),"ai.rizom.brain.post":cG(MB["ai.rizom.brain.post"]),"ai.rizom.brain.project":cG(MB["ai.rizom.brain.project"]),"ai.rizom.brain.series":cG(MB["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":cG(MB["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":cG(MB["ai.rizom.brain.topic"])};function F4w(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=cG(A).safeParse(Q);if(w.success)return;let B=w.error.issues[0];if(!B)throw w.error;throw Error(F4w(A,Q,B))}var P40="atproto:brain-card-discovered",mp1="atproto:brain-discovered",up1="atproto:brain-card-refreshed",cp1=K.object({repoDid:K.string().min(1),uri:K.string().min(1),cid:K.string().min(1),record:q4w["ai.rizom.brain.card"]}).strict(),PT8=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}`)}}NH();AE();Z0();var Ip0=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 I4w=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()}),mT8=GX.extend({title:K.string().optional(),slug:K.string().optional()});class bp0 extends w4{constructor(A,Q){super(A,Q,{schema:I4w,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(),LH.resetInstance(),this.logger.debug("Cleaned up all event subscriptions")}}function WP(A={}){return new Up0(A)}c0();_5();Z0();c0();_5();var Pp1=K.object({}),qr=o1.extend({id:K.literal("site-info"),entityType:K.literal("site-info"),metadata:Pp1}),Gp0=we,ty=zX.omit({url:!0,analyticsScript:!0});c0();class SG extends J2{constructor(){super({entityType:"site-info",purpose:"Singleton configuration describing the published site.",schema:qr,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 mG{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,w){return mG.instance??=new mG(A,Q,w),mG.instance}static resetInstance(){mG.instance=null}static createFresh(A,Q,w){return new mG(A,Q,w)}constructor(A,Q,w){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new SG;let B=mG.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 r7w=new SG;class _40{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?r7w.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 kp1={name:"@brains/site-info",private:!0,version:"0.2.0-alpha.139",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 s7w=new SG;class zp0 extends kQ{entityType="site-info";schema=qr;adapter=s7w;defaultSiteInfo;constructor(A){super("site-info",kp1);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new _40(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=mG.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 zp0(A)}var a7w=new SG;async function Fr(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 a7w.parseSiteInfoBody(w.content)}Z0();var t7w=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 Op1={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 xp1={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 Rp1={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 hp1={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 vp1={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 Cp1={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 yp1={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 Ep1={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 gp1={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 H4w=K.object({type:K.string()}).catchall(K.unknown()),W4w=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(H4w)})})})});function uG(A){return W4w.parse(A)}var MB={"ai.rizom.brain.card":uG(Op1),"ai.rizom.brain.deck":uG(xp1),"ai.rizom.brain.link":uG(Rp1),"ai.rizom.brain.note":uG(hp1),"ai.rizom.brain.post":uG(vp1),"ai.rizom.brain.project":uG(Cp1),"ai.rizom.brain.series":uG(yp1),"ai.rizom.brain.socialPost":uG(Ep1),"ai.rizom.brain.topic":uG(gp1)},f4w="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:f4w}}var Z4w={"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 Vp0(A){return MB[A]}function Jp0(){return Object.entries(Z4w).map(([A,Q])=>({id:A,...Q}))}function Fp0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var K4w=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function U4w(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)=>K4w.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 Tp1(A){switch(A.type){case"string":return U4w(A);case"integer":return K.number().int();case"boolean":return K.boolean();case"array":{let Q=A.items?Tp1(A.items):K.unknown(),w=K.array(Q);if(A.maxLength!==void 0)w=w.max(A.maxLength);return w}case"object":return G4w(A);case"blob":return K.custom(Fp0,{message:"expected blob"});default:return K.unknown()}}function Sp1(A){let Q=new Set(A.required??[]),w={};for(let[B,$]of Object.entries(A.properties??{})){let Y=Tp1($);w[B]=Q.has(B)?Y:Y.optional()}return w}function G4w(A){return K.object(Sp1(A)).passthrough()}function qp0(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 z4w(A,Q){if(qp0(A,new Set(["$type","siteUrl","brain","anchor","skills","model","version","createdAt","updatedAt"]),Q),Fp0(A.brain))qp0(A.brain,new Set(["did","name","role","purpose","values"]),Q,["brain"]);if(Fp0(A.anchor))qp0(A.anchor,new Set(["did","name","kind"]),Q,["anchor"])}function cG(A){let Q=K.object({...Sp1(A.defs.main.record),$type:K.literal(A.id).optional()}).passthrough();return A.id==="ai.rizom.brain.card"?Q.superRefine(z4w):Q}var q4w={"ai.rizom.brain.card":cG(MB["ai.rizom.brain.card"]),"ai.rizom.brain.deck":cG(MB["ai.rizom.brain.deck"]),"ai.rizom.brain.link":cG(MB["ai.rizom.brain.link"]),"ai.rizom.brain.note":cG(MB["ai.rizom.brain.note"]),"ai.rizom.brain.post":cG(MB["ai.rizom.brain.post"]),"ai.rizom.brain.project":cG(MB["ai.rizom.brain.project"]),"ai.rizom.brain.series":cG(MB["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":cG(MB["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":cG(MB["ai.rizom.brain.topic"])};function F4w(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=cG(A).safeParse(Q);if(w.success)return;let B=w.error.issues[0];if(!B)throw w.error;throw Error(F4w(A,Q,B))}var P40="atproto:brain-card-discovered",mp1="atproto:brain-discovered",up1="atproto:brain-card-refreshed",cp1=K.object({repoDid:K.string().min(1),uri:K.string().min(1),cid:K.string().min(1),record:q4w["ai.rizom.brain.card"]}).strict(),PT8=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}`)}}NH();AE();Z0();var Ip0=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 I4w=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()}),mT8=GX.extend({title:K.string().optional(),slug:K.string().optional()});class bp0 extends w4{constructor(A,Q){super(A,Q,{schema:I4w,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();NH();function l4w(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),R7("header",{className:"printable-hero",children:[R7("div",{className:"printable-masthead",children:Q.brandLabel&&R7("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this),R7("div",{children:[R7("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.excerpt&&R7("p",{className:"printable-excerpt",children:Q.excerpt},void 0,!1,void 0,this),R7("div",{className:"printable-meta",children:[Q.author&&R7("span",{children:["By ",Q.author]},void 0,!0,void 0,this),w&&R7("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&&R7("figure",{className:"printable-cover-wrap",children:R7("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this)},void 0,!1,void 0,this),R7($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Q.canonicalUrl||Q.brandLabel)&&R7("footer",{className:"printable-footer",children:[R7("span",{children:Q.brandLabel??"Printable PDF"},void 0,!1,void 0,this),Q.canonicalUrl&&R7("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 MYw=26214400,_Yw=60000;class hp0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==R40)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=PYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await bYw(jYw(NYw(),"brain-blog-printable-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/printable/post/${Q.id}`,template:Xi1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:MYw,timeoutMs:_Yw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${kYw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await LYw(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 PYw(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 kYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}import{mkdtemp as vYw,rm as CYw}from"fs/promises";import{tmpdir as yYw}from"os";import{join as EYw}from"path";Z0();NH();Z0();import{jsxDEV as hYw}from"preact/jsx-dev-runtime";var jr="og-image",OYw="blog:og-image",Hi1=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()}),Wi1={name:OYw,pluginId:"blog",schema:Hi1,renderers:{image:RYw}};function xYw(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 RYw(A){let Q=Hi1.parse(A);return hYw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Journal",title:Q.title,subtitle:Q.excerpt,meta:[Q.author],tag:xYw(Q.publishedAt)},void 0,!1,void 0,this)}var gYw={width:1200,height:630},TYw=60000;class vp0{context;metadata={outputEntityType:"image",targetField:"ogImageId"};screenshotPng;constructor(A,Q={}){this.context=A;this.screenshotPng=Q.screenshotPng??Nr}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==jr)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=SYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await vYw(EYw(yYw(),"brain-blog-og-image-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/og/post/${Q.id}`,template:Wi1,format:"image",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"image",data:await this.screenshotPng(Y.urlFor($.urlPath),gYw,{timeoutMs:TYw,fullPage:!1,omitBackground:!1}),mimeType:"image/png",filename:`${mYw(Q)}-og.png`}}finally{await Y.close()}}finally{await CYw(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 SYw(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 mYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var fi1={name:"@brains/blog",private:!0,version:"0.2.0-alpha.138",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 Cp0 extends kQ{entityType=ZF.entityType;schema=ey;adapter=ZF;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("blog",fi1,A,Ip0)}getEntityTypeConfig(){return{weight:2,publish:{publishStatuses:["queued","published"]}}}createGenerationHandler(A){return new bp0(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return np1()}getDataSources(){return[new Np0(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (Ui1(),Ki1));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),rp1(A,this.logger),op1(A,this.logger),ap1(A,this.logger),tp1(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("post",R40,new hp0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("post",jr,new vp0(A)),this.deferPublishAssetRegistration(A),this.unregisterAtprotoProjection=U5.getInstance().register(_p0()),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:jr,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 yp0(A={}){return new Cp0(A)}NH();AE();c0();Z0();Z0();l$();c0();var wf=K.object({title:K.string(),slug:K.string(),coverImageId:K.string().optional()}),Gi1=wf.pick({title:!0,slug:!0}),Nb=o1.extend({metadata:Gi1}),h40=Nb.extend({frontmatter:wf}),v40=h40.extend({description:K.string().optional(),postCount:K.number(),coverImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()}),zi1=K.object({description:K.string().optional()});function GP(A){return new pw(zi1,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}c0();class Ep0 extends J2{constructor(){super({entityType:"series",purpose:"A series grouping related posts or content under one theme.",schema:Nb,frontmatterSchema:wf,supportsCoverImage:!0,bodyFormatter:GP("")})}toMarkdown(A){let Q,w={};try{Q=this.parseFrontMatter(A.content,wf).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,wf);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,wf);return GP(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var jb=new Ep0;c0();Z0();bX();Z0();var lYw=K.object({seriesName:K.string().optional(),seriesIndex:K.number().optional()});function C40(A){let Q=lYw.safeParse(A);return Q.success?Q.data:{}}function zP(A){return C40(A.metadata).seriesName}function qi1(A){return C40(A.metadata).seriesIndex}function Fi1(A,Q){let w=qi1(A)??Number.MAX_SAFE_INTEGER,B=qi1(Q)??Number.MAX_SAFE_INTEGER;return w-B}class gp0{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 Z7("",Q)}}c0();Z0();var pYw=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()}),iYw=K.object({type:K.enum(["list","detail"]),seriesName:K.string().optional()});function dYw(A){let Q=iYw.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let w=pYw.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 Vi1(A){let Q=v2(A.content,wf);return h40.parse({...A,frontmatter:Q.metadata})}class Tp0{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=dYw(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=Vi1(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 $=Vi1(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(Fi1),w}}c0();Z0();bX();var nYw=K.object({prompt:K.string().optional(),title:K.string().optional(),seriesId:K.string().optional()}),rYw=K.object({title:K.string().optional(),excerpt:K.string().optional()});class y40{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),R7("header",{className:"printable-hero",children:[R7("div",{className:"printable-masthead",children:Q.brandLabel&&R7("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this),R7("div",{children:[R7("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.excerpt&&R7("p",{className:"printable-excerpt",children:Q.excerpt},void 0,!1,void 0,this),R7("div",{className:"printable-meta",children:[Q.author&&R7("span",{children:["By ",Q.author]},void 0,!0,void 0,this),w&&R7("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&&R7("figure",{className:"printable-cover-wrap",children:R7("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this)},void 0,!1,void 0,this),R7($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Q.canonicalUrl||Q.brandLabel)&&R7("footer",{className:"printable-footer",children:[R7("span",{children:Q.brandLabel??"Printable PDF"},void 0,!1,void 0,this),Q.canonicalUrl&&R7("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 MYw=26214400,_Yw=60000;class hp0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==R40)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=PYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await bYw(jYw(NYw(),"brain-blog-printable-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/printable/post/${Q.id}`,template:Xi1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:MYw,timeoutMs:_Yw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${kYw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await LYw(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 PYw(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 kYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}import{mkdtemp as vYw,rm as CYw}from"fs/promises";import{tmpdir as yYw}from"os";import{join as EYw}from"path";Z0();NH();Z0();import{jsxDEV as hYw}from"preact/jsx-dev-runtime";var jr="og-image",OYw="blog:og-image",Hi1=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()}),Wi1={name:OYw,pluginId:"blog",schema:Hi1,renderers:{image:RYw}};function xYw(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 RYw(A){let Q=Hi1.parse(A);return hYw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Journal",title:Q.title,subtitle:Q.excerpt,meta:[Q.author],tag:xYw(Q.publishedAt)},void 0,!1,void 0,this)}var gYw={width:1200,height:630},TYw=60000;class vp0{context;metadata={outputEntityType:"image",targetField:"ogImageId"};screenshotPng;constructor(A,Q={}){this.context=A;this.screenshotPng=Q.screenshotPng??Nr}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==jr)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let w=SYw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await vYw(EYw(yYw(),"brain-blog-og-image-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/og/post/${Q.id}`,template:Wi1,format:"image",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"image",data:await this.screenshotPng(Y.urlFor($.urlPath),gYw,{timeoutMs:TYw,fullPage:!1,omitBackground:!1}),mimeType:"image/png",filename:`${mYw(Q)}-og.png`}}finally{await Y.close()}}finally{await CYw(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 SYw(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 mYw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var fi1={name:"@brains/blog",private:!0,version:"0.2.0-alpha.139",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 Cp0 extends kQ{entityType=ZF.entityType;schema=ey;adapter=ZF;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("blog",fi1,A,Ip0)}getEntityTypeConfig(){return{weight:2,publish:{publishStatuses:["queued","published"]}}}createGenerationHandler(A){return new bp0(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return np1()}getDataSources(){return[new Np0(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (Ui1(),Ki1));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),rp1(A,this.logger),op1(A,this.logger),ap1(A,this.logger),tp1(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("post",R40,new hp0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("post",jr,new vp0(A)),this.deferPublishAssetRegistration(A),this.unregisterAtprotoProjection=U5.getInstance().register(_p0()),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:jr,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 yp0(A={}){return new Cp0(A)}NH();AE();c0();Z0();Z0();l$();c0();var wf=K.object({title:K.string(),slug:K.string(),coverImageId:K.string().optional()}),Gi1=wf.pick({title:!0,slug:!0}),Nb=o1.extend({metadata:Gi1}),h40=Nb.extend({frontmatter:wf}),v40=h40.extend({description:K.string().optional(),postCount:K.number(),coverImageUrl:K.string().optional(),coverImageWidth:K.number().optional(),coverImageHeight:K.number().optional()}),zi1=K.object({description:K.string().optional()});function GP(A){return new pw(zi1,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}c0();class Ep0 extends J2{constructor(){super({entityType:"series",purpose:"A series grouping related posts or content under one theme.",schema:Nb,frontmatterSchema:wf,supportsCoverImage:!0,bodyFormatter:GP("")})}toMarkdown(A){let Q,w={};try{Q=this.parseFrontMatter(A.content,wf).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,wf);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,wf);return GP(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var jb=new Ep0;c0();Z0();bX();Z0();var lYw=K.object({seriesName:K.string().optional(),seriesIndex:K.number().optional()});function C40(A){let Q=lYw.safeParse(A);return Q.success?Q.data:{}}function zP(A){return C40(A.metadata).seriesName}function qi1(A){return C40(A.metadata).seriesIndex}function Fi1(A,Q){let w=qi1(A)??Number.MAX_SAFE_INTEGER,B=qi1(Q)??Number.MAX_SAFE_INTEGER;return w-B}class gp0{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 Z7("",Q)}}c0();Z0();var pYw=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()}),iYw=K.object({type:K.enum(["list","detail"]),seriesName:K.string().optional()});function dYw(A){let Q=iYw.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let w=pYw.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 Vi1(A){let Q=v2(A.content,wf);return h40.parse({...A,frontmatter:Q.metadata})}class Tp0{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=dYw(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=Vi1(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 $=Vi1(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(Fi1),w}}c0();Z0();bX();var nYw=K.object({prompt:K.string().optional(),title:K.string().optional(),seriesId:K.string().optional()}),rYw=K.object({title:K.string().optional(),excerpt:K.string().optional()});class y40{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 Mi1({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 Sp0(){return{entityType:"series",collection:"ai.rizom.brain.series",lexicon:MB["ai.rizom.brain.series"],validate:!1,buildRecord:Mi1}}var _i1={name:"@brains/series",private:!0,version:"0.2.0-alpha.
|
|
5982
|
+
Be concise and focus on what makes this series unique and valuable.`});async function Mi1({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 Sp0(){return{entityType:"series",collection:"ai.rizom.brain.series",lexicon:MB["ai.rizom.brain.series"],validate:!1,buildRecord:Mi1}}var _i1={name:"@brains/series",private:!0,version:"0.2.0-alpha.139",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 Pi1=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 mp0 extends kQ{entityType="series";schema=Nb;adapter=jb;manager;unregisterAtprotoProjection;constructor(){super("series",_i1)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new y40(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...Ni1(),description:ji1}}getDataSources(){return[new Tp0(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=C40(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 gp0(A.entityService,this.logger.child("SeriesManager")),this.unregisterAtprotoProjection=U5.getInstance().register(Sp0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}createSeriesProjectionHandler(A){return{process:async(Q)=>{let w=Pi1.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=Pi1.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 y40(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 up0(){return new mp0}c0();Z0();c0();Z0();Z0();c0();var eYw=K.enum(["generating","draft","queued","published","failed"]),ki1="publishedAt is required when deck status is published",Oi1=(A)=>A.status==="published"&&!A.publishedAt,cp0=(A)=>{if(Oi1(A))throw Error(ki1)},Bf=K.object({title:K.string(),slug:K.string().optional(),description:K.string().optional(),author:K.string().optional(),status:eYw,publishedAt:K.string().datetime().optional(),event:K.string().optional(),coverImageId:K.string().optional(),ogImageId:K.string().optional()}),ADw=Bf.pick({title:!0,description:!0,status:!0,publishedAt:!0,coverImageId:!0}).extend({slug:K.string(),error:K.string().optional()}).superRefine((A,Q)=>{if(!Oi1(A))return;Q.addIssue({code:K.ZodIssueCode.custom,path:["publishedAt"],message:ki1})}),wE=o1.extend({entityType:K.literal("deck"),metadata:ADw}),E40=wE.extend({frontmatter:Bf,body:K.string(),ogImageUrl:K.string().optional()}),qP=E40.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 lp0 extends J2{constructor(){super({entityType:"deck",purpose:"A slide-deck presentation.",schema:wE,frontmatterSchema:Bf,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,Bf);cp0(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);cp0(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 Mr=new lp0;Z0();IB();var QDw=K.object({markdown:K.string().describe("Markdown content with slide separators (---)"),deck:qP.optional()}),pp0=R1({name:"deck-detail",description:"Render a presentation deck as Reveal.js slides",schema:QDw,dataSourceId:"decks:entities",requiredPermission:"public",layout:{component:xu0,fullscreen:!0}});IB();Z0();var ip0=K.object({decks:K.array(E40)}),dp0=K.object({decks:K.array(qP),pageTitle:K.string().optional(),pageLabel:K.string().optional()});import{jsxDEV as np0}from"preact/jsx-dev-runtime";var wDw="Presentations",rp0=({decks:A,pageLabel:Q})=>{let w=A.map(($)=>({id:$.id,url:$.url,title:$.frontmatter.title,date:$.frontmatter.publishedAt??$.created,description:$.frontmatter.description}));return np0("div",{className:"deck-list bg-theme",children:np0("div",{className:"container mx-auto max-w-[1100px] px-6 py-16 md:px-12 md:py-24",children:np0(Jn,{label:Q&&Q!=="Decks"?Q:wDw,items:w},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)};l$();class g40 extends pw{constructor(){super(ip0,{title:"Deck List",mappings:[{key:"decks",label:"Decks",type:"array",itemType:"object"}]})}}var op0=R1({name:"deck-list",description:"List view of all presentation decks",schema:dp0,dataSourceId:"decks:entities",requiredPermission:"public",formatter:new g40,layout:{component:rp0}});Z0();c0();var BDw=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")}),xi1=R1({name:"decks:generation",description:"Template for AI to generate complete slide decks from prompts",schema:BDw,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)=>k4("section",{className:`deck-carousel-slide${f===0?" is-cover":""}`,children:[k4("header",{className:"deck-carousel-header",children:k4("span",{className:"deck-carousel-wordmark","aria-label":w??Q,children:[k4("span",{className:"wm-primary",children:Y.primary},void 0,!1,void 0,this),Y.secondary!==void 0&&k4(WDw,{children:[k4("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),k4("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),k4("div",{className:"deck-carousel-body",children:k4("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:H(W.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),k4("footer",{className:"deck-carousel-footer",children:[k4("span",{className:"deck-carousel-footer-meta",children:B??Q},void 0,!1,void 0,this),k4("span",{className:"deck-carousel-counter","aria-label":`Slide ${f+1} of ${D}`,children:[k4("span",{className:"deck-carousel-counter-current",children:String(f+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",k4("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 fDw,rm as ZDw}from"fs/promises";import{tmpdir as KDw}from"os";import{join as UDw}from"path";Z0();var GDw=26214400,zDw=60000,yi1=20;class tp0{context;metadata={outputEntityType:"document"};renderPdf;getThemeMode;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK,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=qDw(Q,{brandLabel:this.resolveBrandLabel()});if(w.slides.length>yi1)throw Error(`Refusing to render carousel with ${w.slides.length} slides; maxSlides=${yi1}`);let B=await this.getThemeMode(),$=await fDw(UDw(KDw(),"brain-deck-carousel-"));try{let Y=await MH({outputDir:$,mediaPath:`/_media/carousel/${Q.id}`,template:Ci1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:B},themeCSS:this.context.themeCSS}),D=await _H({rootDir:$});try{return{type:"document",data:await this.renderPdf(D.urlFor(Y.urlPath),{maxBytes:GDw,timeoutMs:zDw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${FDw(Q)}-carousel.pdf`}}finally{await D.close()}}finally{await ZDw($,{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 qDw(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 FDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();import{jsxDEV as IDw}from"preact/jsx-dev-runtime";var T40="og-image",VDw="decks:og-image",Ei1=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()}),gi1={name:VDw,pluginId:"decks",schema:Ei1,renderers:{image:JDw}};function JDw(A){let Q=Ei1.parse(A),w=Q.slideCount?`${Q.slideCount} slide${Q.slideCount===1?"":"s"}`:void 0;return IDw(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 ep0{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!==T40)return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w,content:B}=lw(Q.content),$=Bf.parse(w),Y=bDw(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:gi1,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:`${LDw(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 bDw(A){return A.split(/^---$/gm).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).length}function LDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}c0();async function Ti1({entity:A,config:Q}){let w=wE.parse(A),B=v2(w.content,Bf),$=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 Ai0(){return{entityType:"deck",collection:"ai.rizom.brain.deck",lexicon:MB["ai.rizom.brain.deck"],validate:!1,buildRecord:Ti1}}var Si1={name:"@brains/decks",private:!0,version:"0.2.0-alpha.
|
|
6290
|
+
`}},void 0,!1,void 0,this),$.map((W,f)=>k4("section",{className:`deck-carousel-slide${f===0?" is-cover":""}`,children:[k4("header",{className:"deck-carousel-header",children:k4("span",{className:"deck-carousel-wordmark","aria-label":w??Q,children:[k4("span",{className:"wm-primary",children:Y.primary},void 0,!1,void 0,this),Y.secondary!==void 0&&k4(WDw,{children:[k4("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),k4("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),k4("div",{className:"deck-carousel-body",children:k4("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:H(W.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),k4("footer",{className:"deck-carousel-footer",children:[k4("span",{className:"deck-carousel-footer-meta",children:B??Q},void 0,!1,void 0,this),k4("span",{className:"deck-carousel-counter","aria-label":`Slide ${f+1} of ${D}`,children:[k4("span",{className:"deck-carousel-counter-current",children:String(f+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",k4("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 fDw,rm as ZDw}from"fs/promises";import{tmpdir as KDw}from"os";import{join as UDw}from"path";Z0();var GDw=26214400,zDw=60000,yi1=20;class tp0{context;metadata={outputEntityType:"document"};renderPdf;getThemeMode;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK,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=qDw(Q,{brandLabel:this.resolveBrandLabel()});if(w.slides.length>yi1)throw Error(`Refusing to render carousel with ${w.slides.length} slides; maxSlides=${yi1}`);let B=await this.getThemeMode(),$=await fDw(UDw(KDw(),"brain-deck-carousel-"));try{let Y=await MH({outputDir:$,mediaPath:`/_media/carousel/${Q.id}`,template:Ci1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:B},themeCSS:this.context.themeCSS}),D=await _H({rootDir:$});try{return{type:"document",data:await this.renderPdf(D.urlFor(Y.urlPath),{maxBytes:GDw,timeoutMs:zDw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${FDw(Q)}-carousel.pdf`}}finally{await D.close()}}finally{await ZDw($,{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 qDw(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 FDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();import{jsxDEV as IDw}from"preact/jsx-dev-runtime";var T40="og-image",VDw="decks:og-image",Ei1=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()}),gi1={name:VDw,pluginId:"decks",schema:Ei1,renderers:{image:JDw}};function JDw(A){let Q=Ei1.parse(A),w=Q.slideCount?`${Q.slideCount} slide${Q.slideCount===1?"":"s"}`:void 0;return IDw(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 ep0{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!==T40)return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w,content:B}=lw(Q.content),$=Bf.parse(w),Y=bDw(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:gi1,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:`${LDw(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 bDw(A){return A.split(/^---$/gm).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).length}function LDw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}c0();async function Ti1({entity:A,config:Q}){let w=wE.parse(A),B=v2(w.content,Bf),$=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 Ai0(){return{entityType:"deck",collection:"ai.rizom.brain.deck",lexicon:MB["ai.rizom.brain.deck"],validate:!1,buildRecord:Ti1}}var Si1={name:"@brains/decks",private:!0,version:"0.2.0-alpha.139",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 Qi0 extends kQ{deps;entityType=Mr.entityType;schema=Mr.schema;adapter=Mr;unregisterCarouselAttachmentProvider;unregisterOgImageAttachmentProvider;unregisterAtprotoProjection;constructor(A={}){super("decks",Si1);this.deps=A}createGenerationHandler(A){return new ap0(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":pp0,"deck-list":op0,generation:xi1,description:Ri1}}getDataSources(){return[new sp0(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(Ai0()),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 Fr(A.entityService)).themeMode??"dark"}catch{return"dark"}})};this.unregisterCarouselAttachmentProvider=A.attachments.register("deck",hi1,new tp0(A,Q))}registerOgImageAttachmentProvider(A){this.unregisterOgImageAttachmentProvider=A.attachments.register("deck",T40,new ep0(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 Pr(){return new Qi0}c0();Z0();Z0();aB();var wi0=K.literal("application/pdf"),mi1=K.enum(["pending","draft","failed"]),Bi0=K.object({title:K.string().optional(),mimeType:wi0,filename:K.string().min(1),pageCount:K.number().int().min(0).optional(),status:mi1.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:Bi0});function kr(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 S40(A){return`data:application/pdf;base64,${Buffer.from(A).toString("base64")}`}function $i0(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 m40{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 kr(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}=kr(Q);return{entityType:"document",content:Q,metadata:{mimeType:B,...w}}}}var KF=new m40;async function ci0(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(() => (on1(),rn1))).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 DXw}from"crypto";var XXw=26214400,HXw=20,WXw=60000,sn1=80,fXw=10,li0=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()}),Ao=li0.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 PY0 extends _w{context;renderPdf;constructor(A,Q,w={}){super(A,{schema:Ao,jobTypeName:"document-generate"});this.context=Q;this.renderPdf=w.renderPdf??JK}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??HXw,$=A.maxBytes??XXw,Y=A.timeoutMs??WXw;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=kY0(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=$i0(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:S40(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 NX({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 GU({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(KXw):[],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:a4($.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||!UXw(Y,w))B.push($)}return B}}function kY0(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 ZXw($)}function ZXw(A){let Q=w1(A.replace(/[/:]+/g," "))||`document-${an1(A)}`;if(Q.length<=sn1)return Q;let w=`-${an1(A)}`;return`${Q.slice(0,sn1-w.length).replace(/-+$/g,"")}${w}`}function an1(A){return DXw("sha256").update(A).digest("hex").slice(0,fXw)}function KXw(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}function UXw(A,Q){return A.metadata.sourceEntityType===Q.sourceEntityType&&A.metadata.sourceEntityId===Q.sourceEntityId&&A.metadata.attachmentType===Q.attachmentType}var tn1={name:"@brains/document-plugin",private:!0,version:"0.2.0-alpha.
|
|
6297
|
+
`).trim();if(!X)throw Error("Could not extract text from the uploaded PDF");return X}finally{await $.destroy()}}c0();Z0();import{createHash as DXw}from"crypto";var XXw=26214400,HXw=20,WXw=60000,sn1=80,fXw=10,li0=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()}),Ao=li0.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 PY0 extends _w{context;renderPdf;constructor(A,Q,w={}){super(A,{schema:Ao,jobTypeName:"document-generate"});this.context=Q;this.renderPdf=w.renderPdf??JK}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??HXw,$=A.maxBytes??XXw,Y=A.timeoutMs??WXw;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=kY0(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=$i0(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:S40(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 NX({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 GU({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(KXw):[],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:a4($.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||!UXw(Y,w))B.push($)}return B}}function kY0(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 ZXw($)}function ZXw(A){let Q=w1(A.replace(/[/:]+/g," "))||`document-${an1(A)}`;if(Q.length<=sn1)return Q;let w=`-${an1(A)}`;return`${Q.slice(0,sn1-w.length).replace(/-+$/g,"")}${w}`}function an1(A){return DXw("sha256").update(A).digest("hex").slice(0,fXw)}function KXw(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}function UXw(A,Q){return A.metadata.sourceEntityType===Q.sourceEntityType&&A.metadata.sourceEntityId===Q.sourceEntityId&&A.metadata.attachmentType===Q.attachmentType}var tn1={name:"@brains/document-plugin",private:!0,version:"0.2.0-alpha.139",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 zXw=`data:application/pdf;base64,${Buffer.from(`%PDF-1.4
|
|
6298
6298
|
% Pending document placeholder
|
|
6299
6299
|
%%EOF
|
|
6300
6300
|
`).toString("base64")}`,qXw=K.object({}),pi0={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function FXw(A,Q){let w=A.title?.trim();if(w)return w;return Q.replace(/\.[^.]+$/,"").trim()||Q}function VXw(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function JXw(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 ii0 extends IQ{entityType=KF.entityType;schema=BE;adapter=KF;pluginContext;constructor(){super("document",tn1,{},qXw)}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 PY0(this.logger.child("DocumentGenerationJobHandler"),A))}async interceptCreate(A){let Q=this.pluginContext;if(A.from?.kind===pi0.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=Ao.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??kY0(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!==pi0.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let B;try{B=await Q.uploads.scoped(pi0).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 $=FXw(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:VXw(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:JXw({entityId:H.entityId,filename:B.record.filename})}}}}async createPendingDocument(A,Q){let w=new Date().toISOString(),B=KF.createDocumentEntity({dataUrl:zXw,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 di0(){return new ii0}c0();c0();Z0();Z0();c0();var IXw=K.enum(["generating","failed"]),FF=K.object({title:K.string().optional(),status:IXw.optional(),error:K.string().optional()}),en1=FF.pick({title:!0,status:!0,error:!0}).extend({title:K.string()}),xb=o1.extend({entityType:K.literal("note"),metadata:en1}),bXw=xb.extend({frontmatter:FF,body:K.string()});c0();Z0();class ni0 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 ni0;Z0();var ri0=K.object({defaultPrompt:K.string().default("Create a note summarizing key concepts from my knowledge base")});Z0();c0();var Ar1=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")}),oi0=R1({name:"note:generation",description:"Template for AI to generate notes from prompts",schema:Ar1,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 _Xw={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},PXw=K.object({uploadId:K.string().min(1),title:K.string().optional()});class ai0 extends _w{context;constructor(A,Q){super(A,{schema:PXw,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(_Xw).read(A.uploadId);await this.reportProgress(w,{progress:35,message:"Extracting markdown from upload"});let $=await $r1({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 Yr1({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 ti0(){return{entityType:"note",collection:"ai.rizom.brain.note",lexicon:MB["ai.rizom.brain.note"],validate:!1,buildRecord:Yr1}}var Dr1={name:"@brains/note",private:!0,version:"0.2.0-alpha.
|
|
6315
|
+
`}var _Xw={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},PXw=K.object({uploadId:K.string().min(1),title:K.string().optional()});class ai0 extends _w{context;constructor(A,Q){super(A,{schema:PXw,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(_Xw).read(A.uploadId);await this.reportProgress(w,{progress:35,message:"Extracting markdown from upload"});let $=await $r1({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 Yr1({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 ti0(){return{entityType:"note",collection:"ai.rizom.brain.note",lexicon:MB["ai.rizom.brain.note"],validate:!1,buildRecord:Yr1}}var Dr1={name:"@brains/note",private:!0,version:"0.2.0-alpha.139",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 Xr1={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};class ei0 extends kQ{entityType=Rb.entityType;schema=xb;adapter=Rb;unregisterAtprotoProjection;constructor(A={}){super("note",Dr1,A,ri0)}async interceptCreate(A,Q,w){if(A.from?.kind!==Xr1.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(Xr1).readRecord(B)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}try{if(!Br1($.mediaType))return{kind:"handled",result:{success:!1,error:"Only text, JSON, and PDF uploads can be imported as markdown notes"}};let Y=si0({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 OY0(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:oi0}}async onRegister(A){A.jobs.registerHandler("upload-import",new ai0(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(ti0())}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 ei0(A)}c0();Z0();Z0();c0();var Hr1=K.object({ref:K.string(),label:K.string()}),Wr1=K.enum(["pending","draft","published"]),VF=K.object({status:Wr1,title:K.string(),url:K.string().url(),description:K.string().optional(),domain:K.string(),capturedAt:K.string().datetime(),source:Hr1}),fr1=VF.pick({title:!0,status:!0}),NP=o1.extend({entityType:K.literal("link"),metadata:fr1}),Ad0=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 OXw=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.")}),Zr1=R1({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:OXw,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 vXw}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=vXw("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 CXw=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()}),mn8=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 RY0 extends _w{context;linkAdapter;urlFetcher;constructor(A,Q,w){super(A,{schema:CXw,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}`,L=this.linkAdapter.createLinkContent({status:"pending",title:F,url:B,description:V,summary:V,domain:F,capturedAt:H,source:X});return await NX({entityService:this.context.entityService,entity:{id:Y,entityType:"link",content:L,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}),L=await NX({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:L.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 NX({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 Gr1({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 Dd0(){return{entityType:"link",collection:"ai.rizom.brain.link",lexicon:MB["ai.rizom.brain.link"],validate:!1,buildRecord:Gr1}}var zr1={name:"@brains/link",private:!0,version:"0.2.0-alpha.
|
|
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}),L=await NX({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:L.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 NX({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 Gr1({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 Dd0(){return{entityType:"link",collection:"ai.rizom.brain.link",lexicon:MB["ai.rizom.brain.link"],validate:!1,buildRecord:Gr1}}var zr1={name:"@brains/link",private:!0,version:"0.2.0-alpha.139",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 Xd0 extends kQ{entityType=FE.entityType;schema=NP;adapter=FE;shell;unregisterAtprotoProjection;constructor(A={}){super("link",zr1,A,Ad0)}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 RY0(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 RY0(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:Zr1,"link-list":Kr1,"link-detail":Ur1}}getDataSources(){return[new Yd0(this.logger.child("LinksDataSource"))]}async onRegister(A){this.unregisterAtprotoProjection=U5.getInstance().register(Dd0()),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 qr1(A={}){return new Xd0(A)}var jP=qr1;Z0();var Kr8=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 Fr1=K.enum(["generating","draft","published","failed"]),H9=K.object({title:K.string(),slug:K.string().optional(),status:Fr1,publishedAt:K.string().datetime().optional(),description:K.string(),year:K.number(),coverImageId:K.string().optional(),ogImageId:K.string().optional(),url:K.string().url().optional()}),Vr1=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:Vr1}),hY0=K.object({context:K.string(),problem:K.string(),solution:K.string(),outcome:K.string()}),wo=Cb.extend({frontmatter:H9,body:K.string(),structuredContent:hY0.optional(),coverImageUrl:K.string().optional(),ogImageUrl:K.string().optional()}),JE=wo.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()}),EXw=wo.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 Hd0 extends pw{constructor(){super(hY0,{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 Wd0=new Hd0;class fd0 extends J2{constructor(){super({entityType:"project",purpose:"A project record in the user's portfolio.",schema:Cb,frontmatterSchema:H9,supportsCoverImage:!0,bodyFormatter:Wd0})}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 Wd0.parse(this.extractBody(A.content))}createProjectContent(A,Q){let w=Wd0.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 fd0;Z0();var Zd0=K.object({});import{jsxDEV as hH,Fragment as TXw}from"preact/jsx-dev-runtime";var gXw=({project:A})=>{let{frontmatter:Q,url:w,coverImageUrl:B}=A;return hH(uw,{href:w,children:[B&&hH("img",{src:B,alt:Q.title,className:"w-full h-56 object-cover rounded-md mb-4"},void 0,!1,void 0,this),hH(n9,{children:Q.title},void 0,!1,void 0,this),hH("p",{className:"text-theme leading-relaxed",children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Kd0=({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 hH(TXw,{children:[hH(jQ,{title:$,description:D},void 0,!1,void 0,this),hH("div",{className:"project-list bg-theme",children:hH("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[hH("h1",{className:"text-4xl font-bold text-heading mb-12",children:$},void 0,!1,void 0,this),hH("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:A.map((X)=>hH(gXw,{project:X},X.id,!1,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&hH("div",{className:"mt-12",children:hH(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 Jr1}from"preact/jsx-dev-runtime";var SXw=({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)},vY0=({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)},Ud0=({project:A,prevProject:Q,nextProject:w})=>{let{frontmatter:B,structuredContent:$,metadata:Y,coverImageUrl:D}=A,X=A.ogImageUrl??D;return zB(Jr1,{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(Jr1,{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(vY0,{title:"Context",content:$.context},void 0,!1,void 0,this),zB(vY0,{title:"Problem",content:$.problem},void 0,!1,void 0,this),zB(vY0,{title:"Solution",content:$.solution},void 0,!1,void 0,this),zB(vY0,{title:"Outcome",content:$.outcome},void 0,!1,void 0,this)]},void 0,!0,void 0,this),zB(SXw,{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 mXw=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)")}),Gd0=R1({name:"portfolio:generation",description:"Template for AI to generate portfolio project case studies",schema:mXw,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 oXw=26214400,sXw=60000;class Fd0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==EY0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let w=aXw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await iXw(rXw(nXw(),"brain-project-printable-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/printable/project/${Q.id}`,template:Lr1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:oXw,timeoutMs:sXw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${tXw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await dXw(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 aXw(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 tXw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();Z0();import{jsxDEV as QHw}from"preact/jsx-dev-runtime";var gY0="og-image",eXw="portfolio:og-image",Nr1=K.object({title:K.string().min(1),description:K.string().optional(),year:K.number().optional(),brandLabel:K.string().optional(),coverImageUrl:K.string().optional()}),jr1={name:eXw,pluginId:"portfolio",schema:Nr1,renderers:{image:AHw}};function AHw(A){let Q=Nr1.parse(A);return QHw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Project",title:Q.title,subtitle:Q.description,tag:Q.year},void 0,!1,void 0,this)}class Vd0{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!==gY0)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:jr1,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:`${wHw(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 wHw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var Mr1={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.138",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 $Hw=K.object({projects:K.array(JE),pageTitle:K.string().optional(),pagination:A4.nullable(),baseUrl:K.string().optional()});function YHw(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 Jd0 extends kQ{entityType=yb.entityType;schema=Cb;adapter=yb;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("portfolio",Mr1,A,Zd0)}async interceptCreate(A,Q,w){if(!A.prompt||A.content)return{kind:"continue",input:A};let B=YHw(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 CY0(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":R1({name:"project-list",description:"Portfolio project list page template",schema:$Hw,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:Kd0}}),"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:Ud0}}),generation:Gd0}}getDataSources(){return[new yY0(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("project",EY0,new Fd0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("project",gY0,new Vd0(A)),this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.unregisterAtprotoProjection=U5.getInstance().register(qd0())}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:zd0(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=Z7(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 Id0(A={}){return new Jd0(A)}c0();Z0();var DHw=K.enum(["public","shared","restricted"]),_r1=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:DHw.default("public"),sourceChangeBatchDelayMs:K.number().int().min(0).default(1000)});c0();Z0();c0();var XHw=K.object({}),IE=o1.extend({entityType:K.literal("topic"),metadata:XHw}),Xs8=K.object({content:K.string()}),Pr1=K.object({title:K.string().describe("Topic title")});var MP="topics",qB="topic",bd0="topics-projection",kr1="topic:project",TY0="topics-plugin",Or1="topics:batch-completed",xr1="topics-source-batch";class bK extends J2{constructor(){super({entityType:qB,purpose:"A recurring theme or subject derived from the user's content.",schema:IE,frontmatterSchema:Pr1})}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 HHw=K.object({title:K.string().max(100),content:K.string(),relevanceScore:K.number().min(0).max(1)}),Rr1=K.array(HHw);var WHw=K.object({topics:Rr1}),hr1=R1({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:WHw,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 oXw=26214400,sXw=60000;class Fd0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==EY0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let w=aXw(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),B=await iXw(rXw(nXw(),"brain-project-printable-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/printable/project/${Q.id}`,template:Lr1,format:"pdf",content:w,siteConfig:{title:w.title,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:oXw,timeoutMs:sXw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${tXw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await dXw(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 aXw(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 tXw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}Z0();Z0();import{jsxDEV as QHw}from"preact/jsx-dev-runtime";var gY0="og-image",eXw="portfolio:og-image",Nr1=K.object({title:K.string().min(1),description:K.string().optional(),year:K.number().optional(),brandLabel:K.string().optional(),coverImageUrl:K.string().optional()}),jr1={name:eXw,pluginId:"portfolio",schema:Nr1,renderers:{image:AHw}};function AHw(A){let Q=Nr1.parse(A);return QHw(d3,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Project",title:Q.title,subtitle:Q.description,tag:Q.year},void 0,!1,void 0,this)}class Vd0{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!==gY0)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:jr1,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:`${wHw(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 wHw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.title)}var Mr1={name:"@brains/portfolio",private:!0,version:"0.2.0-alpha.139",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 $Hw=K.object({projects:K.array(JE),pageTitle:K.string().optional(),pagination:A4.nullable(),baseUrl:K.string().optional()});function YHw(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 Jd0 extends kQ{entityType=yb.entityType;schema=Cb;adapter=yb;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("portfolio",Mr1,A,Zd0)}async interceptCreate(A,Q,w){if(!A.prompt||A.content)return{kind:"continue",input:A};let B=YHw(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 CY0(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":R1({name:"project-list",description:"Portfolio project list page template",schema:$Hw,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:Kd0}}),"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:Ud0}}),generation:Gd0}}getDataSources(){return[new yY0(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("project",EY0,new Fd0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("project",gY0,new Vd0(A)),this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.unregisterAtprotoProjection=U5.getInstance().register(qd0())}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:zd0(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=Z7(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 Id0(A={}){return new Jd0(A)}c0();Z0();var DHw=K.enum(["public","shared","restricted"]),_r1=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:DHw.default("public"),sourceChangeBatchDelayMs:K.number().int().min(0).default(1000)});c0();Z0();c0();var XHw=K.object({}),IE=o1.extend({entityType:K.literal("topic"),metadata:XHw}),Xs8=K.object({content:K.string()}),Pr1=K.object({title:K.string().describe("Topic title")});var MP="topics",qB="topic",bd0="topics-projection",kr1="topic:project",TY0="topics-plugin",Or1="topics:batch-completed",xr1="topics-source-batch";class bK extends J2{constructor(){super({entityType:qB,purpose:"A recurring theme or subject derived from the user's content.",schema:IE,frontmatterSchema:Pr1})}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 HHw=K.object({title:K.string().max(100),content:K.string(),relevanceScore:K.number().min(0).max(1)}),Rr1=K.array(HHw);var WHw=K.object({topics:Rr1}),hr1=R1({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:WHw,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 IHw(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=lr1(A),W=new LK(Q.entityService,w),f=B.topicMergeSynthesizer??new Pd0(Q,w),Z=await lY0(Q.entityService,void 0,X),G=new Map,F=0,V=0,L=0;for(let N of H){w.info(`Processing batch of ${N.length} entities`);let _=IHw(N),j=pY0({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)){L++;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 L++}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 b={created:F,merged:V,skipped:L,batches:H.length};if(F>0||V>0)await Q.messaging.send({type:Or1,payload:b,broadcast:!0});return b}c0();Z0();var bHw=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 kd0{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 or1(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 LHw({context:Q,logger:w,config:B,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:$.minRelevanceScore??B.minRelevanceScore})},validateAndParse:($)=>{let Y=bHw.safeParse($??{});return Y.success?Y.data:null}}}async function LHw(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 sr1(){return{priority:5,source:TY0,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:MP}}}async function ar1(A){let Q=await er1(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 tr1(A){let Q=await er1(A),w=await Od0(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",w)}async function Od0(A,Q,w,B){let $=new LK(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 er1(A){let Q=NHw(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 NHw(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()}),MHw=K.object({contentA:NE,contentB:NE,minRelevanceScore:K.number().optional(),threshold:K.number().min(0).max(1).optional()}),Do=K.object({title:K.string(),content:K.string()}),_Hw=K.object({existingTopics:K.array(Do),incomingTopic:Do,threshold:K.number().optional()}),PHw=K.object({existingTopics:K.array(Do).default([]),incomingTopic:Do.extend({relevanceScore:K.number().min(0).max(1).optional()}),threshold:K.number().optional()}),kHw=K.object({entities:K.array(NE).min(1),minRelevanceScore:K.number().optional()}),OHw=K.object({existingTopics:K.array(Do).optional(),entities:K.array(NE)}),xHw=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 Ao1(A){return{title:A.title,relevanceScore:A.relevanceScore}}function RHw(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function hHw(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:RHw(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 vHw(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise((w)=>setTimeout(w,100))}}function Qo1(A){let{context:Q,logger:w,config:B}=A,$=new _d0(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)=>hHw(Z,W))}),Q.eval.registerHandler("checkMergeSimilarity",async(D)=>{await PP(Q);let X=MHw.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 LK(Q.entityService,w),F=[];for(let b of f){let N=await G.createTopic(b);if(N)F.push(N)}let V=(await Promise.all(Z.map(async(b)=>{let N=await G.findMergeCandidate({incoming:b,threshold:W,additionalCandidates:F});if(!N)return null;return{incomingTitle:b.title,candidateTitle:N.title,candidateScore:N.score}}))).filter((b)=>b!==null),L=V.map((b)=>b.candidateTitle);return{topicsA:f.map(Ao1),topicsB:Z.map(Ao1),matchingTitles:L,mergeCandidates:V,wouldMerge:V.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(D)=>{await PP(Q);let X=_Hw.parse(D),H=X.threshold??B.mergeSimilarityThreshold,W=new LK(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=PHw.parse(D),H=new LK(Q.entityService,w);for(let G of X.existingTopics)await H.createTopic({title:G.title,content:G.content});await vHw(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(jd0)}}),Q.eval.registerHandler("rebuildTopics",async(D)=>{await PP(Q);let X=OHw.parse(D),H=new LK(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 Od0(W,Q,w,B),Z=await Q.entityService.listEntities({entityType:qB});return{...f,topicCount:Z.length,topics:Z.map(jd0)}}),Q.eval.registerHandler("extractSequentially",async(D)=>{await PP(Q);let X=kHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=new LK(Q.entityService,w),f=[];for(let[G,F]of X.entities.entries()){let V=LE(F,`-sequential-${G}`),L=await $.extractFromEntity(V,H);for(let b of L)await W.createTopic({title:b.title,content:b.content});f.push({extractedTitles:L.map((b)=>b.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=xHw.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 CHw=new bK;async function wo1({entity:A,config:Q}){let w=IE.parse(A),B=CHw.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 xd0(){return{entityType:"topic",collection:"ai.rizom.brain.topic",lexicon:MB["ai.rizom.brain.topic"],validate:!1,buildRecord:wo1}}var Bo1={name:"@brains/topics",private:!0,version:"0.2.0-alpha.138",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 EHw=new bK;class $o1 extends kQ{entityType=qB;schema=IE;adapter=EHw;unregisterAtprotoProjection;sourceBatch=new kd0;constructor(A={}){super(MP,Bo1,A,_r1)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:hr1,"merge-synthesis":vr1,"topic-list":Cr1,"topic-detail":yr1}}getDataSources(){return[new Md0(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:bd0,targetType:qB,job:{type:kr1,handler:or1({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:sr1()},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:TY0,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:xr1,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:MP}})}}]}async onRegister(A){A.insights.register("topic-distribution",Tr1()),Sr1({context:A,pluginId:this.id}),Qo1({context:A,logger:this.logger,config:this.config}),this.unregisterAtprotoProjection=U5.getInstance().register(xd0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(bd0)?.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 ar1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await tr1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function iY0(A){return new $o1(A)}c0();Z0();c0();var Rd0=K.enum(["linkedin"]),hd0=K.enum(["generating","draft","queued","published","failed"]),Yo1=K.enum(["post","deck"]),Do1=K.object({id:K.string().min(1).describe("Document entity ID")}),Xf=K.object({title:K.string().describe("Short descriptive title (3-6 words) for file naming"),platform:Rd0.describe("Target platform"),status:hd0,coverImageId:K.string().optional().describe("Image entity ID for post image"),documents:K.array(Do1).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:Yo1.optional().describe("Source entity type (post, deck)")}),Xo1=Xf.extend({platform:Rd0.optional(),status:hd0.optional()}),Ho1=Xf.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:Ho1}),dY0=Eb.extend({frontmatter:Xf,body:K.string()}),nY0=dY0.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 vd0 extends J2{constructor(){super({entityType:"social-post",purpose:"A short post drafted for social media such as LinkedIn or X.",schema:Eb,frontmatterSchema:Xf,supportsCoverImage:!0})}toMarkdown(A){let Q="",w={};try{w=this.parseFrontMatter(A.content,Xf),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,Xo1),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,Xf)}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 v7=new vd0;c0();c0();Z0();var gHw=FU.extend({platform:K.enum(["linkedin"]).optional(),status:K.enum(["generating","draft","queued","published","failed"]).optional(),sortByQueue:K.boolean().optional(),nextInQueue:K.boolean().optional()}),THw=VU.extend({query:gHw.optional()});function Wo1(A){let Q=v2(A.content,Xf);return dY0.parse({...A,frontmatter:Q.metadata,body:Q.content})}class rY0 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=THw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return Wo1(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?Wo1(B):null;return A.parse({post:$})}}Z0();var fo1=K.object({accessToken:K.string().optional(),refreshToken:K.string().optional(),organizationId:K.string().optional(),apiVersion:K.string().regex(/^\d{6}$/).optional()}),Cd0=K.object({linkedin:fo1.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();Ed0();import{jsxDEV as c5,Fragment as uHw}from"preact/jsx-dev-runtime";function SHw(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function mHw(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var sY0=({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(uHw,{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:mHw(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(CD,{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:SHw(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 cHw}from"preact/jsx-dev-runtime";function Zo1(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var aY0=({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(cHw,{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(PG,{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(CD,{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)," ",Zo1(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)," ",Zo1(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 Xo(A){return`social-media:${A}`}var lHw=K.union([K.boolean(),K.object({generate:K.boolean().optional(),prompt:K.string().optional()})]),gd0=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:lHw.optional().describe("Generic cover image generation request")}),pHw=GX.extend({slug:K.string().optional()});class kP extends w4{constructor(A,Q){super(A,Q,{schema:gd0,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 b=await this.context.ai.generate({prompt:X,templateName:Xo(w)});H=b.title,X=b.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 b=await this.context.entityService.getEntity({entityType:Y,id:D});if(!b)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(b.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=lr1(A),W=new LK(Q.entityService,w),f=B.topicMergeSynthesizer??new Pd0(Q,w),Z=await lY0(Q.entityService,void 0,X),G=new Map,F=0,V=0,L=0;for(let N of H){w.info(`Processing batch of ${N.length} entities`);let _=IHw(N),j=pY0({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)){L++;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 L++}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 b={created:F,merged:V,skipped:L,batches:H.length};if(F>0||V>0)await Q.messaging.send({type:Or1,payload:b,broadcast:!0});return b}c0();Z0();var bHw=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 kd0{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 or1(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 LHw({context:Q,logger:w,config:B,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:$.minRelevanceScore??B.minRelevanceScore})},validateAndParse:($)=>{let Y=bHw.safeParse($??{});return Y.success?Y.data:null}}}async function LHw(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 sr1(){return{priority:5,source:TY0,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:MP}}}async function ar1(A){let Q=await er1(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 tr1(A){let Q=await er1(A),w=await Od0(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",w)}async function Od0(A,Q,w,B){let $=new LK(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 er1(A){let Q=NHw(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 NHw(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()}),MHw=K.object({contentA:NE,contentB:NE,minRelevanceScore:K.number().optional(),threshold:K.number().min(0).max(1).optional()}),Do=K.object({title:K.string(),content:K.string()}),_Hw=K.object({existingTopics:K.array(Do),incomingTopic:Do,threshold:K.number().optional()}),PHw=K.object({existingTopics:K.array(Do).default([]),incomingTopic:Do.extend({relevanceScore:K.number().min(0).max(1).optional()}),threshold:K.number().optional()}),kHw=K.object({entities:K.array(NE).min(1),minRelevanceScore:K.number().optional()}),OHw=K.object({existingTopics:K.array(Do).optional(),entities:K.array(NE)}),xHw=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 Ao1(A){return{title:A.title,relevanceScore:A.relevanceScore}}function RHw(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function hHw(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:RHw(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 vHw(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise((w)=>setTimeout(w,100))}}function Qo1(A){let{context:Q,logger:w,config:B}=A,$=new _d0(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)=>hHw(Z,W))}),Q.eval.registerHandler("checkMergeSimilarity",async(D)=>{await PP(Q);let X=MHw.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 LK(Q.entityService,w),F=[];for(let b of f){let N=await G.createTopic(b);if(N)F.push(N)}let V=(await Promise.all(Z.map(async(b)=>{let N=await G.findMergeCandidate({incoming:b,threshold:W,additionalCandidates:F});if(!N)return null;return{incomingTitle:b.title,candidateTitle:N.title,candidateScore:N.score}}))).filter((b)=>b!==null),L=V.map((b)=>b.candidateTitle);return{topicsA:f.map(Ao1),topicsB:Z.map(Ao1),matchingTitles:L,mergeCandidates:V,wouldMerge:V.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(D)=>{await PP(Q);let X=_Hw.parse(D),H=X.threshold??B.mergeSimilarityThreshold,W=new LK(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=PHw.parse(D),H=new LK(Q.entityService,w);for(let G of X.existingTopics)await H.createTopic({title:G.title,content:G.content});await vHw(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(jd0)}}),Q.eval.registerHandler("rebuildTopics",async(D)=>{await PP(Q);let X=OHw.parse(D),H=new LK(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 Od0(W,Q,w,B),Z=await Q.entityService.listEntities({entityType:qB});return{...f,topicCount:Z.length,topics:Z.map(jd0)}}),Q.eval.registerHandler("extractSequentially",async(D)=>{await PP(Q);let X=kHw.parse(D),H=X.minRelevanceScore??B.minRelevanceScore,W=new LK(Q.entityService,w),f=[];for(let[G,F]of X.entities.entries()){let V=LE(F,`-sequential-${G}`),L=await $.extractFromEntity(V,H);for(let b of L)await W.createTopic({title:b.title,content:b.content});f.push({extractedTitles:L.map((b)=>b.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=xHw.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 CHw=new bK;async function wo1({entity:A,config:Q}){let w=IE.parse(A),B=CHw.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 xd0(){return{entityType:"topic",collection:"ai.rizom.brain.topic",lexicon:MB["ai.rizom.brain.topic"],validate:!1,buildRecord:wo1}}var Bo1={name:"@brains/topics",private:!0,version:"0.2.0-alpha.139",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 EHw=new bK;class $o1 extends kQ{entityType=qB;schema=IE;adapter=EHw;unregisterAtprotoProjection;sourceBatch=new kd0;constructor(A={}){super(MP,Bo1,A,_r1)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:hr1,"merge-synthesis":vr1,"topic-list":Cr1,"topic-detail":yr1}}getDataSources(){return[new Md0(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:bd0,targetType:qB,job:{type:kr1,handler:or1({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:sr1()},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:TY0,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:xr1,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:MP}})}}]}async onRegister(A){A.insights.register("topic-distribution",Tr1()),Sr1({context:A,pluginId:this.id}),Qo1({context:A,logger:this.logger,config:this.config}),this.unregisterAtprotoProjection=U5.getInstance().register(xd0())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(bd0)?.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 ar1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await tr1({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function iY0(A){return new $o1(A)}c0();Z0();c0();var Rd0=K.enum(["linkedin"]),hd0=K.enum(["generating","draft","queued","published","failed"]),Yo1=K.enum(["post","deck"]),Do1=K.object({id:K.string().min(1).describe("Document entity ID")}),Xf=K.object({title:K.string().describe("Short descriptive title (3-6 words) for file naming"),platform:Rd0.describe("Target platform"),status:hd0,coverImageId:K.string().optional().describe("Image entity ID for post image"),documents:K.array(Do1).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:Yo1.optional().describe("Source entity type (post, deck)")}),Xo1=Xf.extend({platform:Rd0.optional(),status:hd0.optional()}),Ho1=Xf.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:Ho1}),dY0=Eb.extend({frontmatter:Xf,body:K.string()}),nY0=dY0.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 vd0 extends J2{constructor(){super({entityType:"social-post",purpose:"A short post drafted for social media such as LinkedIn or X.",schema:Eb,frontmatterSchema:Xf,supportsCoverImage:!0})}toMarkdown(A){let Q="",w={};try{w=this.parseFrontMatter(A.content,Xf),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,Xo1),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,Xf)}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 v7=new vd0;c0();c0();Z0();var gHw=FU.extend({platform:K.enum(["linkedin"]).optional(),status:K.enum(["generating","draft","queued","published","failed"]).optional(),sortByQueue:K.boolean().optional(),nextInQueue:K.boolean().optional()}),THw=VU.extend({query:gHw.optional()});function Wo1(A){let Q=v2(A.content,Xf);return dY0.parse({...A,frontmatter:Q.metadata,body:Q.content})}class rY0 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=THw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return Wo1(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?Wo1(B):null;return A.parse({post:$})}}Z0();var fo1=K.object({accessToken:K.string().optional(),refreshToken:K.string().optional(),organizationId:K.string().optional(),apiVersion:K.string().regex(/^\d{6}$/).optional()}),Cd0=K.object({linkedin:fo1.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();Ed0();import{jsxDEV as c5,Fragment as uHw}from"preact/jsx-dev-runtime";function SHw(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function mHw(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var sY0=({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(uHw,{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:mHw(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(CD,{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:SHw(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 cHw}from"preact/jsx-dev-runtime";function Zo1(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var aY0=({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(cHw,{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(PG,{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(CD,{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)," ",Zo1(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)," ",Zo1(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 Xo(A){return`social-media:${A}`}var lHw=K.union([K.boolean(),K.object({generate:K.boolean().optional(),prompt:K.string().optional()})]),gd0=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:lHw.optional().describe("Generic cover image generation request")}),pHw=GX.extend({slug:K.string().optional()});class kP extends w4{constructor(A,Q){super(A,Q,{schema:gd0,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 b=await this.context.ai.generate({prompt:X,templateName:Xo(w)});H=b.title,X=b.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 b=await this.context.entityService.getEntity({entityType:Y,id:D});if(!b)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(b.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
|
${b.content}`,templateName:Xo(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 b=await this.context.ai.generate({prompt:$,templateName:Xo(w)});H=b.title,X=b.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=v7.createPostContent(f,X),F=v7.fromMarkdown(Z).metadata;if(!F)this.failEarly("Failed to parse social post metadata");let V=await qq({entityType:"social-post",title:H,deriveId:(b)=>`${w}-${w1(b)}`,regeneratePrompt:"Generate a different social media post title on the same topic.",context:this.context}),L=Z;if(V!==H){F.title=V,F.slug=`${w}-${w1(V)}`;let b={...f,title:V};L=v7.createPostContent(b,X)}return{id:F.slug,content:L,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 Ho(A){if(A.length<=200)return A;return`${A.slice(0,200)}\u2026 (truncated, ${A.length} bytes)`}function iHw(A){let Q={status:"READY",media:A.urn};if(A.title)Q.title={text:A.title};return Q}function dHw(A){if(!Td0(A))return null;let Q=tY0(A,"value");if(!Q)return null;let w=tY0(Q,"uploadMechanism");if(!w)return null;let B=tY0(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 nHw(A){if(!Td0(A))return null;let Q=tY0(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 tY0(A,Q){let w=A[Q];return Td0(w)?w:null}function Td0(A){return typeof A==="object"&&A!==null}var rHw="202604";class Sd0{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:[iHw(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=Ho(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??rHw,"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=Ho(await w.text());return this.logger.warn("LinkedIn image upload registration failed",{status:w.status,error:X}),null}let B=dHw(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=Ho(await w.text());throw Error(`LinkedIn document upload initialization failed: ${w.status} - ${Y}`)}let B=nHw(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=Ho(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=Ho(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 md0(A,Q,w={}){return new Sd0(A,Q,w)}c0();Z0();IB();Ed0();var oHw=K.object({posts:K.array(nY0),totalCount:K.number().optional(),pagination:A4.nullable(),baseUrl:K.string().optional()}),sHw=K.object({post:nY0});function Ko1(){return{linkedin:oY0,"social-post-list":R1({name:"social-post-list",description:"Social post list page template",schema:oHw,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:sY0}}),"social-post-detail":R1({name:"social-post-detail",description:"Individual social post template",schema:sHw,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:aY0}})}}Z0();var aHw=K.object({prompt:K.string().optional(),content:K.string().optional(),platform:K.enum(["linkedin"]).default("linkedin")}),tHw=K.object({prompt:K.string().optional(),content:K.string().optional(),title:K.string().optional(),platform:K.enum(["linkedin"]).optional()});function Uo1(A){A.eval.registerHandler("generation",async(Q)=>{let w=aHw.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=tHw.parse(Q),B=[],$=X7.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 Wo{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,Xf),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(),L=F.id||void 0,b={...X.metadata,status:"published",publishedAt:V,...L&&{platformPostId:L}},N=v7.createPostContent(b,X.content);await this.entityService.updateEntity({entity:{...$,content:N,metadata:{...$.metadata,status:"published",publishedAt:V,platformPostId:L}}}),await this.reportSuccess(Q,w,F.id),this.logger.info(`Post published successfully: ${w}`,{platform:Y,platformPostId:L})}catch(Z){let G=Z instanceof Error?Z.message:String(Z),F={...X.metadata,status:"failed"},V=v7.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 Go1(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 zo1(A,Q,w){let B=new Wo({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 qo1(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 Fo1(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:`${v7.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 Vo1(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:`${v7.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 Jo1({entity:A,config:Q}){let w=Eb.parse(A),B=v7.parsePostFrontmatter(w),$=v7.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 ud0(){return{entityType:"social-post",collection:"ai.rizom.brain.socialPost",lexicon:MB["ai.rizom.brain.socialPost"],validate:!1,buildRecord:Jo1}}var Io1={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.138",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 cd0 extends kQ{entityType=v7.entityType;schema=Eb;adapter=v7;providers=new Map;unregisterAtprotoProjection;constructor(A){super("social-media",Io1,A,Cd0)}createGenerationHandler(A){return new kP(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return Ko1()}getDataSources(){return[new rY0(this.logger.child("SocialPostDataSource"))]}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}async onRegister(A){if(this.initializeProviders(),Go1(A,this.providers,this.logger),zo1(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)qo1(A,this.logger),Fo1(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");Vo1(A,this.logger),Uo1(A),this.unregisterAtprotoProjection=U5.getInstance().register(ud0()),this.logger.info("Social media plugin registered successfully")}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}initializeProviders(){if(this.config.linkedin?.accessToken){let A=md0(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function fo(A){return new cd0(A)}Z0();var AWw=K.enum(["draft","queued","published","failed"]),bo1=K.object({status:AWw.default("draft"),queueOrder:K.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:K.string().datetime().optional()});class ld0{name="internal";async publish(A,Q){return{id:"internal"}}}var Zo={interfaceType:"system",userId:"system",userPermissionLevel:"anchor",authorization:"system"},hY={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"},Lo1={REGISTER:"publish-assets:register"};Z0();var QWw=K.enum(["provider"]),No1=K.object({executionMode:QWw.optional(),publishResultIdField:K.string().min(1).optional(),publishTimestampField:K.string().min(1).optional(),enabled:K.boolean().optional()}).strict();var wWw=K.object({skipIfDraftExists:K.boolean().optional(),minSourceEntities:K.number().optional(),maxUnpublishedDrafts:K.number().optional(),sourceEntityType:K.string().optional()}),jo1=K.object({entitySchedules:K.record(K.string(),K.string()).optional(),generationSchedules:K.record(K.string(),K.string()).optional(),generationConditions:K.record(K.string(),wWw).optional()});class aG{static instance=null;queues=new Map;static getInstance(){return aG.instance??=new aG,aG.instance}static resetInstance(){aG.instance=null}static createFresh(){return new aG}constructor(){}async add(A,Q,w=Zo){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 tG{static instance=null;providers=new Map;executionModes=new Map;publishResultIdFields=new Map;publishTimestampFields=new Map;defaultProvider=new ld0;static getInstance(){return tG.instance??=new tG,tG.instance}static resetInstance(){tG.instance=null}static createFresh(){return new tG}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 Mo1(A,Q){if(!Q.publishExecutor){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"Publish executor not configured",retryCount:0,willRetry:!1});return}await BWw(A,Q)}async function BWw(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:hY.FAILED,payload:B,sender:"publish-service"});Q.onFailed?.(B);return}pd0(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 pd0(A,Q,w,B){if(B.retryTracker.clearRetries(Q),B.messageBus)B.messageBus.send({type:hY.COMPLETED,payload:{entityType:A,entityId:Q,result:w},sender:"publish-service"});B.onPublish?.({entityType:A,entityId:Q,result:w})}function _o1(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:hY.FAILED,payload:Y,sender:"publish-service"});B.onFailed?.(Y)}async function Po1(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 ko1(A,Q,w){if(w)w.send({type:gb.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function Oo1(A,Q,w){if(w)w.send({type:gb.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var $Ww=1000;class id0{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($Ww,()=>this.processUnscheduledTypes())}stop(){if(YWw(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 Mo1(A,Q)}get entitySchedules(){return this.deps.config.entitySchedules}}function YWw(A){for(let Q of A.values())Q.stop();A.clear()}class dd0{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(){DWw(this.generationJobs)}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await Po1(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 DWw(A){for(let Q of A.values())Q.stop();A.clear()}class NK{static instance=null;config;publishRunner;generationRunner;running=!1;static getInstance(A){return NK.instance??=new NK(A),NK.instance}static resetInstance(){if(NK.instance)NK.instance.stop();NK.instance=null}static createFresh(A){return new NK(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new id0({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new dd0({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){pd0(A,Q,w,this.publishDeps)}failPublish(A,Q,w){_o1(A,Q,w,this.publishDeps)}completeGeneration(A,Q){ko1(A,Q,this.config.messageBus)}failGeneration(A,Q){Oo1(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 eG{static instance=null;retries=new Map;static getInstance(){return eG.instance??=new eG,eG.instance}static resetInstance(){eG.instance=null}static createFresh(){return new eG}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 O4(A,Q,w,B,$,Y,D,X){return O4.fromTZ(O4.tp(A,Q,w,B,$,Y,D),X)}O4.fromTZISO=(A,Q,w)=>O4.fromTZ(XWw(A,Q),w);O4.fromTZ=function(A,Q){let w=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),B=nd0(A.tz,w),$=new Date(w.getTime()-B),Y=nd0(A.tz,$);if(Y-B===0)return $;{let D=new Date(w.getTime()-Y),X=nd0(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 $}};O4.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}};O4.tp=(A,Q,w,B,$,Y,D)=>({y:A,m:Q,d:w,h:B,i:$,s:Y,tz:D});function nd0(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 XWw(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("+")?O4.tp(w.getUTCFullYear(),w.getUTCMonth()+1,w.getUTCDate(),w.getUTCHours(),w.getUTCMinutes(),w.getUTCSeconds(),"Etc/UTC"):O4.tp(w.getFullYear(),w.getMonth()+1,w.getDate(),w.getHours(),w.getMinutes(),w.getSeconds(),Q)}O4.minitz=O4;var rd0=32,Uo=31|rd0,vo1=[1,2,4,8,16],xo1=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 Hf(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,Uo),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]|rd0;else if(Q===Uo)this.dayOfWeek[A]=Uo;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|vo1[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Ro1=[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]],Hf=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($&Uo&&vo1[D-1]&$)return!0;if($&rd0){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=O4.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>Ro1[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=O4.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(O4.fromTZISO(Q,this.tz))}findNext(Q,w,B,$){let Y=this[w],D;B.lastDayOfMonth&&(this.month!==1?D=Ro1[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&Uo)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)):O4.fromTZ(O4.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function HWw(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 Hf(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new Hf(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 Ko(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function WWw(A){return Ko(A)}function fWw(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var ho1=30000,eY0=[],od0=class{name;options;_states;fn;constructor(A,Q,w){let B,$;if(Ko(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(Ko(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=HWw(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 xo1("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new Hf(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new xo1(A,this.options.timezone),this.name){if(eY0.find((Y)=>Y.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");eY0.push(this)}return $!==void 0&&WWw($)&&(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 Hf||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new Hf(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=eY0.indexOf(this);A>=0&&eY0.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>ho1&&(Q=ho1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(w),Q),this._states.currentTimeout&&this.options.unref&&fWw(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new Hf(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){Ko(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Hf(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&&Ko(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 Hf(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 Hf(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 Hf(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 Hf(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 AD0{scheduleCron(A,Q){let w=new od0(A,()=>{Q()});return{stop:()=>w.stop()}}scheduleInterval(A,Q){let w=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(w)}}validateCron(A){new od0(A).stop()}}Z0();var Co1=K.union([K.string().min(1),K.object({location:K.enum(["metadata","frontmatter"]),field:K.string().min(1)})]),QD0=K.object({entityType:K.string().min(1),attachmentType:K.string().min(1),mediaEntityType:K.enum(["image","document"]),targetEntityField:Co1.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 sd0(A){return`${A.entityType}:${A.attachmentType}`}class Az{static instance=null;definitions=new Map;static getInstance(){return Az.instance??=new Az,Az.instance}static resetInstance(){Az.instance=null}static createFresh(){return new Az}constructor(){}register(A){let Q=QD0.parse(A),w=sd0(Q);return this.definitions.set(w,Q),()=>this.unregister(Q.entityType,Q.attachmentType)}get(A,Q){return this.definitions.get(sd0({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(sd0({entityType:A,attachmentType:Q}))}clear(){this.definitions.clear()}}Z0();class wD0{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 ad0(A.metadata[Q]);if(Q.location==="metadata")return ad0(A.metadata[Q.field]);let{frontmatter:w}=lw(A.content);return ad0(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 ad0(A){return typeof A==="string"?A.length>0:A!==void 0}c0();Z0();var ZWw=K.object({id:K.string().min(1)});async function Eo1(A,Q){let{bodyContent:w,coverImageId:B,documents:$,sourceEntityType:Y,sourceEntityId:D}=KWw(Q.content),X=B?await zWw(A,B):void 0,H;if($&&$.length>0){let f=await qWw(A,$);if(f.length>0)H=f}H??=await GWw(A,Y,D);let W={bodyContent:w};if(X)W.imageData=X;if(H&&H.length>0)W.documentData=H;return W}function KWw(A){try{let Q=v2(A,K.record(K.unknown())),w=Q.metadata.coverImageId,B=typeof w==="string"?w:void 0,$=UWw(Q.metadata.documents),Y=yo1(Q.metadata.sourceEntityType),D=yo1(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...B&&{coverImageId:B},...$.length>0&&{documents:$},...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}}}catch{return{bodyContent:A}}}function UWw(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let w=ZWw.safeParse(Q);return w.success?[w.data]:[]})}function yo1(A){return typeof A==="string"&&A.length>0?A:void 0}async function GWw(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 zWw(A,Q){let w=await A.entityService.getEntity({entityType:"image",id:Q});if(!w?.content)return;let B=go1(w.content);if(!B?.mimeType.startsWith("image/"))return;return{data:B.data,mimeType:B.mimeType}}async function qWw(A,Q){return(await Promise.all(Q.map((B)=>FWw(A,B)))).filter((B)=>B!==void 0)}async function FWw(A,Q){let w=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!w?.content)return;let B=go1(w.content);if(B?.mimeType!=="application/pdf")return;return{type:"document",data:B.data,mimeType:"application/pdf",filename:VWw(w,Q.id)}}function go1(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function VWw(A,Q){let w=A.metadata.filename;return typeof w==="string"&&w.length>0?w:`${Q}.pdf`}Z0();var JWw=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;async function td0(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,...IWw(w.id,B.publishResultIdField)},H={...Q,content:To1(Q.content,D,w.id,B.publishResultIdField,$),metadata:X};return await A.entityService.updateEntity({entity:H}),H}function To1(A,Q,w,B,$="publishedAt"){if(!JWw.test(A))return A;let Y=a4(a4(A,"status","published"),$,Q);if(!w||!B)return Y;return a4(Y,B,w)}function IWw(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 Eo1(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 td0(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 ed0=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)")}),An0=K.object({position:K.number(),entityType:K.string(),entityId:K.string(),queuedAt:K.string()}),bWw=K.object({success:K.literal(!0),message:K.string().optional(),data:K.object({queue:K.array(An0).optional(),entityType:K.string().optional(),entityId:K.string().optional(),position:K.number().optional()}).optional()}),LWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),Qn0=K.union([bWw,LWw]);function BD0(A,Q,w){return{...Sw(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",ed0,async($,Y)=>{let{action:D,entityType:X,entityId:H,position:W}=$;switch(D){case"list":return NWw(w,X);case"add":return jWw(A,w,X,H,Y);case"remove":return MWw(A,w,X,H,Y);case"reorder":return _Ww(A,w,X,H,W,Y);default:return{success:!1,error:`Unknown action: ${D}`}}},{sideEffects:"writes"}),outputSchema:Qn0}}async function NWw(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=wn0("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 MWw(A,Q,w,B,$){let Y=wn0("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 _Ww(A,Q,w,B,$,Y){let D=wn0("reorder",w,B);if(!D.success)return D.error;let X=PWw($);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 wn0(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 PWw(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 kWw}from"crypto";var $D0=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()}),OWw=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()}),xWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),RWw=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()}),Bn0=K.union([OWw,xWw,RWw]),hWw=900000;function YD0(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.). For follow-up requests like 'publish it now', use the entity just read, generated, or updated in the conversation, including a post just changed to draft.",inputSchema:$D0.shape,outputSchema:Bn0,visibility:"anchor",sideEffects:"external",handler:async(D,X)=>{let H=$D0.safeParse(D);if(!H.success)return{success:!1,error:`Invalid input: ${H.error.errors.map((L)=>`${L.path.join(".")}: ${L.message}`).join(", ")}`};let W=H.data,{entityType:f,id:Z,slug:G}=W;try{A.permissions.assertEntityActionAllowed(f,"publish",X)}catch(L){return{success:!1,error:L instanceof Error?L.message:String(L)}}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 L=CWw(Y,W,V);if(L!==null)return L;let b;try{b=await $.publish({entityType:f,id:V.id})}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}if("error"in b)return{success:!1,error:b.error};let{entity:N,result:_}=b;return{success:!0,data:{entityType:f,entityId:N.id,platformId:_.id,url:_.url},message:`Published ${f}:${N.id}`}}return vWw(Y,W,V)}}}function vWw(A,Q,w){let B=new Date(Date.now()+hWw).toISOString(),$=So1(A,w,B),Y=yWw(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 CWw(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!==So1(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 So1(A,Q,w){return kWw("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 yWw(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 $n0=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")}),Yn0=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 DD0(A,Q,w,B){return{...Sw(Q,"ensure-assets","Reconcile configured publish assets for existing entities, queueing missing generated assets such as OG images.",$n0,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:Yn0}}c0();Z0();function mo1(A,Q){EWw(A,Q),gWw(A,Q),TWw(A,Q),SWw(A,Q)}function EWw(A,Q){A.messaging.subscribe(hY.REGISTER,async(w)=>mWw(Q,w.payload)),A.messaging.subscribe(hY.QUEUE,async(w)=>pWw(A,Q,w.payload)),A.messaging.subscribe(hY.DIRECT,async(w)=>iWw(A,Q,w.payload)),A.messaging.subscribe(hY.REMOVE,async(w)=>dWw(Q,w.payload)),A.messaging.subscribe(hY.REORDER,async(w)=>nWw(Q,w.payload)),A.messaging.subscribe(hY.LIST,async(w)=>rWw(A,Q,w.payload)),A.messaging.subscribe(hY.REPORT_SUCCESS,async(w)=>oWw(Q,w.payload)),A.messaging.subscribe(hY.REPORT_FAILURE,async(w)=>sWw(Q,w.payload)),Q.logger.debug("Subscribed to publish messages")}function gWw(A,Q){A.messaging.subscribe(gb.REPORT_SUCCESS,async(w)=>aWw(Q,w.payload)),A.messaging.subscribe(gb.REPORT_FAILURE,async(w)=>tWw(Q,w.payload)),Q.logger.debug("Subscribed to generation messages")}function TWw(A,Q){A.messaging.subscribe(Lo1.REGISTER,async(w)=>uWw(Q,w.payload)),Q.logger.debug("Subscribed to publish asset messages")}function SWw(A,Q){let w=async(B)=>cWw(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 mWw(A,Q){let{entityType:w,provider:B,config:$}=Q;try{let Y=$?No1.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 uWw(A,Q){let w=QD0.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 cWw(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(!lWw(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 lWw(A){if(!A)return!1;let Q=bo1.safeParse(A.metadata);return Q.success&&Q.data.status==="published"}async function pWw(A,Q,w){let{entityType:B,entityId:$}=w;try{let Y=w.authContext??Zo;A.permissions.assertEntityActionAllowed(B,"publish",Y);let D=await Q.queueManager.add(B,$,Y);return await A.messaging.send({type:hY.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 iWw(A,Q,w){let{entityType:B,entityId:$}=w,Y=w.authContext??Zo;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 dWw(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 nWw(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 rWw(A,Q,w){let{entityType:B}=w;try{let $=await Q.queueManager.list(B);return await A.messaging.send({type:hY.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 oWw(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 sWw(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 aWw(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 tWw(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 uo1(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 co1(A){let{context:Q,config:w,queueManager:B,providerRegistry:$,retryTracker:Y,publishExecutor:D,logger:X}=A,H=eWw(Q);return NK.createFresh({queueManager:B,providerRegistry:$,retryTracker:Y,logger:X,backend:new AD0,...w.entitySchedules&&{entitySchedules:w.entitySchedules},...w.generationSchedules&&{generationSchedules:w.generationSchedules},...w.generationConditions&&{generationConditions:w.generationConditions},messageBus:H,publishExecutor:D,onCheckGenerationConditions:(W,f)=>uo1(Q.entityService,X,W,f)})}function eWw(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 lo1(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 Afw=["draft","queued","published","failed"];async function po1(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:()=>Qfw(A)}})}async function Qfw(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=wfw(D.metadata.status);if(!X)continue;B[X]++,w.push({id:D.id,title:Bfw(D.id,D.metadata.title),type:$,status:X})}}return{summary:B,items:w}}function wfw(A){return Afw.find((Q)=>Q===A)}function Bfw(A,Q){return typeof Q==="string"?Q:A}var io1={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.138",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 Dn0 extends IQ{pluginContext;queueManager;providerRegistry;retryTracker;publishExecutor;publishAssetRegistry;publishAssetPreflight;scheduler;constructor(A){super("content-pipeline",io1,A??{},jo1)}async onRegister(A){this.pluginContext=A,this.queueManager=aG.createFresh(),this.providerRegistry=tG.createFresh(),this.retryTracker=eG.createFresh(),this.publishAssetRegistry=Az.createFresh(),this.publishAssetPreflight=new wD0({context:A,registry:this.publishAssetRegistry}),this.publishExecutor=new jE({context:A,providerRegistry:this.providerRegistry,publishAssetPreflight:this.publishAssetPreflight}),this.scheduler=co1({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,logger:this.logger}),mo1(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 lo1(A.entityService,this.queueManager,this.logger),await po1(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[BD0(this.pluginContext,this.id,this.queueManager),YD0(this.pluginContext,this.id,this.providerRegistry,this.publishExecutor),DD0(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. Follow-up requests like "publish it now" should target the entity just read, generated, or updated in the conversation, including a post just changed to draft.\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(),aG.resetInstance(),tG.resetInstance(),eG.resetInstance(),Az.resetInstance()}}function Xn0(A){return new Dn0(A)}c0();Z0();var do1=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")}),Hn0=K.object({cloudflare:do1.optional()});c0();Z0();var Yfw=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 Dfw(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 no1(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=tHw.parse(Q),B=[],$=X7.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 Wo{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,Xf),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(),L=F.id||void 0,b={...X.metadata,status:"published",publishedAt:V,...L&&{platformPostId:L}},N=v7.createPostContent(b,X.content);await this.entityService.updateEntity({entity:{...$,content:N,metadata:{...$.metadata,status:"published",publishedAt:V,platformPostId:L}}}),await this.reportSuccess(Q,w,F.id),this.logger.info(`Post published successfully: ${w}`,{platform:Y,platformPostId:L})}catch(Z){let G=Z instanceof Error?Z.message:String(Z),F={...X.metadata,status:"failed"},V=v7.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 Go1(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 zo1(A,Q,w){let B=new Wo({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 qo1(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 Fo1(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:`${v7.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 Vo1(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:`${v7.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 Jo1({entity:A,config:Q}){let w=Eb.parse(A),B=v7.parsePostFrontmatter(w),$=v7.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 ud0(){return{entityType:"social-post",collection:"ai.rizom.brain.socialPost",lexicon:MB["ai.rizom.brain.socialPost"],validate:!1,buildRecord:Jo1}}var Io1={name:"@brains/social-media",private:!0,version:"0.2.0-alpha.139",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 cd0 extends kQ{entityType=v7.entityType;schema=Eb;adapter=v7;providers=new Map;unregisterAtprotoProjection;constructor(A){super("social-media",Io1,A,Cd0)}createGenerationHandler(A){return new kP(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return Ko1()}getDataSources(){return[new rY0(this.logger.child("SocialPostDataSource"))]}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}async onRegister(A){if(this.initializeProviders(),Go1(A,this.providers,this.logger),zo1(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)qo1(A,this.logger),Fo1(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");Vo1(A,this.logger),Uo1(A),this.unregisterAtprotoProjection=U5.getInstance().register(ud0()),this.logger.info("Social media plugin registered successfully")}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}initializeProviders(){if(this.config.linkedin?.accessToken){let A=md0(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function fo(A){return new cd0(A)}Z0();var AWw=K.enum(["draft","queued","published","failed"]),bo1=K.object({status:AWw.default("draft"),queueOrder:K.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:K.string().datetime().optional()});class ld0{name="internal";async publish(A,Q){return{id:"internal"}}}var Zo={interfaceType:"system",userId:"system",userPermissionLevel:"anchor",authorization:"system"},hY={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"},Lo1={REGISTER:"publish-assets:register"};Z0();var QWw=K.enum(["provider"]),No1=K.object({executionMode:QWw.optional(),publishResultIdField:K.string().min(1).optional(),publishTimestampField:K.string().min(1).optional(),enabled:K.boolean().optional()}).strict();var wWw=K.object({skipIfDraftExists:K.boolean().optional(),minSourceEntities:K.number().optional(),maxUnpublishedDrafts:K.number().optional(),sourceEntityType:K.string().optional()}),jo1=K.object({entitySchedules:K.record(K.string(),K.string()).optional(),generationSchedules:K.record(K.string(),K.string()).optional(),generationConditions:K.record(K.string(),wWw).optional()});class aG{static instance=null;queues=new Map;static getInstance(){return aG.instance??=new aG,aG.instance}static resetInstance(){aG.instance=null}static createFresh(){return new aG}constructor(){}async add(A,Q,w=Zo){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 tG{static instance=null;providers=new Map;executionModes=new Map;publishResultIdFields=new Map;publishTimestampFields=new Map;defaultProvider=new ld0;static getInstance(){return tG.instance??=new tG,tG.instance}static resetInstance(){tG.instance=null}static createFresh(){return new tG}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 Mo1(A,Q){if(!Q.publishExecutor){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"Publish executor not configured",retryCount:0,willRetry:!1});return}await BWw(A,Q)}async function BWw(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:hY.FAILED,payload:B,sender:"publish-service"});Q.onFailed?.(B);return}pd0(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 pd0(A,Q,w,B){if(B.retryTracker.clearRetries(Q),B.messageBus)B.messageBus.send({type:hY.COMPLETED,payload:{entityType:A,entityId:Q,result:w},sender:"publish-service"});B.onPublish?.({entityType:A,entityId:Q,result:w})}function _o1(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:hY.FAILED,payload:Y,sender:"publish-service"});B.onFailed?.(Y)}async function Po1(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 ko1(A,Q,w){if(w)w.send({type:gb.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function Oo1(A,Q,w){if(w)w.send({type:gb.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var $Ww=1000;class id0{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($Ww,()=>this.processUnscheduledTypes())}stop(){if(YWw(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 Mo1(A,Q)}get entitySchedules(){return this.deps.config.entitySchedules}}function YWw(A){for(let Q of A.values())Q.stop();A.clear()}class dd0{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(){DWw(this.generationJobs)}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await Po1(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 DWw(A){for(let Q of A.values())Q.stop();A.clear()}class NK{static instance=null;config;publishRunner;generationRunner;running=!1;static getInstance(A){return NK.instance??=new NK(A),NK.instance}static resetInstance(){if(NK.instance)NK.instance.stop();NK.instance=null}static createFresh(A){return new NK(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new id0({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new dd0({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){pd0(A,Q,w,this.publishDeps)}failPublish(A,Q,w){_o1(A,Q,w,this.publishDeps)}completeGeneration(A,Q){ko1(A,Q,this.config.messageBus)}failGeneration(A,Q){Oo1(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 eG{static instance=null;retries=new Map;static getInstance(){return eG.instance??=new eG,eG.instance}static resetInstance(){eG.instance=null}static createFresh(){return new eG}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 O4(A,Q,w,B,$,Y,D,X){return O4.fromTZ(O4.tp(A,Q,w,B,$,Y,D),X)}O4.fromTZISO=(A,Q,w)=>O4.fromTZ(XWw(A,Q),w);O4.fromTZ=function(A,Q){let w=new Date(Date.UTC(A.y,A.m-1,A.d,A.h,A.i,A.s)),B=nd0(A.tz,w),$=new Date(w.getTime()-B),Y=nd0(A.tz,$);if(Y-B===0)return $;{let D=new Date(w.getTime()-Y),X=nd0(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 $}};O4.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}};O4.tp=(A,Q,w,B,$,Y,D)=>({y:A,m:Q,d:w,h:B,i:$,s:Y,tz:D});function nd0(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 XWw(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("+")?O4.tp(w.getUTCFullYear(),w.getUTCMonth()+1,w.getUTCDate(),w.getUTCHours(),w.getUTCMinutes(),w.getUTCSeconds(),"Etc/UTC"):O4.tp(w.getFullYear(),w.getMonth()+1,w.getDate(),w.getHours(),w.getMinutes(),w.getSeconds(),Q)}O4.minitz=O4;var rd0=32,Uo=31|rd0,vo1=[1,2,4,8,16],xo1=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 Hf(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,Uo),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]|rd0;else if(Q===Uo)this.dayOfWeek[A]=Uo;else if(Q<6&&Q>0)this.dayOfWeek[A]=this.dayOfWeek[A]|vo1[Q-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${Q}, Type: ${typeof Q}`)}},Ro1=[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]],Hf=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($&Uo&&vo1[D-1]&$)return!0;if($&rd0){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=O4.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>Ro1[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=O4.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(O4.fromTZISO(Q,this.tz))}findNext(Q,w,B,$){let Y=this[w],D;B.lastDayOfMonth&&(this.month!==1?D=Ro1[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&Uo)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)):O4.fromTZ(O4.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function HWw(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 Hf(A.startAt,A.timezone)),A.stopAt&&(A.stopAt=new Hf(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 Ko(A){return Object.prototype.toString.call(A)==="[object Function]"||typeof A=="function"||A instanceof Function}function WWw(A){return Ko(A)}function fWw(A){typeof Deno<"u"&&typeof Deno.unrefTimer<"u"?Deno.unrefTimer(A):A&&typeof A.unref<"u"&&A.unref()}var ho1=30000,eY0=[],od0=class{name;options;_states;fn;constructor(A,Q,w){let B,$;if(Ko(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(Ko(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=HWw(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 xo1("* * * * *")},A&&(A instanceof Date||typeof A=="string"&&A.indexOf(":")>0)?this._states.once=new Hf(A,this.options.timezone||this.options.utcOffset):this._states.pattern=new xo1(A,this.options.timezone),this.name){if(eY0.find((Y)=>Y.name===this.name))throw Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.");eY0.push(this)}return $!==void 0&&WWw($)&&(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 Hf||A instanceof Date?Q.getTime()-A.getTime():Q.getTime()-new Hf(A).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let A=eY0.indexOf(this);A>=0&&eY0.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>ho1&&(Q=ho1),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(w),Q),this._states.currentTimeout&&this.options.unref&&fWw(this._states.currentTimeout),this)}async _trigger(A){if(this._states.blocking=!0,this._states.currentRun=new Hf(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){Ko(this.options.catch)&&this.options.catch(Q,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Hf(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&&Ko(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 Hf(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 Hf(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 Hf(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 Hf(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 AD0{scheduleCron(A,Q){let w=new od0(A,()=>{Q()});return{stop:()=>w.stop()}}scheduleInterval(A,Q){let w=setInterval(()=>{Q()},A);return{stop:()=>clearInterval(w)}}validateCron(A){new od0(A).stop()}}Z0();var Co1=K.union([K.string().min(1),K.object({location:K.enum(["metadata","frontmatter"]),field:K.string().min(1)})]),QD0=K.object({entityType:K.string().min(1),attachmentType:K.string().min(1),mediaEntityType:K.enum(["image","document"]),targetEntityField:Co1.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 sd0(A){return`${A.entityType}:${A.attachmentType}`}class Az{static instance=null;definitions=new Map;static getInstance(){return Az.instance??=new Az,Az.instance}static resetInstance(){Az.instance=null}static createFresh(){return new Az}constructor(){}register(A){let Q=QD0.parse(A),w=sd0(Q);return this.definitions.set(w,Q),()=>this.unregister(Q.entityType,Q.attachmentType)}get(A,Q){return this.definitions.get(sd0({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(sd0({entityType:A,attachmentType:Q}))}clear(){this.definitions.clear()}}Z0();class wD0{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 ad0(A.metadata[Q]);if(Q.location==="metadata")return ad0(A.metadata[Q.field]);let{frontmatter:w}=lw(A.content);return ad0(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 ad0(A){return typeof A==="string"?A.length>0:A!==void 0}c0();Z0();var ZWw=K.object({id:K.string().min(1)});async function Eo1(A,Q){let{bodyContent:w,coverImageId:B,documents:$,sourceEntityType:Y,sourceEntityId:D}=KWw(Q.content),X=B?await zWw(A,B):void 0,H;if($&&$.length>0){let f=await qWw(A,$);if(f.length>0)H=f}H??=await GWw(A,Y,D);let W={bodyContent:w};if(X)W.imageData=X;if(H&&H.length>0)W.documentData=H;return W}function KWw(A){try{let Q=v2(A,K.record(K.unknown())),w=Q.metadata.coverImageId,B=typeof w==="string"?w:void 0,$=UWw(Q.metadata.documents),Y=yo1(Q.metadata.sourceEntityType),D=yo1(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...B&&{coverImageId:B},...$.length>0&&{documents:$},...Y&&{sourceEntityType:Y},...D&&{sourceEntityId:D}}}catch{return{bodyContent:A}}}function UWw(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let w=ZWw.safeParse(Q);return w.success?[w.data]:[]})}function yo1(A){return typeof A==="string"&&A.length>0?A:void 0}async function GWw(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 zWw(A,Q){let w=await A.entityService.getEntity({entityType:"image",id:Q});if(!w?.content)return;let B=go1(w.content);if(!B?.mimeType.startsWith("image/"))return;return{data:B.data,mimeType:B.mimeType}}async function qWw(A,Q){return(await Promise.all(Q.map((B)=>FWw(A,B)))).filter((B)=>B!==void 0)}async function FWw(A,Q){let w=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!w?.content)return;let B=go1(w.content);if(B?.mimeType!=="application/pdf")return;return{type:"document",data:B.data,mimeType:"application/pdf",filename:VWw(w,Q.id)}}function go1(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function VWw(A,Q){let w=A.metadata.filename;return typeof w==="string"&&w.length>0?w:`${Q}.pdf`}Z0();var JWw=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;async function td0(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,...IWw(w.id,B.publishResultIdField)},H={...Q,content:To1(Q.content,D,w.id,B.publishResultIdField,$),metadata:X};return await A.entityService.updateEntity({entity:H}),H}function To1(A,Q,w,B,$="publishedAt"){if(!JWw.test(A))return A;let Y=a4(a4(A,"status","published"),$,Q);if(!w||!B)return Y;return a4(Y,B,w)}function IWw(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 Eo1(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 td0(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 ed0=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)")}),An0=K.object({position:K.number(),entityType:K.string(),entityId:K.string(),queuedAt:K.string()}),bWw=K.object({success:K.literal(!0),message:K.string().optional(),data:K.object({queue:K.array(An0).optional(),entityType:K.string().optional(),entityId:K.string().optional(),position:K.number().optional()}).optional()}),LWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),Qn0=K.union([bWw,LWw]);function BD0(A,Q,w){return{...Sw(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",ed0,async($,Y)=>{let{action:D,entityType:X,entityId:H,position:W}=$;switch(D){case"list":return NWw(w,X);case"add":return jWw(A,w,X,H,Y);case"remove":return MWw(A,w,X,H,Y);case"reorder":return _Ww(A,w,X,H,W,Y);default:return{success:!1,error:`Unknown action: ${D}`}}},{sideEffects:"writes"}),outputSchema:Qn0}}async function NWw(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=wn0("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 MWw(A,Q,w,B,$){let Y=wn0("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 _Ww(A,Q,w,B,$,Y){let D=wn0("reorder",w,B);if(!D.success)return D.error;let X=PWw($);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 wn0(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 PWw(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 kWw}from"crypto";var $D0=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()}),OWw=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()}),xWw=K.object({success:K.literal(!1),error:K.string(),code:K.string().optional()}),RWw=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()}),Bn0=K.union([OWw,xWw,RWw]),hWw=900000;function YD0(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.). For follow-up requests like 'publish it now', use the entity just read, generated, or updated in the conversation, including a post just changed to draft.",inputSchema:$D0.shape,outputSchema:Bn0,visibility:"anchor",sideEffects:"external",handler:async(D,X)=>{let H=$D0.safeParse(D);if(!H.success)return{success:!1,error:`Invalid input: ${H.error.errors.map((L)=>`${L.path.join(".")}: ${L.message}`).join(", ")}`};let W=H.data,{entityType:f,id:Z,slug:G}=W;try{A.permissions.assertEntityActionAllowed(f,"publish",X)}catch(L){return{success:!1,error:L instanceof Error?L.message:String(L)}}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 L=CWw(Y,W,V);if(L!==null)return L;let b;try{b=await $.publish({entityType:f,id:V.id})}catch(j){return{success:!1,error:j instanceof Error?j.message:String(j)}}if("error"in b)return{success:!1,error:b.error};let{entity:N,result:_}=b;return{success:!0,data:{entityType:f,entityId:N.id,platformId:_.id,url:_.url},message:`Published ${f}:${N.id}`}}return vWw(Y,W,V)}}}function vWw(A,Q,w){let B=new Date(Date.now()+hWw).toISOString(),$=So1(A,w,B),Y=yWw(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 CWw(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!==So1(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 So1(A,Q,w){return kWw("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 yWw(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 $n0=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")}),Yn0=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 DD0(A,Q,w,B){return{...Sw(Q,"ensure-assets","Reconcile configured publish assets for existing entities, queueing missing generated assets such as OG images.",$n0,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:Yn0}}c0();Z0();function mo1(A,Q){EWw(A,Q),gWw(A,Q),TWw(A,Q),SWw(A,Q)}function EWw(A,Q){A.messaging.subscribe(hY.REGISTER,async(w)=>mWw(Q,w.payload)),A.messaging.subscribe(hY.QUEUE,async(w)=>pWw(A,Q,w.payload)),A.messaging.subscribe(hY.DIRECT,async(w)=>iWw(A,Q,w.payload)),A.messaging.subscribe(hY.REMOVE,async(w)=>dWw(Q,w.payload)),A.messaging.subscribe(hY.REORDER,async(w)=>nWw(Q,w.payload)),A.messaging.subscribe(hY.LIST,async(w)=>rWw(A,Q,w.payload)),A.messaging.subscribe(hY.REPORT_SUCCESS,async(w)=>oWw(Q,w.payload)),A.messaging.subscribe(hY.REPORT_FAILURE,async(w)=>sWw(Q,w.payload)),Q.logger.debug("Subscribed to publish messages")}function gWw(A,Q){A.messaging.subscribe(gb.REPORT_SUCCESS,async(w)=>aWw(Q,w.payload)),A.messaging.subscribe(gb.REPORT_FAILURE,async(w)=>tWw(Q,w.payload)),Q.logger.debug("Subscribed to generation messages")}function TWw(A,Q){A.messaging.subscribe(Lo1.REGISTER,async(w)=>uWw(Q,w.payload)),Q.logger.debug("Subscribed to publish asset messages")}function SWw(A,Q){let w=async(B)=>cWw(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 mWw(A,Q){let{entityType:w,provider:B,config:$}=Q;try{let Y=$?No1.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 uWw(A,Q){let w=QD0.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 cWw(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(!lWw(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 lWw(A){if(!A)return!1;let Q=bo1.safeParse(A.metadata);return Q.success&&Q.data.status==="published"}async function pWw(A,Q,w){let{entityType:B,entityId:$}=w;try{let Y=w.authContext??Zo;A.permissions.assertEntityActionAllowed(B,"publish",Y);let D=await Q.queueManager.add(B,$,Y);return await A.messaging.send({type:hY.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 iWw(A,Q,w){let{entityType:B,entityId:$}=w,Y=w.authContext??Zo;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 dWw(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 nWw(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 rWw(A,Q,w){let{entityType:B}=w;try{let $=await Q.queueManager.list(B);return await A.messaging.send({type:hY.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 oWw(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 sWw(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 aWw(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 tWw(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 uo1(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 co1(A){let{context:Q,config:w,queueManager:B,providerRegistry:$,retryTracker:Y,publishExecutor:D,logger:X}=A,H=eWw(Q);return NK.createFresh({queueManager:B,providerRegistry:$,retryTracker:Y,logger:X,backend:new AD0,...w.entitySchedules&&{entitySchedules:w.entitySchedules},...w.generationSchedules&&{generationSchedules:w.generationSchedules},...w.generationConditions&&{generationConditions:w.generationConditions},messageBus:H,publishExecutor:D,onCheckGenerationConditions:(W,f)=>uo1(Q.entityService,X,W,f)})}function eWw(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 lo1(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 Afw=["draft","queued","published","failed"];async function po1(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:()=>Qfw(A)}})}async function Qfw(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=wfw(D.metadata.status);if(!X)continue;B[X]++,w.push({id:D.id,title:Bfw(D.id,D.metadata.title),type:$,status:X})}}return{summary:B,items:w}}function wfw(A){return Afw.find((Q)=>Q===A)}function Bfw(A,Q){return typeof Q==="string"?Q:A}var io1={name:"@brains/content-pipeline",private:!0,version:"0.2.0-alpha.139",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 Dn0 extends IQ{pluginContext;queueManager;providerRegistry;retryTracker;publishExecutor;publishAssetRegistry;publishAssetPreflight;scheduler;constructor(A){super("content-pipeline",io1,A??{},jo1)}async onRegister(A){this.pluginContext=A,this.queueManager=aG.createFresh(),this.providerRegistry=tG.createFresh(),this.retryTracker=eG.createFresh(),this.publishAssetRegistry=Az.createFresh(),this.publishAssetPreflight=new wD0({context:A,registry:this.publishAssetRegistry}),this.publishExecutor=new jE({context:A,providerRegistry:this.providerRegistry,publishAssetPreflight:this.publishAssetPreflight}),this.scheduler=co1({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,logger:this.logger}),mo1(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 lo1(A.entityService,this.queueManager,this.logger),await po1(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[BD0(this.pluginContext,this.id,this.queueManager),YD0(this.pluginContext,this.id,this.providerRegistry,this.publishExecutor),DD0(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. Follow-up requests like "publish it now" should target the entity just read, generated, or updated in the conversation, including a post just changed to draft.\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(),aG.resetInstance(),tG.resetInstance(),eG.resetInstance(),Az.resetInstance()}}function Xn0(A){return new Dn0(A)}c0();Z0();var do1=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")}),Hn0=K.object({cloudflare:do1.optional()});c0();Z0();var Yfw=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 Dfw(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 no1(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.`,Yfw,
|
|
|
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 fn0=7,Xfw=10;function oo1(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=KO(),w=jt(fn0),B=OV(w),$=OV(Q);try{let[Y,D]=await Promise.all([A.getWebsiteStats({startDate:B,endDate:$}),A.getTopPages({startDate:B,endDate:$,limit:Xfw})]);return{days:fn0,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:fn0}}}}var so1={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.
|
|
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 fn0=7,Xfw=10;function oo1(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=KO(),w=jt(fn0),B=OV(w),$=OV(Q);try{let[Y,D]=await Promise.all([A.getWebsiteStats({startDate:B,endDate:$}),A.getTopPages({startDate:B,endDate:$,limit:Xfw})]);return{days:fn0,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:fn0}}}}var so1={name:"@brains/analytics",private:!0,version:"0.2.0-alpha.139",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 ao1 extends IQ{cloudflareClient;constructor(A={}){super("analytics",so1,A,Hn0)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new Wn0(this.config.cloudflare):void 0,A.insights.register("traffic-overview",oo1(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:ro1(Q)}})}async getTools(){return no1(this.id,this.getContext(),this.cloudflareClient)}}function Wfw(A={}){return new ao1(A)}var XD0=Wfw;import{randomBytes as zfw}from"crypto";c0();Z0();aB();var ffw=new Set(["description","excerpt","summary","tagline","story"]);function Zfw(A){if(A.endsWith("s"))return A;return UX(A)}function Zn0(A,Q=!1,w){let B=A._def.typeName;if(B==="ZodOptional"||B==="ZodNullable")return Zn0(A._def.innerType,!0,w);if(B==="ZodDefault")return Zn0(A._def.innerType,Q,A._def.defaultValue());return{inner:A,isOptional:Q,defaultValue:w}}function Kn0(A,Q){let{inner:w,isOptional:B,defaultValue:$}=Zn0(Q),Y=w._def.typeName,D={name:A,label:DU(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(ffw.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=Kn0("item",X);if(H.widget==="object"&&H.fields)return{...D,widget:"list",fields:H.fields};return{...D,widget:"list",field:{name:A,label:DU(A),widget:H.widget}}}case"ZodObject":{let X=w.shape,H=Object.entries(X).map(([W,f])=>Kn0(W,f));return{...D,widget:"object",fields:H}}default:return{...D,widget:"string"}}}function to1(A,Q){let w=Object.entries(A.shape).map(([B,$])=>Kn0(B,$));if(Q)w.push({name:"body",label:"Body",widget:"markdown"});return w}function eo1(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===Ee?"Note":DU(B),W=X?.label??H,f=X?.pluralName??Zfw(W);if(Y?.isSingleton){w.push({name:B,label:W,file:`${B}/${B}.md`,fields:to1($,D)});continue}if(B===Ee){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:to1($,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 Kfw=new RegExp("[<>&\\u2028\\u2029]","g");function ME(A){return JSON.stringify(A).replace(Kfw,(Q)=>`\\u${Q.charCodeAt(0).toString(16).padStart(4,"0")}`)}var As1="https://unpkg.com/@sveltia/cms@0.165.1/dist/sveltia-cms.js";function HD0(A){let Q=`<script src="${As1}"></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.`,Yfw,
|
|
|
6796
6796
|
showError(error instanceof Error ? error.message : String(error));
|
|
6797
6797
|
}
|
|
6798
6798
|
})();
|
|
6799
|
-
`}Z0();var Qs1={name:"@brains/cms",private:!0,version:"0.2.0-alpha.
|
|
6799
|
+
`}Z0();var Qs1={name:"@brains/cms",private:!0,version:"0.2.0-alpha.139",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 Gn0="brains_cms_oauth_state",qfw=600,Ffw="auth",Vfw=K.object({label:K.string().optional(),pluralName:K.string().optional()}).passthrough(),Jfw=K.object({clientId:K.string().optional(),clientSecret:K.string().optional(),scope:K.string().optional()}),Ifw=K.object({contentRepoToken:K.string().optional()}),bfw=K.object({entityDisplay:K.record(Vfw).optional(),routePath:K.string().default("/cms"),githubOAuth:Jfw.optional(),passkeyLogin:Ifw.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 Lfw(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 Nfw(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 Mfw(A,Q,w){let B=A.entityDisplay??w?.entityDisplay;return{...B?{entityDisplay:B}:{},...jfw(Q)?{authEndpoint:Ffw}:{}}}async function _fw(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 Pfw(A,Q={}){let{repo:w,branch:B}=await _fw(A);return eo1({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 $s1(A,Q={}){return YU(await Pfw(A,Q))}class zn0 extends IQ{constructor(A={}){super("cms",Qs1,A,bfw)}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=Lfw(this.config.routePath),Q=Nfw(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 Bs1(B))return new Response(null,{status:302,headers:{Location:`/login?return_to=${encodeURIComponent(this.config.routePath)}`,"Cache-Control":"no-store"}});return zo(HD0({cmsConfigPath:A,authTokenEndpoint:"/auth/cms-token"}))}return zo(HD0({cmsConfigPath:A}))}},{path:A,method:"GET",public:!0,handler:async(B)=>{try{let $=Mfw(this.config,Q,this.getContext()),Y=await $s1(this.getContext(),{...$,...$.authEndpoint?{baseUrl:Go(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 Bs1(A)?Cfw:vfw;return zo(w(Go(this.getContext(),A)))}return hfw("CMS login is not enabled",404)}redirectToGitHub(A,Q){let w=zfw(32).toString("base64url"),B=`${Go(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":xfw(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 WD0(`GitHub OAuth failed: ${W}`)}let $=w.searchParams.get("state"),Y=Rfw(A.headers.get("cookie"),Gn0);if(!$||!Y||$!==Y)return WD0("GitHub OAuth state did not match");let D=w.searchParams.get("code");if(!D)return WD0("GitHub OAuth callback did not include a code");let X=`${Go(this.getContext(),A)}/auth/callback`,H=await kfw(Q,D,X);if(!H.success)return WD0(H.error);return zo(yfw(H.token,Go(this.getContext(),A)),200,{"Set-Cookie":Ds1()})}async handleCmsToken(A,Q){if(!await gW()?.getOperatorSession(A))return ws1({error:"Operator session required"},401);return ws1({token:Q.contentRepoToken,provider:"github"},200,{"Cache-Control":"no-store"})}}function xP(A){return new zn0(A)}async function kfw(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:Ofw(Y)??"GitHub token exchange failed"};if(Un0(Y)&&typeof Y.error==="string")return{success:!1,error:typeof Y.error_description==="string"?Y.error_description:Y.error};let D=Un0(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 Ofw(A){if(!Un0(A))return;if(typeof A.error_description==="string")return A.error_description;return typeof A.error==="string"?A.error:void 0}function Un0(A){return Boolean(A&&typeof A==="object"&&!Array.isArray(A))}function Go(A,Q){let w=new URL(Q.url).origin;if(Ys1(w))return w;return A.siteUrl??w}function Ys1(A){let{hostname:Q}=new URL(A);return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"||Q==="[::1]"}function xfw(A,Q){let w=Ys1(new URL(Q.url).origin)?"":"; Secure";return`${Gn0}=${A}; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=${qfw}${w}`}function Ds1(){return`${Gn0}=; Path=/auth; HttpOnly; SameSite=Lax; Max-Age=0`}function Rfw(A,Q){if(!A)return;for(let w of A.split(";")){let[B,...$]=w.trim().split("=");if(B===Q)return $.join("=")}return}function zo(A,Q=200,w={}){return new Response(A,{status:Q,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",...w}})}function hfw(A,Q=200){return new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}})}function ws1(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 WD0(A){return zo(`<!doctype html><html><body><h1>CMS login failed</h1><p>${Tfw(A)}</p></body></html>`,400,{"Set-Cookie":Ds1()})}async function Bs1(A){return Boolean(await gW()?.getOperatorSession(A))}function vfw(A){return`<!doctype html>
|
|
6800
6800
|
<html lang="en">
|
|
6801
6801
|
<head>
|
|
6802
6802
|
<meta charset="utf-8" />
|
|
@@ -8201,7 +8201,7 @@ ${Hs1}`;import{jsxDEV as jK,Fragment as Zs1}from"preact/jsx-dev-runtime";functio
|
|
|
8201
8201
|
}
|
|
8202
8202
|
});
|
|
8203
8203
|
})();`;function JZw({input:A}){let Q=A.appInfo.entities,w=A.appInfo.entityCounts,B=qZw(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:zZw,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:fs1}},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(Ks1,{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(Gs1,{character:A.character},void 0,!1,void 0,this),Lw(Jn0,{interactions:Y,baseUrl:A.baseUrl},void 0,!1,void 0,this),X&&A.operatorAccess&&Lw(bs1,{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(Us1,{total:Q,entityCounts:w},void 0,!1,void 0,this),!$&&X&&A.operatorAccess&&Lw(bs1,{hiddenWidgetCount:A.operatorAccess.hiddenWidgetCount,loginUrl:A.operatorAccess.loginUrl},void 0,!1,void 0,this),B.primary.map((W)=>Lw(UD0,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this)),B.secondary.map((W)=>Lw(UD0,{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(Jn0,{interactions:Y,baseUrl:A.baseUrl},void 0,!1,void 0,this),B.sidebar.map((W)=>Lw(UD0,{widget:W},`${W.widget.pluginId}:${W.widget.id}`,!1,void 0,this)),Lw(zs1,{endpoints:A.appInfo.endpoints,baseUrl:A.baseUrl},void 0,!1,void 0,this),Lw(Js1,{appInfo:A.appInfo,now:H},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Lw(Is1,{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:FZw}},void 0,!1,void 0,this),Lw("script",{dangerouslySetInnerHTML:{__html:VZw}},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 Ls1(A){return`<!doctype html>
|
|
8204
|
-
${GZw(Lw(JZw,{input:A},void 0,!1,void 0,this))}`}function Ns1(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 js1={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.
|
|
8204
|
+
${GZw(Lw(JZw,{input:A},void 0,!1,void 0,this))}`}function Ns1(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 js1={name:"@brains/dashboard",private:!0,version:"0.2.0-alpha.139",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 bZw=K.object({version:K.string().default("1.0.0"),routePath:K.string().default("/dashboard"),themeCSS:K.string().optional()}),LZw=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:t4.default("public"),component:K.custom().optional(),clientScript:K.string().optional(),dataProvider:K.function().returns(K.promise(K.unknown()))}).superRefine((A,Q)=>{if(!Vn0(A.rendererName)&&!A.component)Q.addIssue({code:K.ZodIssueCode.custom,message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),NZw=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 bn0 extends IQ{widgetRegistry=null;datasource=null;siteUrl;ctx;constructor(A){super("dashboard",js1,A??{},bZw)}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new ZD0(this.logger),this.datasource=new KD0(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=LZw.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:fD0.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=NZw.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 gW()?.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",L=new URL(A.url),b=`${L.pathname}${L.search}`,N=encodeURIComponent(b),_=Ns1(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(Ls1(j),{headers:{"Content-Type":"text/html; charset=utf-8"}})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function Sb(A){return new bn0(A)}c0();Z0();var MZw=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:t4,component:K.custom().optional()}),_Zw=K.object({widget:MZw,data:K.unknown()}),PZw=K.object({widgets:K.record(_Zw)});Z0();c0();Z0();import{h as uZw}from"preact";Z0();bX();c0();var _E=K.enum(["generating","draft","queued","published","failed"]),Fo=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()}),Ms1=Fo.pick({subject:!0,status:!0,entityIds:!0,scheduledFor:!0,sentAt:!0,buttondownId:!0,sourceEntityType:!0}).extend({error:K.string().optional()}),Vo=o1.extend({entityType:K.literal("newsletter"),metadata:Ms1});c0();class _s1 extends J2{constructor(){super({entityType:"newsletter",purpose:"An email newsletter issue composed for subscribers.",schema:Vo,frontmatterSchema:Fo})}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 Ps1=new _s1;c0();c0();Z0();var kZw=FU.extend({status:K.enum(["generating","draft","queued","published","failed"]).optional()}),OZw=VU.extend({query:kZw.optional()});function ks1(A){try{let{content:Q}=v2(A.content,Fo);return Q}catch{return A.content}}class Ln0 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=OZw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=ks1(A),w={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:H7(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=ks1(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 xZw=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 Nn0 extends w4{constructor(A,Q){super(A,Q,{schema:xZw,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 b=`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 vY,Fragment as yZw}from"preact/jsx-dev-runtime";var hZw=K.object({id:K.string(),subject:K.string(),status:_E,excerpt:K.string(),created:K.string(),sentAt:K.string().optional(),url:K.string()}),vZw=K.object({newsletters:K.array(hZw),totalCount:K.number(),pagination:A4.nullable()}),CZw=({newsletters:A,totalCount:Q,pageTitle:w,pagination:B,baseUrl:$="/newsletters"})=>{let Y=w??"Newsletters",D=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return vY(yZw,{children:[vY(jQ,{title:Y,description:D},void 0,!1,void 0,this),vY("div",{className:"newsletter-list bg-theme",children:vY("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[vY("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:Y},void 0,!1,void 0,this),A.length===0?vY("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):vY("div",{className:"space-y-4",children:A.map((X)=>vY(uw,{href:X.url,children:[vY(n9,{className:"text-lg",children:X.subject},void 0,!1,void 0,this),vY(M7,{children:vY("div",{className:"flex items-center gap-3",children:[vY(CD,{status:X.status},void 0,!1,void 0,this),vY("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&&vY("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&&vY(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)},xs1=R1({name:"newsletter-list",description:"Newsletter list page template",schema:vZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:CZw}});Z0();c0();import{jsxDEV as y8,Fragment as SZw}from"preact/jsx-dev-runtime";var EZw=K.object({id:K.string(),title:K.string(),url:K.string()}),Rs1=K.object({id:K.string(),subject:K.string(),url:K.string()}),gZw=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(EZw).optional(),prevNewsletter:Rs1.nullable().optional(),nextNewsletter:Rs1.nullable().optional()}),TZw=({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(SZw,{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(PG,{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(CD,{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)},hs1=R1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:gZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:TZw}});var vs1={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.
|
|
8273
|
+
The goal is to build a relationship with readers through valuable, authentic content.`});Z0();c0();import{jsxDEV as vY,Fragment as yZw}from"preact/jsx-dev-runtime";var hZw=K.object({id:K.string(),subject:K.string(),status:_E,excerpt:K.string(),created:K.string(),sentAt:K.string().optional(),url:K.string()}),vZw=K.object({newsletters:K.array(hZw),totalCount:K.number(),pagination:A4.nullable()}),CZw=({newsletters:A,totalCount:Q,pageTitle:w,pagination:B,baseUrl:$="/newsletters"})=>{let Y=w??"Newsletters",D=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return vY(yZw,{children:[vY(jQ,{title:Y,description:D},void 0,!1,void 0,this),vY("div",{className:"newsletter-list bg-theme",children:vY("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[vY("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:Y},void 0,!1,void 0,this),A.length===0?vY("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):vY("div",{className:"space-y-4",children:A.map((X)=>vY(uw,{href:X.url,children:[vY(n9,{className:"text-lg",children:X.subject},void 0,!1,void 0,this),vY(M7,{children:vY("div",{className:"flex items-center gap-3",children:[vY(CD,{status:X.status},void 0,!1,void 0,this),vY("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&&vY("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&&vY(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)},xs1=R1({name:"newsletter-list",description:"Newsletter list page template",schema:vZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:CZw}});Z0();c0();import{jsxDEV as y8,Fragment as SZw}from"preact/jsx-dev-runtime";var EZw=K.object({id:K.string(),title:K.string(),url:K.string()}),Rs1=K.object({id:K.string(),subject:K.string(),url:K.string()}),gZw=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(EZw).optional(),prevNewsletter:Rs1.nullable().optional(),nextNewsletter:Rs1.nullable().optional()}),TZw=({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(SZw,{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(PG,{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(CD,{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)},hs1=R1({name:"newsletter-detail",description:"Individual newsletter detail template",schema:gZw,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:TZw}});var vs1={name:"@brains/newsletter-entity",private:!0,version:"0.2.0-alpha.139",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 cZw=K.object({});class jn0 extends kQ{entityType="newsletter";schema=Vo;adapter=Ps1;constructor(A={}){super("newsletter",vs1,A,cZw)}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}createGenerationHandler(A){return new Nn0(this.logger,A)}getTemplates(){return{generation:Os1,"newsletter-list":xs1,"newsletter-detail":hs1}}getDataSources(){return[new Ln0(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:()=>uZw(tu0,{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 Mn0(A={}){return new jn0(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 lZw=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)")}),pZw=K.object({email:K.string().email().describe("Email address to unsubscribe")}),iZw=K.object({type:K.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:K.number().optional().describe("Maximum number of results")});function Cs1(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.",lZw,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.",pZw,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.",iZw,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 ys1(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 Es1={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.
|
|
8275
|
+
${B.content}`:B.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:$,templateName:"newsletter:generation"})})}}function Mn0(A={}){return new jn0(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 lZw=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)")}),pZw=K.object({email:K.string().email().describe("Email address to unsubscribe")}),iZw=K.object({type:K.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:K.number().optional().describe("Maximum number of results")});function Cs1(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.",lZw,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.",pZw,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.",iZw,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 ys1(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 Es1={name:"@brains/buttondown",private:!0,version:"0.2.0-alpha.139",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 nZw=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 _n0 extends IQ{constructor(A={}){super("buttondown",Es1,A,nZw)}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 ys1(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 Cs1(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 Pn0(A={}){return new _n0(A)}var rZw=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 gs1(A={}){let Q=rZw.parse(A);return[Mn0({}),Pn0({...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 DKw,mkdirSync as XKw,writeFileSync as HKw}from"fs";import{join as bF}from"path";Z0();var kn0=K.object({baseFolder:K.string().default("_obsidian")});Z0();function oZw(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 sZw(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 Ts1(A){let Q=A.shape,w=[];for(let[B,$]of Object.entries(Q)){let{inner:Y,required:D,defaultValue:X}=oZw($),H=sZw(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 aZw(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 Ss1(A,Q,w=""){let B=["---"];for(let $ of Q){let Y=aZw($,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 tZw={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function eZw(A){let Q={name:A.name,id:A.name,type:tZw[A.type]};if(A.type==="enum"&&A.enumValues){let w={};A.enumValues.forEach((B,$)=>{w[String($)]=B}),Q.options=w}return Q}function ms1(A,Q){let w={filesPaths:A,fields:Q.map(eZw)};return`---
|
|
8277
8277
|
${YU(w)}---
|
|
8278
|
-
`}Z0();var AKw=new Set(["entityType"]),QKw={base:"Notes"},wKw=new Set(["note"]);function BKw(A){let Q=["file.name"];for(let w of A)if(!AKw.has(w.name))Q.push(w.name);return Q}function $Kw(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function us1(A,Q){let w=QKw[A]??Lt(A),B=$Kw(Q),$=BKw(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:[wKw.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:Y};return{filename:`${w}.base`,content:YU(X),hasStatus:B}}function cs1(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 YU(w)}function ls1(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 YU(w)}var ps1={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.
|
|
8278
|
+
`}Z0();var AKw=new Set(["entityType"]),QKw={base:"Notes"},wKw=new Set(["note"]);function BKw(A){let Q=["file.name"];for(let w of A)if(!AKw.has(w.name))Q.push(w.name);return Q}function $Kw(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function us1(A,Q){let w=QKw[A]??Lt(A),B=$Kw(Q),$=BKw(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:[wKw.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:Y};return{filename:`${w}.base`,content:YU(X),hasStatus:B}}function cs1(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 YU(w)}function ls1(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 YU(w)}var ps1={name:"@brains/obsidian-vault",private:!0,version:"0.2.0-alpha.139",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 WKw={mkdir:XKw,writeFile:HKw,existsFile:DKw},fKw=K.object({entityTypes:K.array(K.string()).optional().describe("Entity types to generate templates for (default: all)")});class On0 extends IQ{deps;constructor(A={},Q={}){super("obsidian-vault",ps1,A,kn0);this.deps={...WKw,...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.",fKw,async(Q)=>{return this.sync(A,Q.entityTypes)},{sideEffects:"external"})]}async sync(A,Q){try{let w=A.entityService.getEntityTypes(),B=Q?w.filter((b)=>Q.includes(b)):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 b of B){let N=A.entities.getEffectiveFrontmatterSchema(b);if(!N){this.logger.debug(`Skipping ${b}: no frontmatter schema`),W.push(b);continue}let _=Ts1(N),j=A.entities.getAdapter(b),g=j?.isSingleton===!0,E=ms1(b,_);if(this.deps.writeFile(bF(D,`${b}.md`),E),f.push(b),g){G.push(b),this.logger.debug(`Generated fileClass (singleton): ${b}`);continue}let y=j?.getBodyTemplate()??"",h=Ss1(b,_,y);this.deps.writeFile(bF(Y,`${b}.md`),h),H.push(b);let T=us1(b,_),S=bF(X,T.filename);if(!this.deps.existsFile(S))this.deps.writeFile(S,T.content),Z.push(b),this.logger.debug(`Generated base: ${T.filename}`);if(T.hasStatus)F.push({entityType:b,fields:_});this.logger.debug(`Generated template + fileClass: ${b}`)}let V=cs1(G);if(V){let b=bF(X,"Settings.base");if(!this.deps.existsFile(b))this.deps.writeFile(b,V),Z.push("Settings"),this.logger.debug("Generated Settings.base")}let L=ls1(F);if(L){let b=bF(X,"Pipeline.base");if(!this.deps.existsFile(b))this.deps.writeFile(b,L),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 xn0(A,Q){return new On0(A,Q)}c0();c0();Z0();l$();c0();Z0();var Rn0=K.enum(["draft","active","archived"]),hn0=K.enum(["anchor","trusted","public"]),vn0=K.enum(["agent-confirmed","manual"]),uD=K.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,K.string().min(1).optional()),is1=K.object({event:K.string().min(1),target:K.string().min(1),operatorAction:K.boolean().optional(),label:uD,description:uD,operatorDescription:uD}),ds1=K.object({id:K.string().min(1),title:K.string().min(1),prompt:uD,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(is1).default([])}),Cn0=K.object({purpose:K.string().min(1),operatingRules:K.array(K.string().min(1)).default([]),initialState:K.string().min(1),states:K.array(ds1).min(1),finalStates:K.array(K.string().min(1)).min(1),nextPrompts:K.array(K.string().min(1)).default([])}),Jo=K.object({title:K.string(),status:Rn0.default("active"),audience:hn0.default("anchor"),trigger:uD,lifecycle:uD,once:K.boolean().optional(),starterText:uD,description:uD,starterPrompt:uD,completionMode:vn0.default("agent-confirmed")}),ns1=K.object({title:K.string(),status:Rn0,audience:hn0,trigger:uD,lifecycle:uD,once:K.boolean().optional(),starterText:uD,description:uD,starterPrompt:uD,completionMode:vn0}),Io=o1.extend({entityType:K.literal("playbook"),metadata:ns1}),yn0=K.object({});class Tn0 extends pw{constructor(){super(Cn0,{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:En0,parser:gn0},{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:ZKw,parser:KKw},{key:"label",label:"Label",type:"custom",formatter:En0,parser:gn0},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:En0,parser:gn0}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var GD0=new Tn0;function En0(A){return typeof A==="string"?A:""}function gn0(A){let Q=A.trim();return Q.length>0?Q:void 0}function ZKw(A){return typeof A==="boolean"?String(A):""}function KKw(A){let Q=A.trim().toLowerCase();if(Q==="true")return!0;if(Q==="false")return!1;return}function rs1(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 UKw(A,w))Q.push(`Playbook state '${$}' is unreachable.`);return{valid:Q.length===0,errors:Q}}function bo(A){let Q=rs1(A);if(!Q.valid)throw Error(Q.errors.join(`
|
|
8279
8279
|
`))}function UKw(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 Sn0 extends J2{constructor(){super({entityType:"playbook",purpose:"A guided multi-step workflow the assistant runs together with the user.",schema:Io,frontmatterSchema:Jo})}createPlaybookContent(A,Q){return this.buildMarkdown(GD0.format(Q),A)}parsePlaybookContent(A){let Q=this.parseFrontMatter(A,Jo),w=this.extractBody(A).trim(),B=GKw(w)?zKw(w):GD0.parse(w);return bo(B),{frontmatter:Jo.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 Sn0;function GKw(A){return/^##\s+Steps\s*$/im.test(A)}function zKw(A){let Q=qKw(mn0(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:FKw(A,"Purpose"),operatingRules:os1(A,"Operating Rules"),initialState:Q[0]?.id??"",states:w,finalStates:[Q.at(-1)?.id??""],nextPrompts:os1(A,"Next Prompts")}}function qKw(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),...ss1($,"Say")?{prompt:ss1($,"Say")}:{},requiredDetails:zD0($,"Required details"),instructions:zD0($,"To do"),doneWhen:zD0($,"Done when"),choices:VKw($,"Choices"),...as1($)?{skip:as1($)}:{}}})}function mn0(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 FKw(A,Q){return mn0(A,Q).split(/\r?\n/).map((w)=>w.trim()).filter((w)=>w.length>0&&!w.startsWith("#")).join(`
|
|
8282
8282
|
`).trim()}function os1(A,Q){return ts1(mn0(A,Q))}function ss1(A,Q){return new RegExp(`^${IKw(Q)}:\\s*(.+?)\\s*$`,"im").exec(A)?.[1]?.trim()}function zD0(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 ts1($.join(`
|
|
8283
|
-
`))}function VKw(A,Q){return zD0(A,Q).map(JKw)}function JKw(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 as1(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 ts1(A){return A.split(/\r?\n/).map((Q)=>/^-\s+(.+?)\s*$/.exec(Q)?.[1]?.trim()).filter((Q)=>Boolean(Q))}function IKw(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var es1={name:"@brains/playbook",private:!0,version:"0.2.0-alpha.138",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 Aa1 extends kQ{entityType=RP.entityType;schema=Io;adapter=RP;constructor(A={}){super("playbook",es1,A,yn0)}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 Qa1(A={}){return new Aa1(A)}CB();c0();Z0();bX();N10();var wa1={name:"@brains/playbooks",private:!0,version:"0.2.0-alpha.138",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 $a1=K.enum(["offered","active","completed","dismissed"]),qD0=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(),Ya1=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:$a1,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(qD0).default([]),gateVerdicts:K.array(Ya1).default([]),startedAt:K.string().datetime().optional(),completedAt:K.string().datetime().optional(),updatedAt:K.string().datetime()}).strict(),NKw="playbooks.runs",jKw=hP;class FD0{store;writeQueue=Promise.resolve();constructor(A){this.store=A.scoped({namespace:NKw,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:Ba1(Q?.evidence??[],A.evidence),gateVerdicts:MKw(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:Ba1(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 un0(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:[],context:{},evidence:[],gateVerdicts:[],...A.status==="active"||A.status===void 0?{startedAt:Q}:{},updatedAt:Q})}function Ba1(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(B.id,B);return Array.from(w.values())}function MKw(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(_Kw(B),B);return Array.from(w.values())}function _Kw(A){return[A.stateId,...A.goal].join("\x00")}var Fa1="playbooks:lifecycle-starters",VD0="playbooks:register-lifecycle-starter",Va1=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(),PKw=K.object({lifecycle:K.record(K.string(),Va1).default({}),triggers:K.record(K.string(),K.boolean()).default({})}).strict(),kKw=K.object({lifecycle:K.string().min(1).optional(),interfaceType:K.string().min(1),userPermissionLevel:K.enum(["anchor","trusted","public"])}).strict(),OKw=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(),Da1=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(),Xa1={runId:K.string().min(1).optional(),playbookId:K.string().min(1).optional(),lifecycle:K.string().min(1).optional()},Ha1={playbookId:K.string().min(1),lifecycle:K.string().min(1).optional()},Wa1={runId:K.string().min(1).optional(),event:K.string().min(1),fromState:K.string().min(1).optional(),context:K.record(K.string(),K.unknown()).optional()},xKw=K.object({met:K.boolean(),reason:K.string().min(1)}).strict(),RKw=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(),hKw=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(RKw).default([])}).passthrough(),vKw=K.object({run:hP,state:hKw,goal:K.array(K.string().min(1)),evidence:K.array(qD0).default([])}).strict();class in0 extends IQ{store;ctx;goalCheck;injectedGoalCheck;startLocks=new Map;runLocks=new Map;registeredLifecycleStarters=new Map;constructor(A={},Q={}){super("playbooks",wa1,A,PKw);this.injectedGoalCheck=Q.goalCheck,this.goalCheck=Q.goalCheck??dKw}async onRegister(A){await super.onRegister(A),this.ctx=A,this.store=new FD0(A.runtimeState),this.goalCheck=this.injectedGoalCheck??cKw(A),A.registerInstructions(this.buildInstructions()),A.eval.registerHandler("goalCheck",async(Q)=>this.goalCheck.evaluate(vKw.parse(Q))),A.messaging.subscribe(Fa1,async(Q)=>{let w=kKw.parse(Q.payload);return{success:!0,data:{starters:await this.resolveLifecycleStarters(w)}}}),A.messaging.subscribe(VD0,async(Q)=>{let w=OKw.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=CZ0.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:Xa1,visibility:"anchor",sideEffects:"none",handler:async(A,Q)=>{let w=K.object(Xa1).parse(A);try{return{success:!0,data:await this.getStatus({...w,conversationId:Q.conversationId})}}catch(B){return{success:!1,error:cn0(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:Ha1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Ha1).parse(A),B=Q.conversationId,$=B?`${B}:${w.playbookId}`:`playbook:${w.playbookId}`;return this.withStartLock($,async()=>{let Y=await this.requirePlaybook(w.playbookId);bo(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.withRunLock(X.id,async()=>{let f=await this.store.findById(X.id)??X;return this.store.upsert({...f,status:"active",...B?{conversationId:B}:{},...f.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. Always pass fromState set to the current state id you are acting on (from playbook_status or the active-playbook context); if the run has advanced past that state, the event is rejected as stale and you must call playbook_status and act on the current state instead. 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:Wa1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Wa1).parse(A),B=await this.resolveScopedRunResponse({runId:w.runId,conversationId:Q.conversationId});if(!B.success)return B;let $=await this.sendEventForRun(B.data.id,w.event,{context:w.context,fromState:w.fromState});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 withRunLock(A,Q){let B=(this.runLocks.get(A)??Promise.resolve()).then(Q),$=B.then(()=>{return},()=>{return});return this.runLocks.set(A,$),$.then(()=>{if(this.runLocks.get(A)===$)this.runLocks.delete(A)}),B}async handleAgentAction(A){if(A.userPermissionLevel!=="anchor")return;let Q=await this.resolveScopedRunResponse({conversationId:A.conversationId});if(!Q.success)return;let w={runId:Q.data.id,event:A.action.event,...A.action.fromState?{fromState:A.action.fromState}:{}},B=await this.sendEventForRun(Q.data.id,A.action.event,{fromState:A.action.fromState});if(!B.success)return{text:`I couldn't continue the playbook: ${B.error}`,toolResults:[{toolName:"playbook_send_event",args:w}],usage:Za1()};let $=this.getCurrentRunState(B.data);return{text:gKw($),...B.data.cards?{cards:B.data.cards}:{},toolResults:[{toolName:"playbook_send_event",args:w,data:B.data}],usage:Za1()}}getCurrentRunState(A){return A.currentState}async sendEventForRun(A,Q,w={}){return this.withRunLock(A,()=>this.sendEventForRunLocked(A,Q,w))}async sendEventForRunLocked(A,Q,w){let B=await this.store.findById(A);if(!B)return{success:!1,error:`Playbook run not found: ${A}`};if(w.fromState&&w.fromState!==B.currentState)return{success:!1,error:`Stale playbook event '${Q}': it was issued from state '${w.fromState}' but the run has advanced to state '${B.currentState}'. Call playbook_status and act on the current state.`};let $=await this.requirePlaybook(B.playbookId);if(B.playbookVersion!==$.version)return{success:!1,error:`Playbook definition changed for '${B.playbookId}'. Run version ${B.playbookVersion} does not match current version ${$.version}.`};let Y=this.getState($.body,B.currentState),D=Y?.transitions.find((Z)=>Z.event===Q),X=await this.transitionRun(B,$.body,Q);if(!X.success){if(X.gateVerdicts)await this.store.upsert({...B,gateVerdicts:X.gateVerdicts});return{success:!1,error:X.error}}let H=$.body.finalStates.includes(X.currentState),W=await this.store.upsert({...B,currentState:X.currentState,completedStates:Ka1(B.completedStates,B.currentState),gateVerdicts:X.gateVerdicts,context:{...B.context,...w.context??{}},...H?{status:"completed",completedAt:new Date().toISOString()}:{}}),f=await this.getStatus({runId:W.id});return{success:!0,data:Y&&D?.operatorAction===!0?CKw(f,Y,D):f}}async createStartedRun(A){return this.store.upsert(un0({playbookId:A.playbookId,playbookVersion:A.playbookVersion,initialState:A.body.initialState,lifecycle:A.lifecycle,conversationId:A.conversationId}))}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.createRunActor(Q,Y);D.start();let X=D.getSnapshot(),H={type:w};if(!X.can(H))return D.stop(),{success:!1,error:`Invalid playbook event '${w}' from state '${A.currentState}'.`,gateVerdicts:$.gateVerdicts};D.send(H);let W=String(D.getSnapshot().value);D.stop();let f=B.transitions.find((Z)=>Z.event===w)?.target;if(f&&W!==f)return{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};return{success:!0,currentState:W,gateVerdicts:$.gateVerdicts}}createRunActor(A,Q){let w=this.buildMachine(Q.playbookId,A,Q);return S1.createActor(w,{snapshot:w.resolveState({value:Q.currentState})})}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: ${cn0(X)}`}}let Y={stateId:Q.id,goal:Q.doneWhen,met:$.met,reason:$.reason,evaluatedAt:new Date().toISOString()};return{success:!0,gateVerdicts:SKw(A.gateVerdicts,[Y])}}evidenceForState(A,Q){return A.evidence.filter((w)=>!w.stateId||w.stateId===Q)}buildMachine(A,Q,w){return S1.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=Va1.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&&TKw(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=Da1.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((F)=>F.conversationId===A.conversationId):[],B=await this.resolveStatusRun(A,Q,w);if(A.conversationId&&!B&&!A.runId&&!A.playbookId&&!A.lifecycle)throw Error(`No active or completed playbook run for conversation '${A.conversationId}'.`);let $=A.playbookId??B?.playbookId??(A.lifecycle?this.config.lifecycle[A.lifecycle]?.playbookId:void 0),Y=$?await this.getPlaybook($):void 0,D=Y&&B?this.getState(Y.body,B.currentState):void 0,X=D&&B&&Y?this.getValidTransitions(B,Y.body,D):D?.transitions??[],H=X.filter((F)=>F.operatorAction!==!0),W=X.filter((F)=>F.operatorAction===!0),f=D&&B&&Y?this.getBlockedTransitions(B,Y.body,D):[],Z=D&&B&&Y?this.buildStateGuidance(B,Y.body,D):void 0,G=B&&Y&&W.length>0?EKw({run:B,title:Y.entity.metadata.title,transitions:W}):void 0;return{runs:(A.conversationId?w:Q).map(fa1),...B?{activeRun:fa1(B)}:{},...Y?{playbook:Y.entity}:{},...Y?{body:Y.body}:{},...D?{currentState:D}:{},...H.length>0?{validEvents:H}:{},...W.length>0?{operatorActions:W}:{},...f.length>0?{blockedEvents:f}:{},...Z?{guidance:Z}:{},...G?{cards:[G]}:{},lifecycle:this.config.lifecycle}}async resolveStatusRun(A,Q,w){let B=w.filter((Y)=>Y.status==="active"||Y.status==="offered"),$=pn0(w.filter((Y)=>(!A.playbookId||Y.playbookId===A.playbookId)&&(!A.lifecycle||Y.lifecycle===A.lifecycle)));if(A.runId)return Q.find((Y)=>Y.id===A.runId)??$;if(A.conversationId){if(A.lifecycle)return B.find((Y)=>Y.lifecycle===A.lifecycle)??$;if(A.playbookId)return B.find((Y)=>Y.playbookId===A.playbookId)??$;if(B.length>0)return this.requireScopedRun({conversationId:A.conversationId});return $}if(A.lifecycle)return Ua1(Q,(Y)=>Y.lifecycle===A.lifecycle);if(A.playbookId)return Ua1(Q,(Y)=>Y.playbookId===A.playbookId);return}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&&ln0(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 VKw(A,Q){return zD0(A,Q).map(JKw)}function JKw(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 as1(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 ts1(A){return A.split(/\r?\n/).map((Q)=>/^-\s+(.+?)\s*$/.exec(Q)?.[1]?.trim()).filter((Q)=>Boolean(Q))}function IKw(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var es1={name:"@brains/playbook",private:!0,version:"0.2.0-alpha.139",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 Aa1 extends kQ{entityType=RP.entityType;schema=Io;adapter=RP;constructor(A={}){super("playbook",es1,A,yn0)}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 Qa1(A={}){return new Aa1(A)}CB();c0();Z0();bX();N10();var wa1={name:"@brains/playbooks",private:!0,version:"0.2.0-alpha.139",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 $a1=K.enum(["offered","active","completed","dismissed"]),qD0=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(),Ya1=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:$a1,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(qD0).default([]),gateVerdicts:K.array(Ya1).default([]),startedAt:K.string().datetime().optional(),completedAt:K.string().datetime().optional(),updatedAt:K.string().datetime()}).strict(),NKw="playbooks.runs",jKw=hP;class FD0{store;writeQueue=Promise.resolve();constructor(A){this.store=A.scoped({namespace:NKw,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:Ba1(Q?.evidence??[],A.evidence),gateVerdicts:MKw(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:Ba1(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 un0(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:[],context:{},evidence:[],gateVerdicts:[],...A.status==="active"||A.status===void 0?{startedAt:Q}:{},updatedAt:Q})}function Ba1(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(B.id,B);return Array.from(w.values())}function MKw(A,Q){let w=new Map;for(let B of[...A,...Q])w.set(_Kw(B),B);return Array.from(w.values())}function _Kw(A){return[A.stateId,...A.goal].join("\x00")}var Fa1="playbooks:lifecycle-starters",VD0="playbooks:register-lifecycle-starter",Va1=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(),PKw=K.object({lifecycle:K.record(K.string(),Va1).default({}),triggers:K.record(K.string(),K.boolean()).default({})}).strict(),kKw=K.object({lifecycle:K.string().min(1).optional(),interfaceType:K.string().min(1),userPermissionLevel:K.enum(["anchor","trusted","public"])}).strict(),OKw=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(),Da1=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(),Xa1={runId:K.string().min(1).optional(),playbookId:K.string().min(1).optional(),lifecycle:K.string().min(1).optional()},Ha1={playbookId:K.string().min(1),lifecycle:K.string().min(1).optional()},Wa1={runId:K.string().min(1).optional(),event:K.string().min(1),fromState:K.string().min(1).optional(),context:K.record(K.string(),K.unknown()).optional()},xKw=K.object({met:K.boolean(),reason:K.string().min(1)}).strict(),RKw=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(),hKw=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(RKw).default([])}).passthrough(),vKw=K.object({run:hP,state:hKw,goal:K.array(K.string().min(1)),evidence:K.array(qD0).default([])}).strict();class in0 extends IQ{store;ctx;goalCheck;injectedGoalCheck;startLocks=new Map;runLocks=new Map;registeredLifecycleStarters=new Map;constructor(A={},Q={}){super("playbooks",wa1,A,PKw);this.injectedGoalCheck=Q.goalCheck,this.goalCheck=Q.goalCheck??dKw}async onRegister(A){await super.onRegister(A),this.ctx=A,this.store=new FD0(A.runtimeState),this.goalCheck=this.injectedGoalCheck??cKw(A),A.registerInstructions(this.buildInstructions()),A.eval.registerHandler("goalCheck",async(Q)=>this.goalCheck.evaluate(vKw.parse(Q))),A.messaging.subscribe(Fa1,async(Q)=>{let w=kKw.parse(Q.payload);return{success:!0,data:{starters:await this.resolveLifecycleStarters(w)}}}),A.messaging.subscribe(VD0,async(Q)=>{let w=OKw.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=CZ0.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:Xa1,visibility:"anchor",sideEffects:"none",handler:async(A,Q)=>{let w=K.object(Xa1).parse(A);try{return{success:!0,data:await this.getStatus({...w,conversationId:Q.conversationId})}}catch(B){return{success:!1,error:cn0(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:Ha1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Ha1).parse(A),B=Q.conversationId,$=B?`${B}:${w.playbookId}`:`playbook:${w.playbookId}`;return this.withStartLock($,async()=>{let Y=await this.requirePlaybook(w.playbookId);bo(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.withRunLock(X.id,async()=>{let f=await this.store.findById(X.id)??X;return this.store.upsert({...f,status:"active",...B?{conversationId:B}:{},...f.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. Always pass fromState set to the current state id you are acting on (from playbook_status or the active-playbook context); if the run has advanced past that state, the event is rejected as stale and you must call playbook_status and act on the current state instead. 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:Wa1,visibility:"anchor",sideEffects:"writes",handler:async(A,Q)=>{let w=K.object(Wa1).parse(A),B=await this.resolveScopedRunResponse({runId:w.runId,conversationId:Q.conversationId});if(!B.success)return B;let $=await this.sendEventForRun(B.data.id,w.event,{context:w.context,fromState:w.fromState});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 withRunLock(A,Q){let B=(this.runLocks.get(A)??Promise.resolve()).then(Q),$=B.then(()=>{return},()=>{return});return this.runLocks.set(A,$),$.then(()=>{if(this.runLocks.get(A)===$)this.runLocks.delete(A)}),B}async handleAgentAction(A){if(A.userPermissionLevel!=="anchor")return;let Q=await this.resolveScopedRunResponse({conversationId:A.conversationId});if(!Q.success)return;let w={runId:Q.data.id,event:A.action.event,...A.action.fromState?{fromState:A.action.fromState}:{}},B=await this.sendEventForRun(Q.data.id,A.action.event,{fromState:A.action.fromState});if(!B.success)return{text:`I couldn't continue the playbook: ${B.error}`,toolResults:[{toolName:"playbook_send_event",args:w}],usage:Za1()};let $=this.getCurrentRunState(B.data);return{text:gKw($),...B.data.cards?{cards:B.data.cards}:{},toolResults:[{toolName:"playbook_send_event",args:w,data:B.data}],usage:Za1()}}getCurrentRunState(A){return A.currentState}async sendEventForRun(A,Q,w={}){return this.withRunLock(A,()=>this.sendEventForRunLocked(A,Q,w))}async sendEventForRunLocked(A,Q,w){let B=await this.store.findById(A);if(!B)return{success:!1,error:`Playbook run not found: ${A}`};if(w.fromState&&w.fromState!==B.currentState)return{success:!1,error:`Stale playbook event '${Q}': it was issued from state '${w.fromState}' but the run has advanced to state '${B.currentState}'. Call playbook_status and act on the current state.`};let $=await this.requirePlaybook(B.playbookId);if(B.playbookVersion!==$.version)return{success:!1,error:`Playbook definition changed for '${B.playbookId}'. Run version ${B.playbookVersion} does not match current version ${$.version}.`};let Y=this.getState($.body,B.currentState),D=Y?.transitions.find((Z)=>Z.event===Q),X=await this.transitionRun(B,$.body,Q);if(!X.success){if(X.gateVerdicts)await this.store.upsert({...B,gateVerdicts:X.gateVerdicts});return{success:!1,error:X.error}}let H=$.body.finalStates.includes(X.currentState),W=await this.store.upsert({...B,currentState:X.currentState,completedStates:Ka1(B.completedStates,B.currentState),gateVerdicts:X.gateVerdicts,context:{...B.context,...w.context??{}},...H?{status:"completed",completedAt:new Date().toISOString()}:{}}),f=await this.getStatus({runId:W.id});return{success:!0,data:Y&&D?.operatorAction===!0?CKw(f,Y,D):f}}async createStartedRun(A){return this.store.upsert(un0({playbookId:A.playbookId,playbookVersion:A.playbookVersion,initialState:A.body.initialState,lifecycle:A.lifecycle,conversationId:A.conversationId}))}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.createRunActor(Q,Y);D.start();let X=D.getSnapshot(),H={type:w};if(!X.can(H))return D.stop(),{success:!1,error:`Invalid playbook event '${w}' from state '${A.currentState}'.`,gateVerdicts:$.gateVerdicts};D.send(H);let W=String(D.getSnapshot().value);D.stop();let f=B.transitions.find((Z)=>Z.event===w)?.target;if(f&&W!==f)return{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};return{success:!0,currentState:W,gateVerdicts:$.gateVerdicts}}createRunActor(A,Q){let w=this.buildMachine(Q.playbookId,A,Q);return S1.createActor(w,{snapshot:w.resolveState({value:Q.currentState})})}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: ${cn0(X)}`}}let Y={stateId:Q.id,goal:Q.doneWhen,met:$.met,reason:$.reason,evaluatedAt:new Date().toISOString()};return{success:!0,gateVerdicts:SKw(A.gateVerdicts,[Y])}}evidenceForState(A,Q){return A.evidence.filter((w)=>!w.stateId||w.stateId===Q)}buildMachine(A,Q,w){return S1.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=Va1.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&&TKw(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=Da1.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((F)=>F.conversationId===A.conversationId):[],B=await this.resolveStatusRun(A,Q,w);if(A.conversationId&&!B&&!A.runId&&!A.playbookId&&!A.lifecycle)throw Error(`No active or completed playbook run for conversation '${A.conversationId}'.`);let $=A.playbookId??B?.playbookId??(A.lifecycle?this.config.lifecycle[A.lifecycle]?.playbookId:void 0),Y=$?await this.getPlaybook($):void 0,D=Y&&B?this.getState(Y.body,B.currentState):void 0,X=D&&B&&Y?this.getValidTransitions(B,Y.body,D):D?.transitions??[],H=X.filter((F)=>F.operatorAction!==!0),W=X.filter((F)=>F.operatorAction===!0),f=D&&B&&Y?this.getBlockedTransitions(B,Y.body,D):[],Z=D&&B&&Y?this.buildStateGuidance(B,Y.body,D):void 0,G=B&&Y&&W.length>0?EKw({run:B,title:Y.entity.metadata.title,transitions:W}):void 0;return{runs:(A.conversationId?w:Q).map(fa1),...B?{activeRun:fa1(B)}:{},...Y?{playbook:Y.entity}:{},...Y?{body:Y.body}:{},...D?{currentState:D}:{},...H.length>0?{validEvents:H}:{},...W.length>0?{operatorActions:W}:{},...f.length>0?{blockedEvents:f}:{},...Z?{guidance:Z}:{},...G?{cards:[G]}:{},lifecycle:this.config.lifecycle}}async resolveStatusRun(A,Q,w){let B=w.filter((Y)=>Y.status==="active"||Y.status==="offered"),$=pn0(w.filter((Y)=>(!A.playbookId||Y.playbookId===A.playbookId)&&(!A.lifecycle||Y.lifecycle===A.lifecycle)));if(A.runId)return Q.find((Y)=>Y.id===A.runId)??$;if(A.conversationId){if(A.lifecycle)return B.find((Y)=>Y.lifecycle===A.lifecycle)??$;if(A.playbookId)return B.find((Y)=>Y.playbookId===A.playbookId)??$;if(B.length>0)return this.requireScopedRun({conversationId:A.conversationId});return $}if(A.lifecycle)return Ua1(Q,(Y)=>Y.lifecycle===A.lifecycle);if(A.playbookId)return Ua1(Q,(Y)=>Y.playbookId===A.playbookId);return}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&&ln0(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,...mKw(Q),...Y?{conversationId:Y}:{},...kE(Q,"toolCallId")?{toolCallId:kE(Q,"toolCallId")}:{}}},H=await this.store.appendEvidence(D.id,X);return await this.evaluateGateAfterEvidence(H.id),{recorded:!0}}async evaluateGateAfterEvidence(A){await this.withRunLock(A,()=>this.evaluateGateAfterEvidenceLocked(A))}async evaluateGateAfterEvidenceLocked(A){let Q=await this.store.findById(A);if(Q?.status!=="active")return;if(this.hasSatisfiedGateForCurrentState(Q))return;let w=await this.getPlaybook(Q.playbookId);if(Q.playbookVersion!==w?.version)return;let B=this.getState(w.body,Q.currentState);if(!B?.doneWhen.length)return;if(B.transitions.filter((W)=>W.event==="NEXT").length!==1)return;let Y=await this.prepareGateVerdicts(Q,B,"NEXT");if(!Y.success)return;let D={...Q,gateVerdicts:Y.gateVerdicts};if(!this.hasSatisfiedGateVerdicts(B,D)){await this.store.upsert(D);return}let X=await this.transitionRun(D,w.body,"NEXT");if(!X.success){await this.store.upsert(D);return}let H=w.body.finalStates.includes(X.currentState);await this.store.upsert({...D,currentState:X.currentState,completedStates:Ka1(D.completedStates,D.currentState),gateVerdicts:X.gateVerdicts,...H?{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=Da1.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:cn0(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&&ln0(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.createRunActor(Q,A);B.start();let $=B.getSnapshot().can({type:w});return B.stop(),$}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&&ln0(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((b)=>b.operatorAction!==!0),D=$.filter((b)=>b.operatorAction===!0),X=new Set($.map((b)=>`${b.event}\x00${b.target}`)),H=B.transitions.filter((b)=>!X.has(`${b.event}\x00${b.target}`)),W=Y.map((b)=>this.formatTransition(b)).join(`
|
|
8285
8285
|
`),f=D.map((b)=>this.formatTransition(b)).join(`
|
|
8286
8286
|
`),Z=H.map((b)=>this.formatTransition(b)).join(`
|
|
@@ -8354,9 +8354,9 @@ ${Object.entries(this.config.lifecycle).map(([Q,w])=>`- ${Q}: playbookId=${w.pla
|
|
|
8354
8354
|
${A.guidance}`:$}}function fa1(A){return{...A,evidence:A.evidence.map((Q)=>({...Q,data:yKw(Q.data)}))}}function yKw(A){return Object.fromEntries(["entityType","entityId","operation"].flatMap((Q)=>A[Q]!==void 0?[[Q,A[Q]]]:[]))}function EKw(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,fromState:A.run.currentState,...Q.operatorDescription??Q.description?{description:Q.operatorDescription??Q.description}:{}}))}}function gKw(A){if(!A)return"Continuing.";return A.prompt??`Continuing to ${A.title}.`}function Za1(){return{promptTokens:0,completionTokens:0,totalTokens:0}}function Ka1(A,Q){return A.includes(Q)?A:[...A,Q]}function Ua1(A,Q){let w=A.filter(Q),B=w.filter(($)=>$.status==="active"||$.status==="offered");return pn0(B)??pn0(w)}function pn0(A){return[...A].sort((Q,w)=>(w.completedAt??w.updatedAt).localeCompare(Q.completedAt??Q.updatedAt))[0]}function cn0(A){return A instanceof Error?A.message:String(A)}function ln0(A,Q){return A.length===Q.length&&A.every((w,B)=>w===Q[B])}function TKw(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 SKw(A,Q){let w=new Set(Q.map(Ga1));return[...A.filter((B)=>!w.has(Ga1(B))),...Q]}function Ga1(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 mKw(A){let Q=za1(A.entity);if(!Q)return{};let w=za1(Q.metadata),B=qa1(w?.title,w?.name,Q.title),$=qa1(Q.content),Y=$?uKw($):void 0;return{...B?{title:B}:{},...Y?{contentPreview:Y}:{}}}function za1(A){if(typeof A!=="object"||A===null||Array.isArray(A))return;return A}function qa1(...A){return A.find((Q)=>typeof Q==="string"&&Q.trim().length>0)?.trim()}function uKw(A){let Q=A.replace(/\s+/g," ").trim();return Q.length>500?`${Q.slice(0,497)}...`:Q}function cKw(A){return{async evaluate(Q){let w=Q.goal.join(`
|
|
8355
8355
|
`),B=await A.entityService.search({query:w,options:{limit:8,excludeTypes:["playbook"],visibilityScope:p8("anchor")}}),$=lKw(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:xKw});return Y}}}function lKw(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)=>pKw(B+1,w)):["No runtime evidence collected for this state."],"","## KB excerpts",...Q.length>0?Q.map((w,B)=>iKw(B+1,w)):["No relevant KB excerpts found."]].join(`
|
|
8356
8356
|
`)}function pKw(A,Q){return`${A}. ${Q.kind} at ${Q.observedAt}: ${Ja1(Q.data)}`}function iKw(A,Q){return[`${A}. ${Q.entity.entityType}/${Q.entity.id} (score ${Q.score})`,`Excerpt: ${Q.excerpt}`,`Content: ${Ia1(Q.entity.content,1200)}`,`Metadata: ${Ja1(Q.entity.metadata)}`].join(`
|
|
8357
|
-
`)}function Ja1(A){try{return Ia1(JSON.stringify(A),1200)}catch{return"[unserializable]"}}function Ia1(A,Q){return A.length>Q?`${A.slice(0,Q)}\u2026`:A}var dKw={async evaluate(){return{met:!1,reason:"No playbook goal check is configured."}}};function dn0(A={},Q={}){return new in0(A,Q)}import{readFile as rKw}from"fs/promises";import{join as oKw}from"path";c0();Z0();var ba1={name:"@brains/rover-onboarding",private:!0,version:"0.2.0-alpha.138",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 sKw=K.object({enabled:K.boolean().default(!1)}).strict(),La1=[{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 Na1 extends IQ{dependencies=["playbook","playbooks"];constructor(A={}){super("rover-onboarding",ba1,A,sKw)}async onReady(A){if(!this.config.enabled)return;for(let Q of La1)await this.seedPlaybookIfMissing(A,Q);for(let Q of La1){if(!Q.starter)continue;await A.messaging.send({type:VD0,payload:Q.starter})}}async seedPlaybookIfMissing(A,Q){if(await A.entityService.getEntity({entityType:"playbook",id:Q.id,visibilityScope:"restricted"}))return;let B=await rKw(oKw(import.meta.dir,"..","content","playbook",Q.fileName),"utf8");await A.entityService.createEntityFromMarkdown({input:{entityType:"playbook",id:Q.id,markdown:B}})}}function ja1(A={}){return new Na1(A)}c0();Z0();c0();var nn0=K.enum(["new","planned","in-progress","done","declined"]),rn0=K.enum(["low","medium","high","critical"]),Lo=K.object({title:K.string(),status:nn0,priority:rn0.default("medium"),requested:K.number().int().default(1),declinedReason:K.string().optional()}),Ma1=K.object({title:K.string(),status:nn0,priority:rn0,requested:K.number().int(),slug:K.string()}),No=o1.extend({entityType:K.literal("wish"),metadata:Ma1}),on0=K.object({});c0();Z0();class jo extends J2{constructor(){super({entityType:"wish",purpose:"An explicitly recorded capability or outcome the assistant cannot currently fulfill, kept for future planning.",schema:No,frontmatterSchema:Lo})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,Lo);return{frontmatter:Lo.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 sn0=new jo;Z0();Z0();async function _a1(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 JD0{logger;context;adapter=new jo;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 _a1({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 Pa1={critical:0,high:1,medium:2,low:3};function ka1(A){A.sort((Q,w)=>{let B=w.metadata.requested-Q.metadata.requested;if(B!==0)return B;return Pa1[Q.metadata.priority]-Pa1[w.metadata.priority]})}var Oa1={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.138",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 xa1 extends kQ{entityType=sn0.entityType;schema=No;adapter=sn0;constructor(A={}){super("wishlist",Oa1,A,on0)}async interceptCreate(A,Q,w){let B=await new JD0(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 ka1(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 JD0(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 tKw(A={}){return new xa1(A)}var ID0=tKw;c0();Z0();c0();var Mo=K.object({title:K.string(),target:K.string()}),Ra1=K.object({title:K.string(),target:K.string(),slug:K.string().optional()}),_o=o1.extend({entityType:K.literal("prompt"),metadata:Ra1});c0();Z0();class an0 extends J2{constructor(){super({entityType:"prompt",purpose:"A reusable prompt or instruction template.",schema:_o,frontmatterSchema:Mo})}toMarkdown(A){let Q=this.extractBody(A.content),w=this.parseFrontMatter(A.content,Mo);return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Mo),w=w1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:w}}}}var bD0=new an0;var ha1={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.138",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 tn0 extends kQ{entityType=bD0.entityType;schema=_o;adapter=bD0;constructor(){super("prompt",ha1,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function vP(){return new tn0}c0();Z0();class LD0{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(AUw),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function AUw(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 va1={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")},Ca1={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 ya1(A,Q){return[QUw(A,Q),wUw(A,Q)]}function QUw(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:va1,visibility:"anchor",sideEffects:"none",handler:async(w)=>{let B=K.object(va1).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 wUw(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:Ca1,visibility:"anchor",sideEffects:"external",handler:async(w)=>{let B=K.object(Ca1).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},L=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:W}}}});if(L[0]){let _={imageEntityId:L[0].id,alreadyExisted:!0,attribution:V};if(G&&F)await BUw(Q.entityService,G,F,L[0].id),_.coverSet=!0;return{success:!0,data:_}}let b=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:b,status:"generating"};if(G&&F)N.coverSet=!0;return{success:!0,data:N}}}}async function BUw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}c0();Z0();H4();var $Uw=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 en0 extends _w{deps;constructor(A,Q){super(A,{schema:$Uw,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=vX.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 YUw(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 YUw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}H4();var Ea1={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.138",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 XUw=K.object({provider:K.enum(["unsplash"]).default("unsplash"),apiKey:K.string().optional().describe("Stock photo provider API key")});class Ar0 extends IQ{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",Ea1,A,XUw);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=ya1(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??NW,jobs:A.jobs}),this.cachedTools}async registerJobHandlers(){if(!this.config.apiKey)return;let A=this.getContext();A.jobs.registerHandler("select-photo",new en0(this.logger.child("SelectPhotoJobHandler"),{provider:this.createProvider(),entityService:A.entityService,fetchImage:this.deps.fetchImage??NW}))}createProvider(){return new LD0(this.config.apiKey??"",this.deps.fetch??globalThis.fetch)}}function Qr0(A={},Q={}){return new Ar0(A,Q)}c0();Z0();c0();c0();Z0();var ga1=K.enum(["ai","foundation","work"]),Ta1=K.object({suffix:ga1,title:K.string(),body:K.string(),linkLabel:K.string(),linkHref:K.string()}),Po=K.object({eyebrow:K.string(),headline:K.string(),cards:K.array(Ta1).min(1)}),ND0=K.object({title:K.string(),slug:K.string(),status:K.enum(["draft","published"])}),ko=o1.extend({entityType:K.literal("ecosystem-section"),metadata:ND0});class Sa1 extends J2{constructor(){super({entityType:"ecosystem-section",purpose:"A section of the Rizom ecosystem overview.",schema:ko,frontmatterSchema:ND0})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var wr0=new Sa1;Z0();function HUw(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function Br0(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function Oo(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function jD0(A){let Q=HUw(A),B=Br0(Q,"Cards").split(/^### Card \d+\s*$/m).map(($)=>$.trim()).filter(Boolean);return Po.parse({eyebrow:Br0(Q,"Eyebrow"),headline:Br0(Q,"Headline"),cards:B.map(($)=>({suffix:Oo($,"Suffix"),title:Oo($,"Title"),body:Oo($,"Body"),linkLabel:Oo($,"Link Label"),linkHref:Oo($,"Link Href")}))})}function ma1(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
|
+
`)}function Ja1(A){try{return Ia1(JSON.stringify(A),1200)}catch{return"[unserializable]"}}function Ia1(A,Q){return A.length>Q?`${A.slice(0,Q)}\u2026`:A}var dKw={async evaluate(){return{met:!1,reason:"No playbook goal check is configured."}}};function dn0(A={},Q={}){return new in0(A,Q)}import{readFile as rKw}from"fs/promises";import{join as oKw}from"path";c0();Z0();var ba1={name:"@brains/rover-onboarding",private:!0,version:"0.2.0-alpha.139",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 sKw=K.object({enabled:K.boolean().default(!1)}).strict(),La1=[{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 Na1 extends IQ{dependencies=["playbook","playbooks"];constructor(A={}){super("rover-onboarding",ba1,A,sKw)}async onReady(A){if(!this.config.enabled)return;for(let Q of La1)await this.seedPlaybookIfMissing(A,Q);for(let Q of La1){if(!Q.starter)continue;await A.messaging.send({type:VD0,payload:Q.starter})}}async seedPlaybookIfMissing(A,Q){if(await A.entityService.getEntity({entityType:"playbook",id:Q.id,visibilityScope:"restricted"}))return;let B=await rKw(oKw(import.meta.dir,"..","content","playbook",Q.fileName),"utf8");await A.entityService.createEntityFromMarkdown({input:{entityType:"playbook",id:Q.id,markdown:B}})}}function ja1(A={}){return new Na1(A)}c0();Z0();c0();var nn0=K.enum(["new","planned","in-progress","done","declined"]),rn0=K.enum(["low","medium","high","critical"]),Lo=K.object({title:K.string(),status:nn0,priority:rn0.default("medium"),requested:K.number().int().default(1),declinedReason:K.string().optional()}),Ma1=K.object({title:K.string(),status:nn0,priority:rn0,requested:K.number().int(),slug:K.string()}),No=o1.extend({entityType:K.literal("wish"),metadata:Ma1}),on0=K.object({});c0();Z0();class jo extends J2{constructor(){super({entityType:"wish",purpose:"An explicitly recorded capability or outcome the assistant cannot currently fulfill, kept for future planning.",schema:No,frontmatterSchema:Lo})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,Lo);return{frontmatter:Lo.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 sn0=new jo;Z0();Z0();async function _a1(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 JD0{logger;context;adapter=new jo;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 _a1({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 Pa1={critical:0,high:1,medium:2,low:3};function ka1(A){A.sort((Q,w)=>{let B=w.metadata.requested-Q.metadata.requested;if(B!==0)return B;return Pa1[Q.metadata.priority]-Pa1[w.metadata.priority]})}var Oa1={name:"@brains/wishlist",private:!0,version:"0.2.0-alpha.139",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 xa1 extends kQ{entityType=sn0.entityType;schema=No;adapter=sn0;constructor(A={}){super("wishlist",Oa1,A,on0)}async interceptCreate(A,Q,w){let B=await new JD0(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 ka1(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 JD0(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 tKw(A={}){return new xa1(A)}var ID0=tKw;c0();Z0();c0();var Mo=K.object({title:K.string(),target:K.string()}),Ra1=K.object({title:K.string(),target:K.string(),slug:K.string().optional()}),_o=o1.extend({entityType:K.literal("prompt"),metadata:Ra1});c0();Z0();class an0 extends J2{constructor(){super({entityType:"prompt",purpose:"A reusable prompt or instruction template.",schema:_o,frontmatterSchema:Mo})}toMarkdown(A){let Q=this.extractBody(A.content),w=this.parseFrontMatter(A.content,Mo);return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Mo),w=w1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:w}}}}var bD0=new an0;var ha1={name:"@brains/prompt",private:!0,version:"0.2.0-alpha.139",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 tn0 extends kQ{entityType=bD0.entityType;schema=_o;adapter=bD0;constructor(){super("prompt",ha1,{},void 0)}getEntityTypeConfig(){return{embeddable:!1}}}function vP(){return new tn0}c0();Z0();class LD0{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(AUw),total:$.total,totalPages:$.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}function AUw(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 va1={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")},Ca1={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 ya1(A,Q){return[QUw(A,Q),wUw(A,Q)]}function QUw(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:va1,visibility:"anchor",sideEffects:"none",handler:async(w)=>{let B=K.object(va1).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 wUw(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:Ca1,visibility:"anchor",sideEffects:"external",handler:async(w)=>{let B=K.object(Ca1).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},L=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:W}}}});if(L[0]){let _={imageEntityId:L[0].id,alreadyExisted:!0,attribution:V};if(G&&F)await BUw(Q.entityService,G,F,L[0].id),_.coverSet=!0;return{success:!0,data:_}}let b=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:b,status:"generating"};if(G&&F)N.coverSet=!0;return{success:!0,data:N}}}}async function BUw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}c0();Z0();H4();var $Uw=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 en0 extends _w{deps;constructor(A,Q){super(A,{schema:$Uw,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=vX.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 YUw(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 YUw(A,Q,w,B){let $=await A.getEntity({entityType:Q,id:w});if(!$)return;await A.updateEntity({entity:{...$,metadata:{...$.metadata,coverImageId:B}}})}H4();var Ea1={name:"@brains/stock-photo",private:!0,version:"0.2.0-alpha.139",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 XUw=K.object({provider:K.enum(["unsplash"]).default("unsplash"),apiKey:K.string().optional().describe("Stock photo provider API key")});class Ar0 extends IQ{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",Ea1,A,XUw);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=ya1(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??NW,jobs:A.jobs}),this.cachedTools}async registerJobHandlers(){if(!this.config.apiKey)return;let A=this.getContext();A.jobs.registerHandler("select-photo",new en0(this.logger.child("SelectPhotoJobHandler"),{provider:this.createProvider(),entityService:A.entityService,fetchImage:this.deps.fetchImage??NW}))}createProvider(){return new LD0(this.config.apiKey??"",this.deps.fetch??globalThis.fetch)}}function Qr0(A={},Q={}){return new Ar0(A,Q)}c0();Z0();c0();c0();Z0();var ga1=K.enum(["ai","foundation","work"]),Ta1=K.object({suffix:ga1,title:K.string(),body:K.string(),linkLabel:K.string(),linkHref:K.string()}),Po=K.object({eyebrow:K.string(),headline:K.string(),cards:K.array(Ta1).min(1)}),ND0=K.object({title:K.string(),slug:K.string(),status:K.enum(["draft","published"])}),ko=o1.extend({entityType:K.literal("ecosystem-section"),metadata:ND0});class Sa1 extends J2{constructor(){super({entityType:"ecosystem-section",purpose:"A section of the Rizom ecosystem overview.",schema:ko,frontmatterSchema:ND0})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var wr0=new Sa1;Z0();function HUw(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function Br0(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function Oo(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function jD0(A){let Q=HUw(A),B=Br0(Q,"Cards").split(/^### Card \d+\s*$/m).map(($)=>$.trim()).filter(Boolean);return Po.parse({eyebrow:Br0(Q,"Eyebrow"),headline:Br0(Q,"Headline"),cards:B.map(($)=>({suffix:Oo($,"Suffix"),title:Oo($,"Title"),body:Oo($,"Body"),linkLabel:Oo($,"Link Label"),linkHref:Oo($,"Link Href")}))})}function ma1(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(`
|
|
8358
8358
|
`)}var WUw=K.object({query:K.object({id:K.string().optional()}).optional()}).passthrough();class MD0{id="rizom-ecosystem:entities";name="Rizom Ecosystem";description="Fetches an ecosystem-section entity for rendering";async fetch(A,Q,w){let $=WUw.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(jD0(Y.content))}}c0();var fUw=d$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 Qz(...A){return fUw(Qy(A))}import{jsxDEV as d86}from"preact/jsx-dev-runtime";import{jsxDEV as s86}from"preact/jsx-dev-runtime";import{jsxDEV as A66}from"preact/jsx-dev-runtime";import{jsxDEV as KUw}from"preact/jsx-dev-runtime";var $r0="px-6 md:px-10 xl:px-20",ZUw=`${$r0} relative z-[1]`,Yr0=({id:A,className:Q,children:w})=>KUw("section",{id:A,className:Qz(ZUw,Q),children:w},void 0,!1,void 0,this);import{jsxDEV as _D0}from"preact/jsx-dev-runtime";var UUw=new Map([["work","text-accent"],["foundation","text-secondary"],["ai","text-accent-bright"]]),xo=({name:A="rizom",brandSuffix:Q,className:w,dotClassName:B,suffixClassName:$})=>{let Y=UUw.get(Q);return _D0("span",{className:Qz("inline-flex items-baseline gap-0 font-display font-medium tracking-[-0.015em] [font-variation-settings:'opsz'_24]",w),children:[_D0("span",{className:"text-theme",children:A},void 0,!1,void 0,this),_D0("span",{className:Qz(Y??"text-accent",B),children:"."},void 0,!1,void 0,this),_D0("span",{className:Qz("italic font-normal text-theme-muted",$),children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as K66}from"preact/jsx-dev-runtime";import{jsxDEV as q66}from"preact/jsx-dev-runtime";import{jsxDEV as I66,Fragment as J66}from"preact/jsx-dev-runtime";import{jsxDEV as N66}from"preact/jsx-dev-runtime";import{Fragment as Dr0}from"preact";import{jsxDEV as Ro}from"preact/jsx-dev-runtime";var GUw=/(\*[^*]+\*)/;function Xr0(A,Q){let w=A.split(`
|
|
8359
|
-
`);return Ro(Dr0,{children:w.map((B,$)=>Ro(Dr0,{children:[$>0&&Ro("br",{},void 0,!1,void 0,this),B.split(GUw).map((Y,D)=>{if(Y.length>=3&&Y.startsWith("*")&&Y.endsWith("*"))return Ro("span",{className:Q,children:Y.slice(1,-1)},D,!1,void 0,this);return Ro(Dr0,{children:Y},D,!1,void 0,this)})]},$,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as cD,Fragment as MUw}from"preact/jsx-dev-runtime";var zUw="italic text-accent font-normal",qUw="You are here",FUw={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},VUw={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},JUw={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},IUw="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",bUw="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",LUw="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",NUw="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",jUw=({card:A})=>{let Q=A.linkLabel===qUw,w=A.linkHref.trim().length===0,B=cD(MUw,{children:[cD(xo,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),cD("span",{className:`${IUw} ${FUw[A.suffix]}`,children:A.title},void 0,!1,void 0,this),cD("p",{className:bUw,children:A.body},void 0,!1,void 0,this),Q?cD("span",{className:NUw,children:A.linkLabel},void 0,!1,void 0,this):cD("span",{className:LUw,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?VUw[A.suffix]:"border-white/10"}`;return Q||w?cD("div",{className:$,children:B},void 0,!1,void 0,this):cD("a",{href:A.linkHref,className:`${$} text-inherit no-underline transition-colors ${JUw[A.suffix]}`,children:B},void 0,!1,void 0,this)},Hr0=({eyebrow:A,headline:Q,cards:w})=>cD(Yr0,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[cD("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[cD("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),cD("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:Xr0(Q,zUw)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),cD("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)=>cD(jUw,{card:B},B.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);var _Uw=[{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 ua1(A){return{eyebrow:"The Ecosystem",headline:"One practice. *Three faces.*",cards:_Uw.map((Q)=>Q.suffix===A?{...Q,linkLabel:"You are here",linkHref:""}:Q)}}var PUw=ua1();var Wr0=R1({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:Po,formatter:{parse:jD0,format:ma1},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:Hr0}});var ca1={name:"@brains/rizom-ecosystem",private:!0,version:"0.2.0-alpha.
|
|
8359
|
+
`);return Ro(Dr0,{children:w.map((B,$)=>Ro(Dr0,{children:[$>0&&Ro("br",{},void 0,!1,void 0,this),B.split(GUw).map((Y,D)=>{if(Y.length>=3&&Y.startsWith("*")&&Y.endsWith("*"))return Ro("span",{className:Q,children:Y.slice(1,-1)},D,!1,void 0,this);return Ro(Dr0,{children:Y},D,!1,void 0,this)})]},$,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as cD,Fragment as MUw}from"preact/jsx-dev-runtime";var zUw="italic text-accent font-normal",qUw="You are here",FUw={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},VUw={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},JUw={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},IUw="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",bUw="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",LUw="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",NUw="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",jUw=({card:A})=>{let Q=A.linkLabel===qUw,w=A.linkHref.trim().length===0,B=cD(MUw,{children:[cD(xo,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),cD("span",{className:`${IUw} ${FUw[A.suffix]}`,children:A.title},void 0,!1,void 0,this),cD("p",{className:bUw,children:A.body},void 0,!1,void 0,this),Q?cD("span",{className:NUw,children:A.linkLabel},void 0,!1,void 0,this):cD("span",{className:LUw,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?VUw[A.suffix]:"border-white/10"}`;return Q||w?cD("div",{className:$,children:B},void 0,!1,void 0,this):cD("a",{href:A.linkHref,className:`${$} text-inherit no-underline transition-colors ${JUw[A.suffix]}`,children:B},void 0,!1,void 0,this)},Hr0=({eyebrow:A,headline:Q,cards:w})=>cD(Yr0,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[cD("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[cD("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),cD("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:Xr0(Q,zUw)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),cD("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)=>cD(jUw,{card:B},B.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);var _Uw=[{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 ua1(A){return{eyebrow:"The Ecosystem",headline:"One practice. *Three faces.*",cards:_Uw.map((Q)=>Q.suffix===A?{...Q,linkLabel:"You are here",linkHref:""}:Q)}}var PUw=ua1();var Wr0=R1({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:Po,formatter:{parse:jD0,format:ma1},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:Hr0}});var ca1={name:"@brains/rizom-ecosystem",private:!0,version:"0.2.0-alpha.139",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 fr0 extends kQ{entityType="ecosystem-section";schema=ko;adapter=wr0;constructor(A={}){super("rizom-ecosystem",ca1,A,K.object({}).default({}))}getTemplates(){return{ecosystem:Wr0}}getDataSources(){return[new MD0]}}function CP(A={}){return new fr0(A)}Z0();c0();c0();Z0();l$();Z0();c0();var K9="agent",la1="agent-discovery";var pa1="agent-network",ia1="AgentNetworkWidget",ho="agent-discovery:entities",Zr0="agent-list",Kr0="agent-detail",z5="skill",da1="skill",PD0="skill-derivation",na1="skill:project",ra1="skill-derivation",oa1="skill:skill-derivation",sa1="skills";var OE=K.object({name:K.string(),description:K.string(),tags:K.array(K.string())}),Wf=K.enum(["discovered","approved"]).describe("Discovered for review or approved for calling"),MK=wZ.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:Wf,discoveredAt:K.string().datetime().describe("When this agent was first discovered")}),aa1=MK.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:aa1}),vo=xE.extend({frontmatter:MK,about:K.string(),skills:K.array(OE),notes:K.string()}),RE=vo.extend({url:K.string().optional(),typeLabel:K.string().optional()}),OUw=vo.extend({url:K.string(),typeLabel:K.string()});Z0();var xUw=K.array(OE);function ta1(A){let Q=xUw.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(`
|
|
8360
8360
|
`)}function ea1(A){if(!A.trim())return[];let Q=[];for(let w of A.split(`
|
|
8361
8361
|
`)){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 RUw=K.object({about:K.string(),skills:K.array(OE),notes:K.string()}),At1=new pw(RUw,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:ta1,parser:ea1},{key:"notes",label:"Notes",type:"string"}]});class x4 extends J2{constructor(){super({entityType:K9,purpose:"A saved remote peer-brain contact in the local agent directory.",schema:xE,frontmatterSchema:MK})}fromMarkdown(A){let Q=this.parseFrontMatter(A,MK),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:Wf.parse(A.status),discoveredAt:A.discoveredAt},w=At1.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=At1.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,MK),body:this.parseAgentContent(A.content)}}}c0();var hUw=new x4,vUw=FU.extend({status:Wf.optional()}),CUw=VU.extend({query:vUw.optional()});function yUw(A){let Q=v2(A.content,MK),w=hUw.parseAgentContent(A.content);return vo.parse({...A,frontmatter:Q.metadata,about:w.about,skills:w.skills,notes:w.notes})}class kD0 extends f${id=ho;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 yUw(A)}buildDetailResult(A,Q){return{agent:A,prevAgent:Q?.prev??null,nextAgent:Q?.next??null}}parseQuery(A){let Q=CUw.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}buildListResult(A,Q,w){let B=Wf.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 OD0(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 TS(Y)}catch{return null}}function Co(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 EUw=new x4;function Qt1(A){return A.trim().toLowerCase().replace(/[_\s]+/g,"-")}function mb(A){let Q=new Set,w=[];for(let B of A){let $=Qt1(B);if(!$||Q.has($))continue;Q.add($),w.push($)}return w}function gUw(A,Q){if(Q.count!==A.count)return Q.count-A.count;return A.tag.localeCompare(Q.tag)}async function wt1(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=EUw.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(gUw).slice(0,B)}function Bt1(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(`
|
|
8362
8362
|
`)}var TUw=new x4;function xD0(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:TUw.createAgentContent({name:w,kind:B,...A.anchor?.organization&&{organization:A.anchor.organization},brainName:A.brainName,url:A.url,status:Y,discoveredAt:D,about:$.join(`
|
|
@@ -8457,7 +8457,7 @@ ${A.guidance}`:$}}function fa1(A){return{...A,evidence:A.evidence.map((Q)=>({...
|
|
|
8457
8457
|
setTagFilter("all");
|
|
8458
8458
|
});
|
|
8459
8459
|
})();`;import{jsxDEV as Aw}from"preact/jsx-dev-runtime";function nUw({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 rUw({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 oUw({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(nUw,{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 sUw({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(rUw,{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 zr0({data:A}){let Q=Ht1.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:Gr0.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),Gr0.map((B)=>Aw(oUw,{kind:B,items:w.agents[B],active:B==="all"},B,!1,void 0,this)),Aw(sUw,{skills:w.skills,count:w.counts.skills,filters:w.skillFilters},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function ft1(A,Q){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:pa1,pluginId:Q,title:"Agent Network",section:"secondary",priority:15,rendererName:ia1,component:zr0,clientScript:hD0,dataProvider:async()=>Wt1(A)}}),{success:!0}})}Z0();var Zt1=new x4;function aUw(A){return A.skills.map((Q)=>({name:Q.name,description:Q.description,tags:Q.tags??[]}))}function tUw(A){return new URL(A).hostname}function eUw(A){return[`ATProto card: ${A.uri}`,`ATProto card CID: ${A.cid}`,`ATProto repo DID: ${A.repoDid}`].join(`
|
|
8460
|
-
`)}function AGw(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 QGw(A,Q,w){await A.messaging.send({type:Q,payload:w,broadcast:!0})}async function wGw(A,Q,w=new Date().toISOString()){let{record:B}=Q,$=tUw(B.siteUrl),Y=await A.entityService.getEntity({entityType:"agent",id:$}),D=Y?Zt1.parseEntity(Y):void 0,X=B.brain.did,H=B.anchor.did,W=aUw(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,L=Y?.metadata.discoveredAt??w,b=B.brain.purpose||D?.body.about||"",N=W.length>0?W:D?.body.skills??[],_={...Y?.metadata??{},name:F,url:Z,status:f,discoveredAt:L,slug:G,repoDid:Q.repoDid,...X&&{brainDid:X},...H&&{anchorDid:H},cardUri:Q.uri,cardCid:Q.cid},j=Zt1.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:L,about:b,skills:N,notes:eUw({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 Kt1(A){A.messaging.subscribe(P40,async(Q)=>{let w=cp1.parse(Q.payload),B=await wGw(A,w),$=AGw({agent:B.agent,repoDid:w.repoDid,uri:w.uri,cid:w.cid,record:w.record});return await QGw(A,B.created?mp1:up1,$),{success:!0,data:$}})}function Ut1(){return["Agent entities represent saved peer-brain contacts in the local agent directory. List saved agent contacts with system_list on entityType agent. For expertise-match or recommendation questions over the user's agent network (for example who to consult/ask about a topic), immediately call one system_search with scope.kind type, scope.entityType agent, and the requested topic/skill; do not run parallel synonym searches unless the first result is inconclusive. Do not answer with generic role categories or offer to search later. If any result is plausible, suggest the saved agent by name/domain, include its exact callable id/domain from the search result (for example: Brand Studio, agent id brand-studio.example), and briefly explain the matching skill evidence. Prefer approved contacts over discovered contacts when both plausibly match; mention discovered contacts only with a clear review/confidence caveat.","If the previous assistant turn offered to search or narrow down the agent network, treat short affirmative follow-ups like please, yes, yes please, do that, or go ahead as consent to run that same agent expertise search using the topic from the prior user request.","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. If an exact-domain agent_call cannot verify or contact an unsaved domain, tell the user they can add/save/connect that domain as a contact, and a short follow-up like 'please add' should call agent_connect for the same domain without requiring a separate approval gate.","Agent lifecycle is tracked with status fields such as discovered and approved; approval operations are system_update field changes for already saved discovered contacts. If the user asks to approve a saved agent contact by exact id such as approval-candidate.io, call system_update on entityType agent with that id and the requested status; do not use agent_connect for approval.","When the user asks to contact/call/ask a saved contact by a human display name or anchor/contact name (for example 'Ask my contact Yeehaa ...'), first resolve that name against saved agent entities with system_search scoped to entityType agent unless the user already supplied an exact domain-like id. Then pass agent_call.agent as the saved agent entity id/domain from the search result (for example yeehaa.io or brand-studio.example), not the display name, anchorName, or brainName. When calling a recommended or previously searched saved agent, also use the saved agent entity id/domain from the search result. Calling remote agents and saving local contact records are separate capabilities. Only approved saved agents are active call targets; do not contact discovered or otherwise unapproved contacts."].join(" ")}c0();IB();Z0();import{jsxDEV as Gt1}from"preact/jsx-dev-runtime";function vD0(A){try{return new URL(A).hostname}catch{return A}}var CD0=({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 Gt1("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)},yD0=({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 Gt1("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 YGw}from"preact/jsx-dev-runtime";var BGw=({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 $Gw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function zt1(A,Q,w){let B=new URLSearchParams({status:Q});if(w>1)B.set("page",String(w));return`${A}?${B.toString()}`}var qr0=({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(CD0,{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(yD0,{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(BGw,{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:vD0(Q.url)},void 0,!1,void 0,this),j2("span",{className:"text-[11px] text-theme-muted opacity-60",children:Y?`Discovered ${$Gw(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)},qt1=({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(YGw,{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(qr0,{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(qr0,{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(qr0,{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:zt1(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:zt1(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 WGw}from"preact/jsx-dev-runtime";function DGw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}var yo=({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),XGw=({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),HGw=({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),Ft1=({agent:A,prevAgent:Q,nextAgent:w})=>{let{frontmatter:B,about:$,skills:Y,notes:D}=A,X=vD0(B.url),H=B.status==="approved";return U2(WGw,{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(CD0,{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(yD0,{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 ",DGw(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(yo,{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(yo,{children:"Skills"},void 0,!1,void 0,this),U2("div",{className:"flex flex-col gap-2.5",children:Y.map((W)=>U2(XGw,{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(yo,{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(yo,{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(yo,{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(HGw,{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 fGw=K.object({agents:K.array(RE),pageTitle:K.string().optional(),pagination:A4.nullable(),baseUrl:K.string().optional(),selectedStatus:K.union([K.literal("all"),Wf])});function Vt1(){return{[Zr0]:R1({name:Zr0,description:"Agent directory list page template",schema:fGw,dataSourceId:ho,requiredPermission:"public",layout:{component:qt1}}),[Kr0]:R1({name:Kr0,description:"Individual agent profile template",schema:K.object({agent:RE,prevAgent:RE.nullable(),nextAgent:RE.nullable()}),dataSourceId:ho,requiredPermission:"public",layout:{component:Ft1}})}}var hE={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.138",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 KGw=new x4;class Fr0 extends kQ{entityType=K9;schema=xE;adapter=KGw;constructor(){super(la1,hE)}createGenerationHandler(A){return new Ur0(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return Vt1()}getDataSources(){return[new kD0(this.logger.child("AgentDataSource"))]}async onRegister(A){Kt1(A),ft1(A,this.id)}async getInstructions(){return Ut1()}}function Vr0(){return new Fr0}c0();Z0();k9();Z0();var Jt1=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()}),UGw=new x4;function GGw(A){let Q=Co(A);if(!Q)return null;return{domain:Q,fetchTarget:A.trim().startsWith("http")?A.trim():Q}}function zGw(A,Q){return(Co(Q)||A).toLowerCase()}async function qGw(A){let{context:Q,entityId:w,card:B}=A,$=new Date().toISOString(),Y=await Q.entityService.getEntity({entityType:K9,id:w}),D=xD0(B,{status:"approved"}),H={...UGw.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 It1(A,Q=globalThis.fetch){let B=new pf;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:Jt1.shape,visibility:"trusted",sideEffects:"external",handler:async($,Y)=>{let D=Jt1.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=GGw(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 OD0(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:L}=await qGw({context:A,entityId:F,sourceUrl:X.source.url,card:G});return{success:!0,data:{status:V.metadata.status,entityId:V.id,connected:!0,created:L,a2aEndpoint:G.url,skills:G.skills.map((b)=>({name:b.name,description:b.description,tags:b.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 FGw=K.object({}).strict();class Jr0 extends IQ{fetchFn;constructor(A){super("agent",hE,{},FGw);this.fetchFn=A}async getTools(){return[It1(this.getContext(),this.fetchFn)]}}function Ir0(){return new Jr0}c0();Z0();c0();var vE=jX,bt1=jX,Eo=o1.extend({entityType:K.literal(z5),metadata:bt1});c0();class CE extends J2{constructor(){super({entityType:z5,purpose:"A capability advertised by a remote agent.",schema:Eo,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 VGw=K.object({skills:K.array(vE).max(8)}),Lt1=R1({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:VGw,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
|
|
8460
|
+
`)}function AGw(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 QGw(A,Q,w){await A.messaging.send({type:Q,payload:w,broadcast:!0})}async function wGw(A,Q,w=new Date().toISOString()){let{record:B}=Q,$=tUw(B.siteUrl),Y=await A.entityService.getEntity({entityType:"agent",id:$}),D=Y?Zt1.parseEntity(Y):void 0,X=B.brain.did,H=B.anchor.did,W=aUw(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,L=Y?.metadata.discoveredAt??w,b=B.brain.purpose||D?.body.about||"",N=W.length>0?W:D?.body.skills??[],_={...Y?.metadata??{},name:F,url:Z,status:f,discoveredAt:L,slug:G,repoDid:Q.repoDid,...X&&{brainDid:X},...H&&{anchorDid:H},cardUri:Q.uri,cardCid:Q.cid},j=Zt1.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:L,about:b,skills:N,notes:eUw({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 Kt1(A){A.messaging.subscribe(P40,async(Q)=>{let w=cp1.parse(Q.payload),B=await wGw(A,w),$=AGw({agent:B.agent,repoDid:w.repoDid,uri:w.uri,cid:w.cid,record:w.record});return await QGw(A,B.created?mp1:up1,$),{success:!0,data:$}})}function Ut1(){return["Agent entities represent saved peer-brain contacts in the local agent directory. List saved agent contacts with system_list on entityType agent. For expertise-match or recommendation questions over the user's agent network (for example who to consult/ask about a topic), immediately call one system_search with scope.kind type, scope.entityType agent, and the requested topic/skill; do not run parallel synonym searches unless the first result is inconclusive. Do not answer with generic role categories or offer to search later. If any result is plausible, suggest the saved agent by name/domain, include its exact callable id/domain from the search result (for example: Brand Studio, agent id brand-studio.example), and briefly explain the matching skill evidence. Prefer approved contacts over discovered contacts when both plausibly match; mention discovered contacts only with a clear review/confidence caveat.","If the previous assistant turn offered to search or narrow down the agent network, treat short affirmative follow-ups like please, yes, yes please, do that, or go ahead as consent to run that same agent expertise search using the topic from the prior user request.","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. If an exact-domain agent_call cannot verify or contact an unsaved domain, tell the user they can add/save/connect that domain as a contact, and a short follow-up like 'please add' should call agent_connect for the same domain without requiring a separate approval gate.","Agent lifecycle is tracked with status fields such as discovered and approved; approval operations are system_update field changes for already saved discovered contacts. If the user asks to approve a saved agent contact by exact id such as approval-candidate.io, call system_update on entityType agent with that id and the requested status; do not use agent_connect for approval.","When the user asks to contact/call/ask a saved contact by a human display name or anchor/contact name (for example 'Ask my contact Yeehaa ...'), first resolve that name against saved agent entities with system_search scoped to entityType agent unless the user already supplied an exact domain-like id. Then pass agent_call.agent as the saved agent entity id/domain from the search result (for example yeehaa.io or brand-studio.example), not the display name, anchorName, or brainName. When calling a recommended or previously searched saved agent, also use the saved agent entity id/domain from the search result. Calling remote agents and saving local contact records are separate capabilities. Only approved saved agents are active call targets; do not contact discovered or otherwise unapproved contacts."].join(" ")}c0();IB();Z0();import{jsxDEV as Gt1}from"preact/jsx-dev-runtime";function vD0(A){try{return new URL(A).hostname}catch{return A}}var CD0=({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 Gt1("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)},yD0=({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 Gt1("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 YGw}from"preact/jsx-dev-runtime";var BGw=({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 $Gw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric"})}function zt1(A,Q,w){let B=new URLSearchParams({status:Q});if(w>1)B.set("page",String(w));return`${A}?${B.toString()}`}var qr0=({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(CD0,{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(yD0,{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(BGw,{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:vD0(Q.url)},void 0,!1,void 0,this),j2("span",{className:"text-[11px] text-theme-muted opacity-60",children:Y?`Discovered ${$Gw(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)},qt1=({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(YGw,{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(qr0,{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(qr0,{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(qr0,{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:zt1(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:zt1(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 WGw}from"preact/jsx-dev-runtime";function DGw(A){return new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}var yo=({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),XGw=({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),HGw=({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),Ft1=({agent:A,prevAgent:Q,nextAgent:w})=>{let{frontmatter:B,about:$,skills:Y,notes:D}=A,X=vD0(B.url),H=B.status==="approved";return U2(WGw,{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(CD0,{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(yD0,{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 ",DGw(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(yo,{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(yo,{children:"Skills"},void 0,!1,void 0,this),U2("div",{className:"flex flex-col gap-2.5",children:Y.map((W)=>U2(XGw,{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(yo,{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(yo,{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(yo,{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(HGw,{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 fGw=K.object({agents:K.array(RE),pageTitle:K.string().optional(),pagination:A4.nullable(),baseUrl:K.string().optional(),selectedStatus:K.union([K.literal("all"),Wf])});function Vt1(){return{[Zr0]:R1({name:Zr0,description:"Agent directory list page template",schema:fGw,dataSourceId:ho,requiredPermission:"public",layout:{component:qt1}}),[Kr0]:R1({name:Kr0,description:"Individual agent profile template",schema:K.object({agent:RE,prevAgent:RE.nullable(),nextAgent:RE.nullable()}),dataSourceId:ho,requiredPermission:"public",layout:{component:Ft1}})}}var hE={name:"@brains/agent-discovery",private:!0,version:"0.2.0-alpha.139",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 KGw=new x4;class Fr0 extends kQ{entityType=K9;schema=xE;adapter=KGw;constructor(){super(la1,hE)}createGenerationHandler(A){return new Ur0(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return Vt1()}getDataSources(){return[new kD0(this.logger.child("AgentDataSource"))]}async onRegister(A){Kt1(A),ft1(A,this.id)}async getInstructions(){return Ut1()}}function Vr0(){return new Fr0}c0();Z0();k9();Z0();var Jt1=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()}),UGw=new x4;function GGw(A){let Q=Co(A);if(!Q)return null;return{domain:Q,fetchTarget:A.trim().startsWith("http")?A.trim():Q}}function zGw(A,Q){return(Co(Q)||A).toLowerCase()}async function qGw(A){let{context:Q,entityId:w,card:B}=A,$=new Date().toISOString(),Y=await Q.entityService.getEntity({entityType:K9,id:w}),D=xD0(B,{status:"approved"}),H={...UGw.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 It1(A,Q=globalThis.fetch){let B=new pf;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:Jt1.shape,visibility:"trusted",sideEffects:"external",handler:async($,Y)=>{let D=Jt1.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=GGw(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 OD0(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:L}=await qGw({context:A,entityId:F,sourceUrl:X.source.url,card:G});return{success:!0,data:{status:V.metadata.status,entityId:V.id,connected:!0,created:L,a2aEndpoint:G.url,skills:G.skills.map((b)=>({name:b.name,description:b.description,tags:b.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 FGw=K.object({}).strict();class Jr0 extends IQ{fetchFn;constructor(A){super("agent",hE,{},FGw);this.fetchFn=A}async getTools(){return[It1(this.getContext(),this.fetchFn)]}}function Ir0(){return new Jr0}c0();Z0();c0();var vE=jX,bt1=jX,Eo=o1.extend({entityType:K.literal(z5),metadata:bt1});c0();class CE extends J2{constructor(){super({entityType:z5,purpose:"A capability advertised by a remote agent.",schema:Eo,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 VGw=K.object({skills:K.array(vE).max(8)}),Lt1=R1({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:VGw,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
|
|
8461
8461
|
|
|
8462
8462
|
Given knowledge domains, CONSOLIDATE related topics into broader skills.
|
|
8463
8463
|
There should be FEWER skills than topics \u2014 combine related domains.
|
|
@@ -8607,9 +8607,9 @@ Context:
|
|
|
8607
8607
|
${JSON.stringify(B,null,2)}
|
|
8608
8608
|
|
|
8609
8609
|
Draft SWOT:
|
|
8610
|
-
${JSON.stringify(w,null,2)}`}function lD0(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function mGw(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 pD0{logger;context;adapter=new LF;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=Nr0.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 kr0(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 gGw(this.context,B),jr0),f=jr0.parse(W);await w.report({progress:0.75,message:"Refining SWOT language"});let Z=await this.context.ai.generateObject(await SGw(this.context,B,f),mD0);$=mD0.parse(Z.object),mGw(f,$)}let D=new Date().toISOString(),X=this.adapter.createSwotContent({strengths:lD0($.strengths),weaknesses:lD0($.weaknesses),opportunities:lD0($.opportunities),threats:lD0($.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 R4}from"preact/jsx-dev-runtime";var iD0=K.object({title:K.string(),detail:K.string().optional()}),uGw=K.discriminatedUnion("status",[K.object({status:K.literal("generating")}),K.object({status:K.literal("ready"),strengths:K.array(iD0).default([]),weaknesses:K.array(iD0).default([]),opportunities:K.array(iD0).default([]),threats:K.array(iD0).default([]),derivedAt:K.string()})]);function cGw({items:A}){if(A.length===0)return R4("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return R4("ul",{class:"swot-list",children:A.map((Q)=>R4("li",{class:"swot-item",children:[R4("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?R4("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 dD0({title:A,tone:Q,items:w}){return R4("section",{class:`swot-cell is-${Q}`,children:[R4("div",{class:"swot-head",children:A},void 0,!1,void 0,this),R4(cGw,{items:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Rr0({data:A}){let Q=uGw.safeParse(A);if(!Q.success||Q.data.status==="generating")return R4("div",{"data-swot-widget":!0,children:R4("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let w=Q.data;return R4("div",{"data-swot-widget":!0,children:R4("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[R4(dD0,{title:"Strengths",tone:"s",items:w.strengths},void 0,!1,void 0,this),R4(dD0,{title:"Weaknesses",tone:"w",items:w.weaknesses},void 0,!1,void 0,this),R4(dD0,{title:"Opportunities",tone:"o",items:w.opportunities},void 0,!1,void 0,this),R4(dD0,{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 hr0={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.
|
|
8610
|
+
${JSON.stringify(w,null,2)}`}function lD0(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function mGw(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 pD0{logger;context;adapter=new LF;constructor(A,Q){this.logger=A;this.context=Q}validateAndParse(A){let Q=Nr0.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 kr0(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 gGw(this.context,B),jr0),f=jr0.parse(W);await w.report({progress:0.75,message:"Refining SWOT language"});let Z=await this.context.ai.generateObject(await SGw(this.context,B,f),mD0);$=mD0.parse(Z.object),mGw(f,$)}let D=new Date().toISOString(),X=this.adapter.createSwotContent({strengths:lD0($.strengths),weaknesses:lD0($.weaknesses),opportunities:lD0($.opportunities),threats:lD0($.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 R4}from"preact/jsx-dev-runtime";var iD0=K.object({title:K.string(),detail:K.string().optional()}),uGw=K.discriminatedUnion("status",[K.object({status:K.literal("generating")}),K.object({status:K.literal("ready"),strengths:K.array(iD0).default([]),weaknesses:K.array(iD0).default([]),opportunities:K.array(iD0).default([]),threats:K.array(iD0).default([]),derivedAt:K.string()})]);function cGw({items:A}){if(A.length===0)return R4("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return R4("ul",{class:"swot-list",children:A.map((Q)=>R4("li",{class:"swot-item",children:[R4("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?R4("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 dD0({title:A,tone:Q,items:w}){return R4("section",{class:`swot-cell is-${Q}`,children:[R4("div",{class:"swot-head",children:A},void 0,!1,void 0,this),R4(cGw,{items:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Rr0({data:A}){let Q=uGw.safeParse(A);if(!Q.success||Q.data.status==="generating")return R4("div",{"data-swot-widget":!0,children:R4("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let w=Q.data;return R4("div",{"data-swot-widget":!0,children:R4("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[R4(dD0,{title:"Strengths",tone:"s",items:w.strengths},void 0,!1,void 0,this),R4(dD0,{title:"Weaknesses",tone:"w",items:w.weaknesses},void 0,!1,void 0,this),R4(dD0,{title:"Opportunities",tone:"o",items:w.opportunities},void 0,!1,void 0,this),R4(dD0,{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 hr0={name:"@brains/assessment",private:!0,version:"0.2.0-alpha.139",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 vr0=new LF;class Cr0 extends kQ{entityType="swot";schema=yE;adapter=vr0;initialSyncComplete=!1;constructor(){super("swot",hr0)}async onRegister(A){let Q=new pD0(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q),A.eval.registerHandler("deriveSwot",async()=>{let Y=X7.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 vr0.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:Rr0,dataProvider:async()=>{let Y=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!Y)return{status:"generating"};let{frontmatter:D}=vr0.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 yr0(){return new Cr0}c0();l$();Z0();var e76=new LF,Et1=K.object({name:K.string(),description:K.string(),tags:K.array(K.string())}),Er0=K.enum(["discovered","approved"]),pGw=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:Er0,discoveredAt:K.string().datetime()}),iGw=o1.extend({entityType:K.literal("agent"),metadata:K.object({name:K.string(),url:K.string().url(),status:Er0,slug:K.string()})}),dGw=o1.extend({entityType:K.literal("skill"),metadata:jX}),nGw=K.object({about:K.string(),skills:K.array(Et1),notes:K.string()});function rGw(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(`
|
|
8611
8611
|
`)}function oGw(A){if(!A.trim())return[];return A.split(`
|
|
8612
|
-
`).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 sGw=new pw(nGw,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:rGw,parser:oGw},{key:"notes",label:"Notes",type:"string"}]});class gt1 extends J2{constructor(){super({entityType:"agent",purpose:"An agent entity used for SWOT evaluation.",schema:iGw,frontmatterSchema:pGw})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=sGw.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 Tt1 extends J2{constructor(){super({entityType:"skill",purpose:"A skill entity used for SWOT evaluation.",schema:dGw,frontmatterSchema:jX})}fromMarkdown(A){let Q=this.parseFrontMatter(A,jX);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var A46=new gt1,Q46=new Tt1,w46=K.object({skills:K.array(jX),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:Er0,discoveredAt:K.string().datetime().optional(),about:K.string(),skills:K.array(Et1),notes:K.string().default("")}))});var aGw=K.object({}).strict();function nD0(A={}){return aGw.parse(A),[yr0()]}c0();Z0();Z0();var gr0=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 tGw(A){return A.replace(/\/+$/,"")}var eGw=(A,Q)=>fetch(A,Q);async function To(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 So{pdsEndpoint;identifier;appPassword;fetchFn;session;constructor(A){this.pdsEndpoint=tGw(A.pdsEndpoint),this.identifier=A.identifier,this.appPassword=A.appPassword,this.fetchFn=A.fetch??eGw}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 To(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 To(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 To(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 To(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 To(w)}async getSession(){return this.session??=await this.createSession(),this.session}}function EP(A){return A?.startsWith("did:web:")??!1}function rD0(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 mt1(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 ut1(A){return A.replace(/\/+$/,"")}function mo(A){return`did:web:${encodeURIComponent(A)}`}function oD0(A){return`${mo(A)}:anchor`}function Tr0(A){return{"@context":["https://www.w3.org/ns/did/v1"],id:A}}function ct1(A,Q){let w=A.identifier?.startsWith("did:")?void 0:A.identifier?[`at://${A.identifier}`]:void 0;return{...Tr0(Q),...w&&{alsoKnownAs:w},service:[{id:"#atproto_pds",type:"AtprotoPersonalDataServer",serviceEndpoint:ut1(A.pdsEndpoint)}]}}function lt1(A){if(!EP(A.brainDid))return null;return ct1(A,A.brainDid)}function St1(A,Q){if(!A||!Q)return;let w=rD0(A),B=mt1(A);if(!w||!B)return;return{path:B,hostname:w,document:Q}}function sD0(A){let Q=[],w=St1(A.brainDid,lt1(A));if(w)Q.push(w);if(EP(A.anchorDid)&&A.anchorDid!==A.brainDid){let B=St1(A.anchorDid,Tr0(A.anchorDid));if(B)Q.push(B)}return Q}function Sr0(A,Q){let w=[];if(!A.brainDid){let B=mo(Q);w.push({path:"/.well-known/did.json",hostname:Q,document:ct1(A,B)})}if(!A.anchorDid){let B=oD0(Q);w.push({path:"/anchor/did.json",hostname:Q,document:Tr0(B)})}return w}function Azw(A,Q){if(!A)return;try{return new URL(A,Q).toString()}catch{return}}function Qzw(A){let Q=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,200);return Q.length>0?Q:"skill"}function pt1(A,Q){let w=A[Q];return typeof w==="string"&&w.length>0?w:void 0}function it1(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 wzw(A){let Q=A.metadata,w=pt1(Q,"name"),B=pt1(Q,"description");if(!w||!B)return;let $=it1(Q,"tags"),Y=it1(Q,"examples");return{id:Qzw(w),name:w,description:B,...$&&{tags:$},...Y&&{examples:Y}}}async function Bzw(A){if(!A.entityService.hasEntityType("skill"))return[];return(await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}})).map((w)=>wzw(w)).filter((w)=>w!==void 0).slice(0,100)}async function mr0(A,Q,w=new Date){let B=A.identity.get(),$=A.identity.getProfile(),Y=await A.identity.getAppInfo(),D=Azw(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??mo(X),W=Q.anchorDid??oD0(X);if(EP(H)){if(rD0(H)!==X)throw Error("AT Protocol brain card did:web host must match siteUrl host")}let f=await Bzw(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 dt1={name:"@brains/atproto",private:!0,version:"0.2.0-alpha.138",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 nt1=MB["ai.rizom.brain.card"],Yzw="ai.rizom.brain.card",Dzw="self",rt1=50;class ur0 extends IQ{deps;projectionRegistry;constructor(A={},Q={}){super("atproto",dt1,A,gr0);this.deps=Q,this.projectionRegistry=Q.projectionRegistry??U5.getInstance()}getWebRoutes(){if(!this.config.enabled)return[];let A=sD0(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=[...sD0(this.config),...Sr0(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 mr0(A,this.config);Lb(nt1,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>rt1)throw Error(`AT Protocol discovery accepts at most ${rt1} 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:Yzw,rkey:Dzw});Lb(nt1,H.value);let W=Hzw(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:P40,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:Xzw(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 So({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(Wzw(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 So({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A})}resolveAppPassword(){return this.config.appPassword}}function Xzw(A){let Q=A.replace(/[^A-Za-z0-9._~:-]/g,"_").slice(0,512);return Q.length>0?Q:"self"}function Hzw(A){return/^at:\/\/([^/]+)/.exec(A)?.[1]}function Wzw(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 aD0(A,Q){return new ur0(A,Q)}c0();Z0();var tD0={name:"@brains/rover",version:"0.2.0-alpha.138",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 Zzw=K.object({}).strict();class ot1 extends IQ{constructor(A={}){super("rover-profile",tD0,A,Zzw)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",xN)}}function st1(A={}){return new ot1(A)}c0();Z0();IB();_5();c0();var ub=wZ.extend(xN.shape);c0();Vq();Z0();var Kzw=new JU;class eD0{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}}),Fr(B)]),H=Kzw.parseProfileBody($,ub),W=Y.sort(xT).slice(0,3).map(Ir),f=D.sort(xT).slice(0,3).map(_r);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 Uzw=new JU;class AX0{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:Uzw.parseProfileBody(B,ub)};return Q.parse(Y)}}import{jsxDEV as F8,Fragment as qzw}from"preact/jsx-dev-runtime";var Gzw="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",cr0=({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:Gzw,children:[F8(nu0,{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),lr0=({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(qzw,{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:u90(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:u90(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F8(cr0,{number:"01",title:"Essays",blurb:D.essays?.blurb,children:F8(m90,{items:H,viewAllUrl:B,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.length>0&&F8(cr0,{number:"02",title:"Presentations",blurb:D.presentations?.blurb,children:F8(m90,{items:W,viewAllUrl:$,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),G&&F8(cr0,{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(ru0,{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(hu0,{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 Fzw}from"preact/jsx-dev-runtime";var pr0=({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(Fzw,{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:Vn({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 h4,Fragment as at1}from"preact/jsx-dev-runtime";var ir0=()=>{return h4(at1,{children:[h4(jQ,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),h4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:h4("div",{className:"text-center max-w-md",children:[h4("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),h4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),h4("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),h4(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)},dr0=()=>{return h4(at1,{children:[h4(jQ,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),h4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:h4("div",{className:"text-center max-w-md",children:[h4("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),h4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),h4("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),h4(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 tt1=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')")}),et1=K.object({entityDisplay:K.object({post:tt1,deck:tt1}).describe("Display metadata for post and deck entity types (required for homepage)")});var Ae1={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.138",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 nr0 extends IQ{dependencies=["blog","decks"];constructor(A){super("professional-site",Ae1,A,et1)}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 eD0(B,$);A.entities.registerDataSource(Y);let D=new AX0;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:Gp0,sections:K.record(K.string(),Be)}),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:lr0}}),about:R1({name:"about",description:"About page with full profile information",schema:H,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:pr0}}),"subscribe-thanks":R1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:W,requiredPermission:"public",layout:{component:ir0}}),"subscribe-error":R1({name:"subscribe-error",description:"Newsletter subscription error page",schema:W,requiredPermission:"public",layout:{component:dr0}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function Qe1(A){return new nr0(A??{})}var we1=[{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 QX0}from"preact/jsx-dev-runtime";function Be1({sections:A,siteInfo:Q,slots:w,wordmark:B}){return QX0("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[QX0(Eu0,{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),QX0("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),QX0(Cu0,{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 Jzw={layouts:{default:Be1},routes:we1,plugin:Qe1,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"}}}},uo=Jzw;var $e1=`/*
|
|
8612
|
+
`).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 sGw=new pw(nGw,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:rGw,parser:oGw},{key:"notes",label:"Notes",type:"string"}]});class gt1 extends J2{constructor(){super({entityType:"agent",purpose:"An agent entity used for SWOT evaluation.",schema:iGw,frontmatterSchema:pGw})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=sGw.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 Tt1 extends J2{constructor(){super({entityType:"skill",purpose:"A skill entity used for SWOT evaluation.",schema:dGw,frontmatterSchema:jX})}fromMarkdown(A){let Q=this.parseFrontMatter(A,jX);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var A46=new gt1,Q46=new Tt1,w46=K.object({skills:K.array(jX),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:Er0,discoveredAt:K.string().datetime().optional(),about:K.string(),skills:K.array(Et1),notes:K.string().default("")}))});var aGw=K.object({}).strict();function nD0(A={}){return aGw.parse(A),[yr0()]}c0();Z0();Z0();var gr0=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 tGw(A){return A.replace(/\/+$/,"")}var eGw=(A,Q)=>fetch(A,Q);async function To(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 So{pdsEndpoint;identifier;appPassword;fetchFn;session;constructor(A){this.pdsEndpoint=tGw(A.pdsEndpoint),this.identifier=A.identifier,this.appPassword=A.appPassword,this.fetchFn=A.fetch??eGw}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 To(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 To(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 To(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 To(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 To(w)}async getSession(){return this.session??=await this.createSession(),this.session}}function EP(A){return A?.startsWith("did:web:")??!1}function rD0(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 mt1(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 ut1(A){return A.replace(/\/+$/,"")}function mo(A){return`did:web:${encodeURIComponent(A)}`}function oD0(A){return`${mo(A)}:anchor`}function Tr0(A){return{"@context":["https://www.w3.org/ns/did/v1"],id:A}}function ct1(A,Q){let w=A.identifier?.startsWith("did:")?void 0:A.identifier?[`at://${A.identifier}`]:void 0;return{...Tr0(Q),...w&&{alsoKnownAs:w},service:[{id:"#atproto_pds",type:"AtprotoPersonalDataServer",serviceEndpoint:ut1(A.pdsEndpoint)}]}}function lt1(A){if(!EP(A.brainDid))return null;return ct1(A,A.brainDid)}function St1(A,Q){if(!A||!Q)return;let w=rD0(A),B=mt1(A);if(!w||!B)return;return{path:B,hostname:w,document:Q}}function sD0(A){let Q=[],w=St1(A.brainDid,lt1(A));if(w)Q.push(w);if(EP(A.anchorDid)&&A.anchorDid!==A.brainDid){let B=St1(A.anchorDid,Tr0(A.anchorDid));if(B)Q.push(B)}return Q}function Sr0(A,Q){let w=[];if(!A.brainDid){let B=mo(Q);w.push({path:"/.well-known/did.json",hostname:Q,document:ct1(A,B)})}if(!A.anchorDid){let B=oD0(Q);w.push({path:"/anchor/did.json",hostname:Q,document:Tr0(B)})}return w}function Azw(A,Q){if(!A)return;try{return new URL(A,Q).toString()}catch{return}}function Qzw(A){let Q=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,200);return Q.length>0?Q:"skill"}function pt1(A,Q){let w=A[Q];return typeof w==="string"&&w.length>0?w:void 0}function it1(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 wzw(A){let Q=A.metadata,w=pt1(Q,"name"),B=pt1(Q,"description");if(!w||!B)return;let $=it1(Q,"tags"),Y=it1(Q,"examples");return{id:Qzw(w),name:w,description:B,...$&&{tags:$},...Y&&{examples:Y}}}async function Bzw(A){if(!A.entityService.hasEntityType("skill"))return[];return(await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}})).map((w)=>wzw(w)).filter((w)=>w!==void 0).slice(0,100)}async function mr0(A,Q,w=new Date){let B=A.identity.get(),$=A.identity.getProfile(),Y=await A.identity.getAppInfo(),D=Azw(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??mo(X),W=Q.anchorDid??oD0(X);if(EP(H)){if(rD0(H)!==X)throw Error("AT Protocol brain card did:web host must match siteUrl host")}let f=await Bzw(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 dt1={name:"@brains/atproto",private:!0,version:"0.2.0-alpha.139",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 nt1=MB["ai.rizom.brain.card"],Yzw="ai.rizom.brain.card",Dzw="self",rt1=50;class ur0 extends IQ{deps;projectionRegistry;constructor(A={},Q={}){super("atproto",dt1,A,gr0);this.deps=Q,this.projectionRegistry=Q.projectionRegistry??U5.getInstance()}getWebRoutes(){if(!this.config.enabled)return[];let A=sD0(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=[...sD0(this.config),...Sr0(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 mr0(A,this.config);Lb(nt1,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>rt1)throw Error(`AT Protocol discovery accepts at most ${rt1} 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:Yzw,rkey:Dzw});Lb(nt1,H.value);let W=Hzw(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:P40,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:Xzw(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 So({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(Wzw(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 So({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A})}resolveAppPassword(){return this.config.appPassword}}function Xzw(A){let Q=A.replace(/[^A-Za-z0-9._~:-]/g,"_").slice(0,512);return Q.length>0?Q:"self"}function Hzw(A){return/^at:\/\/([^/]+)/.exec(A)?.[1]}function Wzw(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 aD0(A,Q){return new ur0(A,Q)}c0();Z0();var tD0={name:"@brains/rover",version:"0.2.0-alpha.139",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 Zzw=K.object({}).strict();class ot1 extends IQ{constructor(A={}){super("rover-profile",tD0,A,Zzw)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",xN)}}function st1(A={}){return new ot1(A)}c0();Z0();IB();_5();c0();var ub=wZ.extend(xN.shape);c0();Vq();Z0();var Kzw=new JU;class eD0{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}}),Fr(B)]),H=Kzw.parseProfileBody($,ub),W=Y.sort(xT).slice(0,3).map(Ir),f=D.sort(xT).slice(0,3).map(_r);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 Uzw=new JU;class AX0{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:Uzw.parseProfileBody(B,ub)};return Q.parse(Y)}}import{jsxDEV as F8,Fragment as qzw}from"preact/jsx-dev-runtime";var Gzw="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",cr0=({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:Gzw,children:[F8(nu0,{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),lr0=({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(qzw,{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:u90(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:u90(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F8(cr0,{number:"01",title:"Essays",blurb:D.essays?.blurb,children:F8(m90,{items:H,viewAllUrl:B,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),W.length>0&&F8(cr0,{number:"02",title:"Presentations",blurb:D.presentations?.blurb,children:F8(m90,{items:W,viewAllUrl:$,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),G&&F8(cr0,{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(ru0,{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(hu0,{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 Fzw}from"preact/jsx-dev-runtime";var pr0=({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(Fzw,{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:Vn({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 h4,Fragment as at1}from"preact/jsx-dev-runtime";var ir0=()=>{return h4(at1,{children:[h4(jQ,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),h4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:h4("div",{className:"text-center max-w-md",children:[h4("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),h4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),h4("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),h4(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)},dr0=()=>{return h4(at1,{children:[h4(jQ,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),h4("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:h4("div",{className:"text-center max-w-md",children:[h4("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),h4("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),h4("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),h4(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 tt1=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')")}),et1=K.object({entityDisplay:K.object({post:tt1,deck:tt1}).describe("Display metadata for post and deck entity types (required for homepage)")});var Ae1={name:"@brains/site-professional",private:!0,version:"0.2.0-alpha.139",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 nr0 extends IQ{dependencies=["blog","decks"];constructor(A){super("professional-site",Ae1,A,et1)}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 eD0(B,$);A.entities.registerDataSource(Y);let D=new AX0;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:Gp0,sections:K.record(K.string(),Be)}),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:lr0}}),about:R1({name:"about",description:"About page with full profile information",schema:H,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:pr0}}),"subscribe-thanks":R1({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:W,requiredPermission:"public",layout:{component:ir0}}),"subscribe-error":R1({name:"subscribe-error",description:"Newsletter subscription error page",schema:W,requiredPermission:"public",layout:{component:dr0}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function Qe1(A){return new nr0(A??{})}var we1=[{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 QX0}from"preact/jsx-dev-runtime";function Be1({sections:A,siteInfo:Q,slots:w,wordmark:B}){return QX0("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[QX0(Eu0,{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),QX0("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),QX0(Cu0,{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 Jzw={layouts:{default:Be1},routes:we1,plugin:Qe1,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"}}}},uo=Jzw;var $e1=`/*
|
|
8613
8613
|
* Default theme \u2014 simplified editorial base inspired by the Rizom family.
|
|
8614
8614
|
*
|
|
8615
8615
|
* This theme is intentionally less branded than @brains/theme-rizom. It
|
|
@@ -8997,8 +8997,8 @@ ${JSON.stringify(w,null,2)}`}function lD0(A){return A.map((Q)=>Q.detail===null?{
|
|
|
8997
8997
|
|
|
8998
8998
|
.btn-primary:disabled { opacity: 0.5; }
|
|
8999
8999
|
}
|
|
9000
|
-
`;var gE=$e1;import{join as bzw}from"path";var Ye1=["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"],De1=[...Ye1.filter((A)=>A!=="dashboard-root"),"dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],Lzw=[...De1,"portfolio","topics","content-pipeline","social-media","newsletter","stock-photo"],Nzw=["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."
|
|
9001
|
-
`,{headers:{"Content-Type":"application/json"}})}class or0 extends IQ{constructor(A={}){super("atproto-registry",He1,A,fe1)}getWebRoutes(){if(!this.config.enabled)return[];return[{path:`${rr0}/index.json`,method:"GET",public:!0,handler:()=>We1(this.getIndex())},...ZP().map((A)=>({path:`${rr0}/${A.id}.json`,method:"GET",public:!0,handler:()=>We1(A)}))]}getIndex(){return{lexicons:Jp0().map((A)=>({...A,path:`${rr0}/${A.id}.json`}))}}getLexicon(A){return Vp0(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:Jp0()}})}}}function sr0(A={}){return new or0(A)}c0();Z0();Z0();c0();var wX0=K.object({routeId:K.string(),sectionId:K.string()}),co=o1.extend({entityType:K.literal("site-content"),template:K.string().optional(),content:K.string(),metadata:wX0});c0();class Ze1 extends J2{constructor(){super({entityType:"site-content",purpose:"A content section bound to a route on the published site.",schema:co,frontmatterSchema:wX0})}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 ar0=new Ze1;Z0();var BX0=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")}),YX6=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 tr0{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 er0{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new tr0(A)}async generateContent(A,Q){let w=BX0.parse(A);return this.operations.generate(w,this.siteConfig,Q)}}l$();Z0();function lo(A,Q){return Q?A.optional():A}function Qo0(A){switch(A.type){case"string":return lo(K.string(),A.optional);case"number":return lo(K.number(),A.optional);case"enum":{let Q=[...A.options];return lo(K.enum(Q),A.optional)}case"object":{let Q={};for(let[w,B]of Object.entries(A.fields))Q[w]=Qo0(B);return lo(K.object(Q),A.optional)}case"array":{let Q=K.array(Mzw(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return lo(Q,A.optional)}}}function Mzw(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]=Qo0($);return K.object(w)}}}function Ao0(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])=>Ao0(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,$])=>Ao0(B,$)),w}}}}function _zw(A,Q){let w={};for(let[Y,D]of Object.entries(Q.fields))w[Y]=Qo0(D);let B=K.object(w),$=new pw(B,{title:Q.title,mappings:Object.entries(Q.fields).map(([Y,D])=>Ao0(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 wo0(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,w])=>[Q,_zw(Q,w)]))}Z0();var Ke1=K.object({namespace:K.string(),sections:K.record(K.any())}),Ue1=K.object({definitions:K.union([Ke1,K.array(Ke1)]).optional()});c0();function Ge1(A,Q){return[Sw(Q,"generate","Generate content for all routes, a specific route, or a specific section",BX0,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 ze1={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.138",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 Bo0 extends IQ{siteContentService;constructor(A={}){super("site-content",ze1,A,Ue1)}async onRegister(A){A.entities.register("site-content",co,ar0);for(let Q of HU(this.config.definitions))A.templates.register(wo0(Q),Q.namespace);this.siteContentService=new er0(A)}async getTools(){return Ge1(()=>this.siteContentService,this.id)}}function po(A={}){return new Bo0(A)}c0();Z0();IB();Z0();c0();var qe1=K.enum(["available","early access","coming soon","planned"]),Fe1=K.object({title:K.string(),description:K.string()}),vH=K.object({name:K.string(),availability:qe1,order:K.number(),ogImageId:K.string().optional()}),$X0=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(Fe1).min(1).max(6),story:K.string()}),kzw=vH.pick({name:!0,availability:!0,order:!0}).extend({slug:K.string()}),TE=o1.extend({entityType:K.literal("product"),metadata:kzw}),YX0=TE.extend({frontmatter:vH,body:$X0,labels:K.record(K.string(),K.string()),ogImageUrl:K.string().optional()}),DX0=YX0.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($X0,{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 $o0 extends J2{constructor(){super({entityType:"product",purpose:"A product entry in the portfolio.",schema:TE,frontmatterSchema:vH,bodyFormatter:new SE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,vH);return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,vH),w=w1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:w,availability:Q.availability,order:Q.order}}}}var XX0=new $o0;Z0();c0();var Ve1=K.object({title:K.string(),description:K.string()}),Je1=K.object({title:K.string(),description:K.string()}),Ozw=K.object({title:K.string(),description:K.string()}),Ie1=K.object({heading:K.string(),buttonText:K.string(),link:K.string()}),NF=K.object({headline:K.string(),tagline:K.string()}),xzw=K.object({title:K.string(),description:K.string()}),HX0=K.object({vision:K.string(),pillars:K.array(Ve1).min(1).max(6),approach:K.array(xzw).min(1).max(6),productsIntro:K.string(),technologies:K.array(Ozw).min(1).max(6),benefits:K.array(Je1).min(1).max(6),cta:Ie1}),be1=NF.pick({headline:!0}).extend({slug:K.string()}),mE=o1.extend({entityType:K.literal("products-overview"),metadata:be1}),io=mE.extend({frontmatter:NF,body:HX0,labels:K.record(K.string(),K.string())});c0();Z0();l$();class uE extends pw{constructor(){super(HX0,{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 Yo0 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 Do0=new Yo0;c0();Z0();var Rzw=K.object({entityType:K.string(),query:K.object({id:K.string().optional()}).optional()});function Le1(A,Q){let w=v2(A.content,vH),B=Q.parse(w.content),$=Q.getLabels();return YX0.parse({...A,frontmatter:w.metadata,body:B,labels:$})}function Ne1(A,Q){let w=v2(A.content,NF),B=Q.parse(w.content),$=Q.getLabels();return io.parse({...A,frontmatter:w.metadata,body:B,labels:$})}class WX0{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=Rzw.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=Ne1(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:Le1(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:Ne1(X,this.overviewFormatter),products:D.map((H)=>Le1(H,this.productFormatter))})}}import{jsxDEV as B1,Fragment as Czw}from"preact/jsx-dev-runtime";var je1=({overview:A,products:Q})=>{let{frontmatter:w,body:B,labels:$}=A;return B1(Czw,{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:`
|
|
9000
|
+
`;var gE=$e1;import{join as bzw}from"path";var Ye1=["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"],De1=[...Ye1.filter((A)=>A!=="dashboard-root"),"dashboard","blog","series","decks","analytics","obsidian-vault","site-info","site-builder"],Lzw=[...De1,"portfolio","topics","content-pipeline","social-media","newsletter","stock-photo"],Nzw=["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.",`When answering questions like "what have I written about X" or "which posts relate to this deck/source", search first and use semantic search results as candidates, not proof. Summarize only clearly relevant entities whose title or content directly matches the asked topic or has substantial overlap with the source's main themes; omit weak/tangential candidates rather than presenting them as definite matches. A match based on only an isolated shared term or pattern is not enough; when one candidate is clearly stronger than the rest, list only the strongest clear match and say the others were tangential rather than naming them as matches.`,'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.'],Xe1=LJ({name:"rover",version:tD0.version,model:"gpt-5.4-mini",site:uo,theme:gE,presets:{core:Ye1,default:De1,full:Lzw},evalDisable:["discord","chat","webserver","web-chat","mcp","atproto","analytics","dashboard","dashboard-root","email-resend"],agentInstructions:Nzw,capabilities:[["prompt",vP,void 0],["rover-profile",st1,{}],["image",zc,void 0],["cms",xP,(A)=>({...A.CMS_CONTENT_REPO_PAT?{passkeyLogin:{contentRepoToken:A.CMS_CONTENT_REPO_PAT}}:{}})],["auth-service",Dp,void 0],["notifications",tw0,void 0],["playbook",Qa1,{}],["playbooks",dn0,{}],["rover-onboarding",ja1,{}],["email-resend",i$0,void 0],["dashboard",Sb,void 0],["dashboard-root",Sb,{routePath:"/"}],["blog",yp0,{}],["series",up0,void 0],["decks",Pr,void 0],["document",di0,void 0],["note",LP,{}],["link",jP,{}],["portfolio",Id0,{}],["topics",iY0,{includeEntityTypes:["post","deck","project","link","anchor-profile"]}],["content-pipeline",Xn0,{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",fo,{autoGenerateOnBlogPublish:!0}],["newsletter",gs1,{doubleOptIn:!0}],["obsidian-vault",xn0,{autoSync:!0}],["wishlist",ID0,{}],["stock-photo",Qr0,{}],["agents",gD0,void 0],["assessment",nD0,void 0],["atproto",aD0,(A)=>({...A.ATPROTO_APP_PASSWORD?{appPassword:A.ATPROTO_APP_PASSWORD}:{}})],["directory-sync",M_,()=>({seedContent:!0,seedContentPath:bzw(import.meta.dir,"..","seed-content-core"),initialSync:!0})],["analytics",XD0,{}],["rizom-ecosystem",CP,void 0],["site-info",fP,void 0],["site-builder",WP,{cms:{}}]],interfaces:[["mcp",BI,()=>({})],["discord",uI,()=>({})],["chat",J50,()=>({})],["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 He1={name:"@brains/atproto-registry",private:!0,version:"0.2.0-alpha.139",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 fe1=K.object({enabled:K.boolean().default(!0)}),rr0="/atproto/lexicons";function We1(A){return new Response(`${JSON.stringify(A,null,2)}
|
|
9001
|
+
`,{headers:{"Content-Type":"application/json"}})}class or0 extends IQ{constructor(A={}){super("atproto-registry",He1,A,fe1)}getWebRoutes(){if(!this.config.enabled)return[];return[{path:`${rr0}/index.json`,method:"GET",public:!0,handler:()=>We1(this.getIndex())},...ZP().map((A)=>({path:`${rr0}/${A.id}.json`,method:"GET",public:!0,handler:()=>We1(A)}))]}getIndex(){return{lexicons:Jp0().map((A)=>({...A,path:`${rr0}/${A.id}.json`}))}}getLexicon(A){return Vp0(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:Jp0()}})}}}function sr0(A={}){return new or0(A)}c0();Z0();Z0();c0();var wX0=K.object({routeId:K.string(),sectionId:K.string()}),co=o1.extend({entityType:K.literal("site-content"),template:K.string().optional(),content:K.string(),metadata:wX0});c0();class Ze1 extends J2{constructor(){super({entityType:"site-content",purpose:"A content section bound to a route on the published site.",schema:co,frontmatterSchema:wX0})}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 ar0=new Ze1;Z0();var BX0=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")}),YX6=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 tr0{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 er0{siteConfig;operations;constructor(A,Q){this.siteConfig=Q;this.operations=new tr0(A)}async generateContent(A,Q){let w=BX0.parse(A);return this.operations.generate(w,this.siteConfig,Q)}}l$();Z0();function lo(A,Q){return Q?A.optional():A}function Qo0(A){switch(A.type){case"string":return lo(K.string(),A.optional);case"number":return lo(K.number(),A.optional);case"enum":{let Q=[...A.options];return lo(K.enum(Q),A.optional)}case"object":{let Q={};for(let[w,B]of Object.entries(A.fields))Q[w]=Qo0(B);return lo(K.object(Q),A.optional)}case"array":{let Q=K.array(Mzw(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return lo(Q,A.optional)}}}function Mzw(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]=Qo0($);return K.object(w)}}}function Ao0(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])=>Ao0(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,$])=>Ao0(B,$)),w}}}}function _zw(A,Q){let w={};for(let[Y,D]of Object.entries(Q.fields))w[Y]=Qo0(D);let B=K.object(w),$=new pw(B,{title:Q.title,mappings:Object.entries(Q.fields).map(([Y,D])=>Ao0(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 wo0(A){return Object.fromEntries(Object.entries(A.sections).map(([Q,w])=>[Q,_zw(Q,w)]))}Z0();var Ke1=K.object({namespace:K.string(),sections:K.record(K.any())}),Ue1=K.object({definitions:K.union([Ke1,K.array(Ke1)]).optional()});c0();function Ge1(A,Q){return[Sw(Q,"generate","Generate content for all routes, a specific route, or a specific section",BX0,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 ze1={name:"@brains/site-content",private:!0,version:"0.2.0-alpha.139",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 Bo0 extends IQ{siteContentService;constructor(A={}){super("site-content",ze1,A,Ue1)}async onRegister(A){A.entities.register("site-content",co,ar0);for(let Q of HU(this.config.definitions))A.templates.register(wo0(Q),Q.namespace);this.siteContentService=new er0(A)}async getTools(){return Ge1(()=>this.siteContentService,this.id)}}function po(A={}){return new Bo0(A)}c0();Z0();IB();Z0();c0();var qe1=K.enum(["available","early access","coming soon","planned"]),Fe1=K.object({title:K.string(),description:K.string()}),vH=K.object({name:K.string(),availability:qe1,order:K.number(),ogImageId:K.string().optional()}),$X0=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(Fe1).min(1).max(6),story:K.string()}),kzw=vH.pick({name:!0,availability:!0,order:!0}).extend({slug:K.string()}),TE=o1.extend({entityType:K.literal("product"),metadata:kzw}),YX0=TE.extend({frontmatter:vH,body:$X0,labels:K.record(K.string(),K.string()),ogImageUrl:K.string().optional()}),DX0=YX0.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($X0,{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 $o0 extends J2{constructor(){super({entityType:"product",purpose:"A product entry in the portfolio.",schema:TE,frontmatterSchema:vH,bodyFormatter:new SE})}toMarkdown(A){let Q=this.extractBody(A.content);try{let w=this.parseFrontMatter(A.content,vH);return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,vH),w=w1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:w,availability:Q.availability,order:Q.order}}}}var XX0=new $o0;Z0();c0();var Ve1=K.object({title:K.string(),description:K.string()}),Je1=K.object({title:K.string(),description:K.string()}),Ozw=K.object({title:K.string(),description:K.string()}),Ie1=K.object({heading:K.string(),buttonText:K.string(),link:K.string()}),NF=K.object({headline:K.string(),tagline:K.string()}),xzw=K.object({title:K.string(),description:K.string()}),HX0=K.object({vision:K.string(),pillars:K.array(Ve1).min(1).max(6),approach:K.array(xzw).min(1).max(6),productsIntro:K.string(),technologies:K.array(Ozw).min(1).max(6),benefits:K.array(Je1).min(1).max(6),cta:Ie1}),be1=NF.pick({headline:!0}).extend({slug:K.string()}),mE=o1.extend({entityType:K.literal("products-overview"),metadata:be1}),io=mE.extend({frontmatter:NF,body:HX0,labels:K.record(K.string(),K.string())});c0();Z0();l$();class uE extends pw{constructor(){super(HX0,{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 Yo0 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 Do0=new Yo0;c0();Z0();var Rzw=K.object({entityType:K.string(),query:K.object({id:K.string().optional()}).optional()});function Le1(A,Q){let w=v2(A.content,vH),B=Q.parse(w.content),$=Q.getLabels();return YX0.parse({...A,frontmatter:w.metadata,body:B,labels:$})}function Ne1(A,Q){let w=v2(A.content,NF),B=Q.parse(w.content),$=Q.getLabels();return io.parse({...A,frontmatter:w.metadata,body:B,labels:$})}class WX0{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=Rzw.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=Ne1(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:Le1(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:Ne1(X,this.overviewFormatter),products:D.map((H)=>Le1(H,this.productFormatter))})}}import{jsxDEV as B1,Fragment as Czw}from"preact/jsx-dev-runtime";var je1=({overview:A,products:Q})=>{let{frontmatter:w,body:B,labels:$}=A;return B1(Czw,{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:`
|
|
9002
9002
|
@keyframes wave-drift {
|
|
9003
9003
|
from { transform: translateX(0); }
|
|
9004
9004
|
to { transform: translateX(-50%); }
|
|
@@ -9193,7 +9193,7 @@ ${JSON.stringify(w,null,2)}`}function lD0(A){return A.map((Q)=>Q.detail===null?{
|
|
|
9193
9193
|
font: 10px/1.45 var(--font-mono, "JetBrains Mono", ui-monospace, monospace);
|
|
9194
9194
|
}
|
|
9195
9195
|
`}},void 0,!1,void 0,this),CH("section",{className:"product-shell",children:[CH("header",{className:"product-hero",children:[Q.brandLabel&&CH("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),CH("h1",{className:"printable-title",children:Q.name},void 0,!1,void 0,this),Q.availability&&CH("div",{className:"printable-meta",children:CH("span",{children:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),CH("div",{className:"product-body-wrap",children:[CH("aside",{className:"product-rail","aria-hidden":"true",children:CH("p",{className:"product-rail-label",children:"Product brief / capabilities"},void 0,!1,void 0,this)},void 0,!1,void 0,this),CH($9,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q.brandLabel&&CH("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 czw=26214400,lzw=60000;class Ho0{context;metadata={outputEntityType:"document"};renderPdf;constructor(A,Q={}){this.context=A;this.renderPdf=Q.renderPdf??JK}async resolve(A){if(A.sourceEntityType!=="product"||A.attachmentType!==fX0)return;let Q=await this.context.entityService.getEntity({entityType:"product",id:A.sourceEntityId});if(!Q)return;let w=pzw(Q,{brandLabel:this.resolveBrandLabel()}),B=await Tzw(uzw(mzw(),"brain-product-printable-"));try{let $=await MH({outputDir:B,mediaPath:`/_media/printable/product/${Q.id}`,template:Pe1,format:"pdf",content:w,siteConfig:{title:w.name,themeMode:"light"},themeCSS:this.context.themeCSS}),Y=await _H({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor($.urlPath),{maxBytes:czw,timeoutMs:lzw,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${izw(Q)}-printable.pdf`}}finally{await Y.close()}}finally{await Szw(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 pzw(A,Q={}){let{frontmatter:w,content:B}=lw(A.content),$=vH.parse(w);return{name:$.name,body:B,availability:$.availability,...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function izw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.name)}Z0();Z0();import{jsxDEV as rzw}from"preact/jsx-dev-runtime";var ZX0="og-image",dzw="products:og-image",ke1=K.object({name:K.string().min(1),tagline:K.string().optional(),availability:K.string().optional(),brandLabel:K.string().optional()}),Oe1={name:dzw,pluginId:"products",schema:ke1,renderers:{image:nzw}};function nzw(A){let Q=ke1.parse(A);return rzw(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 Wo0{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!==ZX0)return;let Q=await this.context.entityService.getEntity({entityType:"product",id:A.sourceEntityId});if(!Q)return;let{frontmatter:w,content:B}=lw(Q.content),$=vH.parse(w),Y=ozw(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:Oe1,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:`${szw(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 ozw(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(`
|
|
9196
|
-
`).trim();return Y.length>0?Y:void 0}function szw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.name)}var xe1={name:"@brains/products",private:!0,version:"0.2.0-alpha.
|
|
9196
|
+
`).trim();return Y.length>0?Y:void 0}function szw(A){let Q=A.metadata.slug;return Q.length>0?Q:w1(A.metadata.name)}var xe1={name:"@brains/products",private:!0,version:"0.2.0-alpha.139",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 tzw=K.object({overview:io,products:K.array(DX0)}),ezw=K.object({product:DX0});class fo0 extends kQ{entityType=XX0.entityType;schema=TE;adapter=XX0;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("products",xe1,A,Xo0)}getTemplates(){return{"product-list":R1({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:tzw,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:je1}}),"product-detail":R1({name:"product-detail",description:"Individual product detail page",schema:ezw,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Me1}})}}getDataSources(){return[new WX0(this.logger.child("ProductsDataSource"))]}async onRegister(A){this.unregisterPrintableAttachmentProvider=A.attachments.register("product",fX0,new Ho0(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("product",ZX0,new Wo0(A)),A.entities.register("products-overview",mE,Do0)}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0}}function Zo0(A={}){return new fo0(A)}import{join as Pqw}from"path";import{jsxDEV as KX0,Fragment as Aqw}from"preact/jsx-dev-runtime";var cE=({children:A})=>KX0(Aqw,{children:[KX0("div",{id:"bgCanvasWrap",className:"rizom-frame-canvas-wrap fixed top-0 left-0 w-full h-full pointer-events-none",children:KX0("canvas",{id:"heroCanvas",className:"w-full h-full block"},void 0,!1,void 0,this)},void 0,!1,void 0,this),KX0("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 wqw}from"preact/jsx-dev-runtime";var UX0="px-6 md:px-10 xl:px-20",Qqw=`${UX0} relative z-[1]`,cb=({id:A,className:Q,children:w})=>wqw("section",{id:A,className:$2(Qqw,Q),children:w},void 0,!1,void 0,this);import{jsxDEV as MW6}from"preact/jsx-dev-runtime";import{jsxDEV as kW6}from"preact/jsx-dev-runtime";import{jsxDEV as Xqw}from"preact/jsx-dev-runtime";var Bqw="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)]",$qw={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)]"},Yqw={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)]"},Dqw="w-full md:w-auto",gP=({href:A,variant:Q="primary",size:w="md",block:B=!1,className:$,children:Y})=>Xqw("a",{href:A,className:$2("rizom-btn",`rizom-btn-${Q}`,`rizom-btn-${w}`,B&&"rizom-btn-block",Bqw,$qw[Q],Yqw[w],B&&Dqw,$),children:Y},void 0,!1,void 0,this);import{jsxDEV as yW6}from"preact/jsx-dev-runtime";import{jsxDEV as SW6}from"preact/jsx-dev-runtime";import{Fragment as cW6}from"preact";import{jsxDEV as pW6}from"preact/jsx-dev-runtime";import{jsxDEV as Re1}from"preact/jsx-dev-runtime";var GX0=({sections:A})=>Re1(cE,{children:Re1("main",{children:A},void 0,!1,void 0,this)},void 0,!1,void 0,this);c0();Z0();var he1=`/*
|
|
9197
9197
|
* Shared globals + helpers used by tree / constellation / roots canvas
|
|
9198
9198
|
* scripts. Loaded as a shared static asset by the Rizom runtime package
|
|
9199
9199
|
* so the variant canvases
|
|
@@ -11683,7 +11683,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});Z0();var S
|
|
|
11683
11683
|
`);return this.truncateContent(B||Q||aE(A))}truncateContent(A){if(A.length<=z02)return A;let Q=A.slice(0,z02-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===yH}getEntitySpaceId(A){let Q=A.metadata;if("spaceId"in Q&&typeof Q.spaceId==="string")return Q.spaceId;return _K(Q)}}var f3w=5,Z3w=3;function bo0(A){A.messaging.subscribe(XN,async(Q)=>{let w=lT.parse(Q.payload);return{success:!0,data:await PX0(A,w)}})}async function PX0(A,Q){let w=p8(Q.userPermissionLevel);if(!Q.channelId)return q02(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:f3w,visibilityScope:w}),Y=$.results.length===0?await B.retrieve({conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,limit:Z3w,visibilityScope:w}):void 0,D=$.results.length>0,X=D?$.results:Y?.results??[];return q02(A,Q,{visibilityScope:w,spaceId:$.spaceId??Y?.spaceId,reason:X.length>0?"memory-injected":"no-same-space-memory",items:X.map((H)=>K3w(H,D))}),{items:X.map(U3w)}}function q02(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 K3w(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 U3w(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();bX();var No0=K.object({role:Qq,content:K.string(),timestamp:K.string().datetime().optional(),actor:MN.optional(),source:_N.optional()}),G3w=K.object({conversationId:K.string().default("eval-conversation"),messages:K.array(No0)}),z3w=K.object({conversationId:K.string()}),q3w=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(No0)}),kX0=K.object({actorId:K.string(),canonicalId:K.string().optional(),displayName:K.string().optional()}),F3w=kX0.extend({roles:K.array(K.enum(["user","assistant","system"])).default(["user"]),sourceActorIds:K.array(K.string()).optional()}),V3w=K.object({actorId:K.string().optional(),canonicalId:K.string().optional(),displayName:K.string()}),J02=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:f7,status:K.string().optional(),participants:K.array(F3w).optional(),decidedBy:K.array(kX0).optional(),mentionedBy:K.array(kX0).optional(),assignedTo:K.array(V3w).optional(),requestedBy:K.array(kX0).optional()}),J3w=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:f7.optional(),memory:K.array(J02).optional()}),I3w=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(J02).optional()}),b3w=K.object({conversationId:K.string().default("eval-conversation"),existingSummary:K.string().optional(),existingMessageCount:K.number().int().min(0).default(0),messages:K.array(No0)});function I02(A){let{context:Q,logger:w,config:B}=A;Q.eval.registerHandler("summarizeMessages",async($)=>{let Y=G3w.parse($),D=Lo0(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(`
|
|
11684
11684
|
`),decisionsText:f.join(`
|
|
11685
11685
|
`),actionItemsText:Z.join(`
|
|
11686
|
-
`)}})}),Q.eval.registerHandler("decideProjection",async($)=>{let Y=b3w.parse($),D=Lo0(Y.messages,Y.conversationId),X=Y.existingSummary?F02({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=J3w.parse($),D=Y.memory?V02(Q,Y.memory):Q;return new tE(D).retrieve(Y)}),Q.eval.registerHandler("buildAgentContext",async($)=>{let Y=I3w.parse($),D=Y.memory?V02(Q,Y.memory):Q;return PX0(D,Y)}),Q.eval.registerHandler("projectMessages",async($)=>{let Y=q3w.parse($),D=Lo0(Y.messages,Y.conversationId),X=L3w({conversationId:Y.conversationId,interfaceType:Y.interfaceType,channelId:Y.channelId,channelName:Y.channelName,messages:D}),H=Y.existingSummary?F02({conversationId:Y.conversationId,content:Y.existingSummary,messageCount:Y.existingMessageCount,projectionVersion:B.projectionVersion,visibility:B.memoryVisibility}):null,W=[],f=[],Z=N3w({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 F02(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 Lo0(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 L3w(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 N3w(A){let Q=_K(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 V02(A,Q){let w=Q.map(j3w),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 j3w(A){if(A.entityType==="summary")return M3w(A);if(A.entityType==="decision")return _3w(A);return P3w(A)}function jo0(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 M3w(A){return{...jo0(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 _3w(A){return{...jo0(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:_K(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 P3w(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...jo0(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:_K(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 b02={name:"@brains/conversation-memory",private:!0,version:"0.2.0-alpha.138",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 O3w=new Zf,x3w=new iE,R3w=new dE,h3w=K.object({conversationId:K.string()});class Mo0 extends kQ{entityType=q5;schema=ro;adapter=O3w;constructor(A={}){super(qX0,b02,A,zo0)}getConfig(){return this.config}getTemplates(){return{"summary-list":ne1,"summary-detail":re1,"ai-response":oe1}}getDataSources(){return[new Io0(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:q5,job:{type:me1,handler:new LX0(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:Go0,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:qX0}}},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:Go0,deduplication:"skip",deduplicationKey:`conversation-memory:${w}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${w}`,pluginId:qX0}}}}}]}parseConversationMessagePayload(A){return h3w.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(yH,oo,x3w),A.entities.register(ff,so,R3w),te1({context:A,pluginId:this.id}),A02({context:A,pluginId:this.id}),f02({context:A,pluginId:this.id}),U02({context:A,pluginId:this.id,config:this.config}),bo0(A),I02({context:A,logger:this.logger,config:this.config})}}function _o0(A){return new Mo0(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()}),L02=jF.pick({title:!0,section:!0,order:!0,description:!0}).extend({slug:K.string()}),eE=o1.extend({entityType:K.literal("doc"),metadata:L02}),MF=eE.extend({frontmatter:jF,body:K.string()});c0();Z0();class Po0 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 OX0=new Po0;c0();function N02(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 j02(A){let Q=v2(A.content,jF);return MF.parse({...A,frontmatter:Q.metadata,body:Q.content})}class xX0 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 j02(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=N02(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:N02(A),pagination:Q,baseUrl:w.baseUrl}}}c0();IB();Z0();import{jsxDEV as x$}from"preact/jsx-dev-runtime";var v3w=["I","II","III","IV","V","VI","VII","VIII","IX","X"];function eo(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 RX0(A){let Q=new Map;for(let w of eo(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 hX0(A){return`section-${A+1}`}function Qg(A){return v3w[A]??String(A+1)}var P02="text-[var(--docs-text)] font-bold",k02="text-[var(--docs-accent)] font-bold",O02="text-[var(--docs-text-muted)]",C3w="docs-font-label text-xs uppercase tracking-[0.18em] text-[var(--docs-accent)]",y3w="docs-font-display text-[var(--docs-heading)]",M02="inline-flex items-center justify-center rounded-lg border px-[18px] py-2.5 text-sm font-semibold transition-colors duration-150",_02="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",ko0="docs-font-label text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:text-[var(--docs-text)]",wz={wrap:"mx-auto max-w-6xl px-6 pt-20 md:px-12 md:pt-24",label:C3w,display:y3w,button:`${M02} border-[var(--docs-text)] text-[var(--docs-text)] hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)]`,primaryButton:`${M02} border-[var(--docs-accent)] bg-[var(--docs-accent)] text-white hover:bg-transparent hover:text-[var(--docs-accent)]`},x02=()=>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:P02,children:"brains"},void 0,!1,void 0,this),x$("span",{className:k02,children:"."},void 0,!1,void 0,this),x$("span",{className:O02,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:_02,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:_02,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),R02=()=>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:P02,children:"rizom"},void 0,!1,void 0,this),x$("span",{className:k02,children:"."},void 0,!1,void 0,this),x$("span",{className:O02,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:ko0,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:ko0,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),x$("a",{className:ko0,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),E3w=`
|
|
11686
|
+
`)}})}),Q.eval.registerHandler("decideProjection",async($)=>{let Y=b3w.parse($),D=Lo0(Y.messages,Y.conversationId),X=Y.existingSummary?F02({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=J3w.parse($),D=Y.memory?V02(Q,Y.memory):Q;return new tE(D).retrieve(Y)}),Q.eval.registerHandler("buildAgentContext",async($)=>{let Y=I3w.parse($),D=Y.memory?V02(Q,Y.memory):Q;return PX0(D,Y)}),Q.eval.registerHandler("projectMessages",async($)=>{let Y=q3w.parse($),D=Lo0(Y.messages,Y.conversationId),X=L3w({conversationId:Y.conversationId,interfaceType:Y.interfaceType,channelId:Y.channelId,channelName:Y.channelName,messages:D}),H=Y.existingSummary?F02({conversationId:Y.conversationId,content:Y.existingSummary,messageCount:Y.existingMessageCount,projectionVersion:B.projectionVersion,visibility:B.memoryVisibility}):null,W=[],f=[],Z=N3w({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 F02(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 Lo0(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 L3w(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 N3w(A){let Q=_K(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 V02(A,Q){let w=Q.map(j3w),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 j3w(A){if(A.entityType==="summary")return M3w(A);if(A.entityType==="decision")return _3w(A);return P3w(A)}function jo0(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 M3w(A){return{...jo0(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 _3w(A){return{...jo0(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:_K(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 P3w(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...jo0(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:_K(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 b02={name:"@brains/conversation-memory",private:!0,version:"0.2.0-alpha.139",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 O3w=new Zf,x3w=new iE,R3w=new dE,h3w=K.object({conversationId:K.string()});class Mo0 extends kQ{entityType=q5;schema=ro;adapter=O3w;constructor(A={}){super(qX0,b02,A,zo0)}getConfig(){return this.config}getTemplates(){return{"summary-list":ne1,"summary-detail":re1,"ai-response":oe1}}getDataSources(){return[new Io0(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:q5,job:{type:me1,handler:new LX0(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:Go0,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:qX0}}},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:Go0,deduplication:"skip",deduplicationKey:`conversation-memory:${w}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${w}`,pluginId:qX0}}}}}]}parseConversationMessagePayload(A){return h3w.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(yH,oo,x3w),A.entities.register(ff,so,R3w),te1({context:A,pluginId:this.id}),A02({context:A,pluginId:this.id}),f02({context:A,pluginId:this.id}),U02({context:A,pluginId:this.id,config:this.config}),bo0(A),I02({context:A,logger:this.logger,config:this.config})}}function _o0(A){return new Mo0(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()}),L02=jF.pick({title:!0,section:!0,order:!0,description:!0}).extend({slug:K.string()}),eE=o1.extend({entityType:K.literal("doc"),metadata:L02}),MF=eE.extend({frontmatter:jF,body:K.string()});c0();Z0();class Po0 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 OX0=new Po0;c0();function N02(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 j02(A){let Q=v2(A.content,jF);return MF.parse({...A,frontmatter:Q.metadata,body:Q.content})}class xX0 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 j02(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=N02(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:N02(A),pagination:Q,baseUrl:w.baseUrl}}}c0();IB();Z0();import{jsxDEV as x$}from"preact/jsx-dev-runtime";var v3w=["I","II","III","IV","V","VI","VII","VIII","IX","X"];function eo(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 RX0(A){let Q=new Map;for(let w of eo(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 hX0(A){return`section-${A+1}`}function Qg(A){return v3w[A]??String(A+1)}var P02="text-[var(--docs-text)] font-bold",k02="text-[var(--docs-accent)] font-bold",O02="text-[var(--docs-text-muted)]",C3w="docs-font-label text-xs uppercase tracking-[0.18em] text-[var(--docs-accent)]",y3w="docs-font-display text-[var(--docs-heading)]",M02="inline-flex items-center justify-center rounded-lg border px-[18px] py-2.5 text-sm font-semibold transition-colors duration-150",_02="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",ko0="docs-font-label text-[13px] text-[var(--docs-text-light)] transition-colors duration-150 hover:text-[var(--docs-text)]",wz={wrap:"mx-auto max-w-6xl px-6 pt-20 md:px-12 md:pt-24",label:C3w,display:y3w,button:`${M02} border-[var(--docs-text)] text-[var(--docs-text)] hover:border-[var(--docs-accent)] hover:text-[var(--docs-accent)]`,primaryButton:`${M02} border-[var(--docs-accent)] bg-[var(--docs-accent)] text-white hover:bg-transparent hover:text-[var(--docs-accent)]`},x02=()=>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:P02,children:"brains"},void 0,!1,void 0,this),x$("span",{className:k02,children:"."},void 0,!1,void 0,this),x$("span",{className:O02,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:_02,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:_02,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),R02=()=>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:P02,children:"rizom"},void 0,!1,void 0,this),x$("span",{className:k02,children:"."},void 0,!1,void 0,this),x$("span",{className:O02,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:ko0,href:"/docs/roadmap",children:"Roadmap"},void 0,!1,void 0,this),x$("a",{className:ko0,href:"https://github.com/rizom-ai/brains",children:"GitHub"},void 0,!1,void 0,this),x$("a",{className:ko0,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),E3w=`
|
|
11687
11687
|
.docs-handbook {
|
|
11688
11688
|
--docs-bg: var(--color-bg, #0d0a1a);
|
|
11689
11689
|
--docs-bg-card: var(--color-bg-card, #1a0a3e);
|
|
@@ -11835,7 +11835,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});Z0();var S
|
|
|
11835
11835
|
background: transparent;
|
|
11836
11836
|
}
|
|
11837
11837
|
|
|
11838
|
-
`,h02=()=>x$("style",{children:E3w},void 0,!1,void 0,this);import{jsxDEV as F2,Fragment as g3w}from"preact/jsx-dev-runtime";var vX0=({title:A,description:Q,children:w,detail:B=!1,footer:$=!1,contentClassName:Y=""})=>F2(g3w,{children:[F2(jQ,{title:A,description:Q},void 0,!1,void 0,this),F2(h02,{},void 0,!1,void 0,this),F2("div",{className:`docs-handbook${B?" docs-handbook--detail":""}`,children:[F2(x02,{},void 0,!1,void 0,this),F2("div",{className:`${wz.wrap} ${Y}`.trim(),children:[w,$&&F2(R02,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),v02=({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:`${wz.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),F2("h1",{className:`${wz.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:wz.primaryButton,href:Ag(w),children:"Start reading"},void 0,!1,void 0,this),F2("a",{className:wz.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),C02=({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:`#${hX0(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),y02=({group:A,index:Q})=>F2("article",{className:"mb-16 last:mb-0",id:hX0(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:`${wz.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),E02=({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),g02=({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#${hX0($)}`,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),T02=({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 Oo0=({docs:A})=>{let Q=eo(A),w=RX0(Q),$=Q.filter((Y)=>Y.metadata.slug!=="index")[0]??Q[0];return wg(vX0,{title:"Documentation",description:"Brains documentation",children:[wg(v02,{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(C02,{groups:w},void 0,!1,void 0,this),wg("div",{children:w.map((Y,D)=>wg(y02,{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 EH}from"preact/jsx-dev-runtime";var xo0=({doc:A,docs:Q,prevDoc:w,nextDoc:B})=>{let $=RX0(Q.length>0?Q:[A]),Y=eo(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 EH(vX0,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[EH(E02,{title:A.metadata.title},void 0,!1,void 0,this),EH("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[EH(g02,{groups:$,activeGroupIndex:X,activeSlug:A.metadata.slug},void 0,!1,void 0,this),EH("article",{className:"min-w-0",children:[EH("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[EH("p",{className:`${wz.label} m-0 mb-6 flex items-baseline gap-3`,children:[EH("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),EH("h1",{className:`${wz.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&&EH("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),EH("div",{className:"docs-article__body",children:EH($9,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),EH(T02,{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 T3w=K.object({docs:K.array(MF),pagination:A4.nullable(),baseUrl:K.string().optional()}),S3w=K.object({doc:MF,docs:K.array(MF),prevDoc:MF.nullable(),nextDoc:MF.nullable()});function S02(){return{"doc-list":R1({name:"doc-list",description:"Documentation index template",schema:T3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:Oo0}}),"doc-detail":R1({name:"doc-detail",description:"Documentation page template",schema:S3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:xo0}})}}var m02={name:"@brains/doc",private:!0,version:"0.2.0-alpha.138",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 Ro0 extends kQ{entityType=OX0.entityType;schema=eE;adapter=OX0;constructor(){super("docs",m02,{},void 0)}getTemplates(){return S02()}getDataSources(){return[new xX0(this.logger.child("DocDataSource"))]}}function ho0(){return new Ro0}c0();Z0();Z0();l$();var u02=K.object({label:K.string(),href:K.string()}),c02=K.object({label:K.string(),title:K.string(),detail:K.string()}),u3w=K.object({eyebrow:K.string(),name:K.string(),sub:K.string()}),c3w=K.object({tone:K.enum(["capture","synthesis","share"]),title:K.string(),text:K.string()}),vo0=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:u02,secondaryCta:u02,inputs:K.array(c02).min(1),outputs:K.array(c02).min(1),core:u3w,legend:K.array(c3w).min(1)}),Co0=Bg.extend({counts:vo0}),l02={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."}]},p02=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 CX0(A){return p02.parse(A)}function i02(A){return p02.format(A)}Z0();var l3w=K.object({query:K.object({routeId:K.string().default("home"),sectionId:K.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}).passthrough(),p3w={captures:"note",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class yo0{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=l3w.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 l02;return Bg.parse(CX0(B.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(p3w).map(async([w,B])=>[w,await this.countOrZero(A,B)]));return vo0.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 d02=K.object({label:K.string(),href:K.string()}),i3w=K.object({eyebrow:K.string(),headline:K.string(),intro:K.string(),primaryCta:d02,secondaryCta:d02,signals:K.array(K.object({label:K.string(),value:K.string(),note:K.string()}))}),d3w=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()}))}),n3w=K.object({title:K.string(),intro:K.string(),cards:K.array(K.object({label:K.string(),title:K.string(),text:K.string()}))}),r3w=K.object({title:K.string(),intro:K.string(),points:K.array(K.string())}),o3w={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."]},s3w="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function n02({href:A,label:Q}){return $1("a",{href:A,className:s3w,children:Q},void 0,!1,void 0,this)}function a3w({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(n02,{...$},`${$.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(n02,{...$},`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 t3w=({sections:A,siteInfo:Q})=>$1(a3w,{siteInfo:Q,children:A},void 0,!1,void 0,this);function e3w({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 AFw({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 QFw({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 wFw({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 BFw=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},$Fw=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),As=(A,Q,w=`${Q}s`)=>`${$Fw(A)} ${A===1?Q:w}`;function YFw({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:As(W.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:As(W.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:As(W.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:As(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:[As(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 ${BFw(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 DFw=R1({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:Co0,formatter:{parse:(A)=>Co0.parse({...CX0(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>i02(Bg.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:YFw}}),XFw=(A)=>e3w(i3w.parse(A)),HFw=(A)=>AFw(d3w.parse(A)),WFw=(A)=>QFw(n3w.parse(A)),fFw=(A)=>wFw(r3w.parse(A)),r02={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},o02={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:XFw,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...r02,label:"Primary CTA"},secondaryCta:{...r02,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:HFw,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:WFw,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:fFw,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},ZFw=[{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:o3w}]}],s02=Uo0({packageName:"@brains/relay/site",contentNamespace:"relay-site",themeProfile:"studio",layout:t3w,routes:ZFw,templates:{"home-diagram":DFw},dataSources:[new yo0]});var a02={name:"@brains/relay",private:!0,version:"0.2.0-alpha.138",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 t02=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","web-chat","discord","a2a"],e02=[...t02,"image","site-info","site-content","site-builder"],GFw=[...e02,"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."],AA2=LJ({name:"relay",version:a02.version,model:"gpt-5.4-mini",site:s02,theme:lE,presets:{core:t02,default:e02,full:GFw},evalDisable:["webserver","web-chat","mcp","discord"],agentInstructions:zFw,capabilities:[["prompt",vP,void 0],["note",LP,{}],["link",jP,{}],["image",zc,void 0],["topics",iY0,{includeEntityTypes:["note","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",_o0,{memoryVisibility:"shared"}],["docs",ho0,void 0],["decks",Pr,void 0],["agents",gD0,void 0],["assessment",nD0,void 0],["auth-service",Dp,void 0],["notifications",tw0,void 0],["email-resend",i$0,void 0],["cms",xP,{}],["dashboard",Sb,void 0],["directory-sync",M_,{seedContent:!0,seedContentPath:UFw(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",po,{definitions:o02}],["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 rIw}from"fs";import{join as oIw}from"path";import{execSync as sIw}from"child_process";import{parseArgs as VFw}from"util";var JFw={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 PK(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 QA2(A){let{values:Q,positionals:w}=VFw({args:A,options:JFw,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:PK(Q,"model"),domain:PK(Q,"domain"),"content-repo":PK(Q,"content-repo"),backend:PK(Q,"backend"),"push-to":PK(Q,"push-to"),"ai-api-key":PK(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:PK(Q,"only"),"dry-run":ib(Q,"dry-run"),"startup-check":ib(Q,"startup-check"),"storage-dir":PK(Q,"storage-dir"),yes:ib(Q,"yes"),remote:PK(Q,"remote"),token:PK(Q,"token"),outputDir:PK(Q,"outputDir")}}}Qs();import{mkdirSync as TIw}from"fs";import{join as SIw}from"path";import{execSync as mIw}from"child_process";var EX0={name:"@rizom/brain",version:"0.2.0-alpha.138",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 qA2,writeFileSync as Bs,chmodSync as $s,existsSync as io0,readFileSync as do0}from"fs";import{basename as no0,dirname as ro0,join as L6,resolve as eFw}from"path";import{fileURLToPath as AVw}from"url";var wA2=`ARG BUN_VERSION=1.3.10
|
|
11838
|
+
`,h02=()=>x$("style",{children:E3w},void 0,!1,void 0,this);import{jsxDEV as F2,Fragment as g3w}from"preact/jsx-dev-runtime";var vX0=({title:A,description:Q,children:w,detail:B=!1,footer:$=!1,contentClassName:Y=""})=>F2(g3w,{children:[F2(jQ,{title:A,description:Q},void 0,!1,void 0,this),F2(h02,{},void 0,!1,void 0,this),F2("div",{className:`docs-handbook${B?" docs-handbook--detail":""}`,children:[F2(x02,{},void 0,!1,void 0,this),F2("div",{className:`${wz.wrap} ${Y}`.trim(),children:[w,$&&F2(R02,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),v02=({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:`${wz.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),F2("h1",{className:`${wz.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:wz.primaryButton,href:Ag(w),children:"Start reading"},void 0,!1,void 0,this),F2("a",{className:wz.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),C02=({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:`#${hX0(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),y02=({group:A,index:Q})=>F2("article",{className:"mb-16 last:mb-0",id:hX0(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:`${wz.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),E02=({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),g02=({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#${hX0($)}`,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),T02=({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 Oo0=({docs:A})=>{let Q=eo(A),w=RX0(Q),$=Q.filter((Y)=>Y.metadata.slug!=="index")[0]??Q[0];return wg(vX0,{title:"Documentation",description:"Brains documentation",children:[wg(v02,{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(C02,{groups:w},void 0,!1,void 0,this),wg("div",{children:w.map((Y,D)=>wg(y02,{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 EH}from"preact/jsx-dev-runtime";var xo0=({doc:A,docs:Q,prevDoc:w,nextDoc:B})=>{let $=RX0(Q.length>0?Q:[A]),Y=eo(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 EH(vX0,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[EH(E02,{title:A.metadata.title},void 0,!1,void 0,this),EH("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[EH(g02,{groups:$,activeGroupIndex:X,activeSlug:A.metadata.slug},void 0,!1,void 0,this),EH("article",{className:"min-w-0",children:[EH("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[EH("p",{className:`${wz.label} m-0 mb-6 flex items-baseline gap-3`,children:[EH("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),EH("h1",{className:`${wz.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&&EH("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),EH("div",{className:"docs-article__body",children:EH($9,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),EH(T02,{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 T3w=K.object({docs:K.array(MF),pagination:A4.nullable(),baseUrl:K.string().optional()}),S3w=K.object({doc:MF,docs:K.array(MF),prevDoc:MF.nullable(),nextDoc:MF.nullable()});function S02(){return{"doc-list":R1({name:"doc-list",description:"Documentation index template",schema:T3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:Oo0}}),"doc-detail":R1({name:"doc-detail",description:"Documentation page template",schema:S3w,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:xo0}})}}var m02={name:"@brains/doc",private:!0,version:"0.2.0-alpha.139",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 Ro0 extends kQ{entityType=OX0.entityType;schema=eE;adapter=OX0;constructor(){super("docs",m02,{},void 0)}getTemplates(){return S02()}getDataSources(){return[new xX0(this.logger.child("DocDataSource"))]}}function ho0(){return new Ro0}c0();Z0();Z0();l$();var u02=K.object({label:K.string(),href:K.string()}),c02=K.object({label:K.string(),title:K.string(),detail:K.string()}),u3w=K.object({eyebrow:K.string(),name:K.string(),sub:K.string()}),c3w=K.object({tone:K.enum(["capture","synthesis","share"]),title:K.string(),text:K.string()}),vo0=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:u02,secondaryCta:u02,inputs:K.array(c02).min(1),outputs:K.array(c02).min(1),core:u3w,legend:K.array(c3w).min(1)}),Co0=Bg.extend({counts:vo0}),l02={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."}]},p02=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 CX0(A){return p02.parse(A)}function i02(A){return p02.format(A)}Z0();var l3w=K.object({query:K.object({routeId:K.string().default("home"),sectionId:K.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}).passthrough(),p3w={captures:"note",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class yo0{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=l3w.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 l02;return Bg.parse(CX0(B.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(p3w).map(async([w,B])=>[w,await this.countOrZero(A,B)]));return vo0.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 d02=K.object({label:K.string(),href:K.string()}),i3w=K.object({eyebrow:K.string(),headline:K.string(),intro:K.string(),primaryCta:d02,secondaryCta:d02,signals:K.array(K.object({label:K.string(),value:K.string(),note:K.string()}))}),d3w=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()}))}),n3w=K.object({title:K.string(),intro:K.string(),cards:K.array(K.object({label:K.string(),title:K.string(),text:K.string()}))}),r3w=K.object({title:K.string(),intro:K.string(),points:K.array(K.string())}),o3w={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."]},s3w="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function n02({href:A,label:Q}){return $1("a",{href:A,className:s3w,children:Q},void 0,!1,void 0,this)}function a3w({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(n02,{...$},`${$.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(n02,{...$},`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 t3w=({sections:A,siteInfo:Q})=>$1(a3w,{siteInfo:Q,children:A},void 0,!1,void 0,this);function e3w({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 AFw({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 QFw({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 wFw({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 BFw=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},$Fw=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),As=(A,Q,w=`${Q}s`)=>`${$Fw(A)} ${A===1?Q:w}`;function YFw({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:As(W.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:As(W.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:As(W.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:As(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:[As(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 ${BFw(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 DFw=R1({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:Co0,formatter:{parse:(A)=>Co0.parse({...CX0(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>i02(Bg.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:YFw}}),XFw=(A)=>e3w(i3w.parse(A)),HFw=(A)=>AFw(d3w.parse(A)),WFw=(A)=>QFw(n3w.parse(A)),fFw=(A)=>wFw(r3w.parse(A)),r02={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},o02={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:XFw,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...r02,label:"Primary CTA"},secondaryCta:{...r02,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:HFw,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:WFw,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:fFw,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},ZFw=[{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:o3w}]}],s02=Uo0({packageName:"@brains/relay/site",contentNamespace:"relay-site",themeProfile:"studio",layout:t3w,routes:ZFw,templates:{"home-diagram":DFw},dataSources:[new yo0]});var a02={name:"@brains/relay",private:!0,version:"0.2.0-alpha.139",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 t02=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","web-chat","discord","a2a"],e02=[...t02,"image","site-info","site-content","site-builder"],GFw=[...e02,"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."],AA2=LJ({name:"relay",version:a02.version,model:"gpt-5.4-mini",site:s02,theme:lE,presets:{core:t02,default:e02,full:GFw},evalDisable:["webserver","web-chat","mcp","discord"],agentInstructions:zFw,capabilities:[["prompt",vP,void 0],["note",LP,{}],["link",jP,{}],["image",zc,void 0],["topics",iY0,{includeEntityTypes:["note","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",_o0,{memoryVisibility:"shared"}],["docs",ho0,void 0],["decks",Pr,void 0],["agents",gD0,void 0],["assessment",nD0,void 0],["auth-service",Dp,void 0],["notifications",tw0,void 0],["email-resend",i$0,void 0],["cms",xP,{}],["dashboard",Sb,void 0],["directory-sync",M_,{seedContent:!0,seedContentPath:UFw(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",po,{definitions:o02}],["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 rIw}from"fs";import{join as oIw}from"path";import{execSync as sIw}from"child_process";import{parseArgs as VFw}from"util";var JFw={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 PK(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 QA2(A){let{values:Q,positionals:w}=VFw({args:A,options:JFw,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:PK(Q,"model"),domain:PK(Q,"domain"),"content-repo":PK(Q,"content-repo"),backend:PK(Q,"backend"),"push-to":PK(Q,"push-to"),"ai-api-key":PK(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:PK(Q,"only"),"dry-run":ib(Q,"dry-run"),"startup-check":ib(Q,"startup-check"),"storage-dir":PK(Q,"storage-dir"),yes:ib(Q,"yes"),remote:PK(Q,"remote"),token:PK(Q,"token"),outputDir:PK(Q,"outputDir")}}}Qs();import{mkdirSync as TIw}from"fs";import{join as SIw}from"path";import{execSync as mIw}from"child_process";var EX0={name:"@rizom/brain",version:"0.2.0-alpha.139",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 qA2,writeFileSync as Bs,chmodSync as $s,existsSync as io0,readFileSync as do0}from"fs";import{basename as no0,dirname as ro0,join as L6,resolve as eFw}from"path";import{fileURLToPath as AVw}from"url";var wA2=`ARG BUN_VERSION=1.3.10
|
|
11839
11839
|
FROM oven/bun:\${BUN_VERSION}-slim AS runtime
|
|
11840
11840
|
|
|
11841
11841
|
WORKDIR /app
|