@rizom/brain 0.2.0-alpha.183 → 0.2.0-alpha.184

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/brain.js CHANGED
@@ -144,7 +144,7 @@ ${A}
144
144
  `+m.slice(L0+1);else l0+=m.slice(I0);return l0.slice(1)}function l1(m){let J0="",e=0;for(let z0=0;z0<m.length;e>=65536?z0+=2:z0++){e=O0(m,z0);let I0=b[e];if(!I0&&k0(e)){if(J0+=m[z0],e>=65536)J0+=m[z0+1]}else J0+=I0||a(e)}return J0}function j1(m,J0,e){let z0="",I0=m.tag;for(let M0=0,L0=e.length;M0<L0;M0+=1){let o0=e[M0];if(m.replacer)o0=m.replacer.call(e,String(M0),o0);if(v0(m,J0,o0,!1,!1)||typeof o0>"u"&&v0(m,J0,null,!1,!1)){if(z0!=="")z0+=","+(!m.condenseFlow?" ":"");z0+=m.dump}}m.tag=I0,m.dump="["+z0+"]"}function T0(m,J0,e,z0){let I0="",M0=m.tag;for(let L0=0,o0=e.length;L0<o0;L0+=1){let l0=e[L0];if(m.replacer)l0=m.replacer.call(e,String(L0),l0);if(v0(m,J0+1,l0,!0,!0,!1,!0)||typeof l0>"u"&&v0(m,J0+1,null,!0,!0,!1,!0)){if(!z0||I0!=="")I0+=i(m,J0);if(m.dump&&Z===m.dump.charCodeAt(0))I0+="-";else I0+="- ";I0+=m.dump}}m.tag=M0,m.dump=I0||"[]"}function R0(m,J0,e){let z0="",I0=m.tag,M0=Object.keys(e);for(let L0=0,o0=M0.length;L0<o0;L0+=1){let l0="";if(z0!=="")l0+=", ";if(m.condenseFlow)l0+='"';let YA=M0[L0],HA=e[YA];if(m.replacer)HA=m.replacer.call(e,YA,HA);if(!v0(m,J0,YA,!1,!1))continue;if(m.dump.length>1024)l0+="? ";if(l0+=m.dump+(m.condenseFlow?'"':"")+":"+(m.condenseFlow?"":" "),!v0(m,J0,HA,!1,!1))continue;l0+=m.dump,z0+=l0}m.tag=I0,m.dump="{"+z0+"}"}function _(m,J0,e,z0){let I0="",M0=m.tag,L0=Object.keys(e);if(m.sortKeys===!0)L0.sort();else if(typeof m.sortKeys==="function")L0.sort(m.sortKeys);else if(m.sortKeys)throw new Q("sortKeys must be a boolean or a function");for(let o0=0,l0=L0.length;o0<l0;o0+=1){let YA="";if(!z0||I0!=="")YA+=i(m,J0);let HA=L0[o0],gA=e[HA];if(m.replacer)gA=m.replacer.call(e,HA,gA);if(!v0(m,J0+1,HA,!0,!0,!0))continue;let L1=m.tag!==null&&m.tag!=="?"||m.dump&&m.dump.length>1024;if(L1)if(m.dump&&Z===m.dump.charCodeAt(0))YA+="?";else YA+="? ";if(YA+=m.dump,L1)YA+=i(m,J0);if(!v0(m,J0+1,gA,!0,L1))continue;if(m.dump&&Z===m.dump.charCodeAt(0))YA+=":";else YA+=": ";YA+=m.dump,I0+=YA}m.tag=M0,m.dump=I0||"{}"}function K0(m,J0,e){let z0=e?m.explicitTypes:m.implicitTypes;for(let I0=0,M0=z0.length;I0<M0;I0+=1){let L0=z0[I0];if((L0.instanceOf||L0.predicate)&&(!L0.instanceOf||typeof J0==="object"&&J0 instanceof L0.instanceOf)&&(!L0.predicate||L0.predicate(J0))){if(e)if(L0.multi&&L0.representName)m.tag=L0.representName(J0);else m.tag=L0.tag;else m.tag="?";if(L0.represent){let o0=m.styleMap[L0.tag]||L0.defaultStyle,l0;if(w.call(L0.represent)==="[object Function]")l0=L0.represent(J0,o0);else if(B.call(L0.represent,o0))l0=L0.represent[o0](J0,o0);else throw new Q("!<"+L0.tag+'> tag resolver accepts not "'+o0+'" style');m.dump=l0}return!0}}return!1}function v0(m,J0,e,z0,I0,M0,L0){if(m.tag=null,m.dump=e,!K0(m,e,!1))K0(m,e,!0);let o0=w.call(m.dump),l0=z0;if(z0)z0=m.flowLevel<0||m.flowLevel>J0;let YA=o0==="[object Object]"||o0==="[object Array]",HA,gA;if(YA)HA=m.duplicates.indexOf(e),gA=HA!==-1;if(m.tag!==null&&m.tag!=="?"||gA||m.indent!==2&&J0>0)I0=!1;if(gA&&m.usedDuplicates[HA])m.dump="*ref_"+HA;else{if(YA&&gA&&!m.usedDuplicates[HA])m.usedDuplicates[HA]=!0;if(o0==="[object Object]"){if(z0&&Object.keys(m.dump).length!==0){if(_(m,J0,m.dump,I0),gA)m.dump="&ref_"+HA+m.dump}else if(R0(m,J0,m.dump),gA)m.dump="&ref_"+HA+" "+m.dump}else if(o0==="[object Array]"){if(z0&&m.dump.length!==0){if(m.noArrayIndent&&!L0&&J0>0)T0(m,J0-1,m.dump,I0);else T0(m,J0,m.dump,I0);if(gA)m.dump="&ref_"+HA+m.dump}else if(j1(m,J0,m.dump),gA)m.dump="&ref_"+HA+" "+m.dump}else if(o0==="[object String]"){if(m.tag!=="?")s0(m,m.dump,J0,M0,l0)}else if(o0==="[object Undefined]")return!1;else{if(m.skipInvalid)return!1;throw new Q("unacceptable kind of an object to dump "+o0)}if(m.tag!==null&&m.tag!=="?"){let L1=encodeURI(m.tag[0]==="!"?m.tag.slice(1):m.tag).replace(/!/g,"%21");if(m.tag[0]==="!")L1="!"+L1;else if(L1.slice(0,18)==="tag:yaml.org,2002:")L1="!!"+L1.slice(18);else L1="!<"+L1+">";m.dump=L1+" "+m.dump}}return!0}function W0(m,J0){let e=[],z0=[];d(m,e,z0);let I0=z0.length;for(let M0=0;M0<I0;M0+=1)J0.duplicates.push(e[z0[M0]]);J0.usedDuplicates=Array(I0)}function d(m,J0,e){if(m!==null&&typeof m==="object"){let z0=J0.indexOf(m);if(z0!==-1){if(e.indexOf(z0)===-1)e.push(z0)}else if(J0.push(m),Array.isArray(m))for(let I0=0,M0=m.length;I0<M0;I0+=1)d(m[I0],J0,e);else{let I0=Object.keys(m);for(let M0=0,L0=I0.length;M0<L0;M0+=1)d(m[I0[M0]],J0,e)}}}function U0(m,J0){J0=J0||{};let e=new H0(J0);if(!e.noRefs)W0(m,e);let z0=m;if(e.replacer)z0=e.replacer.call({"":z0},"",z0);if(v0(e,0,z0,!0,!0))return e.dump+`
145
145
  `;return""}return sy0.dump=U0,sy0}function SwQ(){if(nxA)return dY;nxA=1;let A=ywQ(),Q=gwQ();function $(w,B){return function(){throw Error("Function yaml."+w+" is removed in js-yaml 4. Use yaml."+B+" instead, which is now safe by default.")}}return dY.Type=UH(),dY.Schema=rxA(),dY.FAILSAFE_SCHEMA=txA(),dY.JSON_SCHEMA=wRA(),dY.CORE_SCHEMA=BRA(),dY.DEFAULT_SCHEMA=ay0(),dY.load=A.load,dY.loadAll=A.loadAll,dY.dump=Q.dump,dY.YAMLException=Vs(),dY.types={binary:ZRA(),float:$RA(),map:axA(),null:exA(),pairs:WRA(),set:KRA(),timestamp:XRA(),bool:ARA(),int:QRA(),merge:YRA(),omap:HRA(),seq:sxA(),str:oxA()},dY.safeLoad=$("safeLoad","load"),dY.safeLoadAll=$("safeLoadAll","loadAll"),dY.safeDump=$("safeDump","dump"),dY}var dY,yX0,pk,PxA,fy0,kxA,xy0,jxA,Ry0,MxA,vy0,bxA,Cy0,OxA,hy0,fxA,Ey0,xxA,Ty0,RxA,yy0,vxA,gy0,CxA,Sy0,hxA,my0,ExA,uy0,TxA,cy0,yxA,py0,gxA,ly0,SxA,dy0,mxA,iy0,uxA,ny0,cxA,ry0,pxA,oy0,lxA,dxA,sy0,ixA,nxA,mwQ,uwQ,B58,X58,Y58,Z58,H58,W58,gX0,K58,ty0,U58,G58,D58,q58,z58;var SX0=c(()=>{dY={},yX0={},pk={};sy0={};mwQ=SwQ(),uwQ=EwQ(mwQ),{Type:B58,Schema:X58,FAILSAFE_SCHEMA:Y58,JSON_SCHEMA:Z58,CORE_SCHEMA:H58,DEFAULT_SCHEMA:W58,load:gX0,loadAll:K58,dump:ty0,YAMLException:U58,types:G58,safeLoad:D58,safeLoadAll:q58,safeDump:z58}=uwQ});var J58;var URA=c(()=>{C0();SX0();J58=H.record(H.string(),H.unknown())});class mX0{format(A){return A.message}parse(A){return{message:A.trim()}}}var GRA=c(()=>{SX0()});var DRA=c(()=>{to();pMA();HbA();WbA();_xA();URA();GRA();qT0()});var m58;var qRA=c(()=>{C0();m58=H.object({slug:H.string(),title:H.string(),type:H.string(),entityId:H.string(),contentHash:H.string()})});var y9=c(()=>{DRA();qRA()});function Js(A,Q){return Q?A.optional():A}function Qg0(A){switch(A.type){case"string":return Js(H.string(),A.optional);case"number":return Js(H.number(),A.optional);case"enum":return Js(H.enum(A.options),A.optional);case"object":{let Q={};for(let[$,w]of Object.entries(A.fields))Q[$]=Qg0(w);return Js(H.object(Q),A.optional)}case"array":{let Q=H.array(cwQ(A));if(A.minItems!==void 0)Q=Q.min(A.minItems);if(A.length!==void 0)Q=Q.length(A.length);return Js(Q,A.optional)}}}function cwQ(A){let{items:Q}=A;switch(Q.type){case"string":return H.string();case"number":return H.number();case"enum":return H.enum(Q.options);case"object":{let $={};for(let[w,B]of Object.entries(Q.fields))$[w]=Qg0(B);return H.object($)}}}function Ag0(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])=>Ag0($,w))};case"array":{let $={key:A,label:Q.label,type:"array"};switch(Q.items.type){case"string":case"enum":return $.itemType="string",$;case"number":return $.itemType="number",$;case"object":return $.itemType="object",$.itemMappings=Object.entries(Q.items.fields).map(([w,B])=>Ag0(w,B)),$}}}}function $g0(A,Q){let $={};for(let[X,Y]of Object.entries(Q.fields))$[X]=Qg0(Y);let w=H.object($),B=new d$(w,{title:Q.title,mappings:Object.entries(Q.fields).map(([X,Y])=>Ag0(X,Y))});return{name:A,description:Q.description,schema:w,formatter:B,requiredPermission:Q.requiredPermission??"public",layout:{component:Q.layout,...Q.fullscreen!==void 0?{fullscreen:Q.fullscreen}:{}},...Q.runtimeScripts?{runtimeScripts:Q.runtimeScripts}:{}}}function lk(A){let Q={};for(let[$,w]of Object.entries(A.sections))Q[$]=$g0($,w);return Q}var zRA=c(()=>{y9();C0()});function pwQ(A){return A.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").split(" ").map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function VRA(A){let Q=A;while(Q instanceof H.ZodOptional||Q instanceof H.ZodNullable)Q=Q.unwrap();return Q}function lwQ(A,Q){let $=pwQ(A),w=VRA(Q);if(w instanceof H.ZodString||w instanceof H.ZodEnum||w instanceof H.ZodLiteral)return{key:A,label:$,type:"string"};if(w instanceof H.ZodNumber)return{key:A,label:$,type:"number"};if(w instanceof H.ZodObject)return{key:A,label:$,type:"object",children:wg0(w)};if(w instanceof H.ZodArray){let B=VRA(w.element);if(B instanceof H.ZodObject)return{key:A,label:$,type:"array",itemType:"object",itemMappings:wg0(B)};if(B instanceof H.ZodNumber)return{key:A,label:$,type:"array",itemType:"number"};return{key:A,label:$,type:"array",itemType:"string"}}throw Error(`Section field "${A}" has a schema type the markdown formatter cannot `+"derive headings for \u2014 use string/number/enum/object/array.")}function wg0(A){return Object.entries(A.shape).map(([Q,$])=>lwQ(Q,$))}function JRA(A,Q){let $=Q.schema;if(!($ instanceof H.ZodObject))throw Error(`Section "${A}" schema must be a zod object.`);let w=new d$($,{title:Q.title,mappings:wg0($)});return{name:A,description:Q.description,schema:$,formatter:w,requiredPermission:Q.requiredPermission??"public",layout:{component:Q.component,...Q.fullscreen!==void 0?{fullscreen:Q.fullscreen}:{}}}}function uX0(A){let Q={};for(let[$,w]of Object.entries(A.sections))Q[$]=JRA($,w);return Q}var FRA=c(()=>{y9();C0()});function Bg0(A){return`preview.${A.trim().replace(/^https?:\/\//,"")}`}function IRA(A){let Q=A.match(dwQ);if(!Q)return A;let $=A;for(let w of Q){let B=w.slice(2,-1),X=process.env[B];if(X===void 0)return;$=$.replace(w,X)}return $}function cX0(A){if(typeof A==="string")return IRA(A);if(Array.isArray(A))return A.map((Q)=>cX0(Q)).filter((Q)=>Q!==void 0);if(typeof A==="object"&&A!==null){let Q={};for(let[$,w]of Object.entries(A)){let B=IRA($);if(B===void 0)continue;let X=cX0(w);if(X===void 0)continue;Q[B]=X}return Q}return A}function k1(A){return A.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function _g(A){try{return new URL(A).hostname.replace(/\./g,"-")}catch{return(A.split("/")[0]??A).replace(/\./g,"-")}}function pX0(A,Q){let $=k1(A);if(!$){let w=Date.now().toString(36);return Q?`id-${w}-${Q}`:`id-${w}`}return Q?`${$}-${Q}`:$}function Dz(A){if(iwQ.has(A.toLowerCase()))return A;if(A.endsWith("y")&&A.length>1){let Q=A[A.length-2];if(!"aeiou".includes(Q?.toLowerCase()??""))return A.slice(0,-1)+"ies"}if(A.endsWith("s")||A.endsWith("x")||A.endsWith("ch"))return A+"es";return A+"s"}function dk(A){return A.replace(/[-_]/g," ").replace(/([A-Z])/g," $1").replace(/\b\w/g,(Q)=>Q.toUpperCase()).replace(/\s+/g," ").trim()}function LRA(A){let $=A.split("-").map((B)=>B.charAt(0).toUpperCase()+B.slice(1)),w=$.pop();if(w)$.push(Dz(w));return $.join(" ")}function lX0(A){let Q=A.toLowerCase(),$=nwQ[Q];if($!==void 0)return $;return A.replace(/\b\w/g,(w)=>w.toUpperCase())}function Pg(A,Q){if(!Q)return A;try{return new URL(A,Q).toString()}catch{return A}}function NRA(A){let $=A.split(/\s+/).filter((w)=>w.length>0).length;return Math.max(1,Math.ceil($/200))}function ik(A){let Q=A.replace(/\s+/g," ").trim();if(!Q)return;let $=Q.match(/^(.*?[.!?])(?:\s|$)/);if($?.[1])return $[1];return Q.length<=200?Q:`${Q.slice(0,197)}\u2026`}function GH(A,Q){if(A.length<=Q)return A;let $=A.slice(0,Q),w=$.lastIndexOf(" ");return w>0?$.slice(0,w)+"...":$+"..."}var dwQ,iwQ,nwQ;var S2=c(()=>{dwQ=/\$\{[^}]+\}/g;iwQ=new Set(["series","species","sheep","deer","fish"]);nwQ={github:"GitHub",instagram:"Instagram",linkedin:"LinkedIn",email:"Email",website:"Website"}});class iY{static instance=null;entityDisplay;constructor(){}static getInstance(){return iY.instance??=new iY,iY.instance}configure(A){this.entityDisplay=A}static resetInstance(){iY.instance=null}hasRoute(A){return this.entityDisplay?.[A]!==void 0}generateUrl(A,Q){let $=this.entityDisplay?.[A];if($)return`/${$.pluralName??$.label.toLowerCase()+"s"}/${Q}`;return`/${Dz(A)}/${Q}`}}var _RA=c(()=>{S2()});function PRA(A){if(!A)return[];return Array.isArray(A)?A:[A]}function rwQ(A,Q){let $=[...PRA(A),...PRA(Q)];return $.length>0?$:void 0}function kRA(A){if(!A)return[];return Array.isArray(A)?A:[A]}function owQ(A,Q){let $=[...kRA(A),...kRA(Q)];return $.length>0?$:void 0}function swQ(A,Q){if(!Q||Q.length===0)return A;let $=[...A],w=new Map;for(let[B,X]of $.entries())w.set(X.id,B);for(let B of Q){let X=w.get(B.id);if(X!==void 0){$[X]=B;continue}w.set(B.id,$.length),$.push(B)}return $}function kg(A,Q={}){if(Object.keys(Q).length===0)return A;let{layouts:$,entityDisplay:w,staticAssets:B,themeOverride:X,headScripts:Y}=Q,Z=Object.hasOwn(Q,"plugin")?Q.plugin:A.plugin,W=$?{...A.layouts,...$}:A.layouts,K=w?{...A.entityDisplay,...w}:A.entityDisplay,U=B?{...A.staticAssets??{},...B}:A.staticAssets,G=[A.themeOverride,X].filter(Boolean).join(`
146
146
 
147
- `),D=[...A.headScripts??[],...Y??[]],q=rwQ(A.content,Q.content),J=owQ(A.sections,Q.sections);return{layouts:W,routes:swQ(A.routes,Q.routes),...Z?{plugin:Z}:{},entityDisplay:K,...q?{content:q}:{},...J?{sections:J}:{},...G?{themeOverride:G}:{},...D.length>0?{headScripts:D}:{},...U&&Object.keys(U).length>0?{staticAssets:U}:{}}}var dX0,awQ,twQ,ewQ,Xg0;var jRA=c(()=>{C0();dX0=H.string(),awQ=H.looseObject({id:H.string().min(1)}),twQ=H.looseObject({label:H.string().min(1)}),ewQ=H.looseObject({layouts:H.record(H.string(),H.unknown()),plugin:H.custom((A)=>typeof A==="function").optional(),routes:H.array(awQ),entityDisplay:H.record(H.string(),twQ),content:H.unknown().optional(),themeOverride:H.string().optional(),headScripts:H.array(H.string()).optional(),staticAssets:H.record(H.string(),H.string()).optional()}),Xg0=H.custom((A)=>ewQ.safeParse(A).success)});var XX=c(()=>{UT0();uMA();zRA();FRA();_RA();jRA()});var MRA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as bRA}from"crypto";function Q5Q(A){if(A<0)throw RangeError("Wrong ID size");try{if(!nk||nk.length<A)nk=Buffer.allocUnsafe(A*A5Q),bRA.getRandomValues(nk),jg=0;else if(jg+A>nk.length)bRA.getRandomValues(nk),jg=0}catch(Q){throw nk=void 0,Q}jg+=A}function Yg0(A=21){Q5Q(A|=0);let Q="";for(let $=jg-A;$<jg;$++)Q+=MRA[nk[$]&63];return Q}var A5Q=128,nk,jg;var ORA=()=>{};function nY(A=12){return Yg0(A)}function Mg(A){return`${A}_${Yg0(12)}`}var iV=c(()=>{ORA()});var Zg0,$5Q,hx,LB8;var Fs=c(()=>{C0();Zg0=H.enum(["file_operations","content_operations","data_processing","batch_processing"]),$5Q=H.object({pluginId:H.string().optional(),progressToken:H.union([H.string(),H.number()]).optional(),operationType:Zg0,operationTarget:H.string().optional(),interfaceType:H.string().optional(),conversationId:H.string().optional(),channelId:H.string().optional(),silent:H.boolean().optional()}),hx=H.object({pluginId:H.string().optional(),progressToken:H.union([H.string(),H.number()]).optional(),operationType:Zg0,operationTarget:H.string().optional(),interfaceType:H.string().optional(),conversationId:H.string().optional(),channelId:H.string().optional(),silent:H.boolean().optional(),rootJobId:H.string()}),LB8=H.enum(["none","skip","replace","coalesce"])});var Hg0,fRA,_$,w5Q,B5Q,Wg0,bg;var rk=c(()=>{C0();Fs();Hg0=H.enum(["pending","processing","completed","failed"]),fRA=H.enum(["completed","failed"]),_$={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},w5Q=H.object({id:H.string(),type:H.string(),status:Hg0,data:H.unknown(),result:H.unknown().optional(),lastError:H.string().optional().nullable(),attempts:H.number(),maxRetries:H.number(),priority:H.number(),createdAt:H.date(),updatedAt:H.date(),processedAt:H.date().optional().nullable(),completedAt:H.date().optional().nullable(),failedAt:H.date().optional().nullable()}),B5Q=H.object({jobId:H.string(),type:H.string(),status:fRA,result:H.unknown().optional(),error:H.string().optional()}),Wg0=H.object({success:H.literal(!1),error:H.string().optional()}),bg=H.object({id:H.string(),type:H.enum(["job","batch"]),status:Hg0,message:H.string().optional(),progress:H.object({current:H.number(),total:H.number(),percentage:H.number()}).optional(),aggregationKey:H.string().optional(),batchDetails:H.object({totalOperations:H.number(),completedOperations:H.number(),failedOperations:H.number(),currentOperation:H.string().optional(),errors:H.array(H.string()).optional()}).optional(),jobDetails:H.object({jobType:H.string(),priority:H.number(),retryCount:H.number()}).optional(),metadata:hx})});function q1(A,Q){if(!A||typeof A!=="object")return!1;if(A instanceof Q)return!0;if(!Object.prototype.hasOwnProperty.call(Q,lA))throw Error(`Class "${Q.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let $=Object.getPrototypeOf(A).constructor;if($)while($){if(lA in $&&$[lA]===Q[lA])return!0;$=Object.getPrototypeOf($)}return!1}var lA;var Z6=c(()=>{lA=Symbol.for("drizzle:entityKind")});var Aw;var qz=c(()=>{Z6();Aw=class Aw{constructor(A,Q){this.table=A,this.config=Q,this.name=Q.name,this.keyAsName=Q.keyAsName,this.notNull=Q.notNull,this.default=Q.default,this.defaultFn=Q.defaultFn,this.onUpdateFn=Q.onUpdateFn,this.hasDefault=Q.hasDefault,this.primary=Q.primaryKey,this.isUnique=Q.isUnique,this.uniqueName=Q.uniqueName,this.uniqueType=Q.uniqueType,this.dataType=Q.dataType,this.columnType=Q.columnType,this.generated=Q.generated,this.generatedIdentity=Q.generatedIdentity}static[lA]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(A){return A}mapToDriverValue(A){return A}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var Kg0;var Ug0=c(()=>{Z6();Kg0=class Kg0{static[lA]="ColumnBuilder";config;constructor(A,Q,$){this.config={name:A,keyAsName:A==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Q,columnType:$,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(A){return this.config.default=A,this.config.hasDefault=!0,this}$defaultFn(A){return this.config.defaultFn=A,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(A){return this.config.onUpdateFn=A,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(A){if(this.config.name!=="")return;this.config.name=A}}});var oK;var Is=c(()=>{oK=Symbol.for("drizzle:Name")});function xRA(A,...Q){return A(...Q)}var RRA=()=>{};function vRA(A,Q){return`${A[oK]}_${Q.join("_")}_unique`}var CRA=c(()=>{Is()});var Ls,X5Q;var hRA=c(()=>{qz();Z6();CRA();Ls=class Ls extends Aw{constructor(A,Q){if(!Q.uniqueName)Q.uniqueName=vRA(A,[Q.name]);super(A,Q);this.table=A}static[lA]="PgColumn"};X5Q=class X5Q extends Ls{static[lA]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(A){return this.indexConfig.opClass=A,this}}});function TRA(A){return!!A&&typeof A==="function"&&ERA in A&&A[ERA]===!0}var Y5Q,ERA,Z5Q;var yRA=c(()=>{Z6();hRA();Y5Q=class Y5Q extends Ls{static[lA]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(A,Q){super(A,Q);this.enum=Q.enum}getSQLType(){return this.enum.enumName}};ERA=Symbol.for("drizzle:isPgEnum");Z5Q=class Z5Q extends Ls{static[lA]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(A,Q){super(A,Q);this.enum=Q.enum}getSQLType(){return this.enum.enumName}}});var yB,Ns;var zz=c(()=>{Z6();yB=class yB{static[lA]="Subquery";constructor(A,Q,$,w=!1,B=[]){this._={brand:"Subquery",sql:A,selectedFields:Q,alias:$,isWith:w,usedTables:B}}};Ns=class Ns extends yB{static[lA]="WithSubquery"}});var gRA="0.45.2";var SRA=()=>{};var Gg0,Dg0,mRA;var uRA=c(()=>{RRA();SRA();mRA={startActiveSpan(A,Q){if(!Gg0)return Q();if(!Dg0)Dg0=Gg0.trace.getTracer("drizzle-orm",gRA);return xRA(($,w)=>w.startActiveSpan(A,(B)=>{try{return Q(B)}catch(X){throw B.setStatus({code:$.SpanStatusCode.ERROR,message:X instanceof Error?X.message:"Unknown error"}),X}finally{B.end()}}),Gg0,Dg0)}}});var gB;var zL=c(()=>{gB=Symbol.for("drizzle:ViewBaseConfig")});function ok(A){return A[oK]}function Ex(A){return`${A[iX0]??"public"}.${A[oK]}`}var iX0,nX0,cRA,qg0,zg0,_s,pRA,H5Q,Z2;var rY=c(()=>{Z6();Is();iX0=Symbol.for("drizzle:Schema"),nX0=Symbol.for("drizzle:Columns"),cRA=Symbol.for("drizzle:ExtraConfigColumns"),qg0=Symbol.for("drizzle:OriginalName"),zg0=Symbol.for("drizzle:BaseName"),_s=Symbol.for("drizzle:IsAlias"),pRA=Symbol.for("drizzle:ExtraConfigBuilder"),H5Q=Symbol.for("drizzle:IsDrizzleTable");Z2=class Z2{static[lA]="Table";static Symbol={Name:oK,Schema:iX0,OriginalName:qg0,Columns:nX0,ExtraConfigColumns:cRA,BaseName:zg0,IsAlias:_s,ExtraConfigBuilder:pRA};[oK];[qg0];[iX0];[nX0];[cRA];[zg0];[_s]=!1;[H5Q]=!0;[pRA]=void 0;constructor(A,Q,$){this[oK]=this[qg0]=A,this[iX0]=Q,this[zg0]=$}}});function Vg0(A){return A!==null&&A!==void 0&&typeof A.getSQL==="function"}function W5Q(A){let Q={sql:"",params:[]};for(let $ of A)if(Q.sql+=$.sql,Q.params.push(...$.params),$.typings?.length){if(!Q.typings)Q.typings=[];Q.typings.push(...$.typings)}return Q}function lRA(A){return typeof A==="object"&&A!==null&&"mapToDriverValue"in A&&typeof A.mapToDriverValue==="function"}function $A(A,...Q){let $=[];if(Q.length>0||A.length>0&&A[0]!=="")$.push(new W4(A[0]));for(let[w,B]of Q.entries())$.push(B,new W4(A[w+1]));return new d2($)}function Ps(A,Q){return A.map(($)=>{if(q1($,sk)){if(!($.name in Q))throw Error(`No value for placeholder "${$.name}" was provided`);return Q[$.name]}if(q1($,sK)&&q1($.value,sk)){if(!($.value.name in Q))throw Error(`No value for placeholder "${$.value.name}" was provided`);return $.encoder.mapToDriverValue(Q[$.value.name])}return $})}var W4,d2,rX0,dRA,iRA,X98,sK,sk,K5Q,XD;var K4=c(()=>{Z6();yRA();zz();uRA();zL();qz();rY();W4=class W4{static[lA]="StringChunk";value;constructor(A){this.value=Array.isArray(A)?A:[A]}getSQL(){return new d2([this])}};d2=class d2{constructor(A){this.queryChunks=A;for(let Q of A)if(q1(Q,Z2)){let $=Q[Z2.Symbol.Schema];this.usedTables.push($===void 0?Q[Z2.Symbol.Name]:$+"."+Q[Z2.Symbol.Name])}}static[lA]="SQL";decoder=dRA;shouldInlineParams=!1;usedTables=[];append(A){return this.queryChunks.push(...A.queryChunks),this}toQuery(A){return mRA.startActiveSpan("drizzle.buildSQL",(Q)=>{let $=this.buildQueryFromSourceParams(this.queryChunks,A);return Q?.setAttributes({"drizzle.query.text":$.sql,"drizzle.query.params":JSON.stringify($.params)}),$})}buildQueryFromSourceParams(A,Q){let $=Object.assign({},Q,{inlineParams:Q.inlineParams||this.shouldInlineParams,paramStartIndex:Q.paramStartIndex||{value:0}}),{casing:w,escapeName:B,escapeParam:X,prepareTyping:Y,inlineParams:Z,paramStartIndex:W}=$;return W5Q(A.map((K)=>{if(q1(K,W4))return{sql:K.value.join(""),params:[]};if(q1(K,rX0))return{sql:B(K.value),params:[]};if(K===void 0)return{sql:"",params:[]};if(Array.isArray(K)){let U=[new W4("(")];for(let[G,D]of K.entries())if(U.push(D),G<K.length-1)U.push(new W4(", "));return U.push(new W4(")")),this.buildQueryFromSourceParams(U,$)}if(q1(K,d2))return this.buildQueryFromSourceParams(K.queryChunks,{...$,inlineParams:Z||K.shouldInlineParams});if(q1(K,Z2)){let U=K[Z2.Symbol.Schema],G=K[Z2.Symbol.Name];return{sql:U===void 0||K[_s]?B(G):B(U)+"."+B(G),params:[]}}if(q1(K,Aw)){let U=w.getColumnCasing(K);if(Q.invokeSource==="indexes")return{sql:B(U),params:[]};let G=K.table[Z2.Symbol.Schema];return{sql:K.table[_s]||G===void 0?B(K.table[Z2.Symbol.Name])+"."+B(U):B(G)+"."+B(K.table[Z2.Symbol.Name])+"."+B(U),params:[]}}if(q1(K,XD)){let U=K[gB].schema,G=K[gB].name;return{sql:U===void 0||K[gB].isAlias?B(G):B(U)+"."+B(G),params:[]}}if(q1(K,sK)){if(q1(K.value,sk))return{sql:X(W.value++,K),params:[K],typings:["none"]};let U=K.value===null?null:K.encoder.mapToDriverValue(K.value);if(q1(U,d2))return this.buildQueryFromSourceParams([U],$);if(Z)return{sql:this.mapInlineParam(U,$),params:[]};let G=["none"];if(Y)G=[Y(K.encoder)];return{sql:X(W.value++,U),params:[U],typings:G}}if(q1(K,sk))return{sql:X(W.value++,K),params:[K],typings:["none"]};if(q1(K,d2.Aliased)&&K.fieldAlias!==void 0)return{sql:B(K.fieldAlias),params:[]};if(q1(K,yB)){if(K._.isWith)return{sql:B(K._.alias),params:[]};return this.buildQueryFromSourceParams([new W4("("),K._.sql,new W4(") "),new rX0(K._.alias)],$)}if(TRA(K)){if(K.schema)return{sql:B(K.schema)+"."+B(K.enumName),params:[]};return{sql:B(K.enumName),params:[]}}if(Vg0(K)){if(K.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([K.getSQL()],$);return this.buildQueryFromSourceParams([new W4("("),K.getSQL(),new W4(")")],$)}if(Z)return{sql:this.mapInlineParam(K,$),params:[]};return{sql:X(W.value++,K),params:[K],typings:["none"]}}))}mapInlineParam(A,{escapeString:Q}){if(A===null)return"null";if(typeof A==="number"||typeof A==="boolean")return A.toString();if(typeof A==="string")return Q(A);if(typeof A==="object"){let $=A.toString();if($==="[object Object]")return Q(JSON.stringify(A));return Q($)}throw Error("Unexpected param value: "+A)}getSQL(){return this}as(A){if(A===void 0)return this;return new d2.Aliased(this,A)}mapWith(A){return this.decoder=typeof A==="function"?{mapFromDriverValue:A}:A,this}inlineParams(){return this.shouldInlineParams=!0,this}if(A){return A?this:void 0}};rX0=class rX0{constructor(A){this.value=A}static[lA]="Name";brand;getSQL(){return new d2([this])}};dRA={mapFromDriverValue:(A)=>A},iRA={mapToDriverValue:(A)=>A},X98={...dRA,...iRA};sK=class sK{constructor(A,Q=iRA){this.value=A,this.encoder=Q}static[lA]="Param";brand;getSQL(){return new d2([this])}};((A)=>{function Q(){return new d2([])}A.empty=Q;function $(W){return new d2(W)}A.fromList=$;function w(W){return new d2([new W4(W)])}A.raw=w;function B(W,K){let U=[];for(let[G,D]of W.entries()){if(G>0&&K!==void 0)U.push(K);U.push(D)}return new d2(U)}A.join=B;function X(W){return new rX0(W)}A.identifier=X;function Y(W){return new sk(W)}A.placeholder=Y;function Z(W,K){return new sK(W,K)}A.param=Z})($A||($A={}));((A)=>{class Q{constructor($,w){this.sql=$,this.fieldAlias=w}static[lA]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Q(this.sql,this.fieldAlias)}}A.Aliased=Q})(d2||(d2={}));sk=class sk{constructor(A){this.name=A}static[lA]="Placeholder";getSQL(){return new d2([this])}};K5Q=Symbol.for("drizzle:IsDrizzleView");XD=class XD{static[lA]="View";[gB];[K5Q]=!0;constructor({name:A,schema:Q,selectedFields:$,query:w}){this[gB]={name:A,originalName:A,schema:Q,selectedFields:$,query:w,isExisting:!w,isAlias:!1}}getSQL(){return new d2([this])}};Aw.prototype.getSQL=function(){return new d2([this])};Z2.prototype.getSQL=function(){return new d2([this])};yB.prototype.getSQL=function(){return new d2([this])}});function Jg0(A,Q,$){let w={},B=A.reduce((X,{path:Y,field:Z},W)=>{let K;if(q1(Z,Aw))K=Z;else if(q1(Z,d2))K=Z.decoder;else if(q1(Z,yB))K=Z._.sql.decoder;else K=Z.sql.decoder;let U=X;for(let[G,D]of Y.entries())if(G<Y.length-1){if(!(D in U))U[D]={};U=U[D]}else{let q=Q[W],J=U[D]=q===null?null:K.mapFromDriverValue(q);if($&&q1(Z,Aw)&&Y.length===2){let F=Y[0];if(!(F in w))w[F]=J===null?ok(Z.table):!1;else if(typeof w[F]==="string"&&w[F]!==ok(Z.table))w[F]=!1}}return X},{});if($&&Object.keys(w).length>0){for(let[X,Y]of Object.entries(w))if(typeof Y==="string"&&!$[Y])B[X]=null}return B}function YD(A,Q){return Object.entries(A).reduce(($,[w,B])=>{if(typeof w!=="string")return $;let X=Q?[...Q,w]:[w];if(q1(B,Aw)||q1(B,d2)||q1(B,d2.Aliased)||q1(B,yB))$.push({path:X,field:B});else if(q1(B,Z2))$.push(...YD(B[Z2.Symbol.Columns],X));else $.push(...YD(B,X));return $},[])}function ks(A,Q){let $=Object.keys(A),w=Object.keys(Q);if($.length!==w.length)return!1;for(let[B,X]of $.entries())if(X!==w[B])return!1;return!0}function oX0(A,Q){let $=Object.entries(Q).filter(([,w])=>w!==void 0).map(([w,B])=>{if(q1(B,d2)||q1(B,Aw))return[w,B];else return[w,new sK(B,A[Z2.Symbol.Columns][w])]});if($.length===0)throw Error("No values to set");return Object.fromEntries($)}function nRA(A,Q){for(let $ of Q)for(let w of Object.getOwnPropertyNames($.prototype)){if(w==="constructor")continue;Object.defineProperty(A.prototype,w,Object.getOwnPropertyDescriptor($.prototype,w)||Object.create(null))}}function rRA(A){return A[Z2.Symbol.Columns]}function js(A){return q1(A,yB)?A._.alias:q1(A,XD)?A[gB].name:q1(A,d2)?void 0:A[Z2.Symbol.IsAlias]?A[Z2.Symbol.Name]:A[Z2.Symbol.BaseName]}function nV(A,Q){return{name:typeof A==="string"&&A.length>0?A:"",config:typeof A==="object"?A:Q}}function oRA(A){if(typeof A!=="object"||A===null)return!1;if(A.constructor.name!=="Object")return!1;if("logger"in A){let Q=typeof A.logger;if(Q!=="boolean"&&(Q!=="object"||typeof A.logger.logQuery!=="function")&&Q!=="undefined")return!1;return!0}if("schema"in A){let Q=typeof A.schema;if(Q!=="object"&&Q!=="undefined")return!1;return!0}if("casing"in A){let Q=typeof A.casing;if(Q!=="string"&&Q!=="undefined")return!1;return!0}if("mode"in A){if(A.mode!=="default"||A.mode!=="planetscale"||A.mode!==void 0)return!1;return!0}if("connection"in A){let Q=typeof A.connection;if(Q!=="string"&&Q!=="object"&&Q!=="undefined")return!1;return!0}if("client"in A){let Q=typeof A.client;if(Q!=="object"&&Q!=="function"&&Q!=="undefined")return!1;return!0}if(Object.keys(A).length===0)return!0;return!1}var Fg0;var LW=c(()=>{qz();Z6();K4();zz();rY();zL();Fg0=typeof TextDecoder>"u"?null:new TextDecoder});var sRA,Ig0,Lg0;var sX0=c(()=>{Z6();sRA=class sRA{static[lA]="ConsoleLogWriter";write(A){console.log(A)}};Ig0=class Ig0{static[lA]="DefaultLogger";writer;constructor(A){this.writer=A?.writer??new sRA}logQuery(A,Q){let $=Q.map((B)=>{try{return JSON.stringify(B)}catch{return String(B)}}),w=$.length?` -- params: [${$.join(", ")}]`:"";this.writer.write(`Query: ${A}${w}`)}};Lg0=class Lg0{static[lA]="NoopLogger";logQuery(){}}});var aRA,tRA,Ng0;var eRA=c(()=>{Z6();rY();aRA=Symbol.for("drizzle:PgInlineForeignKeys"),tRA=Symbol.for("drizzle:EnableRLS");Ng0=class Ng0 extends Z2{static[lA]="PgTable";static Symbol=Object.assign({},Z2.Symbol,{InlineForeignKeys:aRA,EnableRLS:tRA});[aRA]=[];[tRA]=!1;[Z2.Symbol.ExtraConfigBuilder]=void 0;[Z2.Symbol.ExtraConfigColumns]={}}});var _g0,AvA;var QvA=c(()=>{Z6();eRA();_g0=class _g0{static[lA]="PgPrimaryKeyBuilder";columns;name;constructor(A,Q){this.columns=A,this.name=Q}build(A){return new AvA(A,this.columns,this.name)}};AvA=class AvA{constructor(A,Q,$){this.table=A,this.columns=Q,this.name=$}static[lA]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Ng0.Symbol.Name]}_${this.columns.map((A)=>A.name).join("_")}_pk`}}});function NW(A,Q){if(lRA(Q)&&!Vg0(A)&&!q1(A,sK)&&!q1(A,sk)&&!q1(A,Aw)&&!q1(A,Z2)&&!q1(A,XD))return new sK(A,Q);return A}function Qw(...A){let Q=A.filter(($)=>$!==void 0);if(Q.length===0)return;if(Q.length===1)return new d2(Q);return new d2([new W4("("),$A.join(Q,new W4(" and ")),new W4(")")])}function Og(...A){let Q=A.filter(($)=>$!==void 0);if(Q.length===0)return;if(Q.length===1)return new d2(Q);return new d2([new W4("("),$A.join(Q,new W4(" or ")),new W4(")")])}function wvA(A){return $A`not ${A}`}function aK(A,Q){if(Array.isArray(Q)){if(Q.length===0)return $A`false`;return $A`${A} in ${Q.map(($)=>NW($,A))}`}return $A`${A} in ${NW(Q,A)}`}function YvA(A,Q){if(Array.isArray(Q)){if(Q.length===0)return $A`true`;return $A`${A} not in ${Q.map(($)=>NW($,A))}`}return $A`${A} not in ${NW(Q,A)}`}function ZvA(A){return $A`${A} is null`}function xg(A){return $A`${A} is not null`}function HvA(A){return $A`exists ${A}`}function WvA(A){return $A`not exists ${A}`}function KvA(A,Q,$){return $A`${A} between ${NW(Q,A)} and ${NW($,A)}`}function UvA(A,Q,$){return $A`${A} not between ${NW(Q,A)} and ${NW($,A)}`}function GvA(A,Q){return $A`${A} like ${Q}`}function DvA(A,Q){return $A`${A} not like ${Q}`}function qvA(A,Q){return $A`${A} ilike ${Q}`}function zvA(A,Q){return $A`${A} not ilike ${Q}`}var NQ=(A,Q)=>{return $A`${A} = ${NW(Q,A)}`},$vA=(A,Q)=>{return $A`${A} <> ${NW(Q,A)}`},aX0=(A,Q)=>{return $A`${A} > ${NW(Q,A)}`},BvA=(A,Q)=>{return $A`${A} >= ${NW(Q,A)}`},XvA=(A,Q)=>{return $A`${A} < ${NW(Q,A)}`},fg=(A,Q)=>{return $A`${A} <= ${NW(Q,A)}`};var VvA=c(()=>{qz();Z6();rY();K4()});function DH(A){return $A`${A} asc`}function qH(A){return $A`${A} desc`}var JvA=c(()=>{K4()});var Pg0=c(()=>{VvA();JvA()});function IvA(){return{and:Qw,between:KvA,eq:NQ,exists:HvA,gt:aX0,gte:BvA,ilike:qvA,inArray:aK,isNull:ZvA,isNotNull:xg,like:GvA,lt:XvA,lte:fg,ne:$vA,not:wvA,notBetween:UvA,notExists:WvA,notLike:DvA,notIlike:zvA,notInArray:YvA,or:Og,sql:$A}}function LvA(){return{sql:$A,asc:DH,desc:qH}}function NvA(A,Q){if(Object.keys(A).length===1&&"default"in A&&!q1(A.default,Z2))A=A.default;let $={},w={},B={};for(let[X,Y]of Object.entries(A))if(q1(Y,Z2)){let Z=Ex(Y),W=w[Z];$[Z]=X,B[X]={tsName:X,dbName:Y[Z2.Symbol.Name],schema:Y[Z2.Symbol.Schema],columns:Y[Z2.Symbol.Columns],relations:W?.relations??{},primaryKey:W?.primaryKey??[]};for(let U of Object.values(Y[Z2.Symbol.Columns]))if(U.primary)B[X].primaryKey.push(U);let K=Y[Z2.Symbol.ExtraConfigBuilder]?.(Y[Z2.Symbol.ExtraConfigColumns]);if(K){for(let U of Object.values(K))if(q1(U,_g0))B[X].primaryKey.push(...U.columns)}}else if(q1(Y,FvA)){let Z=Ex(Y.table),W=$[Z],K=Y.config(Q(Y.table)),U;for(let[G,D]of Object.entries(K))if(W){let q=B[W];if(q.relations[G]=D,U)q.primaryKey.push(...U)}else{if(!(Z in w))w[Z]={relations:{},primaryKey:U};w[Z].relations[G]=D}}return{tables:B,tableNamesMap:$}}function U5Q(A){return function($,w){return new ak(A,$,w,w?.fields.reduce((B,X)=>B&&X.notNull,!0)??!1)}}function G5Q(A){return function($,w){return new Ms(A,$,w)}}function _vA(A,Q,$){if(q1($,ak)&&$.config)return{fields:$.config.fields,references:$.config.references};let w=Q[Ex($.referencedTable)];if(!w)throw Error(`Table "${$.referencedTable[Z2.Symbol.Name]}" not found in schema`);let B=A[w];if(!B)throw Error(`Table "${w}" not found in schema`);let X=$.sourceTable,Y=Q[Ex(X)];if(!Y)throw Error(`Table "${X[Z2.Symbol.Name]}" not found in schema`);let Z=[];for(let W of Object.values(B.relations))if($.relationName&&$!==W&&W.relationName===$.relationName||!$.relationName&&W.referencedTable===$.sourceTable)Z.push(W);if(Z.length>1)throw $.relationName?Error(`There are multiple relations with name "${$.relationName}" in table "${w}"`):Error(`There are multiple relations between "${w}" and "${$.sourceTable[Z2.Symbol.Name]}". Please specify relation name`);if(Z[0]&&q1(Z[0],ak)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw Error(`There is not enough information to infer relation "${Y}.${$.fieldName}"`)}function PvA(A){return{one:U5Q(A),many:G5Q(A)}}function tX0(A,Q,$,w,B=(X)=>X){let X={};for(let[Y,Z]of w.entries())if(Z.isJson){let W=Q.relations[Z.tsKey],K=$[Y],U=typeof K==="string"?JSON.parse(K):K;X[Z.tsKey]=q1(W,ak)?U&&tX0(A,A[Z.relationTableTsKey],U,Z.selection,B):U.map((G)=>tX0(A,A[Z.relationTableTsKey],G,Z.selection,B))}else{let W=B($[Y]),K=Z.field,U;if(q1(K,Aw))U=K;else if(q1(K,d2))U=K.decoder;else U=K.sql.decoder;X[Z.tsKey]=W===null?null:U.mapFromDriverValue(W)}return X}var kg0,FvA,ak,Ms;var bs=c(()=>{rY();qz();Z6();QvA();Pg0();K4();kg0=class kg0{constructor(A,Q,$){this.sourceTable=A,this.referencedTable=Q,this.relationName=$,this.referencedTableName=Q[Z2.Symbol.Name]}static[lA]="Relation";referencedTableName;fieldName};FvA=class FvA{constructor(A,Q){this.table=A,this.config=Q}static[lA]="Relations"};ak=class ak extends kg0{constructor(A,Q,$,w){super(A,Q,$?.relationName);this.config=$,this.isNullable=w}static[lA]="One";withFieldName(A){let Q=new ak(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Q.fieldName=A,Q}};Ms=class Ms extends kg0{constructor(A,Q,$){super(A,Q,$?.relationName);this.config=$}static[lA]="Many";withFieldName(A){let Q=new Ms(this.sourceTable,this.referencedTable,this.config);return Q.fieldName=A,Q}}});function eX0(A,Q){return new Proxy(A,new Os(Q,!1))}function rV(A,Q){return new Proxy(A,new Rg(new Proxy(A.table,new Os(Q,!1))))}function jg0(A,Q){return new d2.Aliased(fs(A.sql,Q),A.fieldAlias)}function fs(A,Q){return $A.join(A.queryChunks.map(($)=>{if(q1($,Aw))return rV($,Q);if(q1($,d2))return fs($,Q);if(q1($,d2.Aliased))return jg0($,Q);return $}))}var Rg,Os;var AY0=c(()=>{qz();Z6();K4();rY();zL();Rg=class Rg{constructor(A){this.table=A}static[lA]="ColumnAliasProxyHandler";get(A,Q){if(Q==="table")return this.table;return A[Q]}};Os=class Os{constructor(A,Q){this.alias=A,this.replaceOriginalName=Q}static[lA]="TableAliasProxyHandler";get(A,Q){if(Q===Z2.Symbol.IsAlias)return!0;if(Q===Z2.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Q===Z2.Symbol.OriginalName)return this.alias;if(Q===gB)return{...A[gB],name:this.alias,isAlias:!0};if(Q===Z2.Symbol.Columns){let w=A[Z2.Symbol.Columns];if(!w)return w;let B={};return Object.keys(w).map((X)=>{B[X]=new Proxy(w[X],new Rg(new Proxy(A,this)))}),B}let $=A[Q];if(q1($,Aw))return new Proxy($,new Rg(new Proxy(A,this)));return $}}});var J7;var vg=c(()=>{AY0();qz();Z6();K4();zz();zL();J7=class J7{static[lA]="SelectionProxyHandler";config;constructor(A){this.config={...A}}get(A,Q){if(Q==="_")return{...A._,selectedFields:new Proxy(A._.selectedFields,this)};if(Q===gB)return{...A[gB],selectedFields:new Proxy(A[gB].selectedFields,this)};if(typeof Q==="symbol")return A[Q];let w=(q1(A,yB)?A._.selectedFields:q1(A,XD)?A[gB].selectedFields:A)[Q];if(q1(w,d2.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!w.isSelectionField)return w.sql;let B=w.clone();return B.isSelectionField=!0,B}if(q1(w,d2)){if(this.config.sqlBehavior==="sql")return w;throw Error(`You tried to reference "${Q}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(q1(w,Aw)){if(this.config.alias)return new Proxy(w,new Rg(new Proxy(w.table,new Os(this.config.alias,this.config.replaceOriginalName??!1))));return w}if(typeof w!=="object"||w===null)return w;return new Proxy(w,new J7(this.config))}}});var zH;var VL=c(()=>{Z6();zH=class zH{static[lA]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(A){return this.then(void 0,A)}finally(A){return this.then((Q)=>{return A?.(),Q},(Q)=>{throw A?.(),Q})}then(A,Q){return this.execute().then(A,Q)}}});var Mg0,kvA;var bg0=c(()=>{Z6();Is();Mg0=class Mg0{static[lA]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(A,Q){if(this.reference=()=>{let{name:$,columns:w,foreignColumns:B}=A();return{name:$,columns:w,foreignTable:B[0].table,foreignColumns:B}},Q)this._onUpdate=Q.onUpdate,this._onDelete=Q.onDelete}onUpdate(A){return this._onUpdate=A,this}onDelete(A){return this._onDelete=A,this}build(A){return new kvA(A,this)}};kvA=class kvA{constructor(A,Q){this.table=A,this.reference=Q.reference,this.onUpdate=Q._onUpdate,this.onDelete=Q._onDelete}static[lA]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:A,columns:Q,foreignColumns:$}=this.reference(),w=Q.map((Y)=>Y.name),B=$.map((Y)=>Y.name),X=[this.table[oK],...w,$[0].table[oK],...B];return A??`${X.join("_")}_fk`}}});function jvA(A,Q){return`${A[oK]}_${Q.join("_")}_unique`}var Og0=c(()=>{Is()});var YX,H9;var tk=c(()=>{Ug0();qz();Z6();bg0();Og0();YX=class YX extends Kg0{static[lA]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(A,Q={}){return this.foreignKeyConfigs.push({ref:A,actions:Q}),this}unique(A){return this.config.isUnique=!0,this.config.uniqueName=A,this}generatedAlwaysAs(A,Q){return this.config.generated={as:A,type:"always",mode:Q?.mode??"virtual"},this}buildForeignKeys(A,Q){return this.foreignKeyConfigs.map(({ref:$,actions:w})=>{return((B,X)=>{let Y=new Mg0(()=>{let Z=B();return{columns:[A],foreignColumns:[Z]}});if(X.onUpdate)Y.onUpdate(X.onUpdate);if(X.onDelete)Y.onDelete(X.onDelete);return Y.build(Q)})($,w)})}};H9=class H9 extends Aw{constructor(A,Q){if(!Q.uniqueName)Q.uniqueName=jvA(A,[Q.name]);super(A,Q);this.table=A}static[lA]="SQLiteColumn"}});function vvA(A,Q){let{name:$,config:w}=nV(A,Q);if(w?.mode==="json")return new OvA($);if(w?.mode==="bigint")return new MvA($);return new xvA($)}var MvA,bvA,OvA,fvA,xvA,RvA;var fg0=c(()=>{Z6();LW();tk();MvA=class MvA extends YX{static[lA]="SQLiteBigIntBuilder";constructor(A){super(A,"bigint","SQLiteBigInt")}build(A){return new bvA(A,this.config)}};bvA=class bvA extends H9{static[lA]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(A){if(typeof Buffer<"u"&&Buffer.from){let Q=Buffer.isBuffer(A)?A:A instanceof ArrayBuffer?Buffer.from(A):A.buffer?Buffer.from(A.buffer,A.byteOffset,A.byteLength):Buffer.from(A);return BigInt(Q.toString("utf8"))}return BigInt(Fg0.decode(A))}mapToDriverValue(A){return Buffer.from(A.toString())}};OvA=class OvA extends YX{static[lA]="SQLiteBlobJsonBuilder";constructor(A){super(A,"json","SQLiteBlobJson")}build(A){return new fvA(A,this.config)}};fvA=class fvA extends H9{static[lA]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(A){if(typeof Buffer<"u"&&Buffer.from){let Q=Buffer.isBuffer(A)?A:A instanceof ArrayBuffer?Buffer.from(A):A.buffer?Buffer.from(A.buffer,A.byteOffset,A.byteLength):Buffer.from(A);return JSON.parse(Q.toString("utf8"))}return JSON.parse(Fg0.decode(A))}mapToDriverValue(A){return Buffer.from(JSON.stringify(A))}};xvA=class xvA extends YX{static[lA]="SQLiteBlobBufferBuilder";constructor(A){super(A,"buffer","SQLiteBlobBuffer")}build(A){return new RvA(A,this.config)}};RvA=class RvA extends H9{static[lA]="SQLiteBlobBuffer";mapFromDriverValue(A){if(Buffer.isBuffer(A))return A;return Buffer.from(A)}getSQLType(){return"blob"}}});function QY0(A){return(Q,$)=>{let{name:w,config:B}=nV(Q,$);return new CvA(w,B,A)}}var CvA,hvA;var xg0=c(()=>{Z6();LW();tk();CvA=class CvA extends YX{static[lA]="SQLiteCustomColumnBuilder";constructor(A,Q,$){super(A,"custom","SQLiteCustomColumn");this.config.fieldConfig=Q,this.config.customTypeParams=$}build(A){return new hvA(A,this.config)}};hvA=class hvA extends H9{static[lA]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(A,Q){super(A,Q);this.sqlName=Q.customTypeParams.dataType(Q.fieldConfig),this.mapTo=Q.customTypeParams.toDriver,this.mapFrom=Q.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(A){return typeof this.mapFrom==="function"?this.mapFrom(A):A}mapToDriverValue(A){return typeof this.mapTo==="function"?this.mapTo(A):A}}});function ZX(A,Q){let{name:$,config:w}=nV(A,Q);if(w?.mode==="timestamp"||w?.mode==="timestamp_ms")return new yvA($,w.mode);if(w?.mode==="boolean")return new SvA($,w.mode);return new EvA($)}var $Y0,wY0,EvA,TvA,yvA,gvA,SvA,mvA;var Rg0=c(()=>{Z6();K4();LW();tk();$Y0=class $Y0 extends YX{static[lA]="SQLiteBaseIntegerBuilder";constructor(A,Q,$){super(A,Q,$);this.config.autoIncrement=!1}primaryKey(A){if(A?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};wY0=class wY0 extends H9{static[lA]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};EvA=class EvA extends $Y0{static[lA]="SQLiteIntegerBuilder";constructor(A){super(A,"number","SQLiteInteger")}build(A){return new TvA(A,this.config)}};TvA=class TvA extends wY0{static[lA]="SQLiteInteger"};yvA=class yvA extends $Y0{static[lA]="SQLiteTimestampBuilder";constructor(A,Q){super(A,"date","SQLiteTimestamp");this.config.mode=Q}defaultNow(){return this.default($A`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(A){return new gvA(A,this.config)}};gvA=class gvA extends wY0{static[lA]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(A){if(this.config.mode==="timestamp")return new Date(A*1000);return new Date(A)}mapToDriverValue(A){let Q=A.getTime();if(this.config.mode==="timestamp")return Math.floor(Q/1000);return Q}};SvA=class SvA extends $Y0{static[lA]="SQLiteBooleanBuilder";constructor(A,Q){super(A,"boolean","SQLiteBoolean");this.config.mode=Q}build(A){return new mvA(A,this.config)}};mvA=class mvA extends wY0{static[lA]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(A){return Number(A)===1}mapToDriverValue(A){return A?1:0}}});function nvA(A,Q){let{name:$,config:w}=nV(A,Q),B=w?.mode;return B==="number"?new pvA($):B==="bigint"?new dvA($):new uvA($)}var uvA,cvA,pvA,lvA,dvA,ivA;var vg0=c(()=>{Z6();LW();tk();uvA=class uvA extends YX{static[lA]="SQLiteNumericBuilder";constructor(A){super(A,"string","SQLiteNumeric")}build(A){return new cvA(A,this.config)}};cvA=class cvA extends H9{static[lA]="SQLiteNumeric";mapFromDriverValue(A){if(typeof A==="string")return A;return String(A)}getSQLType(){return"numeric"}};pvA=class pvA extends YX{static[lA]="SQLiteNumericNumberBuilder";constructor(A){super(A,"number","SQLiteNumericNumber")}build(A){return new lvA(A,this.config)}};lvA=class lvA extends H9{static[lA]="SQLiteNumericNumber";mapFromDriverValue(A){if(typeof A==="number")return A;return Number(A)}mapToDriverValue=String;getSQLType(){return"numeric"}};dvA=class dvA extends YX{static[lA]="SQLiteNumericBigIntBuilder";constructor(A){super(A,"bigint","SQLiteNumericBigInt")}build(A){return new ivA(A,this.config)}};ivA=class ivA extends H9{static[lA]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function svA(A){return new rvA(A??"")}var rvA,ovA;var Cg0=c(()=>{Z6();tk();rvA=class rvA extends YX{static[lA]="SQLiteRealBuilder";constructor(A){super(A,"number","SQLiteReal")}build(A){return new ovA(A,this.config)}};ovA=class ovA extends H9{static[lA]="SQLiteReal";getSQLType(){return"real"}}});function x6(A,Q={}){let{name:$,config:w}=nV(A,Q);if(w.mode==="json")return new evA($);return new avA($,w)}var avA,tvA,evA,ACA;var hg0=c(()=>{Z6();LW();tk();avA=class avA extends YX{static[lA]="SQLiteTextBuilder";constructor(A,Q){super(A,"string","SQLiteText");this.config.enumValues=Q.enum,this.config.length=Q.length}build(A){return new tvA(A,this.config)}};tvA=class tvA extends H9{static[lA]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(A,Q){super(A,Q)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};evA=class evA extends YX{static[lA]="SQLiteTextJsonBuilder";constructor(A){super(A,"json","SQLiteTextJson")}build(A){return new ACA(A,this.config)}};ACA=class ACA extends H9{static[lA]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(A){return JSON.parse(A)}mapToDriverValue(A){return JSON.stringify(A)}}});function QCA(){return{blob:vvA,customType:QY0,integer:ZX,numeric:nvA,real:svA,text:x6}}var $CA=c(()=>{fg0();xg0();Rg0();vg0();Cg0();hg0()});function D5Q(A,Q,$,w,B=A){let X=new F7(A,w,B),Y=typeof Q==="function"?Q(QCA()):Q,Z=Object.fromEntries(Object.entries(Y).map(([K,U])=>{let G=U;G.setName(K);let D=G.build(X);return X[Eg0].push(...G.buildForeignKeys(D,X)),[K,D]})),W=Object.assign(X,Z);if(W[Z2.Symbol.Columns]=Z,W[Z2.Symbol.ExtraConfigColumns]=Z,$)W[F7.Symbol.ExtraConfigBuilder]=$;return W}var Eg0,F7,ZD=(A,Q,$)=>{return D5Q(A,Q,$)};var ek=c(()=>{Z6();rY();$CA();Eg0=Symbol.for("drizzle:SQLiteInlineForeignKeys");F7=class F7 extends Z2{static[lA]="SQLiteTable";static Symbol=Object.assign({},Z2.Symbol,{InlineForeignKeys:Eg0});[Z2.Symbol.Columns];[Eg0]=[];[Z2.Symbol.ExtraConfigBuilder]=void 0}});function XCA(A,Q){return new wCA(A,Q)}var wCA,BCA;var YCA=c(()=>{Z6();wCA=class wCA{constructor(A,Q){this.name=A,this.value=Q}static[lA]="SQLiteCheckBuilder";brand;build(A){return new BCA(A,this)}};BCA=class BCA{constructor(A,Q){this.table=A,this.name=Q.name,this.value=Q.value}static[lA]="SQLiteCheck";name;value}});function tK(A){return new ZCA(A,!1)}var ZCA,HCA,WCA;var KCA=c(()=>{Z6();ZCA=class ZCA{constructor(A,Q){this.name=A,this.unique=Q}static[lA]="SQLiteIndexBuilderOn";on(...A){return new HCA(this.name,A,this.unique)}};HCA=class HCA{static[lA]="SQLiteIndexBuilder";config;constructor(A,Q,$){this.config={name:A,columns:Q,unique:$,where:void 0}}where(A){return this.config.where=A,this}build(A){return new WCA(this.config,A)}};WCA=class WCA{static[lA]="SQLiteIndex";config;constructor(A,Q){this.config={...A,table:Q}}}});function Cg(...A){if(A[0].columns)return new Tg0(A[0].columns,A[0].name);return new Tg0(A)}var Tg0,UCA;var GCA=c(()=>{Z6();ek();Tg0=class Tg0{static[lA]="SQLitePrimaryKeyBuilder";columns;name;constructor(A,Q){this.columns=A,this.name=Q}build(A){return new UCA(A,this.columns,this.name)}};UCA=class UCA{constructor(A,Q,$){this.table=A,this.columns=Q,this.name=$}static[lA]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[F7.Symbol.Name]}_${this.columns.map((A)=>A.name).join("_")}_pk`}}});function Vz(A){if(q1(A,F7))return[`${A[Z2.Symbol.BaseName]}`];if(q1(A,yB))return A._.usedTables??[];if(q1(A,d2))return A.usedTables??[];return[]}var hg=c(()=>{Z6();K4();zz();rY();ek()});var BY0;var DCA=c(()=>{Z6();VL();vg();ek();rY();LW();hg();BY0=class BY0 extends zH{constructor(A,Q,$,w){super();this.table=A,this.session=Q,this.dialect=$,this.config={table:A,withList:w}}static[lA]="SQLiteDelete";config;where(A){return this.config.where=A,this}orderBy(...A){if(typeof A[0]==="function"){let Q=A[0](new Proxy(this.config.table[Z2.Symbol.Columns],new J7({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(Q)?Q:[Q];this.config.orderBy=$}else{let Q=A;this.config.orderBy=Q}return this}limit(A){return this.config.limit=A,this}returning(A=this.table[F7.Symbol.Columns]){return this.config.returning=YD(A),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:A,...Q}=this.dialect.sqlToQuery(this.getSQL());return Q}_prepare(A=!0){return this.session[A?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:Vz(this.config.table)})}prepare(){return this._prepare(!1)}run=(A)=>{return this._prepare().run(A)};all=(A)=>{return this._prepare().all(A)};get=(A)=>{return this._prepare().get(A)};values=(A)=>{return this._prepare().values(A)};async execute(A){return this._prepare().execute(A)}$dynamic(){return this}}});function q5Q(A){return(A.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(($)=>$.toLowerCase()).join("_")}function z5Q(A){return(A.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce(($,w,B)=>{let X=B===0?w.toLowerCase():`${w[0].toUpperCase()}${w.slice(1)}`;return $+X},"")}function V5Q(A){return A}var yg0;var qCA=c(()=>{Z6();rY();yg0=class yg0{static[lA]="CasingCache";cache={};cachedTables={};convert;constructor(A){this.convert=A==="snake_case"?q5Q:A==="camelCase"?z5Q:V5Q}getColumnCasing(A){if(!A.keyAsName)return A.name;let Q=A.table[Z2.Symbol.Schema]??"public",$=A.table[Z2.Symbol.OriginalName],w=`${Q}.${$}.${A.name}`;if(!this.cache[w])this.cacheTable(A.table);return this.cache[w]}cacheTable(A){let Q=A[Z2.Symbol.Schema]??"public",$=A[Z2.Symbol.OriginalName],w=`${Q}.${$}`;if(!this.cachedTables[w]){for(let B of Object.values(A[Z2.Symbol.Columns])){let X=`${w}.${B.name}`;this.cache[X]=this.convert(B.name)}this.cachedTables[w]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Eg,JL,gg0;var XY0=c(()=>{Z6();Eg=class Eg extends Error{static[lA]="DrizzleError";constructor({message:A,cause:Q}){super(A);this.name="DrizzleError",this.cause=Q}};JL=class JL extends Error{constructor(A,Q,$){super(`Failed query: ${A}
147
+ `),D=Y??A.headScripts??[],q=rwQ(A.content,Q.content),J=owQ(A.sections,Q.sections);return{layouts:W,routes:swQ(A.routes,Q.routes),...Z?{plugin:Z}:{},entityDisplay:K,...q?{content:q}:{},...J?{sections:J}:{},...G?{themeOverride:G}:{},...D.length>0?{headScripts:D}:{},...U&&Object.keys(U).length>0?{staticAssets:U}:{}}}var dX0,awQ,twQ,ewQ,Xg0;var jRA=c(()=>{C0();dX0=H.string(),awQ=H.looseObject({id:H.string().min(1)}),twQ=H.looseObject({label:H.string().min(1)}),ewQ=H.looseObject({layouts:H.record(H.string(),H.unknown()),plugin:H.custom((A)=>typeof A==="function").optional(),routes:H.array(awQ),entityDisplay:H.record(H.string(),twQ),content:H.unknown().optional(),themeOverride:H.string().optional(),headScripts:H.array(H.string()).optional(),staticAssets:H.record(H.string(),H.string()).optional()}),Xg0=H.custom((A)=>ewQ.safeParse(A).success)});var XX=c(()=>{UT0();uMA();zRA();FRA();_RA();jRA()});var MRA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as bRA}from"crypto";function Q5Q(A){if(A<0)throw RangeError("Wrong ID size");try{if(!nk||nk.length<A)nk=Buffer.allocUnsafe(A*A5Q),bRA.getRandomValues(nk),jg=0;else if(jg+A>nk.length)bRA.getRandomValues(nk),jg=0}catch(Q){throw nk=void 0,Q}jg+=A}function Yg0(A=21){Q5Q(A|=0);let Q="";for(let $=jg-A;$<jg;$++)Q+=MRA[nk[$]&63];return Q}var A5Q=128,nk,jg;var ORA=()=>{};function nY(A=12){return Yg0(A)}function Mg(A){return`${A}_${Yg0(12)}`}var iV=c(()=>{ORA()});var Zg0,$5Q,hx,LB8;var Fs=c(()=>{C0();Zg0=H.enum(["file_operations","content_operations","data_processing","batch_processing"]),$5Q=H.object({pluginId:H.string().optional(),progressToken:H.union([H.string(),H.number()]).optional(),operationType:Zg0,operationTarget:H.string().optional(),interfaceType:H.string().optional(),conversationId:H.string().optional(),channelId:H.string().optional(),silent:H.boolean().optional()}),hx=H.object({pluginId:H.string().optional(),progressToken:H.union([H.string(),H.number()]).optional(),operationType:Zg0,operationTarget:H.string().optional(),interfaceType:H.string().optional(),conversationId:H.string().optional(),channelId:H.string().optional(),silent:H.boolean().optional(),rootJobId:H.string()}),LB8=H.enum(["none","skip","replace","coalesce"])});var Hg0,fRA,_$,w5Q,B5Q,Wg0,bg;var rk=c(()=>{C0();Fs();Hg0=H.enum(["pending","processing","completed","failed"]),fRA=H.enum(["completed","failed"]),_$={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},w5Q=H.object({id:H.string(),type:H.string(),status:Hg0,data:H.unknown(),result:H.unknown().optional(),lastError:H.string().optional().nullable(),attempts:H.number(),maxRetries:H.number(),priority:H.number(),createdAt:H.date(),updatedAt:H.date(),processedAt:H.date().optional().nullable(),completedAt:H.date().optional().nullable(),failedAt:H.date().optional().nullable()}),B5Q=H.object({jobId:H.string(),type:H.string(),status:fRA,result:H.unknown().optional(),error:H.string().optional()}),Wg0=H.object({success:H.literal(!1),error:H.string().optional()}),bg=H.object({id:H.string(),type:H.enum(["job","batch"]),status:Hg0,message:H.string().optional(),progress:H.object({current:H.number(),total:H.number(),percentage:H.number()}).optional(),aggregationKey:H.string().optional(),batchDetails:H.object({totalOperations:H.number(),completedOperations:H.number(),failedOperations:H.number(),currentOperation:H.string().optional(),errors:H.array(H.string()).optional()}).optional(),jobDetails:H.object({jobType:H.string(),priority:H.number(),retryCount:H.number()}).optional(),metadata:hx})});function q1(A,Q){if(!A||typeof A!=="object")return!1;if(A instanceof Q)return!0;if(!Object.prototype.hasOwnProperty.call(Q,lA))throw Error(`Class "${Q.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let $=Object.getPrototypeOf(A).constructor;if($)while($){if(lA in $&&$[lA]===Q[lA])return!0;$=Object.getPrototypeOf($)}return!1}var lA;var Z6=c(()=>{lA=Symbol.for("drizzle:entityKind")});var Aw;var qz=c(()=>{Z6();Aw=class Aw{constructor(A,Q){this.table=A,this.config=Q,this.name=Q.name,this.keyAsName=Q.keyAsName,this.notNull=Q.notNull,this.default=Q.default,this.defaultFn=Q.defaultFn,this.onUpdateFn=Q.onUpdateFn,this.hasDefault=Q.hasDefault,this.primary=Q.primaryKey,this.isUnique=Q.isUnique,this.uniqueName=Q.uniqueName,this.uniqueType=Q.uniqueType,this.dataType=Q.dataType,this.columnType=Q.columnType,this.generated=Q.generated,this.generatedIdentity=Q.generatedIdentity}static[lA]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(A){return A}mapToDriverValue(A){return A}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var Kg0;var Ug0=c(()=>{Z6();Kg0=class Kg0{static[lA]="ColumnBuilder";config;constructor(A,Q,$){this.config={name:A,keyAsName:A==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:Q,columnType:$,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(A){return this.config.default=A,this.config.hasDefault=!0,this}$defaultFn(A){return this.config.defaultFn=A,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(A){return this.config.onUpdateFn=A,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(A){if(this.config.name!=="")return;this.config.name=A}}});var oK;var Is=c(()=>{oK=Symbol.for("drizzle:Name")});function xRA(A,...Q){return A(...Q)}var RRA=()=>{};function vRA(A,Q){return`${A[oK]}_${Q.join("_")}_unique`}var CRA=c(()=>{Is()});var Ls,X5Q;var hRA=c(()=>{qz();Z6();CRA();Ls=class Ls extends Aw{constructor(A,Q){if(!Q.uniqueName)Q.uniqueName=vRA(A,[Q.name]);super(A,Q);this.table=A}static[lA]="PgColumn"};X5Q=class X5Q extends Ls{static[lA]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(A){return this.indexConfig.opClass=A,this}}});function TRA(A){return!!A&&typeof A==="function"&&ERA in A&&A[ERA]===!0}var Y5Q,ERA,Z5Q;var yRA=c(()=>{Z6();hRA();Y5Q=class Y5Q extends Ls{static[lA]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(A,Q){super(A,Q);this.enum=Q.enum}getSQLType(){return this.enum.enumName}};ERA=Symbol.for("drizzle:isPgEnum");Z5Q=class Z5Q extends Ls{static[lA]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(A,Q){super(A,Q);this.enum=Q.enum}getSQLType(){return this.enum.enumName}}});var yB,Ns;var zz=c(()=>{Z6();yB=class yB{static[lA]="Subquery";constructor(A,Q,$,w=!1,B=[]){this._={brand:"Subquery",sql:A,selectedFields:Q,alias:$,isWith:w,usedTables:B}}};Ns=class Ns extends yB{static[lA]="WithSubquery"}});var gRA="0.45.2";var SRA=()=>{};var Gg0,Dg0,mRA;var uRA=c(()=>{RRA();SRA();mRA={startActiveSpan(A,Q){if(!Gg0)return Q();if(!Dg0)Dg0=Gg0.trace.getTracer("drizzle-orm",gRA);return xRA(($,w)=>w.startActiveSpan(A,(B)=>{try{return Q(B)}catch(X){throw B.setStatus({code:$.SpanStatusCode.ERROR,message:X instanceof Error?X.message:"Unknown error"}),X}finally{B.end()}}),Gg0,Dg0)}}});var gB;var zL=c(()=>{gB=Symbol.for("drizzle:ViewBaseConfig")});function ok(A){return A[oK]}function Ex(A){return`${A[iX0]??"public"}.${A[oK]}`}var iX0,nX0,cRA,qg0,zg0,_s,pRA,H5Q,Z2;var rY=c(()=>{Z6();Is();iX0=Symbol.for("drizzle:Schema"),nX0=Symbol.for("drizzle:Columns"),cRA=Symbol.for("drizzle:ExtraConfigColumns"),qg0=Symbol.for("drizzle:OriginalName"),zg0=Symbol.for("drizzle:BaseName"),_s=Symbol.for("drizzle:IsAlias"),pRA=Symbol.for("drizzle:ExtraConfigBuilder"),H5Q=Symbol.for("drizzle:IsDrizzleTable");Z2=class Z2{static[lA]="Table";static Symbol={Name:oK,Schema:iX0,OriginalName:qg0,Columns:nX0,ExtraConfigColumns:cRA,BaseName:zg0,IsAlias:_s,ExtraConfigBuilder:pRA};[oK];[qg0];[iX0];[nX0];[cRA];[zg0];[_s]=!1;[H5Q]=!0;[pRA]=void 0;constructor(A,Q,$){this[oK]=this[qg0]=A,this[iX0]=Q,this[zg0]=$}}});function Vg0(A){return A!==null&&A!==void 0&&typeof A.getSQL==="function"}function W5Q(A){let Q={sql:"",params:[]};for(let $ of A)if(Q.sql+=$.sql,Q.params.push(...$.params),$.typings?.length){if(!Q.typings)Q.typings=[];Q.typings.push(...$.typings)}return Q}function lRA(A){return typeof A==="object"&&A!==null&&"mapToDriverValue"in A&&typeof A.mapToDriverValue==="function"}function $A(A,...Q){let $=[];if(Q.length>0||A.length>0&&A[0]!=="")$.push(new W4(A[0]));for(let[w,B]of Q.entries())$.push(B,new W4(A[w+1]));return new d2($)}function Ps(A,Q){return A.map(($)=>{if(q1($,sk)){if(!($.name in Q))throw Error(`No value for placeholder "${$.name}" was provided`);return Q[$.name]}if(q1($,sK)&&q1($.value,sk)){if(!($.value.name in Q))throw Error(`No value for placeholder "${$.value.name}" was provided`);return $.encoder.mapToDriverValue(Q[$.value.name])}return $})}var W4,d2,rX0,dRA,iRA,X98,sK,sk,K5Q,XD;var K4=c(()=>{Z6();yRA();zz();uRA();zL();qz();rY();W4=class W4{static[lA]="StringChunk";value;constructor(A){this.value=Array.isArray(A)?A:[A]}getSQL(){return new d2([this])}};d2=class d2{constructor(A){this.queryChunks=A;for(let Q of A)if(q1(Q,Z2)){let $=Q[Z2.Symbol.Schema];this.usedTables.push($===void 0?Q[Z2.Symbol.Name]:$+"."+Q[Z2.Symbol.Name])}}static[lA]="SQL";decoder=dRA;shouldInlineParams=!1;usedTables=[];append(A){return this.queryChunks.push(...A.queryChunks),this}toQuery(A){return mRA.startActiveSpan("drizzle.buildSQL",(Q)=>{let $=this.buildQueryFromSourceParams(this.queryChunks,A);return Q?.setAttributes({"drizzle.query.text":$.sql,"drizzle.query.params":JSON.stringify($.params)}),$})}buildQueryFromSourceParams(A,Q){let $=Object.assign({},Q,{inlineParams:Q.inlineParams||this.shouldInlineParams,paramStartIndex:Q.paramStartIndex||{value:0}}),{casing:w,escapeName:B,escapeParam:X,prepareTyping:Y,inlineParams:Z,paramStartIndex:W}=$;return W5Q(A.map((K)=>{if(q1(K,W4))return{sql:K.value.join(""),params:[]};if(q1(K,rX0))return{sql:B(K.value),params:[]};if(K===void 0)return{sql:"",params:[]};if(Array.isArray(K)){let U=[new W4("(")];for(let[G,D]of K.entries())if(U.push(D),G<K.length-1)U.push(new W4(", "));return U.push(new W4(")")),this.buildQueryFromSourceParams(U,$)}if(q1(K,d2))return this.buildQueryFromSourceParams(K.queryChunks,{...$,inlineParams:Z||K.shouldInlineParams});if(q1(K,Z2)){let U=K[Z2.Symbol.Schema],G=K[Z2.Symbol.Name];return{sql:U===void 0||K[_s]?B(G):B(U)+"."+B(G),params:[]}}if(q1(K,Aw)){let U=w.getColumnCasing(K);if(Q.invokeSource==="indexes")return{sql:B(U),params:[]};let G=K.table[Z2.Symbol.Schema];return{sql:K.table[_s]||G===void 0?B(K.table[Z2.Symbol.Name])+"."+B(U):B(G)+"."+B(K.table[Z2.Symbol.Name])+"."+B(U),params:[]}}if(q1(K,XD)){let U=K[gB].schema,G=K[gB].name;return{sql:U===void 0||K[gB].isAlias?B(G):B(U)+"."+B(G),params:[]}}if(q1(K,sK)){if(q1(K.value,sk))return{sql:X(W.value++,K),params:[K],typings:["none"]};let U=K.value===null?null:K.encoder.mapToDriverValue(K.value);if(q1(U,d2))return this.buildQueryFromSourceParams([U],$);if(Z)return{sql:this.mapInlineParam(U,$),params:[]};let G=["none"];if(Y)G=[Y(K.encoder)];return{sql:X(W.value++,U),params:[U],typings:G}}if(q1(K,sk))return{sql:X(W.value++,K),params:[K],typings:["none"]};if(q1(K,d2.Aliased)&&K.fieldAlias!==void 0)return{sql:B(K.fieldAlias),params:[]};if(q1(K,yB)){if(K._.isWith)return{sql:B(K._.alias),params:[]};return this.buildQueryFromSourceParams([new W4("("),K._.sql,new W4(") "),new rX0(K._.alias)],$)}if(TRA(K)){if(K.schema)return{sql:B(K.schema)+"."+B(K.enumName),params:[]};return{sql:B(K.enumName),params:[]}}if(Vg0(K)){if(K.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([K.getSQL()],$);return this.buildQueryFromSourceParams([new W4("("),K.getSQL(),new W4(")")],$)}if(Z)return{sql:this.mapInlineParam(K,$),params:[]};return{sql:X(W.value++,K),params:[K],typings:["none"]}}))}mapInlineParam(A,{escapeString:Q}){if(A===null)return"null";if(typeof A==="number"||typeof A==="boolean")return A.toString();if(typeof A==="string")return Q(A);if(typeof A==="object"){let $=A.toString();if($==="[object Object]")return Q(JSON.stringify(A));return Q($)}throw Error("Unexpected param value: "+A)}getSQL(){return this}as(A){if(A===void 0)return this;return new d2.Aliased(this,A)}mapWith(A){return this.decoder=typeof A==="function"?{mapFromDriverValue:A}:A,this}inlineParams(){return this.shouldInlineParams=!0,this}if(A){return A?this:void 0}};rX0=class rX0{constructor(A){this.value=A}static[lA]="Name";brand;getSQL(){return new d2([this])}};dRA={mapFromDriverValue:(A)=>A},iRA={mapToDriverValue:(A)=>A},X98={...dRA,...iRA};sK=class sK{constructor(A,Q=iRA){this.value=A,this.encoder=Q}static[lA]="Param";brand;getSQL(){return new d2([this])}};((A)=>{function Q(){return new d2([])}A.empty=Q;function $(W){return new d2(W)}A.fromList=$;function w(W){return new d2([new W4(W)])}A.raw=w;function B(W,K){let U=[];for(let[G,D]of W.entries()){if(G>0&&K!==void 0)U.push(K);U.push(D)}return new d2(U)}A.join=B;function X(W){return new rX0(W)}A.identifier=X;function Y(W){return new sk(W)}A.placeholder=Y;function Z(W,K){return new sK(W,K)}A.param=Z})($A||($A={}));((A)=>{class Q{constructor($,w){this.sql=$,this.fieldAlias=w}static[lA]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new Q(this.sql,this.fieldAlias)}}A.Aliased=Q})(d2||(d2={}));sk=class sk{constructor(A){this.name=A}static[lA]="Placeholder";getSQL(){return new d2([this])}};K5Q=Symbol.for("drizzle:IsDrizzleView");XD=class XD{static[lA]="View";[gB];[K5Q]=!0;constructor({name:A,schema:Q,selectedFields:$,query:w}){this[gB]={name:A,originalName:A,schema:Q,selectedFields:$,query:w,isExisting:!w,isAlias:!1}}getSQL(){return new d2([this])}};Aw.prototype.getSQL=function(){return new d2([this])};Z2.prototype.getSQL=function(){return new d2([this])};yB.prototype.getSQL=function(){return new d2([this])}});function Jg0(A,Q,$){let w={},B=A.reduce((X,{path:Y,field:Z},W)=>{let K;if(q1(Z,Aw))K=Z;else if(q1(Z,d2))K=Z.decoder;else if(q1(Z,yB))K=Z._.sql.decoder;else K=Z.sql.decoder;let U=X;for(let[G,D]of Y.entries())if(G<Y.length-1){if(!(D in U))U[D]={};U=U[D]}else{let q=Q[W],J=U[D]=q===null?null:K.mapFromDriverValue(q);if($&&q1(Z,Aw)&&Y.length===2){let F=Y[0];if(!(F in w))w[F]=J===null?ok(Z.table):!1;else if(typeof w[F]==="string"&&w[F]!==ok(Z.table))w[F]=!1}}return X},{});if($&&Object.keys(w).length>0){for(let[X,Y]of Object.entries(w))if(typeof Y==="string"&&!$[Y])B[X]=null}return B}function YD(A,Q){return Object.entries(A).reduce(($,[w,B])=>{if(typeof w!=="string")return $;let X=Q?[...Q,w]:[w];if(q1(B,Aw)||q1(B,d2)||q1(B,d2.Aliased)||q1(B,yB))$.push({path:X,field:B});else if(q1(B,Z2))$.push(...YD(B[Z2.Symbol.Columns],X));else $.push(...YD(B,X));return $},[])}function ks(A,Q){let $=Object.keys(A),w=Object.keys(Q);if($.length!==w.length)return!1;for(let[B,X]of $.entries())if(X!==w[B])return!1;return!0}function oX0(A,Q){let $=Object.entries(Q).filter(([,w])=>w!==void 0).map(([w,B])=>{if(q1(B,d2)||q1(B,Aw))return[w,B];else return[w,new sK(B,A[Z2.Symbol.Columns][w])]});if($.length===0)throw Error("No values to set");return Object.fromEntries($)}function nRA(A,Q){for(let $ of Q)for(let w of Object.getOwnPropertyNames($.prototype)){if(w==="constructor")continue;Object.defineProperty(A.prototype,w,Object.getOwnPropertyDescriptor($.prototype,w)||Object.create(null))}}function rRA(A){return A[Z2.Symbol.Columns]}function js(A){return q1(A,yB)?A._.alias:q1(A,XD)?A[gB].name:q1(A,d2)?void 0:A[Z2.Symbol.IsAlias]?A[Z2.Symbol.Name]:A[Z2.Symbol.BaseName]}function nV(A,Q){return{name:typeof A==="string"&&A.length>0?A:"",config:typeof A==="object"?A:Q}}function oRA(A){if(typeof A!=="object"||A===null)return!1;if(A.constructor.name!=="Object")return!1;if("logger"in A){let Q=typeof A.logger;if(Q!=="boolean"&&(Q!=="object"||typeof A.logger.logQuery!=="function")&&Q!=="undefined")return!1;return!0}if("schema"in A){let Q=typeof A.schema;if(Q!=="object"&&Q!=="undefined")return!1;return!0}if("casing"in A){let Q=typeof A.casing;if(Q!=="string"&&Q!=="undefined")return!1;return!0}if("mode"in A){if(A.mode!=="default"||A.mode!=="planetscale"||A.mode!==void 0)return!1;return!0}if("connection"in A){let Q=typeof A.connection;if(Q!=="string"&&Q!=="object"&&Q!=="undefined")return!1;return!0}if("client"in A){let Q=typeof A.client;if(Q!=="object"&&Q!=="function"&&Q!=="undefined")return!1;return!0}if(Object.keys(A).length===0)return!0;return!1}var Fg0;var LW=c(()=>{qz();Z6();K4();zz();rY();zL();Fg0=typeof TextDecoder>"u"?null:new TextDecoder});var sRA,Ig0,Lg0;var sX0=c(()=>{Z6();sRA=class sRA{static[lA]="ConsoleLogWriter";write(A){console.log(A)}};Ig0=class Ig0{static[lA]="DefaultLogger";writer;constructor(A){this.writer=A?.writer??new sRA}logQuery(A,Q){let $=Q.map((B)=>{try{return JSON.stringify(B)}catch{return String(B)}}),w=$.length?` -- params: [${$.join(", ")}]`:"";this.writer.write(`Query: ${A}${w}`)}};Lg0=class Lg0{static[lA]="NoopLogger";logQuery(){}}});var aRA,tRA,Ng0;var eRA=c(()=>{Z6();rY();aRA=Symbol.for("drizzle:PgInlineForeignKeys"),tRA=Symbol.for("drizzle:EnableRLS");Ng0=class Ng0 extends Z2{static[lA]="PgTable";static Symbol=Object.assign({},Z2.Symbol,{InlineForeignKeys:aRA,EnableRLS:tRA});[aRA]=[];[tRA]=!1;[Z2.Symbol.ExtraConfigBuilder]=void 0;[Z2.Symbol.ExtraConfigColumns]={}}});var _g0,AvA;var QvA=c(()=>{Z6();eRA();_g0=class _g0{static[lA]="PgPrimaryKeyBuilder";columns;name;constructor(A,Q){this.columns=A,this.name=Q}build(A){return new AvA(A,this.columns,this.name)}};AvA=class AvA{constructor(A,Q,$){this.table=A,this.columns=Q,this.name=$}static[lA]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Ng0.Symbol.Name]}_${this.columns.map((A)=>A.name).join("_")}_pk`}}});function NW(A,Q){if(lRA(Q)&&!Vg0(A)&&!q1(A,sK)&&!q1(A,sk)&&!q1(A,Aw)&&!q1(A,Z2)&&!q1(A,XD))return new sK(A,Q);return A}function Qw(...A){let Q=A.filter(($)=>$!==void 0);if(Q.length===0)return;if(Q.length===1)return new d2(Q);return new d2([new W4("("),$A.join(Q,new W4(" and ")),new W4(")")])}function Og(...A){let Q=A.filter(($)=>$!==void 0);if(Q.length===0)return;if(Q.length===1)return new d2(Q);return new d2([new W4("("),$A.join(Q,new W4(" or ")),new W4(")")])}function wvA(A){return $A`not ${A}`}function aK(A,Q){if(Array.isArray(Q)){if(Q.length===0)return $A`false`;return $A`${A} in ${Q.map(($)=>NW($,A))}`}return $A`${A} in ${NW(Q,A)}`}function YvA(A,Q){if(Array.isArray(Q)){if(Q.length===0)return $A`true`;return $A`${A} not in ${Q.map(($)=>NW($,A))}`}return $A`${A} not in ${NW(Q,A)}`}function ZvA(A){return $A`${A} is null`}function xg(A){return $A`${A} is not null`}function HvA(A){return $A`exists ${A}`}function WvA(A){return $A`not exists ${A}`}function KvA(A,Q,$){return $A`${A} between ${NW(Q,A)} and ${NW($,A)}`}function UvA(A,Q,$){return $A`${A} not between ${NW(Q,A)} and ${NW($,A)}`}function GvA(A,Q){return $A`${A} like ${Q}`}function DvA(A,Q){return $A`${A} not like ${Q}`}function qvA(A,Q){return $A`${A} ilike ${Q}`}function zvA(A,Q){return $A`${A} not ilike ${Q}`}var NQ=(A,Q)=>{return $A`${A} = ${NW(Q,A)}`},$vA=(A,Q)=>{return $A`${A} <> ${NW(Q,A)}`},aX0=(A,Q)=>{return $A`${A} > ${NW(Q,A)}`},BvA=(A,Q)=>{return $A`${A} >= ${NW(Q,A)}`},XvA=(A,Q)=>{return $A`${A} < ${NW(Q,A)}`},fg=(A,Q)=>{return $A`${A} <= ${NW(Q,A)}`};var VvA=c(()=>{qz();Z6();rY();K4()});function DH(A){return $A`${A} asc`}function qH(A){return $A`${A} desc`}var JvA=c(()=>{K4()});var Pg0=c(()=>{VvA();JvA()});function IvA(){return{and:Qw,between:KvA,eq:NQ,exists:HvA,gt:aX0,gte:BvA,ilike:qvA,inArray:aK,isNull:ZvA,isNotNull:xg,like:GvA,lt:XvA,lte:fg,ne:$vA,not:wvA,notBetween:UvA,notExists:WvA,notLike:DvA,notIlike:zvA,notInArray:YvA,or:Og,sql:$A}}function LvA(){return{sql:$A,asc:DH,desc:qH}}function NvA(A,Q){if(Object.keys(A).length===1&&"default"in A&&!q1(A.default,Z2))A=A.default;let $={},w={},B={};for(let[X,Y]of Object.entries(A))if(q1(Y,Z2)){let Z=Ex(Y),W=w[Z];$[Z]=X,B[X]={tsName:X,dbName:Y[Z2.Symbol.Name],schema:Y[Z2.Symbol.Schema],columns:Y[Z2.Symbol.Columns],relations:W?.relations??{},primaryKey:W?.primaryKey??[]};for(let U of Object.values(Y[Z2.Symbol.Columns]))if(U.primary)B[X].primaryKey.push(U);let K=Y[Z2.Symbol.ExtraConfigBuilder]?.(Y[Z2.Symbol.ExtraConfigColumns]);if(K){for(let U of Object.values(K))if(q1(U,_g0))B[X].primaryKey.push(...U.columns)}}else if(q1(Y,FvA)){let Z=Ex(Y.table),W=$[Z],K=Y.config(Q(Y.table)),U;for(let[G,D]of Object.entries(K))if(W){let q=B[W];if(q.relations[G]=D,U)q.primaryKey.push(...U)}else{if(!(Z in w))w[Z]={relations:{},primaryKey:U};w[Z].relations[G]=D}}return{tables:B,tableNamesMap:$}}function U5Q(A){return function($,w){return new ak(A,$,w,w?.fields.reduce((B,X)=>B&&X.notNull,!0)??!1)}}function G5Q(A){return function($,w){return new Ms(A,$,w)}}function _vA(A,Q,$){if(q1($,ak)&&$.config)return{fields:$.config.fields,references:$.config.references};let w=Q[Ex($.referencedTable)];if(!w)throw Error(`Table "${$.referencedTable[Z2.Symbol.Name]}" not found in schema`);let B=A[w];if(!B)throw Error(`Table "${w}" not found in schema`);let X=$.sourceTable,Y=Q[Ex(X)];if(!Y)throw Error(`Table "${X[Z2.Symbol.Name]}" not found in schema`);let Z=[];for(let W of Object.values(B.relations))if($.relationName&&$!==W&&W.relationName===$.relationName||!$.relationName&&W.referencedTable===$.sourceTable)Z.push(W);if(Z.length>1)throw $.relationName?Error(`There are multiple relations with name "${$.relationName}" in table "${w}"`):Error(`There are multiple relations between "${w}" and "${$.sourceTable[Z2.Symbol.Name]}". Please specify relation name`);if(Z[0]&&q1(Z[0],ak)&&Z[0].config)return{fields:Z[0].config.references,references:Z[0].config.fields};throw Error(`There is not enough information to infer relation "${Y}.${$.fieldName}"`)}function PvA(A){return{one:U5Q(A),many:G5Q(A)}}function tX0(A,Q,$,w,B=(X)=>X){let X={};for(let[Y,Z]of w.entries())if(Z.isJson){let W=Q.relations[Z.tsKey],K=$[Y],U=typeof K==="string"?JSON.parse(K):K;X[Z.tsKey]=q1(W,ak)?U&&tX0(A,A[Z.relationTableTsKey],U,Z.selection,B):U.map((G)=>tX0(A,A[Z.relationTableTsKey],G,Z.selection,B))}else{let W=B($[Y]),K=Z.field,U;if(q1(K,Aw))U=K;else if(q1(K,d2))U=K.decoder;else U=K.sql.decoder;X[Z.tsKey]=W===null?null:U.mapFromDriverValue(W)}return X}var kg0,FvA,ak,Ms;var bs=c(()=>{rY();qz();Z6();QvA();Pg0();K4();kg0=class kg0{constructor(A,Q,$){this.sourceTable=A,this.referencedTable=Q,this.relationName=$,this.referencedTableName=Q[Z2.Symbol.Name]}static[lA]="Relation";referencedTableName;fieldName};FvA=class FvA{constructor(A,Q){this.table=A,this.config=Q}static[lA]="Relations"};ak=class ak extends kg0{constructor(A,Q,$,w){super(A,Q,$?.relationName);this.config=$,this.isNullable=w}static[lA]="One";withFieldName(A){let Q=new ak(this.sourceTable,this.referencedTable,this.config,this.isNullable);return Q.fieldName=A,Q}};Ms=class Ms extends kg0{constructor(A,Q,$){super(A,Q,$?.relationName);this.config=$}static[lA]="Many";withFieldName(A){let Q=new Ms(this.sourceTable,this.referencedTable,this.config);return Q.fieldName=A,Q}}});function eX0(A,Q){return new Proxy(A,new Os(Q,!1))}function rV(A,Q){return new Proxy(A,new Rg(new Proxy(A.table,new Os(Q,!1))))}function jg0(A,Q){return new d2.Aliased(fs(A.sql,Q),A.fieldAlias)}function fs(A,Q){return $A.join(A.queryChunks.map(($)=>{if(q1($,Aw))return rV($,Q);if(q1($,d2))return fs($,Q);if(q1($,d2.Aliased))return jg0($,Q);return $}))}var Rg,Os;var AY0=c(()=>{qz();Z6();K4();rY();zL();Rg=class Rg{constructor(A){this.table=A}static[lA]="ColumnAliasProxyHandler";get(A,Q){if(Q==="table")return this.table;return A[Q]}};Os=class Os{constructor(A,Q){this.alias=A,this.replaceOriginalName=Q}static[lA]="TableAliasProxyHandler";get(A,Q){if(Q===Z2.Symbol.IsAlias)return!0;if(Q===Z2.Symbol.Name)return this.alias;if(this.replaceOriginalName&&Q===Z2.Symbol.OriginalName)return this.alias;if(Q===gB)return{...A[gB],name:this.alias,isAlias:!0};if(Q===Z2.Symbol.Columns){let w=A[Z2.Symbol.Columns];if(!w)return w;let B={};return Object.keys(w).map((X)=>{B[X]=new Proxy(w[X],new Rg(new Proxy(A,this)))}),B}let $=A[Q];if(q1($,Aw))return new Proxy($,new Rg(new Proxy(A,this)));return $}}});var J7;var vg=c(()=>{AY0();qz();Z6();K4();zz();zL();J7=class J7{static[lA]="SelectionProxyHandler";config;constructor(A){this.config={...A}}get(A,Q){if(Q==="_")return{...A._,selectedFields:new Proxy(A._.selectedFields,this)};if(Q===gB)return{...A[gB],selectedFields:new Proxy(A[gB].selectedFields,this)};if(typeof Q==="symbol")return A[Q];let w=(q1(A,yB)?A._.selectedFields:q1(A,XD)?A[gB].selectedFields:A)[Q];if(q1(w,d2.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!w.isSelectionField)return w.sql;let B=w.clone();return B.isSelectionField=!0,B}if(q1(w,d2)){if(this.config.sqlBehavior==="sql")return w;throw Error(`You tried to reference "${Q}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(q1(w,Aw)){if(this.config.alias)return new Proxy(w,new Rg(new Proxy(w.table,new Os(this.config.alias,this.config.replaceOriginalName??!1))));return w}if(typeof w!=="object"||w===null)return w;return new Proxy(w,new J7(this.config))}}});var zH;var VL=c(()=>{Z6();zH=class zH{static[lA]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(A){return this.then(void 0,A)}finally(A){return this.then((Q)=>{return A?.(),Q},(Q)=>{throw A?.(),Q})}then(A,Q){return this.execute().then(A,Q)}}});var Mg0,kvA;var bg0=c(()=>{Z6();Is();Mg0=class Mg0{static[lA]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(A,Q){if(this.reference=()=>{let{name:$,columns:w,foreignColumns:B}=A();return{name:$,columns:w,foreignTable:B[0].table,foreignColumns:B}},Q)this._onUpdate=Q.onUpdate,this._onDelete=Q.onDelete}onUpdate(A){return this._onUpdate=A,this}onDelete(A){return this._onDelete=A,this}build(A){return new kvA(A,this)}};kvA=class kvA{constructor(A,Q){this.table=A,this.reference=Q.reference,this.onUpdate=Q._onUpdate,this.onDelete=Q._onDelete}static[lA]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:A,columns:Q,foreignColumns:$}=this.reference(),w=Q.map((Y)=>Y.name),B=$.map((Y)=>Y.name),X=[this.table[oK],...w,$[0].table[oK],...B];return A??`${X.join("_")}_fk`}}});function jvA(A,Q){return`${A[oK]}_${Q.join("_")}_unique`}var Og0=c(()=>{Is()});var YX,H9;var tk=c(()=>{Ug0();qz();Z6();bg0();Og0();YX=class YX extends Kg0{static[lA]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(A,Q={}){return this.foreignKeyConfigs.push({ref:A,actions:Q}),this}unique(A){return this.config.isUnique=!0,this.config.uniqueName=A,this}generatedAlwaysAs(A,Q){return this.config.generated={as:A,type:"always",mode:Q?.mode??"virtual"},this}buildForeignKeys(A,Q){return this.foreignKeyConfigs.map(({ref:$,actions:w})=>{return((B,X)=>{let Y=new Mg0(()=>{let Z=B();return{columns:[A],foreignColumns:[Z]}});if(X.onUpdate)Y.onUpdate(X.onUpdate);if(X.onDelete)Y.onDelete(X.onDelete);return Y.build(Q)})($,w)})}};H9=class H9 extends Aw{constructor(A,Q){if(!Q.uniqueName)Q.uniqueName=jvA(A,[Q.name]);super(A,Q);this.table=A}static[lA]="SQLiteColumn"}});function vvA(A,Q){let{name:$,config:w}=nV(A,Q);if(w?.mode==="json")return new OvA($);if(w?.mode==="bigint")return new MvA($);return new xvA($)}var MvA,bvA,OvA,fvA,xvA,RvA;var fg0=c(()=>{Z6();LW();tk();MvA=class MvA extends YX{static[lA]="SQLiteBigIntBuilder";constructor(A){super(A,"bigint","SQLiteBigInt")}build(A){return new bvA(A,this.config)}};bvA=class bvA extends H9{static[lA]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(A){if(typeof Buffer<"u"&&Buffer.from){let Q=Buffer.isBuffer(A)?A:A instanceof ArrayBuffer?Buffer.from(A):A.buffer?Buffer.from(A.buffer,A.byteOffset,A.byteLength):Buffer.from(A);return BigInt(Q.toString("utf8"))}return BigInt(Fg0.decode(A))}mapToDriverValue(A){return Buffer.from(A.toString())}};OvA=class OvA extends YX{static[lA]="SQLiteBlobJsonBuilder";constructor(A){super(A,"json","SQLiteBlobJson")}build(A){return new fvA(A,this.config)}};fvA=class fvA extends H9{static[lA]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(A){if(typeof Buffer<"u"&&Buffer.from){let Q=Buffer.isBuffer(A)?A:A instanceof ArrayBuffer?Buffer.from(A):A.buffer?Buffer.from(A.buffer,A.byteOffset,A.byteLength):Buffer.from(A);return JSON.parse(Q.toString("utf8"))}return JSON.parse(Fg0.decode(A))}mapToDriverValue(A){return Buffer.from(JSON.stringify(A))}};xvA=class xvA extends YX{static[lA]="SQLiteBlobBufferBuilder";constructor(A){super(A,"buffer","SQLiteBlobBuffer")}build(A){return new RvA(A,this.config)}};RvA=class RvA extends H9{static[lA]="SQLiteBlobBuffer";mapFromDriverValue(A){if(Buffer.isBuffer(A))return A;return Buffer.from(A)}getSQLType(){return"blob"}}});function QY0(A){return(Q,$)=>{let{name:w,config:B}=nV(Q,$);return new CvA(w,B,A)}}var CvA,hvA;var xg0=c(()=>{Z6();LW();tk();CvA=class CvA extends YX{static[lA]="SQLiteCustomColumnBuilder";constructor(A,Q,$){super(A,"custom","SQLiteCustomColumn");this.config.fieldConfig=Q,this.config.customTypeParams=$}build(A){return new hvA(A,this.config)}};hvA=class hvA extends H9{static[lA]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(A,Q){super(A,Q);this.sqlName=Q.customTypeParams.dataType(Q.fieldConfig),this.mapTo=Q.customTypeParams.toDriver,this.mapFrom=Q.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(A){return typeof this.mapFrom==="function"?this.mapFrom(A):A}mapToDriverValue(A){return typeof this.mapTo==="function"?this.mapTo(A):A}}});function ZX(A,Q){let{name:$,config:w}=nV(A,Q);if(w?.mode==="timestamp"||w?.mode==="timestamp_ms")return new yvA($,w.mode);if(w?.mode==="boolean")return new SvA($,w.mode);return new EvA($)}var $Y0,wY0,EvA,TvA,yvA,gvA,SvA,mvA;var Rg0=c(()=>{Z6();K4();LW();tk();$Y0=class $Y0 extends YX{static[lA]="SQLiteBaseIntegerBuilder";constructor(A,Q,$){super(A,Q,$);this.config.autoIncrement=!1}primaryKey(A){if(A?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};wY0=class wY0 extends H9{static[lA]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};EvA=class EvA extends $Y0{static[lA]="SQLiteIntegerBuilder";constructor(A){super(A,"number","SQLiteInteger")}build(A){return new TvA(A,this.config)}};TvA=class TvA extends wY0{static[lA]="SQLiteInteger"};yvA=class yvA extends $Y0{static[lA]="SQLiteTimestampBuilder";constructor(A,Q){super(A,"date","SQLiteTimestamp");this.config.mode=Q}defaultNow(){return this.default($A`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(A){return new gvA(A,this.config)}};gvA=class gvA extends wY0{static[lA]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(A){if(this.config.mode==="timestamp")return new Date(A*1000);return new Date(A)}mapToDriverValue(A){let Q=A.getTime();if(this.config.mode==="timestamp")return Math.floor(Q/1000);return Q}};SvA=class SvA extends $Y0{static[lA]="SQLiteBooleanBuilder";constructor(A,Q){super(A,"boolean","SQLiteBoolean");this.config.mode=Q}build(A){return new mvA(A,this.config)}};mvA=class mvA extends wY0{static[lA]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(A){return Number(A)===1}mapToDriverValue(A){return A?1:0}}});function nvA(A,Q){let{name:$,config:w}=nV(A,Q),B=w?.mode;return B==="number"?new pvA($):B==="bigint"?new dvA($):new uvA($)}var uvA,cvA,pvA,lvA,dvA,ivA;var vg0=c(()=>{Z6();LW();tk();uvA=class uvA extends YX{static[lA]="SQLiteNumericBuilder";constructor(A){super(A,"string","SQLiteNumeric")}build(A){return new cvA(A,this.config)}};cvA=class cvA extends H9{static[lA]="SQLiteNumeric";mapFromDriverValue(A){if(typeof A==="string")return A;return String(A)}getSQLType(){return"numeric"}};pvA=class pvA extends YX{static[lA]="SQLiteNumericNumberBuilder";constructor(A){super(A,"number","SQLiteNumericNumber")}build(A){return new lvA(A,this.config)}};lvA=class lvA extends H9{static[lA]="SQLiteNumericNumber";mapFromDriverValue(A){if(typeof A==="number")return A;return Number(A)}mapToDriverValue=String;getSQLType(){return"numeric"}};dvA=class dvA extends YX{static[lA]="SQLiteNumericBigIntBuilder";constructor(A){super(A,"bigint","SQLiteNumericBigInt")}build(A){return new ivA(A,this.config)}};ivA=class ivA extends H9{static[lA]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function svA(A){return new rvA(A??"")}var rvA,ovA;var Cg0=c(()=>{Z6();tk();rvA=class rvA extends YX{static[lA]="SQLiteRealBuilder";constructor(A){super(A,"number","SQLiteReal")}build(A){return new ovA(A,this.config)}};ovA=class ovA extends H9{static[lA]="SQLiteReal";getSQLType(){return"real"}}});function x6(A,Q={}){let{name:$,config:w}=nV(A,Q);if(w.mode==="json")return new evA($);return new avA($,w)}var avA,tvA,evA,ACA;var hg0=c(()=>{Z6();LW();tk();avA=class avA extends YX{static[lA]="SQLiteTextBuilder";constructor(A,Q){super(A,"string","SQLiteText");this.config.enumValues=Q.enum,this.config.length=Q.length}build(A){return new tvA(A,this.config)}};tvA=class tvA extends H9{static[lA]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(A,Q){super(A,Q)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};evA=class evA extends YX{static[lA]="SQLiteTextJsonBuilder";constructor(A){super(A,"json","SQLiteTextJson")}build(A){return new ACA(A,this.config)}};ACA=class ACA extends H9{static[lA]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(A){return JSON.parse(A)}mapToDriverValue(A){return JSON.stringify(A)}}});function QCA(){return{blob:vvA,customType:QY0,integer:ZX,numeric:nvA,real:svA,text:x6}}var $CA=c(()=>{fg0();xg0();Rg0();vg0();Cg0();hg0()});function D5Q(A,Q,$,w,B=A){let X=new F7(A,w,B),Y=typeof Q==="function"?Q(QCA()):Q,Z=Object.fromEntries(Object.entries(Y).map(([K,U])=>{let G=U;G.setName(K);let D=G.build(X);return X[Eg0].push(...G.buildForeignKeys(D,X)),[K,D]})),W=Object.assign(X,Z);if(W[Z2.Symbol.Columns]=Z,W[Z2.Symbol.ExtraConfigColumns]=Z,$)W[F7.Symbol.ExtraConfigBuilder]=$;return W}var Eg0,F7,ZD=(A,Q,$)=>{return D5Q(A,Q,$)};var ek=c(()=>{Z6();rY();$CA();Eg0=Symbol.for("drizzle:SQLiteInlineForeignKeys");F7=class F7 extends Z2{static[lA]="SQLiteTable";static Symbol=Object.assign({},Z2.Symbol,{InlineForeignKeys:Eg0});[Z2.Symbol.Columns];[Eg0]=[];[Z2.Symbol.ExtraConfigBuilder]=void 0}});function XCA(A,Q){return new wCA(A,Q)}var wCA,BCA;var YCA=c(()=>{Z6();wCA=class wCA{constructor(A,Q){this.name=A,this.value=Q}static[lA]="SQLiteCheckBuilder";brand;build(A){return new BCA(A,this)}};BCA=class BCA{constructor(A,Q){this.table=A,this.name=Q.name,this.value=Q.value}static[lA]="SQLiteCheck";name;value}});function tK(A){return new ZCA(A,!1)}var ZCA,HCA,WCA;var KCA=c(()=>{Z6();ZCA=class ZCA{constructor(A,Q){this.name=A,this.unique=Q}static[lA]="SQLiteIndexBuilderOn";on(...A){return new HCA(this.name,A,this.unique)}};HCA=class HCA{static[lA]="SQLiteIndexBuilder";config;constructor(A,Q,$){this.config={name:A,columns:Q,unique:$,where:void 0}}where(A){return this.config.where=A,this}build(A){return new WCA(this.config,A)}};WCA=class WCA{static[lA]="SQLiteIndex";config;constructor(A,Q){this.config={...A,table:Q}}}});function Cg(...A){if(A[0].columns)return new Tg0(A[0].columns,A[0].name);return new Tg0(A)}var Tg0,UCA;var GCA=c(()=>{Z6();ek();Tg0=class Tg0{static[lA]="SQLitePrimaryKeyBuilder";columns;name;constructor(A,Q){this.columns=A,this.name=Q}build(A){return new UCA(A,this.columns,this.name)}};UCA=class UCA{constructor(A,Q,$){this.table=A,this.columns=Q,this.name=$}static[lA]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[F7.Symbol.Name]}_${this.columns.map((A)=>A.name).join("_")}_pk`}}});function Vz(A){if(q1(A,F7))return[`${A[Z2.Symbol.BaseName]}`];if(q1(A,yB))return A._.usedTables??[];if(q1(A,d2))return A.usedTables??[];return[]}var hg=c(()=>{Z6();K4();zz();rY();ek()});var BY0;var DCA=c(()=>{Z6();VL();vg();ek();rY();LW();hg();BY0=class BY0 extends zH{constructor(A,Q,$,w){super();this.table=A,this.session=Q,this.dialect=$,this.config={table:A,withList:w}}static[lA]="SQLiteDelete";config;where(A){return this.config.where=A,this}orderBy(...A){if(typeof A[0]==="function"){let Q=A[0](new Proxy(this.config.table[Z2.Symbol.Columns],new J7({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),$=Array.isArray(Q)?Q:[Q];this.config.orderBy=$}else{let Q=A;this.config.orderBy=Q}return this}limit(A){return this.config.limit=A,this}returning(A=this.table[F7.Symbol.Columns]){return this.config.returning=YD(A),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:A,...Q}=this.dialect.sqlToQuery(this.getSQL());return Q}_prepare(A=!0){return this.session[A?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:Vz(this.config.table)})}prepare(){return this._prepare(!1)}run=(A)=>{return this._prepare().run(A)};all=(A)=>{return this._prepare().all(A)};get=(A)=>{return this._prepare().get(A)};values=(A)=>{return this._prepare().values(A)};async execute(A){return this._prepare().execute(A)}$dynamic(){return this}}});function q5Q(A){return(A.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(($)=>$.toLowerCase()).join("_")}function z5Q(A){return(A.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce(($,w,B)=>{let X=B===0?w.toLowerCase():`${w[0].toUpperCase()}${w.slice(1)}`;return $+X},"")}function V5Q(A){return A}var yg0;var qCA=c(()=>{Z6();rY();yg0=class yg0{static[lA]="CasingCache";cache={};cachedTables={};convert;constructor(A){this.convert=A==="snake_case"?q5Q:A==="camelCase"?z5Q:V5Q}getColumnCasing(A){if(!A.keyAsName)return A.name;let Q=A.table[Z2.Symbol.Schema]??"public",$=A.table[Z2.Symbol.OriginalName],w=`${Q}.${$}.${A.name}`;if(!this.cache[w])this.cacheTable(A.table);return this.cache[w]}cacheTable(A){let Q=A[Z2.Symbol.Schema]??"public",$=A[Z2.Symbol.OriginalName],w=`${Q}.${$}`;if(!this.cachedTables[w]){for(let B of Object.values(A[Z2.Symbol.Columns])){let X=`${w}.${B.name}`;this.cache[X]=this.convert(B.name)}this.cachedTables[w]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Eg,JL,gg0;var XY0=c(()=>{Z6();Eg=class Eg extends Error{static[lA]="DrizzleError";constructor({message:A,cause:Q}){super(A);this.name="DrizzleError",this.cause=Q}};JL=class JL extends Error{constructor(A,Q,$){super(`Failed query: ${A}
148
148
  params: ${Q}`);if(this.query=A,this.params=Q,this.cause=$,Error.captureStackTrace(this,JL),$)this.cause=$}};gg0=class gg0 extends Eg{static[lA]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});function zCA(A){return $A`count(${A||$A.raw("*")})`.mapWith(Number)}var VCA=c(()=>{K4()});var JCA=()=>{};var FCA=c(()=>{VCA();JCA()});var Sg0=c(()=>{Pg0();FCA();K4()});var mg0=c(()=>{fg0();tk();xg0();Rg0();vg0();Cg0();hg0()});var Tx;var YY0=c(()=>{Z6();K4();Tx=class Tx extends XD{static[lA]="SQLiteViewBase"}});var Tg,ug0,cg0;var ZY0=c(()=>{AY0();qCA();qz();Z6();XY0();bs();Sg0();K4();mg0();ek();zz();rY();LW();zL();YY0();Tg=class Tg{static[lA]="SQLiteDialect";casing;constructor(A){this.casing=new yg0(A?.casing)}escapeName(A){return`"${A.replace(/"/g,'""')}"`}escapeParam(A){return"?"}escapeString(A){return`'${A.replace(/'/g,"''")}'`}buildWithCTE(A){if(!A?.length)return;let Q=[$A`with `];for(let[$,w]of A.entries())if(Q.push($A`${$A.identifier(w._.alias)} as (${w._.sql})`),$<A.length-1)Q.push($A`, `);return Q.push($A` `),$A.join(Q)}buildDeleteQuery({table:A,where:Q,returning:$,withList:w,limit:B,orderBy:X}){let Y=this.buildWithCTE(w),Z=$?$A` returning ${this.buildSelection($,{isSingleTable:!0})}`:void 0,W=Q?$A` where ${Q}`:void 0,K=this.buildOrderBy(X),U=this.buildLimit(B);return $A`${Y}delete from ${A}${W}${Z}${K}${U}`}buildUpdateSet(A,Q){let $=A[Z2.Symbol.Columns],w=Object.keys($).filter((X)=>Q[X]!==void 0||$[X]?.onUpdateFn!==void 0),B=w.length;return $A.join(w.flatMap((X,Y)=>{let Z=$[X],W=Z.onUpdateFn?.(),K=Q[X]??(q1(W,d2)?W:$A.param(W,Z)),U=$A`${$A.identifier(this.casing.getColumnCasing(Z))} = ${K}`;if(Y<B-1)return[U,$A.raw(", ")];return[U]}))}buildUpdateQuery({table:A,set:Q,where:$,returning:w,withList:B,joins:X,from:Y,limit:Z,orderBy:W}){let K=this.buildWithCTE(B),U=this.buildUpdateSet(A,Q),G=Y&&$A.join([$A.raw(" from "),this.buildFromTable(Y)]),D=this.buildJoins(X),q=w?$A` returning ${this.buildSelection(w,{isSingleTable:!0})}`:void 0,J=$?$A` where ${$}`:void 0,F=this.buildOrderBy(W),I=this.buildLimit(Z);return $A`${K}update ${A} set ${U}${G}${D}${J}${q}${F}${I}`}buildSelection(A,{isSingleTable:Q=!1}={}){let $=A.length,w=A.flatMap(({field:B},X)=>{let Y=[];if(q1(B,d2.Aliased)&&B.isSelectionField)Y.push($A.identifier(B.fieldAlias));else if(q1(B,d2.Aliased)||q1(B,d2)){let Z=q1(B,d2.Aliased)?B.sql:B;if(Q)Y.push(new d2(Z.queryChunks.map((W)=>{if(q1(W,Aw))return $A.identifier(this.casing.getColumnCasing(W));return W})));else Y.push(Z);if(q1(B,d2.Aliased))Y.push($A` as ${$A.identifier(B.fieldAlias)}`)}else if(q1(B,Aw)){let Z=B.table[Z2.Symbol.Name];if(B.columnType==="SQLiteNumericBigInt")if(Q)Y.push($A`cast(${$A.identifier(this.casing.getColumnCasing(B))} as text)`);else Y.push($A`cast(${$A.identifier(Z)}.${$A.identifier(this.casing.getColumnCasing(B))} as text)`);else if(Q)Y.push($A.identifier(this.casing.getColumnCasing(B)));else Y.push($A`${$A.identifier(Z)}.${$A.identifier(this.casing.getColumnCasing(B))}`)}else if(q1(B,yB)){let Z=Object.entries(B._.selectedFields);if(Z.length===1){let W=Z[0][1],K=q1(W,d2)?W.decoder:q1(W,Aw)?{mapFromDriverValue:(U)=>W.mapFromDriverValue(U)}:W.sql.decoder;if(K)B._.sql.decoder=K}Y.push(B)}if(X<$-1)Y.push($A`, `);return Y});return $A.join(w)}buildJoins(A){if(!A||A.length===0)return;let Q=[];if(A)for(let[$,w]of A.entries()){if($===0)Q.push($A` `);let B=w.table,X=w.on?$A` on ${w.on}`:void 0;if(q1(B,F7)){let Y=B[F7.Symbol.Name],Z=B[F7.Symbol.Schema],W=B[F7.Symbol.OriginalName],K=Y===W?void 0:w.alias;Q.push($A`${$A.raw(w.joinType)} join ${Z?$A`${$A.identifier(Z)}.`:void 0}${$A.identifier(W)}${K&&$A` ${$A.identifier(K)}`}${X}`)}else Q.push($A`${$A.raw(w.joinType)} join ${B}${X}`);if($<A.length-1)Q.push($A` `)}return $A.join(Q)}buildLimit(A){return typeof A==="object"||typeof A==="number"&&A>=0?$A` limit ${A}`:void 0}buildOrderBy(A){let Q=[];if(A){for(let[$,w]of A.entries())if(Q.push(w),$<A.length-1)Q.push($A`, `)}return Q.length>0?$A` order by ${$A.join(Q)}`:void 0}buildFromTable(A){if(q1(A,Z2)&&A[Z2.Symbol.IsAlias])return $A`${$A`${$A.identifier(A[Z2.Symbol.Schema]??"")}.`.if(A[Z2.Symbol.Schema])}${$A.identifier(A[Z2.Symbol.OriginalName])} ${$A.identifier(A[Z2.Symbol.Name])}`;return A}buildSelectQuery({withList:A,fields:Q,fieldsFlat:$,where:w,having:B,table:X,joins:Y,orderBy:Z,groupBy:W,limit:K,offset:U,distinct:G,setOperators:D}){let q=$??YD(Q);for(let B0 of q)if(q1(B0.field,Aw)&&ok(B0.field.table)!==(q1(X,yB)?X._.alias:q1(X,Tx)?X[gB].name:q1(X,d2)?void 0:ok(X))&&!((l)=>Y?.some(({alias:b})=>b===(l[Z2.Symbol.IsAlias]?ok(l):l[Z2.Symbol.BaseName])))(B0.field.table)){let l=ok(B0.field.table);throw Error(`Your "${B0.path.join("->")}" field references a column "${l}"."${B0.field.name}", but the table "${l}" is not part of the query! Did you forget to join it?`)}let J=!Y||Y.length===0,F=this.buildWithCTE(A),I=G?$A` distinct`:void 0,P=this.buildSelection(q,{isSingleTable:J}),j=this.buildFromTable(X),k=this.buildJoins(Y),f=w?$A` where ${w}`:void 0,R=B?$A` having ${B}`:void 0,x=[];if(W){for(let[B0,l]of W.entries())if(x.push(l),B0<W.length-1)x.push($A`, `)}let O=x.length>0?$A` group by ${$A.join(x)}`:void 0,g=this.buildOrderBy(Z),u=this.buildLimit(K),n=U?$A` offset ${U}`:void 0,t=$A`${F}select${I} ${P} from ${j}${k}${f}${O}${R}${g}${u}${n}`;if(D.length>0)return this.buildSetOperations(t,D);return t}buildSetOperations(A,Q){let[$,...w]=Q;if(!$)throw Error("Cannot pass undefined values to any set operator");if(w.length===0)return this.buildSetOperationQuery({leftSelect:A,setOperator:$});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:A,setOperator:$}),w)}buildSetOperationQuery({leftSelect:A,setOperator:{type:Q,isAll:$,rightSelect:w,limit:B,orderBy:X,offset:Y}}){let Z=$A`${A.getSQL()} `,W=$A`${w.getSQL()}`,K;if(X&&X.length>0){let q=[];for(let J of X)if(q1(J,H9))q.push($A.identifier(J.name));else if(q1(J,d2)){for(let F=0;F<J.queryChunks.length;F++){let I=J.queryChunks[F];if(q1(I,H9))J.queryChunks[F]=$A.identifier(this.casing.getColumnCasing(I))}q.push($A`${J}`)}else q.push($A`${J}`);K=$A` order by ${$A.join(q,$A`, `)}`}let U=typeof B==="object"||typeof B==="number"&&B>=0?$A` limit ${B}`:void 0,G=$A.raw(`${Q} ${$?"all ":""}`),D=Y?$A` offset ${Y}`:void 0;return $A`${Z}${G}${W}${K}${U}${D}`}buildInsertQuery({table:A,values:Q,onConflict:$,returning:w,withList:B,select:X}){let Y=[],Z=A[Z2.Symbol.Columns],W=Object.entries(Z).filter(([J,F])=>!F.shouldDisableInsert()),K=W.map(([,J])=>$A.identifier(this.casing.getColumnCasing(J)));if(X){let J=Q;if(q1(J,d2))Y.push(J);else Y.push(J.getSQL())}else{let J=Q;Y.push($A.raw("values "));for(let[F,I]of J.entries()){let P=[];for(let[j,k]of W){let f=I[j];if(f===void 0||q1(f,sK)&&f.value===void 0){let R;if(k.default!==null&&k.default!==void 0)R=q1(k.default,d2)?k.default:$A.param(k.default,k);else if(k.defaultFn!==void 0){let x=k.defaultFn();R=q1(x,d2)?x:$A.param(x,k)}else if(!k.default&&k.onUpdateFn!==void 0){let x=k.onUpdateFn();R=q1(x,d2)?x:$A.param(x,k)}else R=$A`null`;P.push(R)}else P.push(f)}if(Y.push(P),F<J.length-1)Y.push($A`, `)}}let U=this.buildWithCTE(B),G=$A.join(Y),D=w?$A` returning ${this.buildSelection(w,{isSingleTable:!0})}`:void 0,q=$?.length?$A.join($):void 0;return $A`${U}insert into ${A} ${K} ${G}${q}${D}`}sqlToQuery(A,Q){return A.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:Q})}buildRelationalQuery({fullSchema:A,schema:Q,tableNamesMap:$,table:w,tableConfig:B,queryConfig:X,tableAlias:Y,nestedQueryRelation:Z,joinOn:W}){let K=[],U,G,D=[],q,J=[];if(X===!0)K=Object.entries(B.columns).map(([P,j])=>({dbKey:j.name,tsKey:P,field:rV(j,Y),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let I=Object.fromEntries(Object.entries(B.columns).map(([x,O])=>[x,rV(O,Y)]));if(X.where){let x=typeof X.where==="function"?X.where(I,IvA()):X.where;q=x&&fs(x,Y)}let P=[],j=[];if(X.columns){let x=!1;for(let[O,g]of Object.entries(X.columns)){if(g===void 0)continue;if(O in B.columns){if(!x&&g===!0)x=!0;j.push(O)}}if(j.length>0)j=x?j.filter((O)=>X.columns?.[O]===!0):Object.keys(B.columns).filter((O)=>!j.includes(O))}else j=Object.keys(B.columns);for(let x of j){let O=B.columns[x];P.push({tsKey:x,value:O})}let k=[];if(X.with)k=Object.entries(X.with).filter((x)=>!!x[1]).map(([x,O])=>({tsKey:x,queryConfig:O,relation:B.relations[x]}));let f;if(X.extras){f=typeof X.extras==="function"?X.extras(I,{sql:$A}):X.extras;for(let[x,O]of Object.entries(f))P.push({tsKey:x,value:jg0(O,Y)})}for(let{tsKey:x,value:O}of P)K.push({dbKey:q1(O,d2.Aliased)?O.fieldAlias:B.columns[x].name,tsKey:x,field:q1(O,Aw)?rV(O,Y):O,relationTableTsKey:void 0,isJson:!1,selection:[]});let R=typeof X.orderBy==="function"?X.orderBy(I,LvA()):X.orderBy??[];if(!Array.isArray(R))R=[R];D=R.map((x)=>{if(q1(x,Aw))return rV(x,Y);return fs(x,Y)}),U=X.limit,G=X.offset;for(let{tsKey:x,queryConfig:O,relation:g}of k){let u=_vA(Q,$,g),n=Ex(g.referencedTable),t=$[n],B0=`${Y}_${x}`,l=Qw(...u.fields.map((E,o)=>NQ(rV(u.references[o],B0),rV(E,Y)))),b=this.buildRelationalQuery({fullSchema:A,schema:Q,tableNamesMap:$,table:A[t],tableConfig:Q[t],queryConfig:q1(g,ak)?O===!0?{limit:1}:{...O,limit:1}:O,tableAlias:B0,joinOn:l,nestedQueryRelation:g}),T=$A`(${b.sql})`.as(x);K.push({dbKey:x,tsKey:x,field:T,relationTableTsKey:t,isJson:!0,selection:b.selection})}}if(K.length===0)throw new Eg({message:`No fields selected for table "${B.tsName}" ("${Y}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let F;if(q=Qw(W,q),Z){let I=$A`json_array(${$A.join(K.map(({field:k})=>q1(k,H9)?$A.identifier(this.casing.getColumnCasing(k)):q1(k,d2.Aliased)?k.sql:k),$A`, `)})`;if(q1(Z,Ms))I=$A`coalesce(json_group_array(${I}), json_array())`;let P=[{dbKey:"data",tsKey:"data",field:I.as("data"),isJson:!0,relationTableTsKey:B.tsName,selection:K}];if(U!==void 0||G!==void 0||D.length>0)F=this.buildSelectQuery({table:eX0(w,Y),fields:{},fieldsFlat:[{path:[],field:$A.raw("*")}],where:q,limit:U,offset:G,orderBy:D,setOperators:[]}),q=void 0,U=void 0,G=void 0,D=void 0;else F=eX0(w,Y);F=this.buildSelectQuery({table:q1(F,F7)?F:new yB(F,{},Y),fields:{},fieldsFlat:P.map(({field:k})=>({path:[],field:q1(k,Aw)?rV(k,Y):k})),joins:J,where:q,limit:U,offset:G,orderBy:D,setOperators:[]})}else F=this.buildSelectQuery({table:eX0(w,Y),fields:{},fieldsFlat:K.map(({field:I})=>({path:[],field:q1(I,Aw)?rV(I,Y):I})),joins:J,where:q,limit:U,offset:G,orderBy:D,setOperators:[]});return{tableTsKey:B.tsName,sql:F,selection:K}}};ug0=class ug0 extends Tg{static[lA]="SQLiteSyncDialect";migrate(A,Q,$){let w=$===void 0?"__drizzle_migrations":typeof $==="string"?"__drizzle_migrations":$.migrationsTable??"__drizzle_migrations",B=$A`
149
149
  CREATE TABLE IF NOT EXISTS ${$A.identifier(w)} (
150
150
  id SERIAL PRIMARY KEY,
@@ -460,7 +460,7 @@ ${X}`:"")}function Na0(A,Q,$,w){return async(B,X)=>{if(w){let Y={toolName:A,args
460
460
  hash text NOT NULL,
461
461
  created_at numeric
462
462
  )
463
- `;await A.session.run(B);let Y=(await A.values($A`SELECT id, hash, created_at FROM ${$A.identifier(w)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,Z=[];for(let W of $)if(!Y||Number(Y[2])<W.folderMillis){for(let K of W.sql)Z.push(A.run($A.raw(K)));Z.push(A.run($A`INSERT INTO ${$A.identifier(w)} ("hash", "created_at") VALUES(${W.hash}, ${W.folderMillis})`))}await A.session.migrate(Z)}var MA0=c(()=>{iY1();K4()});async function nY1(A,Q){let $=Q?.child("entity-migrate")??Y6.getInstance().child("entity-migrate"),{db:w,client:B,url:X}=uK0(A);$.debug("Running entity database migrations...");try{await cK0(B,X);let Z=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),await pK0(B),$.debug("Entity database migrations completed successfully")}catch(Y){throw $.error("Entity database migration failed:",Y),Y}finally{B.close()}}var rY1=c(()=>{MA0();nd0();wX()});async function oY1(A,Q){let $=Q?.child("job-queue-migrate")??Y6.getInstance().child("job-queue-migrate"),{db:w,client:B,url:X}=zY0(A);$.debug("Running job queue migrations...");try{await VY0(B,X);let Z=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),$.debug("Job queue migrations completed successfully")}catch(Y){throw $.error("Job queue migration failed:",Y),Y}finally{B.close()}}var sY1=c(()=>{MA0();ZS0();wX()});async function aY1(A,Q){let $=Q?.child("conversation-migrate")??Y6.getInstance().child("conversation-migrate"),{db:w,client:B,url:X}=tR(A);$.debug("Running conversation database migrations...");try{if(X.startsWith("file:"))await B.execute("PRAGMA journal_mode = WAL");let Z=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),$.debug("Conversation database migrations completed successfully")}catch(Y){throw $.error("Conversation database migration failed:",Y),Y}finally{B.close()}}var tY1=c(()=>{MA0();yK0();wX()});async function eY1(A,Q){let $=Q?.child("runtime-state-migrate")??Y6.getInstance().child("runtime-state-migrate"),{db:w,client:B,url:X}=GD0(A);$.debug("Running runtime state migrations...");try{await DD0(B,X);let Z=import.meta.url.includes("/dist/")?new URL("./migrations/runtime-state",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),$.debug("Runtime state migrations completed successfully")}catch(Y){throw $.error("Runtime state migration failed:",Y),Y}finally{B.close()}}var AZ1=c(()=>{MA0();wX();ma0()});import{mkdir as Vt0}from"fs/promises";function OD0(A=process.env){return{dataDir:A.XDG_DATA_HOME??"./data",cacheDir:A.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function fD0(A=process.env){return ZM(OD0(A))}async function xD0(A=process.env){let Q=OD0(A);try{await Vt0(Q.dataDir,{recursive:!0}),await Vt0(Q.cacheDir,{recursive:!0}),await Vt0(Q.distDir,{recursive:!0})}catch($){let w=$ instanceof Error&&$.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${Q.dataDir}`:`Cannot create data directories: ${$ instanceof Error?$.message:String($)}`;throw Error(w,{cause:$})}return ZM(Q)}var RD0=c(()=>{MD0()});class bA0{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:()=>xD0(),migrateEntities:nY1,migrateJobQueue:oY1,migrateConversations:aY1,migrateRuntimeState:eY1}}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 Jt0=c(()=>{rY1();sY1();tY1();AZ1();RD0()});function nrQ(){return process.env[irQ]}function QZ1(){return nrQ()!=="production"}var irQ="NODE_ENV";var vD0;var Ft0=c(()=>{C0();vD0=H.object({theme:H.object({primaryColor:H.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:H.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})})});var wZ1;var $Z1=c(()=>{wZ1={name:"@brains/chat-repl",version:"0.2.0-alpha.183",dependencies:{"@brains/plugins":"workspace:*",chalk:"^5.4.1",ink:"^7.0.6","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^18.0.5",react:"^19.2.7"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/react":"^19.2.17",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"}});var l6=C((orQ,CD0)=>{(function(){function A(e,z0){Object.defineProperty(w.prototype,e,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",z0[0],z0[1])}})}function Q(e){if(e===null||typeof e!=="object")return null;return e=b0&&e[b0]||e["@@iterator"],typeof e==="function"?e:null}function $(e,z0){e=(e=e.constructor)&&(e.displayName||e.name)||"ReactClass";var I0=e+"."+z0;O0[I0]||(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.",z0,e),O0[I0]=!0)}function w(e,z0,I0){this.props=e,this.context=z0,this.refs=r0,this.updater=I0||g0}function B(){}function X(e,z0,I0){this.props=e,this.context=z0,this.refs=r0,this.updater=I0||g0}function Y(){}function Z(e){return""+e}function W(e){try{Z(e);var z0=!1}catch(L0){z0=!0}if(z0){z0=console;var I0=z0.error,M0=typeof Symbol==="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return I0.call(z0,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",M0),Z(e)}}function K(e){if(e==null)return null;if(typeof e==="function")return e.$$typeof===UA?null:e.displayName||e.name||null;if(typeof e==="string")return e;switch(e){case q0:return"Fragment";case H0:return"Profiler";case S:return"StrictMode";case i0:return"Suspense";case k0:return"SuspenseList";case m0:return"Activity"}if(typeof e==="object")switch(typeof e.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case a:return"Portal";case i:return e.displayName||"Context";case N0:return(e._context.displayName||"Context")+".Consumer";case u0:var z0=e.render;return e=e.displayName,e||(e=z0.displayName||z0.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case j0:return z0=e.displayName||null,z0!==null?z0:K(e.type)||"Memo";case h0:z0=e._payload,e=e._init;try{return K(e(z0))}catch(I0){}}return null}function U(e){if(e===q0)return"<>";if(typeof e==="object"&&e!==null&&e.$$typeof===h0)return"<...>";try{var z0=K(e);return z0?"<"+z0+">":"<...>"}catch(I0){return"<...>"}}function G(){var e=GA.A;return e===null?null:e.getOwner()}function D(){return Error("react-stack-top-frame")}function q(e){if(s0.call(e,"key")){var z0=Object.getOwnPropertyDescriptor(e,"key").get;if(z0&&z0.isReactWarning)return!1}return e.key!==void 0}function J(e,z0){function I0(){JA||(JA=!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)",z0))}I0.isReactWarning=!0,Object.defineProperty(e,"key",{get:I0,configurable:!0})}function F(){var e=K(this.type);return TA[e]||(TA[e]=!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.")),e=this.props.ref,e!==void 0?e:null}function I(e,z0,I0,M0,L0,o0){var l0=I0.ref;return e={$$typeof:o,type:e,key:z0,props:I0,_owner:M0},(l0!==void 0?l0:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:F}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:L0}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:o0}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function P(e,z0){return z0=I(e.type,z0,e.props,e._owner,e._debugStack,e._debugTask),e._store&&(z0._store.validated=e._store.validated),z0}function j(e){k(e)?e._store&&(e._store.validated=1):typeof e==="object"&&e!==null&&e.$$typeof===h0&&(e._payload.status==="fulfilled"?k(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function k(e){return typeof e==="object"&&e!==null&&e.$$typeof===o}function f(e){var z0={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(I0){return z0[I0]})}function R(e,z0){return typeof e==="object"&&e!==null&&e.key!=null?(W(e.key),f(""+e.key)):z0.toString(36)}function x(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status==="string"?e.then(Y,Y):(e.status="pending",e.then(function(z0){e.status==="pending"&&(e.status="fulfilled",e.value=z0)},function(z0){e.status==="pending"&&(e.status="rejected",e.reason=z0)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function O(e,z0,I0,M0,L0){var o0=typeof e;if(o0==="undefined"||o0==="boolean")e=null;var l0=!1;if(e===null)l0=!0;else switch(o0){case"bigint":case"string":case"number":l0=!0;break;case"object":switch(e.$$typeof){case o:case a:l0=!0;break;case h0:return l0=e._init,O(l0(e._payload),z0,I0,M0,L0)}}if(l0){l0=e,L0=L0(l0);var YA=M0===""?"."+R(l0,0):M0;return _A(L0)?(I0="",YA!=null&&(I0=YA.replace(R0,"$&/")+"/"),O(L0,z0,I0,"",function(gA){return gA})):L0!=null&&(k(L0)&&(L0.key!=null&&(l0&&l0.key===L0.key||W(L0.key)),I0=P(L0,I0+(L0.key==null||l0&&l0.key===L0.key?"":(""+L0.key).replace(R0,"$&/")+"/")+YA),M0!==""&&l0!=null&&k(l0)&&l0.key==null&&l0._store&&!l0._store.validated&&(I0._store.validated=2),L0=I0),z0.push(L0)),1}if(l0=0,YA=M0===""?".":M0+":",_A(e))for(var HA=0;HA<e.length;HA++)M0=e[HA],o0=YA+R(M0,HA),l0+=O(M0,z0,I0,o0,L0);else if(HA=Q(e),typeof HA==="function")for(HA===e.entries&&(T0||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),T0=!0),e=HA.call(e),HA=0;!(M0=e.next()).done;)M0=M0.value,o0=YA+R(M0,HA++),l0+=O(M0,z0,I0,o0,L0);else if(o0==="object"){if(typeof e.then==="function")return O(x(e),z0,I0,M0,L0);throw z0=String(e),Error("Objects are not valid as a React child (found: "+(z0==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":z0)+"). If you meant to render a collection of children, use an array instead.")}return l0}function g(e,z0,I0){if(e==null)return e;var M0=[],L0=0;return O(e,M0,"","",function(o0){return z0.call(I0,o0,L0++)}),M0}function u(e){if(e._status===-1){var z0=e._ioInfo;z0!=null&&(z0.start=z0.end=performance.now()),z0=e._result;var I0=z0();if(I0.then(function(L0){if(e._status===0||e._status===-1){e._status=1,e._result=L0;var o0=e._ioInfo;o0!=null&&(o0.end=performance.now()),I0.status===void 0&&(I0.status="fulfilled",I0.value=L0)}},function(L0){if(e._status===0||e._status===-1){e._status=2,e._result=L0;var o0=e._ioInfo;o0!=null&&(o0.end=performance.now()),I0.status===void 0&&(I0.status="rejected",I0.reason=L0)}}),z0=e._ioInfo,z0!=null){z0.value=I0;var M0=I0.displayName;typeof M0==="string"&&(z0.name=M0)}e._status===-1&&(e._status=0,e._result=I0)}if(e._status===1)return z0=e._result,z0===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
463
+ `;await A.session.run(B);let Y=(await A.values($A`SELECT id, hash, created_at FROM ${$A.identifier(w)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,Z=[];for(let W of $)if(!Y||Number(Y[2])<W.folderMillis){for(let K of W.sql)Z.push(A.run($A.raw(K)));Z.push(A.run($A`INSERT INTO ${$A.identifier(w)} ("hash", "created_at") VALUES(${W.hash}, ${W.folderMillis})`))}await A.session.migrate(Z)}var MA0=c(()=>{iY1();K4()});async function nY1(A,Q){let $=Q?.child("entity-migrate")??Y6.getInstance().child("entity-migrate"),{db:w,client:B,url:X}=uK0(A);$.debug("Running entity database migrations...");try{await cK0(B,X);let Z=import.meta.url.includes("/dist/")?new URL("./migrations/entity-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),await pK0(B),$.debug("Entity database migrations completed successfully")}catch(Y){throw $.error("Entity database migration failed:",Y),Y}finally{B.close()}}var rY1=c(()=>{MA0();nd0();wX()});async function oY1(A,Q){let $=Q?.child("job-queue-migrate")??Y6.getInstance().child("job-queue-migrate"),{db:w,client:B,url:X}=zY0(A);$.debug("Running job queue migrations...");try{await VY0(B,X);let Z=import.meta.url.includes("/dist/")?new URL("./migrations/job-queue",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),$.debug("Job queue migrations completed successfully")}catch(Y){throw $.error("Job queue migration failed:",Y),Y}finally{B.close()}}var sY1=c(()=>{MA0();ZS0();wX()});async function aY1(A,Q){let $=Q?.child("conversation-migrate")??Y6.getInstance().child("conversation-migrate"),{db:w,client:B,url:X}=tR(A);$.debug("Running conversation database migrations...");try{if(X.startsWith("file:"))await B.execute("PRAGMA journal_mode = WAL");let Z=import.meta.url.includes("/dist/")?new URL("./migrations/conversation-service",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),$.debug("Conversation database migrations completed successfully")}catch(Y){throw $.error("Conversation database migration failed:",Y),Y}finally{B.close()}}var tY1=c(()=>{MA0();yK0();wX()});async function eY1(A,Q){let $=Q?.child("runtime-state-migrate")??Y6.getInstance().child("runtime-state-migrate"),{db:w,client:B,url:X}=GD0(A);$.debug("Running runtime state migrations...");try{await DD0(B,X);let Z=import.meta.url.includes("/dist/")?new URL("./migrations/runtime-state",import.meta.url).pathname:new URL("../drizzle",import.meta.url).pathname;await IM(w,{migrationsFolder:Z}),$.debug("Runtime state migrations completed successfully")}catch(Y){throw $.error("Runtime state migration failed:",Y),Y}finally{B.close()}}var AZ1=c(()=>{MA0();wX();ma0()});import{mkdir as Vt0}from"fs/promises";function OD0(A=process.env){return{dataDir:A.XDG_DATA_HOME??"./data",cacheDir:A.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function fD0(A=process.env){return ZM(OD0(A))}async function xD0(A=process.env){let Q=OD0(A);try{await Vt0(Q.dataDir,{recursive:!0}),await Vt0(Q.cacheDir,{recursive:!0}),await Vt0(Q.distDir,{recursive:!0})}catch($){let w=$ instanceof Error&&$.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${Q.dataDir}`:`Cannot create data directories: ${$ instanceof Error?$.message:String($)}`;throw Error(w,{cause:$})}return ZM(Q)}var RD0=c(()=>{MD0()});class bA0{logger;migrations;constructor(A,Q){this.logger=A,this.migrations=Q??{getStandardConfigWithDirectories:()=>xD0(),migrateEntities:nY1,migrateJobQueue:oY1,migrateConversations:aY1,migrateRuntimeState:eY1}}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 Jt0=c(()=>{rY1();sY1();tY1();AZ1();RD0()});function nrQ(){return process.env[irQ]}function QZ1(){return nrQ()!=="production"}var irQ="NODE_ENV";var vD0;var Ft0=c(()=>{C0();vD0=H.object({theme:H.object({primaryColor:H.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:H.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})})});var wZ1;var $Z1=c(()=>{wZ1={name:"@brains/chat-repl",version:"0.2.0-alpha.184",dependencies:{"@brains/plugins":"workspace:*",chalk:"^5.4.1",ink:"^7.0.6","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^18.0.5",react:"^19.2.7"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/react":"^19.2.17",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"}});var l6=C((orQ,CD0)=>{(function(){function A(e,z0){Object.defineProperty(w.prototype,e,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",z0[0],z0[1])}})}function Q(e){if(e===null||typeof e!=="object")return null;return e=b0&&e[b0]||e["@@iterator"],typeof e==="function"?e:null}function $(e,z0){e=(e=e.constructor)&&(e.displayName||e.name)||"ReactClass";var I0=e+"."+z0;O0[I0]||(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.",z0,e),O0[I0]=!0)}function w(e,z0,I0){this.props=e,this.context=z0,this.refs=r0,this.updater=I0||g0}function B(){}function X(e,z0,I0){this.props=e,this.context=z0,this.refs=r0,this.updater=I0||g0}function Y(){}function Z(e){return""+e}function W(e){try{Z(e);var z0=!1}catch(L0){z0=!0}if(z0){z0=console;var I0=z0.error,M0=typeof Symbol==="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return I0.call(z0,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",M0),Z(e)}}function K(e){if(e==null)return null;if(typeof e==="function")return e.$$typeof===UA?null:e.displayName||e.name||null;if(typeof e==="string")return e;switch(e){case q0:return"Fragment";case H0:return"Profiler";case S:return"StrictMode";case i0:return"Suspense";case k0:return"SuspenseList";case m0:return"Activity"}if(typeof e==="object")switch(typeof e.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case a:return"Portal";case i:return e.displayName||"Context";case N0:return(e._context.displayName||"Context")+".Consumer";case u0:var z0=e.render;return e=e.displayName,e||(e=z0.displayName||z0.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case j0:return z0=e.displayName||null,z0!==null?z0:K(e.type)||"Memo";case h0:z0=e._payload,e=e._init;try{return K(e(z0))}catch(I0){}}return null}function U(e){if(e===q0)return"<>";if(typeof e==="object"&&e!==null&&e.$$typeof===h0)return"<...>";try{var z0=K(e);return z0?"<"+z0+">":"<...>"}catch(I0){return"<...>"}}function G(){var e=GA.A;return e===null?null:e.getOwner()}function D(){return Error("react-stack-top-frame")}function q(e){if(s0.call(e,"key")){var z0=Object.getOwnPropertyDescriptor(e,"key").get;if(z0&&z0.isReactWarning)return!1}return e.key!==void 0}function J(e,z0){function I0(){JA||(JA=!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)",z0))}I0.isReactWarning=!0,Object.defineProperty(e,"key",{get:I0,configurable:!0})}function F(){var e=K(this.type);return TA[e]||(TA[e]=!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.")),e=this.props.ref,e!==void 0?e:null}function I(e,z0,I0,M0,L0,o0){var l0=I0.ref;return e={$$typeof:o,type:e,key:z0,props:I0,_owner:M0},(l0!==void 0?l0:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:F}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:L0}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:o0}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function P(e,z0){return z0=I(e.type,z0,e.props,e._owner,e._debugStack,e._debugTask),e._store&&(z0._store.validated=e._store.validated),z0}function j(e){k(e)?e._store&&(e._store.validated=1):typeof e==="object"&&e!==null&&e.$$typeof===h0&&(e._payload.status==="fulfilled"?k(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function k(e){return typeof e==="object"&&e!==null&&e.$$typeof===o}function f(e){var z0={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(I0){return z0[I0]})}function R(e,z0){return typeof e==="object"&&e!==null&&e.key!=null?(W(e.key),f(""+e.key)):z0.toString(36)}function x(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status==="string"?e.then(Y,Y):(e.status="pending",e.then(function(z0){e.status==="pending"&&(e.status="fulfilled",e.value=z0)},function(z0){e.status==="pending"&&(e.status="rejected",e.reason=z0)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function O(e,z0,I0,M0,L0){var o0=typeof e;if(o0==="undefined"||o0==="boolean")e=null;var l0=!1;if(e===null)l0=!0;else switch(o0){case"bigint":case"string":case"number":l0=!0;break;case"object":switch(e.$$typeof){case o:case a:l0=!0;break;case h0:return l0=e._init,O(l0(e._payload),z0,I0,M0,L0)}}if(l0){l0=e,L0=L0(l0);var YA=M0===""?"."+R(l0,0):M0;return _A(L0)?(I0="",YA!=null&&(I0=YA.replace(R0,"$&/")+"/"),O(L0,z0,I0,"",function(gA){return gA})):L0!=null&&(k(L0)&&(L0.key!=null&&(l0&&l0.key===L0.key||W(L0.key)),I0=P(L0,I0+(L0.key==null||l0&&l0.key===L0.key?"":(""+L0.key).replace(R0,"$&/")+"/")+YA),M0!==""&&l0!=null&&k(l0)&&l0.key==null&&l0._store&&!l0._store.validated&&(I0._store.validated=2),L0=I0),z0.push(L0)),1}if(l0=0,YA=M0===""?".":M0+":",_A(e))for(var HA=0;HA<e.length;HA++)M0=e[HA],o0=YA+R(M0,HA),l0+=O(M0,z0,I0,o0,L0);else if(HA=Q(e),typeof HA==="function")for(HA===e.entries&&(T0||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),T0=!0),e=HA.call(e),HA=0;!(M0=e.next()).done;)M0=M0.value,o0=YA+R(M0,HA++),l0+=O(M0,z0,I0,o0,L0);else if(o0==="object"){if(typeof e.then==="function")return O(x(e),z0,I0,M0,L0);throw z0=String(e),Error("Objects are not valid as a React child (found: "+(z0==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":z0)+"). If you meant to render a collection of children, use an array instead.")}return l0}function g(e,z0,I0){if(e==null)return e;var M0=[],L0=0;return O(e,M0,"","",function(o0){return z0.call(I0,o0,L0++)}),M0}function u(e){if(e._status===-1){var z0=e._ioInfo;z0!=null&&(z0.start=z0.end=performance.now()),z0=e._result;var I0=z0();if(I0.then(function(L0){if(e._status===0||e._status===-1){e._status=1,e._result=L0;var o0=e._ioInfo;o0!=null&&(o0.end=performance.now()),I0.status===void 0&&(I0.status="fulfilled",I0.value=L0)}},function(L0){if(e._status===0||e._status===-1){e._status=2,e._result=L0;var o0=e._ioInfo;o0!=null&&(o0.end=performance.now()),I0.status===void 0&&(I0.status="rejected",I0.reason=L0)}}),z0=e._ioInfo,z0!=null){z0.value=I0;var M0=I0.displayName;typeof M0==="string"&&(z0.name=M0)}e._status===-1&&(e._status=0,e._result=I0)}if(e._status===1)return z0=e._result,z0===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
464
464
 
465
465
  Your code should look like:
466
466
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -1747,7 +1747,7 @@ Example bad output: "A dreamlike crystal formation glowing with ethereal light i
1747
1747
  Title: "${A.entityTitle??Z}"
1748
1748
 
1749
1749
  Content:
1750
- ${U}`,U16);K=`${w.trim()} ${P.imagePrompt}`}catch(P){this.logger.warn("AI prompt distillation failed, using fallback",{error:aA(P)})}}await this.reportProgress($,{progress:T6.PROCESS,message:"Generating image"});let G=this.context.identity.get(),D=this.context.identity.getProfile(),J=vD1(G,D)+K,F;try{F=await this.context.ai.generateImage(J,{...B&&{aspectRatio:B}})}catch(P){return this.logger.error("Image generation failed",{jobId:Q,error:aA(P)}),y5.failure(P)}await this.reportProgress($,{progress:T6.GENERATE,message:"Creating image entity"});let I=PU.createImageEntity({dataUrl:F.dataUrl,title:Z,status:"draft",attachmentType:"generated",...X&&{sourceEntityType:X},...Y&&{sourceEntityId:Y}});if(await OH({entityService:this.context.entityService,entity:{...I,id:W}}),this.logger.debug("Created image entity",{imageId:W}),X&&Y){await this.reportProgress($,{progress:T6.SAVE,message:`Updating ${X} with cover image`});let P=await Kv(this.context.entityService,X,Y,this.logger);if(!P)return y5.failure(Error(`Target entity not found: ${X}/${Y}`));let j=pv(P,W);await this.context.entities.update(j),this.logger.debug("Updated target entity with cover image",{targetEntityType:X,targetEntityId:Y,imageId:W})}return await this.reportProgress($,{progress:T6.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:W,targetEntityType:X,targetEntityId:Y}),{success:!0,imageId:W}}catch(K){let U=aA(K);return this.logger.error("Image generation job failed",{jobId:Q,error:U}),await xJ({entityService:this.context.entityService,entityType:"image",id:W,error:U}),y5.failure(K)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}KA();C0();e8();JZ();var D16=H.object({sourceEntityType:H.string().min(1),sourceEntityId:H.string().min(1),attachmentType:H.string().min(1),imageId:H.string().min(1),dedupKey:H.string().min(1).optional(),replace:H.boolean().optional(),targetEntityType:H.string().min(1).optional(),targetEntityId:H.string().min(1).optional(),targetImageField:H.enum(["coverImageId","ogImageId"]).optional()});class u0A extends X8{context;constructor(A,Q){super(Q,{schema:D16,jobTypeName:"image-render-source"});this.context=A}async process(A,Q,$){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 Y=await this.findImageByDedupKey(A.dedupKey);if(Y)return await this.updateTarget(A,Y.id),await this.reportProgress($,{progress:T6.COMPLETE,message:"Reusing existing generated image"}),{success:!0,imageId:Y.id,reused:!0}}await this.reportProgress($,{progress:T6.PROCESS,message:"Rendering source image"});let w=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!w)return y5.failure(Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`));if(w.type!=="image")return y5.failure(Error(`Attachment provider returned ${w.type}; expected image`));await this.reportProgress($,{progress:T6.GENERATE,message:"Creating image entity"});let B=w.mimeType.split("/")[1]??"png",X=PU.createImageEntity({dataUrl:Zt0(w.data.toString("base64"),B),title:A.imageId,status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,...A.dedupKey&&{dedupKey:A.dedupKey}});return await OH({entityService:this.context.entityService,entity:{...X,id:A.imageId}}),await this.updateTarget(A,A.imageId),await this.reportProgress($,{progress:T6.COMPLETE,message:"Image render complete"}),{success:!0,imageId:A.imageId,reused:!1}}catch(w){let B=aA(w);return this.logger.error("Source image render job failed",{jobId:Q,error:B}),await xJ({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:B}),y5.failure(w)}}async findImageByDedupKey(A){return(await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{dedupKey:A}}}})).find(($)=>$.metadata.status!=="pending"&&$.metadata.status!=="failed")}async updateTarget(A,Q){if(!A.targetEntityType||!A.targetEntityId)return;let $=await Kv(this.context.entityService,A.targetEntityType,A.targetEntityId,this.logger);if(!$)throw Error(`Target entity not found: ${A.targetEntityType}/${A.targetEntityId}`);let B=(A.targetImageField??"coverImageId")==="ogImageId"?kA0($,Q):pv($,Q);await this.context.entities.update(B)}}KA();C0();e8();JZ();S2();var bc={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function wz0(A){return["image/png","image/jpeg","image/webp","image/gif"].includes(A.toLowerCase())}function Bz0(A){let Q=q16(A.title,A.filename),$=k1(Q);if(!$)throw Error("Could not derive an image id from the uploaded filename. Provide a title.");return{id:$,title:Q}}function CD1(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function q16(A,Q){let $=A?.trim();if($)return $;return Q.replace(/\.[^.]+$/,"").trim()||Q}var z16=H.object({uploadId:H.string().min(1),imageId:H.string().min(1).optional(),title:H.string().optional()});class c0A extends X8{context;constructor(A,Q){super(A,{schema:z16,jobTypeName:"upload-promote"});this.context=Q}async process(A,Q,$){try{await this.reportProgress($,{progress:10,message:"Reading uploaded image"});let w=await this.context.uploads.scoped(bc).read(A.uploadId);if(!wz0(w.record.mediaType))throw Error("Only image uploads can be promoted to image entities");let B=Bz0({filename:w.record.filename,...A.title!==void 0?{title:A.title}:{}}),X=A.imageId??B.id;await this.reportProgress($,{progress:60,message:"Saving uploaded image"});let Y=new Date().toISOString(),Z=PU.createImageEntity({dataUrl:CD1(w.record.mediaType,w.content),title:B.title,status:"draft",sourceUploadId:A.uploadId,sourceFilename:w.record.filename,sourceMediaType:w.record.mediaType,attachmentType:"uploaded"}),W=await OH({entityService:this.context.entityService,entity:{id:X,...Z,created:Y,updated:Y}});return await this.reportProgress($,{progress:100,message:"Uploaded image promoted"}),{entityId:W.entityId,status:"created"}}catch(w){if(A.imageId)await xJ({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:aA(w)});return y5.failure(w)}}summarizeDataForLog(A){return{uploadId:A.uploadId,imageId:A.imageId,hasTitle:A.title!==void 0}}}var hD1={name:"@brains/image-plugin",version:"0.2.0-alpha.183",description:"Plugin for AI-powered image generation and management",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":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},main:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var J16="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",F16=H.object({defaultAspectRatio:H.enum(["1:1","16:9","9:16","4:3","3:4"]).default("16:9").describe("Default aspect ratio for generated images")});function Y3(A){let Q=A?.trim();if(!Q)return;return Q}function I16(A){let Q=Y3(A.prompt);if(Q)return Q;let $=Y3(A.content);if($&&!m0A($))return $;return}function L16(A){let Q=A.attachmentType==="og-image"?"og":A.attachmentType;return k1(`${Q}-${A.sourceEntityType}-${A.sourceEntityId}`)}function ED1(A){let Q=Y3(A.title)??(A.targetEntityId?`cover-${A.targetEntityId}`:A.prompt.slice(0,60).trim());return k1(Q)}async function N16(A,Q){let $=`${Q.attachmentType}:${Q.sourceEntityType}:${Q.sourceEntityId}:resolved-attachment`,w=await A.entityService.getEntity({entityType:Q.sourceEntityType,id:Q.sourceEntityId});return w?`${$}:${w.contentHash}`:$}function p0A(A,Q="generated"){let $=encodeURIComponent(A);return{mediaType:"image/png",url:`/api/chat/attachments/image?id=${$}`,downloadUrl:`/api/chat/attachments/image?id=${$}&download=1`,filename:`${A}.png`,source:{entityType:"image",entityId:A,attachmentType:Q}}}function _16(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 l0A extends S6{entityType=PU.entityType;schema=_A0;adapter=PU;constructor(A={}){super("image",hD1,A,F16)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,$){if(A.from?.kind===bc.refKind)return this.promoteUpload(A,$);let w=I16(A),B=Y3(A.targetEntityType),X=Y3(A.targetEntityId),Y=B===this.entityType?X:void 0,Z=A.from;if(Z?.kind==="entity-attachment")return this.enqueueSourceImageRender({...A,from:Z},$);if(!B||!X||Y){if(!w)return{kind:"continue",input:A};let D=Y3(A.title)??Y,q=ED1({prompt:w,...D&&{title:D}});await this.createPendingImage($,{id:q,title:D??w.slice(0,60).trim(),alt:D??w.slice(0,60).trim(),attachmentType:"generated"});let J=await $.jobs.enqueue({type:"image-generate",data:{prompt:w,...D&&{title:D}}});return{kind:"handled",result:{success:!0,data:{entityId:q,status:"generating",jobId:J,attachment:p0A(q)}}}}let W=await UZ($.entityService,B,X,this.logger,"Target entity");if(!W.ok)return{kind:"handled",result:{success:!1,error:W.error}};if(!w)return{kind:"continue",input:{...A,targetEntityId:W.entity.id}};let K=Qz0(W.entity.content),U=ED1({prompt:w,...A.title&&{title:A.title},targetEntityId:W.entity.id});await this.createPendingImage($,{id:U,title:A.title??`cover-${W.entity.id}`,alt:A.title??`cover-${W.entity.id}`,attachmentType:"generated",sourceEntityType:B,sourceEntityId:W.entity.id});let G=await $.jobs.enqueue({type:"image-generate",data:{prompt:w,...A.title&&{title:A.title},targetEntityType:B,targetEntityId:W.entity.id,entityTitle:typeof W.entity.metadata.title==="string"?W.entity.metadata.title:W.entity.id,...K&&{entityContent:K}}});return{kind:"handled",result:{success:!0,data:{entityId:U,status:"generating",jobId:G,attachment:p0A(U)}}}}async promoteUpload(A,Q){let $=A.from;if($?.kind!==bc.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let w=$.id,B;try{B=await Q.uploads.scoped(bc).readRecord(w)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}if(!wz0(B.mediaType))return{kind:"handled",result:{success:!1,error:"Only image uploads can be promoted to image entities"}};let X;try{X=Bz0({filename:B.filename,...A.title!==void 0?{title:A.title}:{}})}catch(Z){return{kind:"handled",result:{success:!1,error:Z instanceof Error?Z.message:String(Z)}}}await this.createPendingImage(Q,{id:X.id,title:X.title,alt:X.title,sourceUploadId:w,sourceFilename:B.filename,sourceMediaType:B.mediaType,attachmentType:"uploaded"});let Y=await Q.jobs.enqueue({type:"upload-promote",data:{uploadId:w,imageId:X.id,title:X.title}});return{kind:"handled",result:{success:!0,data:{entityId:X.id,status:"generating",jobId:Y,attachment:_16({mediaType:B.mediaType,entityId:X.id,filename:B.filename})}}}}async enqueueSourceImageRender(A,Q){let $=Y3(A.from.sourceEntityType),w=Y3(A.from.sourceEntityId),B=Y3(A.from.attachmentType);if(!$||!w||!B)return{kind:"handled",result:{success:!1,error:"Image source requires sourceEntityType, sourceEntityId, and attachmentType"}};let X=await UZ(Q.entityService,$,w,this.logger,"Source entity");if(!X.ok)return{kind:"handled",result:{success:!1,error:X.error}};let Y=Y3(A.targetEntityType),Z=Y3(A.targetEntityId),W;if(Y&&Z){let q=await UZ(Q.entityService,Y,Z,this.logger,"Target entity");if(!q.ok)return{kind:"handled",result:{success:!1,error:q.error}};W=q.entity.id}let K={sourceEntityType:$,sourceEntityId:X.entity.id,attachmentType:B},U=await N16(Q,K),G=L16(K);await this.createPendingImage(Q,{id:G,title:G,alt:G,sourceEntityType:K.sourceEntityType,sourceEntityId:K.sourceEntityId,attachmentType:B,dedupKey:U});let D=await Q.jobs.enqueue({type:"image-render-source",data:{...K,imageId:G,dedupKey:U,...A.replace===!0&&{replace:!0},...Y&&{targetEntityType:Y},...W&&{targetEntityId:W},...B==="og-image"&&{targetImageField:"ogImageId"}}});return{kind:"handled",result:{success:!0,data:{entityId:G,status:"generating",jobId:D,attachment:p0A(G,B)}}}}async createPendingImage(A,Q){let $=new Date().toISOString(),w=PU.createImageEntity({dataUrl:J16,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 Gv({entityService:A.entityService,entity:{id:Q.id,...w,created:$,updated:$}})}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 $z0(A,this.logger)}async onRegister(A){A.entities.registerUploadSaveHandler({entityType:this.entityType,mediaTypes:["image/*"],handler:async($)=>{let w=await this.promoteUpload({entityType:this.entityType,...$.title!==void 0?{title:$.title}:{},from:$.upload},A);return w.kind==="handled"?w.result:{success:!1,error:"Image upload save was not handled"}}});let Q=new $z0(A,this.logger);A.jobs.registerHandler("image-generate",Q),A.jobs.registerHandler("image-render-source",new u0A(A,this.logger)),A.jobs.registerHandler("upload-promote",new c0A(this.logger.child("UploadPromotionJobHandler"),A))}}function M10(A={}){return new l0A(A)}KA();import{StdioServerTransport as k16}from"@modelcontextprotocol/sdk/server/stdio.js";C0();var P16=H.custom((A)=>typeof A==="object"&&A!==null&&("info"in A)&&typeof A.info==="function"&&("debug"in A)&&typeof A.debug==="function"&&("error"in A)&&typeof A.error==="function"&&("warn"in A)&&typeof A.warn==="function");function TD1(){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 d0A(){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 Xz0(A){let Q=P16.safeParse(A);if(Q.success)return{info:($,...w)=>Q.data.info($,...w),debug:($,...w)=>Q.data.debug($,...w),error:($,...w)=>Q.data.error($,...w),warn:($,...w)=>Q.data.warn($,...w)};return d0A()}class Z3{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return Z3.instance??=new Z3(A),Z3.instance}static resetInstance(){if(Z3.instance)Z3.instance.stop(),Z3.instance=null}static createFresh(A){return new Z3(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?Xz0(this.config.logger):TD1()}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 k16,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 j16,timingSafeEqual as M16}from"crypto";import{WebStandardStreamableHTTPServerTransport as b16}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as O16}from"@modelcontextprotocol/sdk/types.js";C0();var f16=1800000,x16=60000,R16={"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"},v16=H.looseObject({code:H.string().optional()});function C16(A){let Q=new URL(A.url),w=A.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),B=A.headers.get("x-forwarded-host")??A.headers.get("host");if(!B)return Q.origin;return`${w??Q.protocol.replace(":","")}://${B}`}class Q_{static instance=null;transports={};sessionLastActivity=new Map;mcpServer=null;mcpTransport=null;server=null;boundPort=null;evictionTimer=null;config;logger;authConfig;sessionIdleTtlMs;constructor(A={}){if(this.config=A,this.logger=this.config.logger?Xz0(this.config.logger):d0A(),this.authConfig=A.auth??{},this.sessionIdleTtlMs=A.sessionIdleTtlMs??f16,this.evictionTimer=setInterval(()=>this.evictIdleSessions(),Math.min(this.sessionIdleTtlMs,x16)),this.evictionTimer.unref(),!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 Q_.instance??=new Q_(A),Q_.instance}static resetInstance(){Q_.instance=null}static createFresh(A){return new Q_(A)}withCors(A){let Q=new Headers(A.headers);for(let[$,w]of Object.entries(R16))Q.set($,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}createJsonResponse(A,Q=200){return this.withCors(new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json"}}))}createTextResponse(A,Q=200){return this.withCors(new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8"}}))}getAuthErrorResponse(A,Q=401,$){let w=this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},Q);if(!$)return w;let B=new Headers(w.headers);return B.set("WWW-Authenticate",$),new Response(w.body,{status:w.status,statusText:w.statusText,headers:B})}getBearerChallenge(A,Q={}){let $={...this.authConfig.token?{}:{resource_metadata:`${C16(A)}/.well-known/oauth-protected-resource`},...Q};return`Bearer ${Object.entries($).map(([B,X])=>`${B}="${h16(X)}"`).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 $=A.headers.get("authorization");if(!$?.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){let w=$.substring(7);if(!E16(w,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"),{token:w,clientId:"static-token-client",scopes:this.authConfig.requiredScopes??[],extra:{subject:"static-token-operator"}}}try{let w=await this.authConfig.verifyBearerToken?.(A);if(!w)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));let B=this.authConfig.requiredScopes??[],X=B.filter((Y)=>!w.scope?.includes(Y));if(X.length>0)return this.logger.warn(`Authentication failed: Missing required scope(s): ${X.join(", ")}`),this.getAuthErrorResponse("Forbidden: Missing required scope",403,this.getBearerChallenge(A,{error:"insufficient_scope",scope:B.join(" ")}));return this.logger.debug("Authentication successful"),{token:$.substring(7),clientId:w.subject,scopes:w.scope??[],extra:{subject:w.subject}}}catch(w){return this.logger.warn("Authentication failed: Invalid token",w),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}))}}touchSession(A){this.sessionLastActivity.set(A,Date.now())}evictIdleSessions(){let A=Date.now();for(let[Q,$]of this.sessionLastActivity){if(A-$<this.sessionIdleTtlMs)continue;this.logger.info(`Evicting idle session ${Q}`),this.sessionLastActivity.delete(Q);let w=this.transports[Q];if(w)delete this.transports[Q],w.close().catch((B)=>{this.logger.error(`Error closing idle transport for session ${Q}:`,B)})}}async handleMcpRequest(A,Q){let $=A.headers.get("mcp-session-id")??void 0;if(A.method==="GET"){if(!$||!this.transports[$])return this.createTextResponse("Invalid or missing session ID",400);return this.touchSession($),this.logger.debug(`GET /mcp - SSE stream for session ${$}`),this.withCors(await this.transports[$].handleRequest(A,{authInfo:Q}))}if(A.method==="DELETE"){if(!$||!this.transports[$])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.info(`DELETE /mcp - Terminating session ${$}`),this.withCors(await this.transports[$].handleRequest(A,{authInfo:Q}))}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;try{w=await A.json()}catch{return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32700,message:"Parse error: Invalid JSON body"},id:null},400)}this.logger.debug(`POST /mcp - Session: ${$??"new"}`);try{let B;if($&&this.transports[$])B=this.transports[$],this.touchSession($);else if(!$&&O16(w))B=new b16({sessionIdGenerator:()=>j16(),onsessioninitialized:(Y)=>{this.logger.info(`Session initialized: ${Y}`),this.transports[Y]=B,this.touchSession(Y)},onsessionclosed:(Y)=>{this.logger.info(`Session closed: ${Y}`),delete this.transports[Y],this.sessionLastActivity.delete(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,authInfo:Q}))}catch(B){return this.logger.error("MCP transport error:",B),this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}},500)}}async handleRequest(A){let Q=new URL(A.url);this.logger.debug(`${A.method} ${Q.pathname}`);let $=await this.authenticate(A);if($ instanceof Response)return $;let w=$??void 0;if(Q.pathname==="/health")return this.createJsonResponse({status:"ok",transport:"streamable-http",timestamp:new Date().toISOString()});if(Q.pathname==="/status")return this.createJsonResponse({status:"ok",sessions:Object.keys(this.transports).length});if(Q.pathname==="/mcp")return this.handleMcpRequest(A,w);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")}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:($)=>this.handleRequest($)}),this.boundPort=this.server.port??A,this.logger.info(`StreamableHTTP server listening on http://${Q}:${this.boundPort}/mcp`)}catch($){let w=v16.safeParse($);if(w.success&&w.data.code==="EADDRINUSE")this.logger.error(`Port ${A} is already in use`);throw $}}async stop(){if(this.evictionTimer)clearInterval(this.evictionTimer),this.evictionTimer=null;this.sessionLastActivity.clear();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 h16(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}function E16(A,Q){let $=Buffer.from(A),w=Buffer.from(Q);if($.length!==w.length)return!1;return M16($,w)}import{randomUUID as c16}from"crypto";import{chmod as T16,mkdir as y16,readFile as g16,rename as yD1,writeFile as S16}from"fs/promises";import{dirname as m16}from"path";class EH{filePath;parse;empty;logError;onCorrupt;writeQueue=Promise.resolve();constructor(A){this.filePath=A.filePath,this.parse=A.parse,this.empty=A.empty,this.onCorrupt=A.onCorrupt??"quarantine",this.logError=A.logError??((Q,$)=>{console.error(Q,$)})}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async read(){let A;try{A=await g16(this.filePath,"utf8")}catch(Q){if(Q.code==="ENOENT")return this.empty();throw Q}try{return this.parse(JSON.parse(A))}catch(Q){if(this.onCorrupt==="throw")throw Error(`Corrupt JSON store at ${this.filePath}; refusing to start empty. Inspect or remove the file to proceed.`,{cause:Q});return await this.quarantineCorruptFile(Q),this.empty()}}async write(A){await y16(m16(this.filePath),{recursive:!0,mode:448});let Q=`${this.filePath}.tmp`;await S16(Q,`${JSON.stringify(A,null,2)}
1750
+ ${U}`,U16);K=`${w.trim()} ${P.imagePrompt}`}catch(P){this.logger.warn("AI prompt distillation failed, using fallback",{error:aA(P)})}}await this.reportProgress($,{progress:T6.PROCESS,message:"Generating image"});let G=this.context.identity.get(),D=this.context.identity.getProfile(),J=vD1(G,D)+K,F;try{F=await this.context.ai.generateImage(J,{...B&&{aspectRatio:B}})}catch(P){return this.logger.error("Image generation failed",{jobId:Q,error:aA(P)}),y5.failure(P)}await this.reportProgress($,{progress:T6.GENERATE,message:"Creating image entity"});let I=PU.createImageEntity({dataUrl:F.dataUrl,title:Z,status:"draft",attachmentType:"generated",...X&&{sourceEntityType:X},...Y&&{sourceEntityId:Y}});if(await OH({entityService:this.context.entityService,entity:{...I,id:W}}),this.logger.debug("Created image entity",{imageId:W}),X&&Y){await this.reportProgress($,{progress:T6.SAVE,message:`Updating ${X} with cover image`});let P=await Kv(this.context.entityService,X,Y,this.logger);if(!P)return y5.failure(Error(`Target entity not found: ${X}/${Y}`));let j=pv(P,W);await this.context.entities.update(j),this.logger.debug("Updated target entity with cover image",{targetEntityType:X,targetEntityId:Y,imageId:W})}return await this.reportProgress($,{progress:T6.COMPLETE,message:"Image generation complete"}),this.logger.info("Image generation job complete",{jobId:Q,imageId:W,targetEntityType:X,targetEntityId:Y}),{success:!0,imageId:W}}catch(K){let U=aA(K);return this.logger.error("Image generation job failed",{jobId:Q,error:U}),await xJ({entityService:this.context.entityService,entityType:"image",id:W,error:U}),y5.failure(K)}}summarizeDataForLog(A){return{title:A.title,promptLength:A.prompt.length,aspectRatio:A.aspectRatio,targetEntityType:A.targetEntityType,targetEntityId:A.targetEntityId}}}KA();C0();e8();JZ();var D16=H.object({sourceEntityType:H.string().min(1),sourceEntityId:H.string().min(1),attachmentType:H.string().min(1),imageId:H.string().min(1),dedupKey:H.string().min(1).optional(),replace:H.boolean().optional(),targetEntityType:H.string().min(1).optional(),targetEntityId:H.string().min(1).optional(),targetImageField:H.enum(["coverImageId","ogImageId"]).optional()});class u0A extends X8{context;constructor(A,Q){super(Q,{schema:D16,jobTypeName:"image-render-source"});this.context=A}async process(A,Q,$){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 Y=await this.findImageByDedupKey(A.dedupKey);if(Y)return await this.updateTarget(A,Y.id),await this.reportProgress($,{progress:T6.COMPLETE,message:"Reusing existing generated image"}),{success:!0,imageId:Y.id,reused:!0}}await this.reportProgress($,{progress:T6.PROCESS,message:"Rendering source image"});let w=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!w)return y5.failure(Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`));if(w.type!=="image")return y5.failure(Error(`Attachment provider returned ${w.type}; expected image`));await this.reportProgress($,{progress:T6.GENERATE,message:"Creating image entity"});let B=w.mimeType.split("/")[1]??"png",X=PU.createImageEntity({dataUrl:Zt0(w.data.toString("base64"),B),title:A.imageId,status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,...A.dedupKey&&{dedupKey:A.dedupKey}});return await OH({entityService:this.context.entityService,entity:{...X,id:A.imageId}}),await this.updateTarget(A,A.imageId),await this.reportProgress($,{progress:T6.COMPLETE,message:"Image render complete"}),{success:!0,imageId:A.imageId,reused:!1}}catch(w){let B=aA(w);return this.logger.error("Source image render job failed",{jobId:Q,error:B}),await xJ({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:B}),y5.failure(w)}}async findImageByDedupKey(A){return(await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{dedupKey:A}}}})).find(($)=>$.metadata.status!=="pending"&&$.metadata.status!=="failed")}async updateTarget(A,Q){if(!A.targetEntityType||!A.targetEntityId)return;let $=await Kv(this.context.entityService,A.targetEntityType,A.targetEntityId,this.logger);if(!$)throw Error(`Target entity not found: ${A.targetEntityType}/${A.targetEntityId}`);let B=(A.targetImageField??"coverImageId")==="ogImageId"?kA0($,Q):pv($,Q);await this.context.entities.update(B)}}KA();C0();e8();JZ();S2();var bc={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function wz0(A){return["image/png","image/jpeg","image/webp","image/gif"].includes(A.toLowerCase())}function Bz0(A){let Q=q16(A.title,A.filename),$=k1(Q);if(!$)throw Error("Could not derive an image id from the uploaded filename. Provide a title.");return{id:$,title:Q}}function CD1(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function q16(A,Q){let $=A?.trim();if($)return $;return Q.replace(/\.[^.]+$/,"").trim()||Q}var z16=H.object({uploadId:H.string().min(1),imageId:H.string().min(1).optional(),title:H.string().optional()});class c0A extends X8{context;constructor(A,Q){super(A,{schema:z16,jobTypeName:"upload-promote"});this.context=Q}async process(A,Q,$){try{await this.reportProgress($,{progress:10,message:"Reading uploaded image"});let w=await this.context.uploads.scoped(bc).read(A.uploadId);if(!wz0(w.record.mediaType))throw Error("Only image uploads can be promoted to image entities");let B=Bz0({filename:w.record.filename,...A.title!==void 0?{title:A.title}:{}}),X=A.imageId??B.id;await this.reportProgress($,{progress:60,message:"Saving uploaded image"});let Y=new Date().toISOString(),Z=PU.createImageEntity({dataUrl:CD1(w.record.mediaType,w.content),title:B.title,status:"draft",sourceUploadId:A.uploadId,sourceFilename:w.record.filename,sourceMediaType:w.record.mediaType,attachmentType:"uploaded"}),W=await OH({entityService:this.context.entityService,entity:{id:X,...Z,created:Y,updated:Y}});return await this.reportProgress($,{progress:100,message:"Uploaded image promoted"}),{entityId:W.entityId,status:"created"}}catch(w){if(A.imageId)await xJ({entityService:this.context.entityService,entityType:"image",id:A.imageId,error:aA(w)});return y5.failure(w)}}summarizeDataForLog(A){return{uploadId:A.uploadId,imageId:A.imageId,hasTitle:A.title!==void 0}}}var hD1={name:"@brains/image-plugin",version:"0.2.0-alpha.184",description:"Plugin for AI-powered image generation and management",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":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},main:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var J16="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",F16=H.object({defaultAspectRatio:H.enum(["1:1","16:9","9:16","4:3","3:4"]).default("16:9").describe("Default aspect ratio for generated images")});function Y3(A){let Q=A?.trim();if(!Q)return;return Q}function I16(A){let Q=Y3(A.prompt);if(Q)return Q;let $=Y3(A.content);if($&&!m0A($))return $;return}function L16(A){let Q=A.attachmentType==="og-image"?"og":A.attachmentType;return k1(`${Q}-${A.sourceEntityType}-${A.sourceEntityId}`)}function ED1(A){let Q=Y3(A.title)??(A.targetEntityId?`cover-${A.targetEntityId}`:A.prompt.slice(0,60).trim());return k1(Q)}async function N16(A,Q){let $=`${Q.attachmentType}:${Q.sourceEntityType}:${Q.sourceEntityId}:resolved-attachment`,w=await A.entityService.getEntity({entityType:Q.sourceEntityType,id:Q.sourceEntityId});return w?`${$}:${w.contentHash}`:$}function p0A(A,Q="generated"){let $=encodeURIComponent(A);return{mediaType:"image/png",url:`/api/chat/attachments/image?id=${$}`,downloadUrl:`/api/chat/attachments/image?id=${$}&download=1`,filename:`${A}.png`,source:{entityType:"image",entityId:A,attachmentType:Q}}}function _16(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 l0A extends S6{entityType=PU.entityType;schema=_A0;adapter=PU;constructor(A={}){super("image",hD1,A,F16)}getEntityTypeConfig(){return{embeddable:!1}}async interceptCreate(A,Q,$){if(A.from?.kind===bc.refKind)return this.promoteUpload(A,$);let w=I16(A),B=Y3(A.targetEntityType),X=Y3(A.targetEntityId),Y=B===this.entityType?X:void 0,Z=A.from;if(Z?.kind==="entity-attachment")return this.enqueueSourceImageRender({...A,from:Z},$);if(!B||!X||Y){if(!w)return{kind:"continue",input:A};let D=Y3(A.title)??Y,q=ED1({prompt:w,...D&&{title:D}});await this.createPendingImage($,{id:q,title:D??w.slice(0,60).trim(),alt:D??w.slice(0,60).trim(),attachmentType:"generated"});let J=await $.jobs.enqueue({type:"image-generate",data:{prompt:w,...D&&{title:D}}});return{kind:"handled",result:{success:!0,data:{entityId:q,status:"generating",jobId:J,attachment:p0A(q)}}}}let W=await UZ($.entityService,B,X,this.logger,"Target entity");if(!W.ok)return{kind:"handled",result:{success:!1,error:W.error}};if(!w)return{kind:"continue",input:{...A,targetEntityId:W.entity.id}};let K=Qz0(W.entity.content),U=ED1({prompt:w,...A.title&&{title:A.title},targetEntityId:W.entity.id});await this.createPendingImage($,{id:U,title:A.title??`cover-${W.entity.id}`,alt:A.title??`cover-${W.entity.id}`,attachmentType:"generated",sourceEntityType:B,sourceEntityId:W.entity.id});let G=await $.jobs.enqueue({type:"image-generate",data:{prompt:w,...A.title&&{title:A.title},targetEntityType:B,targetEntityId:W.entity.id,entityTitle:typeof W.entity.metadata.title==="string"?W.entity.metadata.title:W.entity.id,...K&&{entityContent:K}}});return{kind:"handled",result:{success:!0,data:{entityId:U,status:"generating",jobId:G,attachment:p0A(U)}}}}async promoteUpload(A,Q){let $=A.from;if($?.kind!==bc.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let w=$.id,B;try{B=await Q.uploads.scoped(bc).readRecord(w)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}if(!wz0(B.mediaType))return{kind:"handled",result:{success:!1,error:"Only image uploads can be promoted to image entities"}};let X;try{X=Bz0({filename:B.filename,...A.title!==void 0?{title:A.title}:{}})}catch(Z){return{kind:"handled",result:{success:!1,error:Z instanceof Error?Z.message:String(Z)}}}await this.createPendingImage(Q,{id:X.id,title:X.title,alt:X.title,sourceUploadId:w,sourceFilename:B.filename,sourceMediaType:B.mediaType,attachmentType:"uploaded"});let Y=await Q.jobs.enqueue({type:"upload-promote",data:{uploadId:w,imageId:X.id,title:X.title}});return{kind:"handled",result:{success:!0,data:{entityId:X.id,status:"generating",jobId:Y,attachment:_16({mediaType:B.mediaType,entityId:X.id,filename:B.filename})}}}}async enqueueSourceImageRender(A,Q){let $=Y3(A.from.sourceEntityType),w=Y3(A.from.sourceEntityId),B=Y3(A.from.attachmentType);if(!$||!w||!B)return{kind:"handled",result:{success:!1,error:"Image source requires sourceEntityType, sourceEntityId, and attachmentType"}};let X=await UZ(Q.entityService,$,w,this.logger,"Source entity");if(!X.ok)return{kind:"handled",result:{success:!1,error:X.error}};let Y=Y3(A.targetEntityType),Z=Y3(A.targetEntityId),W;if(Y&&Z){let q=await UZ(Q.entityService,Y,Z,this.logger,"Target entity");if(!q.ok)return{kind:"handled",result:{success:!1,error:q.error}};W=q.entity.id}let K={sourceEntityType:$,sourceEntityId:X.entity.id,attachmentType:B},U=await N16(Q,K),G=L16(K);await this.createPendingImage(Q,{id:G,title:G,alt:G,sourceEntityType:K.sourceEntityType,sourceEntityId:K.sourceEntityId,attachmentType:B,dedupKey:U});let D=await Q.jobs.enqueue({type:"image-render-source",data:{...K,imageId:G,dedupKey:U,...A.replace===!0&&{replace:!0},...Y&&{targetEntityType:Y},...W&&{targetEntityId:W},...B==="og-image"&&{targetImageField:"ogImageId"}}});return{kind:"handled",result:{success:!0,data:{entityId:G,status:"generating",jobId:D,attachment:p0A(G,B)}}}}async createPendingImage(A,Q){let $=new Date().toISOString(),w=PU.createImageEntity({dataUrl:J16,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 Gv({entityService:A.entityService,entity:{id:Q.id,...w,created:$,updated:$}})}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 $z0(A,this.logger)}async onRegister(A){A.entities.registerUploadSaveHandler({entityType:this.entityType,mediaTypes:["image/*"],handler:async($)=>{let w=await this.promoteUpload({entityType:this.entityType,...$.title!==void 0?{title:$.title}:{},from:$.upload},A);return w.kind==="handled"?w.result:{success:!1,error:"Image upload save was not handled"}}});let Q=new $z0(A,this.logger);A.jobs.registerHandler("image-generate",Q),A.jobs.registerHandler("image-render-source",new u0A(A,this.logger)),A.jobs.registerHandler("upload-promote",new c0A(this.logger.child("UploadPromotionJobHandler"),A))}}function M10(A={}){return new l0A(A)}KA();import{StdioServerTransport as k16}from"@modelcontextprotocol/sdk/server/stdio.js";C0();var P16=H.custom((A)=>typeof A==="object"&&A!==null&&("info"in A)&&typeof A.info==="function"&&("debug"in A)&&typeof A.debug==="function"&&("error"in A)&&typeof A.error==="function"&&("warn"in A)&&typeof A.warn==="function");function TD1(){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 d0A(){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 Xz0(A){let Q=P16.safeParse(A);if(Q.success)return{info:($,...w)=>Q.data.info($,...w),debug:($,...w)=>Q.data.debug($,...w),error:($,...w)=>Q.data.error($,...w),warn:($,...w)=>Q.data.warn($,...w)};return d0A()}class Z3{static instance=null;mcpServer=null;transport=null;config;logger;static getInstance(A){return Z3.instance??=new Z3(A),Z3.instance}static resetInstance(){if(Z3.instance)Z3.instance.stop(),Z3.instance=null}static createFresh(A){return new Z3(A)}constructor(A={}){this.config=A,this.logger=this.config.logger?Xz0(this.config.logger):TD1()}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 k16,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 j16,timingSafeEqual as M16}from"crypto";import{WebStandardStreamableHTTPServerTransport as b16}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{isInitializeRequest as O16}from"@modelcontextprotocol/sdk/types.js";C0();var f16=1800000,x16=60000,R16={"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"},v16=H.looseObject({code:H.string().optional()});function C16(A){let Q=new URL(A.url),w=A.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),B=A.headers.get("x-forwarded-host")??A.headers.get("host");if(!B)return Q.origin;return`${w??Q.protocol.replace(":","")}://${B}`}class Q_{static instance=null;transports={};sessionLastActivity=new Map;mcpServer=null;mcpTransport=null;server=null;boundPort=null;evictionTimer=null;config;logger;authConfig;sessionIdleTtlMs;constructor(A={}){if(this.config=A,this.logger=this.config.logger?Xz0(this.config.logger):d0A(),this.authConfig=A.auth??{},this.sessionIdleTtlMs=A.sessionIdleTtlMs??f16,this.evictionTimer=setInterval(()=>this.evictIdleSessions(),Math.min(this.sessionIdleTtlMs,x16)),this.evictionTimer.unref(),!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 Q_.instance??=new Q_(A),Q_.instance}static resetInstance(){Q_.instance=null}static createFresh(A){return new Q_(A)}withCors(A){let Q=new Headers(A.headers);for(let[$,w]of Object.entries(R16))Q.set($,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}createJsonResponse(A,Q=200){return this.withCors(new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json"}}))}createTextResponse(A,Q=200){return this.withCors(new Response(A,{status:Q,headers:{"Content-Type":"text/plain; charset=utf-8"}}))}getAuthErrorResponse(A,Q=401,$){let w=this.createJsonResponse({jsonrpc:"2.0",error:{code:-32001,message:A},id:null},Q);if(!$)return w;let B=new Headers(w.headers);return B.set("WWW-Authenticate",$),new Response(w.body,{status:w.status,statusText:w.statusText,headers:B})}getBearerChallenge(A,Q={}){let $={...this.authConfig.token?{}:{resource_metadata:`${C16(A)}/.well-known/oauth-protected-resource`},...Q};return`Bearer ${Object.entries($).map(([B,X])=>`${B}="${h16(X)}"`).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 $=A.headers.get("authorization");if(!$?.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){let w=$.substring(7);if(!E16(w,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"),{token:w,clientId:"static-token-client",scopes:this.authConfig.requiredScopes??[],extra:{subject:"static-token-operator"}}}try{let w=await this.authConfig.verifyBearerToken?.(A);if(!w)return this.logger.warn("Authentication failed: Invalid token"),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}));let B=this.authConfig.requiredScopes??[],X=B.filter((Y)=>!w.scope?.includes(Y));if(X.length>0)return this.logger.warn(`Authentication failed: Missing required scope(s): ${X.join(", ")}`),this.getAuthErrorResponse("Forbidden: Missing required scope",403,this.getBearerChallenge(A,{error:"insufficient_scope",scope:B.join(" ")}));return this.logger.debug("Authentication successful"),{token:$.substring(7),clientId:w.subject,scopes:w.scope??[],extra:{subject:w.subject}}}catch(w){return this.logger.warn("Authentication failed: Invalid token",w),this.getAuthErrorResponse("Unauthorized: Invalid token",401,this.getBearerChallenge(A,{error:"invalid_token"}))}}touchSession(A){this.sessionLastActivity.set(A,Date.now())}evictIdleSessions(){let A=Date.now();for(let[Q,$]of this.sessionLastActivity){if(A-$<this.sessionIdleTtlMs)continue;this.logger.info(`Evicting idle session ${Q}`),this.sessionLastActivity.delete(Q);let w=this.transports[Q];if(w)delete this.transports[Q],w.close().catch((B)=>{this.logger.error(`Error closing idle transport for session ${Q}:`,B)})}}async handleMcpRequest(A,Q){let $=A.headers.get("mcp-session-id")??void 0;if(A.method==="GET"){if(!$||!this.transports[$])return this.createTextResponse("Invalid or missing session ID",400);return this.touchSession($),this.logger.debug(`GET /mcp - SSE stream for session ${$}`),this.withCors(await this.transports[$].handleRequest(A,{authInfo:Q}))}if(A.method==="DELETE"){if(!$||!this.transports[$])return this.createTextResponse("Invalid or missing session ID",400);return this.logger.info(`DELETE /mcp - Terminating session ${$}`),this.withCors(await this.transports[$].handleRequest(A,{authInfo:Q}))}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;try{w=await A.json()}catch{return this.createJsonResponse({jsonrpc:"2.0",error:{code:-32700,message:"Parse error: Invalid JSON body"},id:null},400)}this.logger.debug(`POST /mcp - Session: ${$??"new"}`);try{let B;if($&&this.transports[$])B=this.transports[$],this.touchSession($);else if(!$&&O16(w))B=new b16({sessionIdGenerator:()=>j16(),onsessioninitialized:(Y)=>{this.logger.info(`Session initialized: ${Y}`),this.transports[Y]=B,this.touchSession(Y)},onsessionclosed:(Y)=>{this.logger.info(`Session closed: ${Y}`),delete this.transports[Y],this.sessionLastActivity.delete(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,authInfo:Q}))}catch(B){return this.logger.error("MCP transport error:",B),this.createJsonResponse({jsonrpc:"2.0",error:{code:-32603,message:"Internal error"}},500)}}async handleRequest(A){let Q=new URL(A.url);this.logger.debug(`${A.method} ${Q.pathname}`);let $=await this.authenticate(A);if($ instanceof Response)return $;let w=$??void 0;if(Q.pathname==="/health")return this.createJsonResponse({status:"ok",transport:"streamable-http",timestamp:new Date().toISOString()});if(Q.pathname==="/status")return this.createJsonResponse({status:"ok",sessions:Object.keys(this.transports).length});if(Q.pathname==="/mcp")return this.handleMcpRequest(A,w);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")}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:($)=>this.handleRequest($)}),this.boundPort=this.server.port??A,this.logger.info(`StreamableHTTP server listening on http://${Q}:${this.boundPort}/mcp`)}catch($){let w=v16.safeParse($);if(w.success&&w.data.code==="EADDRINUSE")this.logger.error(`Port ${A} is already in use`);throw $}}async stop(){if(this.evictionTimer)clearInterval(this.evictionTimer),this.evictionTimer=null;this.sessionLastActivity.clear();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 h16(A){return A.replace(/["\\]/g,(Q)=>`\\${Q}`)}function E16(A,Q){let $=Buffer.from(A),w=Buffer.from(Q);if($.length!==w.length)return!1;return M16($,w)}import{randomUUID as c16}from"crypto";import{chmod as T16,mkdir as y16,readFile as g16,rename as yD1,writeFile as S16}from"fs/promises";import{dirname as m16}from"path";class EH{filePath;parse;empty;logError;onCorrupt;writeQueue=Promise.resolve();constructor(A){this.filePath=A.filePath,this.parse=A.parse,this.empty=A.empty,this.onCorrupt=A.onCorrupt??"quarantine",this.logError=A.logError??((Q,$)=>{console.error(Q,$)})}async enqueueWrite(A){return this.writeQueue=this.writeQueue.then(A,A),this.writeQueue}async read(){let A;try{A=await g16(this.filePath,"utf8")}catch(Q){if(Q.code==="ENOENT")return this.empty();throw Q}try{return this.parse(JSON.parse(A))}catch(Q){if(this.onCorrupt==="throw")throw Error(`Corrupt JSON store at ${this.filePath}; refusing to start empty. Inspect or remove the file to proceed.`,{cause:Q});return await this.quarantineCorruptFile(Q),this.empty()}}async write(A){await y16(m16(this.filePath),{recursive:!0,mode:448});let Q=`${this.filePath}.tmp`;await S16(Q,`${JSON.stringify(A,null,2)}
1751
1751
  `,{mode:384}),await T16(Q,384),await yD1(Q,this.filePath)}async quarantineCorruptFile(A){let Q=`${this.filePath}.corrupt-${process.pid}`;this.logError(`Corrupt JSON store at ${this.filePath}; moving it to ${Q} and starting from an empty store`,A);try{await yD1(this.filePath,Q)}catch($){this.logError(`Failed to quarantine corrupt JSON store at ${this.filePath}`,$)}}}function Oc(A){let Q=A.toISOString();return Q.substring(0,Q.indexOf("T"))}function Yz0(){let A=new Date;return A.setDate(A.getDate()-1),A}function gD1(A){let Q=new Date;return Q.setDate(Q.getDate()-A),Q}function O4(){return Math.floor(Date.now()/1000)}C0();import{join as p16}from"path";function SD1(A){let Q=A.toLowerCase();return Q==="localhost"||Q==="[::1]"||Q==="::1"||Q.startsWith("127.")}function mD1(A){try{return new URL(A)}catch{return}}function i0A(A,Q){if(A===Q)return!0;let $=mD1(A),w=mD1(Q);if(!$||!w)return!1;if(!SD1($.hostname)||!SD1(w.hostname))return!1;return $.protocol===w.protocol&&$.port===w.port&&u16($.pathname,w.pathname)&&$.search===w.search&&$.hash===w.hash}function u16(A,Q){return A===Q||A===`${Q}/debug`||Q===`${A}/debug`}function n0A(A,Q){return A.some(($)=>i0A($,Q))}var l16="oauth-auth-codes.json",d16=600,i16=H.looseObject({code:H.string(),client_id:H.string(),redirect_uri:H.string(),code_challenge:H.string(),code_challenge_method:H.literal("S256"),scope:H.string().optional(),subject:H.string(),created_at:H.number(),expires_at:H.number(),consumed_at:H.number().optional()}).transform((A)=>({code:A.code,client_id:A.client_id,redirect_uri:A.redirect_uri,code_challenge:A.code_challenge,code_challenge_method:A.code_challenge_method,...A.scope!==void 0?{scope:A.scope}:{},subject:A.subject,created_at:A.created_at,expires_at:A.expires_at,...A.consumed_at!==void 0?{consumed_at:A.consumed_at}:{}})),n16=H.looseObject({codes:H.array(H.unknown()).optional()});function r16(A){let Q=n16.safeParse(A);if(!Q.success)return{codes:[]};return{codes:Q.data.codes?.flatMap(o16)??[]}}function o16(A){let Q=i16.safeParse(A);return Q.success?[Q.data]:[]}async function s16(A){let Q=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(A));return Buffer.from(Q).toString("base64url")}class Zz0{store;constructor(A){this.store=new EH({filePath:p16(A.storageDir,A.storeFile??l16),parse:r16,empty:()=>({codes:[]})})}async createCode(A){let Q=O4(),$={code:`ocd_${c16()}`,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+d16};return await this.store.enqueueWrite(async()=>{let w=await this.store.read();w.codes=w.codes.filter((B)=>B.expires_at>Q),w.codes.push($),await this.store.write(w)}),$}async consumeCode(A){let Q=O4(),$;if(await this.store.enqueueWrite(async()=>{let w=await this.store.read(),B=w.codes.findIndex((Z)=>Z.code===A.code),X=B>=0?w.codes[B]:void 0;if(!X)throw new H3("Authorization code not found");if(X.consumed_at!==void 0)throw new H3("Authorization code already consumed");if(X.expires_at<=Q)throw new H3("Authorization code expired");if(X.client_id!==A.clientId)throw new H3("Authorization code client mismatch");if(!i0A(X.redirect_uri,A.redirectUri))throw new H3("Authorization code redirect URI mismatch");let Y=await s16(A.codeVerifier);if(X.code_challenge!==Y)throw new H3("PKCE verification failed");$={...X,consumed_at:Q},w.codes[B]=$,await this.store.write(w)}),!$)throw new H3("Authorization code not consumed");return $}}class H3 extends Error{constructor(A){super(A);this.name="InvalidGrantError"}}import{randomUUID as uD1}from"crypto";C0();import{join as a16}from"path";var t16="oauth-clients.json",e16=H.enum(["none","client_secret_basic","client_secret_post"]),A26=H.object({redirect_uris:H.array(H.url()).min(1),token_endpoint_auth_method:e16.default("none"),grant_types:H.array(H.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),response_types:H.array(H.literal("code")).default(["code"]),scope:H.string().optional(),client_name:H.string().optional(),client_uri:H.url().optional(),logo_uri:H.url().optional(),contacts:H.array(H.string()).optional()}),Q26=H.looseObject({client_id:H.string(),client_id_issued_at:H.number(),redirect_uris:H.array(H.string()),token_endpoint_auth_method:H.string().optional(),grant_types:H.array(H.string()).optional(),response_types:H.array(H.string()).optional(),scope:H.string().optional(),client_name:H.string().optional(),client_uri:H.string().optional(),logo_uri:H.string().optional(),contacts:H.array(H.string()).optional(),client_secret:H.string().optional(),client_secret_expires_at:H.number().optional()}).transform((A)=>({client_id:A.client_id,client_id_issued_at:A.client_id_issued_at,redirect_uris:A.redirect_uris,token_endpoint_auth_method:A.token_endpoint_auth_method??"none",grant_types:A.grant_types??["authorization_code","refresh_token"],response_types:A.response_types??["code"],...A.scope!==void 0?{scope:A.scope}:{},...A.client_name!==void 0?{client_name:A.client_name}:{},...A.client_uri!==void 0?{client_uri:A.client_uri}:{},...A.logo_uri!==void 0?{logo_uri:A.logo_uri}:{},...A.contacts!==void 0?{contacts:A.contacts}:{},...A.client_secret!==void 0?{client_secret:A.client_secret}:{},...A.client_secret_expires_at!==void 0?{client_secret_expires_at:A.client_secret_expires_at}:{}})),$26=H.looseObject({clients:H.array(H.unknown()).optional()});function w26(){return`ocs_${uD1().replaceAll("-","")}`}function B26(A){let Q=$26.safeParse(A);if(!Q.success)return{clients:[]};return{clients:Q.data.clients?.flatMap(X26)??[]}}function X26(A){let Q=Q26.safeParse(A);return Q.success?[Q.data]:[]}class Hz0{store;constructor(A){this.store=new EH({filePath:a16(A.storageDir,A.storeFile??t16),parse:B26,empty:()=>({clients:[]})})}async registerClient(A){let Q=A26.safeParse(A);if(!Q.success)throw new b10(Q.error.message);let $=Q.data,w=O4(),B=`oc_${uD1()}`,X=$.token_endpoint_auth_method==="none",Y={client_id:B,client_id_issued_at:w,redirect_uris:$.redirect_uris,token_endpoint_auth_method:$.token_endpoint_auth_method,grant_types:$.grant_types,response_types:$.response_types,...$.scope?{scope:$.scope}:{},...$.client_name?{client_name:$.client_name}:{},...$.client_uri?{client_uri:$.client_uri}:{},...$.logo_uri?{logo_uri:$.logo_uri}:{},...$.contacts?{contacts:$.contacts}:{},...!X?{client_secret:w26(),client_secret_expires_at:0}:{}};return await this.store.enqueueWrite(async()=>{let Z=await this.store.read();Z.clients.push(Y),await this.store.write(Z)}),Y}async getClient(A){return(await this.store.read()).clients.find(($)=>$.client_id===A)}}class b10 extends Error{constructor(A){super(A);this.name="InvalidClientMetadataError"}}C0();import{createHash as cD1,generateKeyPairSync as Y26}from"crypto";import{mkdir as Z26,readFile as pD1,writeFile as H26,chmod as W26}from"fs/promises";import{dirname as K26,join as lD1}from"path";var U26="oauth-signing-key.jwk",G26="a2a-signing-key.jwk",dD1=H.object({kty:H.literal("EC"),crv:H.literal("P-256"),x:H.string(),y:H.string(),d:H.string(),kid:H.string().optional()}),iD1=H.object({kty:H.literal("OKP"),crv:H.literal("Ed25519"),x:H.string(),d:H.string(),kid:H.string().optional()});function D26(A){let Q=JSON.stringify({crv:A.crv,kty:A.kty,x:A.x,y:A.y});return cD1("sha256").update(Q).digest("base64url")}function q26(A){let Q=JSON.stringify({crv:A.crv,kty:A.kty,x:A.x});return cD1("sha256").update(Q).digest("base64url")}function z26(A){return{kty:"EC",crv:"P-256",x:A.x,y:A.y,kid:A.kid,use:"sig",alg:"ES256"}}function V26(A){return{kty:"OKP",crv:"Ed25519",x:A.x,kid:A.kid,use:"sig",alg:"EdDSA"}}async function J26(){let A=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),Q=dD1.safeParse(await crypto.subtle.exportKey("jwk",A.privateKey));if(!Q.success)throw Error("Generated OAuth signing key is not a P-256 private JWK");return nD1(Q.data)}function F26(){let{privateKey:A}=Y26("ed25519"),Q=iD1.safeParse(A.export({format:"jwk"}));if(!Q.success)throw Error("Generated A2A signing key is not an Ed25519 private JWK");return rD1(Q.data)}function nD1(A){return{kty:"EC",crv:"P-256",x:A.x,y:A.y,d:A.d,kid:A.kid??D26(A),use:"sig",alg:"ES256"}}function rD1(A){return{kty:"OKP",crv:"Ed25519",x:A.x,d:A.d,kid:A.kid??q26(A),use:"sig",alg:"EdDSA"}}class Wz0{keyFile;cachedKey;loadPromise;constructor(A){this.keyFile=lD1(A.storageDir,A.keyFile??U26)}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 J26();return await oD1(this.keyFile,Q),Q}async getPublicJwk(){return z26(await this.getPrivateJwk())}async readExistingKey(){try{let A=dD1.safeParse(JSON.parse(await pD1(this.keyFile,"utf8")));if(!A.success)throw Error(`OAuth signing key at ${this.keyFile} is not a private P-256 JWK`);return nD1(A.data)}catch(A){if(sD1(A))return;throw A}}}class r0A{keyFile;cachedKey;loadPromise;constructor(A){this.keyFile=lD1(A.storageDir,A.keyFile??G26)}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=F26();return await oD1(this.keyFile,Q),Q}async getPublicJwk(){return V26(await this.getPrivateJwk())}async readExistingKey(){try{let A=iD1.safeParse(JSON.parse(await pD1(this.keyFile,"utf8")));if(!A.success)throw Error(`A2A signing key at ${this.keyFile} is not a private Ed25519 JWK`);return rD1(A.data)}catch(A){if(sD1(A))return;throw A}}}async function oD1(A,Q){await Z26(K26(A),{recursive:!0,mode:448}),await H26(A,`${JSON.stringify(Q,null,2)}
1752
1752
  `,{mode:384}),await W26(A,384)}function sD1(A){return A instanceof Error&&"code"in A&&A.code==="ENOENT"}var U6={};N6(U6,{trimPadding:()=>tD1,toUTF8String:()=>b26,toBuffer:()=>P26,toBase64:()=>j26,isBase64URL:()=>f26,isBase64:()=>O26,fromUTF8String:()=>M26,fromBuffer:()=>k26});var aD1=(A)=>{let Q=typeof Uint8Array>"u"?[]:new Uint8Array(256),$=64;for(let w=0;w<64;w++)Q[A.charCodeAt(w)]=w;return Q},I26=aD1("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),L26=aD1("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),N26=/^[-A-Za-z0-9\-_]*$/,_26=/^[-A-Za-z0-9+/]*={0,3}$/,rJ={};rJ.toArrayBuffer=(A,Q)=>{let $=A.length,w=A.length*0.75,B,X=0,Y,Z,W,K;if(A[A.length-1]==="="){if(w--,A[A.length-2]==="=")w--}let U=new ArrayBuffer(w),G=new Uint8Array(U),D=Q?L26:I26;for(B=0;B<$;B+=4)Y=D[A.charCodeAt(B)],Z=D[A.charCodeAt(B+1)],W=D[A.charCodeAt(B+2)],K=D[A.charCodeAt(B+3)],G[X++]=Y<<2|Z>>4,G[X++]=(Z&15)<<4|W>>2,G[X++]=(W&3)<<6|K&63;return U};rJ.fromArrayBuffer=(A,Q)=>{let $=new Uint8Array(A),w,B="",X=$.length,Y=Q?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(w=0;w<X;w+=3)B+=Y[$[w]>>2],B+=Y[($[w]&3)<<4|$[w+1]>>4],B+=Y[($[w+1]&15)<<2|$[w+2]>>6],B+=Y[$[w+2]&63];let Z=X%3;if(Z===2)B=B.substring(0,B.length-1)+(Q?"":"=");else if(Z===1)B=B.substring(0,B.length-2)+(Q?"":"==");return B};rJ.toString=(A,Q)=>{return new TextDecoder().decode(rJ.toArrayBuffer(A,Q))};rJ.fromString=(A,Q)=>{return rJ.fromArrayBuffer(new TextEncoder().encode(A),Q)};rJ.validate=(A,Q)=>{if(!(typeof A==="string"||A instanceof String))return!1;try{return Q?N26.test(A):_26.test(A)}catch($){return!1}};rJ.base64=rJ;var $_=rJ;function P26(A,Q="base64url"){let $=$_.toArrayBuffer(A,Q==="base64url");return new Uint8Array($)}function k26(A,Q="base64url"){let $=new Uint8Array(A);return $_.fromArrayBuffer($.buffer,Q==="base64url")}function j26(A){let Q=$_.toArrayBuffer(A,!0);return $_.fromArrayBuffer(Q)}function M26(A){return $_.fromString(A,!0)}function b26(A){return $_.toString(A,!0)}function O26(A){return $_.validate(A,!1)}function f26(A){return A=tD1(A),$_.validate(A,!0)}function tD1(A){return A.replace(/=/g,"")}var TH={};N6(TH,{encode:()=>s26,decodeFirst:()=>o26});function fc(A,Q,$){if(Q<24)return[Q,1];let w=A.byteLength-$-1,B=new DataView(A.buffer,$+1),X,Y=0;switch(Q){case 24:{if(w>0)X=B.getUint8(0),Y=2;break}case 25:{if(w>1)X=B.getUint16(0,!1),Y=3;break}case 26:{if(w>3)X=B.getUint32(0,!1),Y=5;break}case 27:{if(w>7){let Z=B.getBigUint64(0,!1);if(Z>=24n&&Z<=Number.MAX_SAFE_INTEGER)return[Number(Z),9]}break}}if(X&&X>=24)return[X,Y];throw Error("Length not supported or not well formed")}var Kz0=0,O10=1,o0A=2,s0A=3,a0A=4,t0A=5,e0A=6,eD1=7;function oJ(A,Q){let $=A<<5;if(Q<0)throw Error("CBOR Data Item argument must not be negative");let w;if(typeof Q=="number"){if(!Number.isInteger(Q))throw Error("CBOR Data Item argument must be an integer");w=BigInt(Q)}else w=Q;if(A==O10){if(w==0n)throw Error("CBOR Data Item argument cannot be zero when negative");w=w-1n}if(w>18446744073709551615n)throw Error("CBOR number out of range");let B=new Uint8Array(8);if(new DataView(B.buffer).setBigUint64(0,w,!1),w<=23)return[$|B[7]];else if(w<=255)return[$|24,B[7]];else if(w<=65535)return[$|25,...B.slice(6)];else if(w<=4294967295)return[$|26,...B.slice(4)];else return[$|27,...B]}class Gz0{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 Aq1(A,Q,$){return fc(A,Q,$)}function x26(A,Q,$){let[w,B]=Aq1(A,Q,$);return[-w-1,B]}function Qq1(A,Q,$){let[w,B]=fc(A,Q,$),X=$+B;return[new Uint8Array(A.buffer.slice(X,X+w)),B+w]}var R26=new TextDecoder;function v26(A,Q,$){let[w,B]=Qq1(A,Q,$);return[R26.decode(w),B]}function C26(A,Q,$){if(Q===0)return[[],1];let[w,B]=fc(A,Q,$),X=B,Y=[];for(let Z=0;Z<w;Z++){if(A.byteLength-$-X<=0)throw Error("array is not supported or well formed");let[K,U]=WC(A,$+X);Y.push(K),X+=U}return[Y,X]}var Uz0="Map is not supported or well formed";function h26(A,Q,$){if(Q===0)return[new Map,1];let[w,B]=fc(A,Q,$),X=B,Y=new Map;for(let Z=0;Z<w;Z++){let W=A.byteLength-$-X;if(W<=0)throw Error(Uz0);let[K,U]=WC(A,$+X);if(X+=U,W-=U,W<=0)throw Error(Uz0);if(typeof K!=="string"&&typeof K!=="number")throw Error(Uz0);if(Y.has(K))throw Error(Uz0);let[G,D]=WC(A,$+X);X+=D,Y.set(K,G)}return[Y,X]}function E26(A,Q){if(Q+3>A.byteLength)throw Error("CBOR stream ended before end of Float 16");let $=A.getUint16(Q+1,!1);if($==31744)return[1/0,3];else if($==32256)return[NaN,3];else if($==64512)return[-1/0,3];throw Error("Float16 data is unsupported")}function T26(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 y26(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 g26(A,Q,$){let[w,B]=fc(A,Q,$),[X,Y]=WC(A,$+B);return[new Gz0(w,X),B+Y]}function WC(A,Q){if(Q>=A.byteLength)throw Error("CBOR stream ended before tag value");let $=A.getUint8(Q),w=$>>5,B=$&31;switch(w){case Kz0:return Aq1(A,B,Q);case O10:return x26(A,B,Q);case o0A:return Qq1(A,B,Q);case s0A:return v26(A,B,Q);case a0A:return C26(A,B,Q);case t0A:return h26(A,B,Q);case e0A:return g26(A,B,Q);case eD1:switch(B){case 20:return[!1,1];case 21:return[!0,1];case 22:return[null,1];case 23:return[void 0,1];case 25:return E26(A,Q);case 26:return T26(A,Q);case 27:return y26(A,Q)}}throw Error(`Unsupported or not well formed at ${Q}`)}function S26(A){if(A===!0)return 245;else if(A===!1)return 244;else if(A===null)return 246;return 247}function m26(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 u26(A){if(typeof A=="number"){if(Number.isSafeInteger(A))if(A<0)return oJ(O10,Math.abs(A));else return oJ(Kz0,A);return[m26(A)]}else if(A<0n)return oJ(O10,A*-1n);else return oJ(Kz0,A)}var c26=new TextEncoder;function p26(A,Q){Q.push(...oJ(s0A,A.length)),Q.push(c26.encode(A))}function l26(A,Q){Q.push(...oJ(o0A,A.length)),Q.push(A)}function d26(A,Q){Q.push(...oJ(a0A,A.length));for(let $ of A)f10($,Q)}function i26(A,Q){Q.push(new Uint8Array(oJ(t0A,A.size)));for(let[$,w]of A.entries())f10($,Q),f10(w,Q)}function n26(A,Q){Q.push(...oJ(e0A,A.tag)),f10(A.value,Q)}function f10(A,Q){if(typeof A=="boolean"||A===null||A==null){Q.push(S26(A));return}if(typeof A=="number"||typeof A=="bigint"){Q.push(...u26(A));return}if(typeof A=="string"){p26(A,Q);return}if(A instanceof Uint8Array){l26(A,Q);return}if(Array.isArray(A)){d26(A,Q);return}if(A instanceof Map){i26(A,Q);return}if(A instanceof Gz0){n26(A,Q);return}throw Error("Not implemented")}function AAA(A,Q){if(A.byteLength===0||A.byteLength<=Q||Q<0)throw Error("No data");if(A instanceof Uint8Array)return WC(new DataView(A.buffer),Q);else if(A instanceof ArrayBuffer)return WC(new DataView(A),Q);return WC(A,Q)}function QAA(A){let Q=[];f10(A,Q);let $=0;for(let X of Q)if(typeof X=="number")$+=1;else $+=X.length;let w=new Uint8Array($),B=0;for(let X of Q)if(typeof X=="number")w[B]=X,B+=1;else w.set(X,B),B+=X.length;return w}function o26(A){let Q=new Uint8Array(A),$=AAA(Q,0),[w]=$;return w}function s26(A){return QAA(A)}var aJ={};N6(aJ,{verify:()=>yJ1,getRandomValues:()=>Yq1,digest:()=>Xq1});function $q1(A){let Q=A.get(B6.kty);return $AA(Q)&&Q===jU.OKP}function yM(A){let Q=A.get(B6.kty);return $AA(Q)&&Q===jU.EC2}function xc(A){let Q=A.get(B6.kty);return $AA(Q)&&Q===jU.RSA}var B6;(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"})(B6||(B6={}));var jU;(function(A){A[A.OKP=1]="OKP",A[A.EC2=2]="EC2",A[A.RSA=3]="RSA"})(jU||(jU={}));function $AA(A){return Object.values(jU).indexOf(A)>=0}var LZ;(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"})(LZ||(LZ={}));function wq1(A){return Object.values(LZ).indexOf(A)>=0}var d6;(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"})(d6||(d6={}));function sJ(A){return Object.values(d6).indexOf(A)>=0}function gM(A){if([d6.RS1].indexOf(A)>=0)return"SHA-1";else if([d6.ES256,d6.PS256,d6.RS256].indexOf(A)>=0)return"SHA-256";else if([d6.ES384,d6.PS384,d6.RS384].indexOf(A)>=0)return"SHA-384";else if([d6.ES512,d6.PS512,d6.RS512,d6.EdDSA].indexOf(A)>=0)return"SHA-512";throw Error(`Could not map COSE alg value of ${A} to a WebCrypto alg`)}var x10=void 0;function aD(){return new Promise((Q,$)=>{if(x10)return Q(x10);let w=t26.stubThisGlobalThisCrypto();if(w)return x10=w,Q(x10);return $(new Bq1)})}class Bq1 extends Error{constructor(){super("An instance of the Crypto API could not be located");this.name="MissingWebCrypto"}}var t26={stubThisGlobalThisCrypto:()=>globalThis.crypto,setCachedCrypto:(A)=>{x10=A}};async function Xq1(A,Q){let $=await aD(),w=gM(Q),B=await $.subtle.digest(w,A);return new Uint8Array(B)}async function Yq1(A){return(await aD()).getRandomValues(A),A}async function Rc(A){let Q=await aD(),{keyData:$,algorithm:w}=A;return Q.subtle.importKey("jwk",$,w,!1,["verify"])}async function Dz0(A){let{cosePublicKey:Q,signature:$,data:w,shaHashOverride:B}=A,X=await aD(),Y=Q.get(B6.alg),Z=Q.get(B6.crv),W=Q.get(B6.x),K=Q.get(B6.y);if(!Y)throw Error("Public key was missing alg (EC2)");if(!Z)throw Error("Public key was missing crv (EC2)");if(!W)throw Error("Public key was missing x (EC2)");if(!K)throw Error("Public key was missing y (EC2)");let U;if(Z===LZ.P256)U="P-256";else if(Z===LZ.P384)U="P-384";else if(Z===LZ.P521)U="P-521";else throw Error(`Unexpected COSE crv value of ${Z} (EC2)`);let G={kty:"EC",crv:U,x:U6.fromBuffer(W),y:U6.fromBuffer(K),ext:!1},q=await Rc({keyData:G,algorithm:{name:"ECDSA",namedCurve:U}}),J=gM(Y);if(B)J=gM(B);let F={name:"ECDSA",hash:{name:J}};return X.subtle.verify(F,q,$,w)}function wAA(A){if([d6.EdDSA].indexOf(A)>=0)return"Ed25519";else if([d6.ES256,d6.ES384,d6.ES512,d6.ES256K].indexOf(A)>=0)return"ECDSA";else if([d6.RS256,d6.RS384,d6.RS512,d6.RS1].indexOf(A)>=0)return"RSASSA-PKCS1-v1_5";else if([d6.PS256,d6.PS384,d6.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 qz0(A){let{cosePublicKey:Q,signature:$,data:w,shaHashOverride:B}=A,X=await aD(),Y=Q.get(B6.alg),Z=Q.get(B6.n),W=Q.get(B6.e);if(!Y)throw Error("Public key was missing alg (RSA)");if(!sJ(Y))throw Error(`Public key had invalid alg ${Y} (RSA)`);if(!Z)throw Error("Public key was missing n (RSA)");if(!W)throw Error("Public key was missing e (RSA)");let K={kty:"RSA",alg:"",n:U6.fromBuffer(Z),e:U6.fromBuffer(W),ext:!1},U={name:wAA(Y),hash:{name:gM(Y)}},G={name:wAA(Y)};if(B)U.hash.name=gM(B);if(U.name==="RSASSA-PKCS1-v1_5"){if(U.hash.name==="SHA-256")K.alg="RS256";else if(U.hash.name==="SHA-384")K.alg="RS384";else if(U.hash.name==="SHA-512")K.alg="RS512";else if(U.hash.name==="SHA-1")K.alg="RS1"}else if(U.name==="RSA-PSS"){let q=0;if(U.hash.name==="SHA-256")K.alg="PS256",q=32;else if(U.hash.name==="SHA-384")K.alg="PS384",q=48;else if(U.hash.name==="SHA-512")K.alg="PS512",q=64;G.saltLength=q}else throw Error(`Unexpected RSA key algorithm ${Y} (${U.name})`);let D=await Rc({keyData:K,algorithm:U});return X.subtle.verify(G,D,$,w)}function zz0(A){let Q=ZQ.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 C7(A){let Q;if(typeof A==="string")if(U6.isBase64URL(A))Q=U6.toBase64(A);else if(U6.isBase64(A))Q=A;else throw Error("Certificate is not a valid base64 or base64url string");else Q=U6.fromBuffer(A,"base64");let $="";for(let w=0;w<Math.ceil(Q.length/64);w+=1){let B=64*w;$+=`${Q.substr(B,64)}
1753
1753
  `}return $=`-----BEGIN CERTIFICATE-----
@@ -2319,14 +2319,14 @@ ${P}`)}if(w!==void 0&&X?.algorithms!==void 0){let I=X.algorithms.map((P)=>P.alg)
2319
2319
  </form>
2320
2320
  </main>
2321
2321
  </body>
2322
- </html>`}function qQ0(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(FQA(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function GF(A){return A.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}import{randomUUID as j86}from"crypto";function sF1(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function k86(A){let Q=new Uint8Array(A);if(Q.length===64)return Q;if(Q[0]!==48)return Q;let $=2;if(Q[1]&&Q[1]>128)$+=Q[1]-128;if(Q[$]!==2)throw Error("Invalid DER ECDSA signature");let w=Q[$+1];if(w===void 0)throw Error("Invalid DER ECDSA signature");let B=$+2,X=Q.slice(B,B+w);if($=B+w,Q[$]!==2)throw Error("Invalid DER ECDSA signature");let Y=Q[$+1];if(Y===void 0)throw Error("Invalid DER ECDSA signature");let Z=$+2,W=Q.slice(Z,Z+Y);return new Uint8Array([...aF1(X),...aF1(W)])}function aF1(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 $=new Uint8Array(32);return $.set(Q,32-Q.length),$}async function LQA(A,Q){let $={typ:"JWT",alg:"ES256",kid:A.kid},w=`${sF1($)}.${sF1(Q)}`,B=await crypto.subtle.importKey("jwk",A,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),X=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},B,new TextEncoder().encode(w));return`${w}.${Buffer.from(k86(X)).toString("base64url")}`}var M86=600;class NQA{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 qQ0(A);let $=await this.validateAuthorizationRequest(new URL(A.url).searchParams);if(!$.success)return new Response($.error,{status:400});let w=this.createAuthorizationApprovalToken(Q,$.params);return rp(oF1($.params,w))}async handleAuthorizeApproval(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return qQ0(A);let $=await A.formData(),w=await this.validateAuthorizationRequest(new URLSearchParams(qQA($)));if(!w.success)return new Response(w.error,{status:400});let B=$.get("approval_token"),X=typeof B==="string"?B:void 0;if(!X||!this.consumeAuthorizationApprovalToken(X,Q,w.params))return new Response("Invalid authorization approval token",{status:400});let Y=await this.authCodeStore.createCode({clientId:w.params.clientId,redirectUri:w.params.redirectUri,codeChallenge:w.params.codeChallenge,...w.params.scope?{scope:w.params.scope}:{},subject:Q.subject}),Z=new URL(w.params.redirectUri);if(Z.searchParams.set("code",Y.code),w.params.state)Z.searchParams.set("state",w.params.state);return Response.redirect(Z.toString(),302)}createAuthorizationApprovalToken(A,Q){this.pruneExpiredAuthorizationApprovalTokens();let $=`oat_${j86()}`;return this.authorizationApprovalTokens.set($,{token:$,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)+M86}),$}consumeAuthorizationApprovalToken(A,Q,$){this.pruneExpiredAuthorizationApprovalTokens();let w=this.authorizationApprovalTokens.get(A);if(!w)return!1;return this.authorizationApprovalTokens.delete(A),w.sessionId===Q.id&&w.clientId===$.clientId&&w.redirectUri===$.redirectUri&&w.codeChallenge===$.codeChallenge&&w.scope===$.scope&&w.state===$.state}pruneExpiredAuthorizationApprovalTokens(){let A=Math.floor(Date.now()/1000);for(let[Q,$]of this.authorizationApprovalTokens.entries())if($.expiresAt<=A)this.authorizationApprovalTokens.delete(Q)}async validateAuthorizationRequest(A){let Q=A.get("response_type"),$=A.get("client_id"),w=A.get("redirect_uri"),B=A.get("code_challenge"),X=A.get("code_challenge_method"),Y=A.get("scope")??void 0,Z=A.get("state")??void 0;if(Q!=="code")return{success:!1,error:"Unsupported response_type"};if(!$)return{success:!1,error:"Missing client_id"};if(!w)return{success:!1,error:"Missing redirect_uri"};if(!B)return{success:!1,error:"Missing code_challenge"};if(X!=="S256")return{success:!1,error:"Unsupported code_challenge_method"};let W=await this.clientStore.getClient($);if(!W)return{success:!1,error:"Unknown client_id"};if(!n0A(W.redirect_uris,w))return{success:!1,error:"Unregistered redirect_uri"};let K=Y??W.scope;return{success:!0,params:{clientId:$,redirectUri:w,codeChallenge:B,...K?{scope:K}:{},...Z?{state:Z}:{},clientName:W.client_name??W.client_id}}}async handleClientRegistration(A){let Q;try{Q=await A.json()}catch{return dB("invalid_client_metadata","Request body must be JSON")}try{let $=await this.clientStore.registerClient(Q);return hU($,201)}catch($){if($ instanceof b10)return dB("invalid_client_metadata",$.message);throw $}}async handleTokenRequest(A,Q){let $=await DQA(A),w=$.get("grant_type"),B=VQA(A,$),X=B.clientId??$.get("client_id");if(B.error)return dB("invalid_client",B.error);if(!X)return dB("invalid_request","client_id is required");let Y=await this.clientStore.getClient(X),Z=zQA(Y,B);if(Z)return dB("invalid_client",Z);if(w==="authorization_code")return this.handleAuthorizationCodeGrant($,X,Q);if(w==="refresh_token")return this.handleRefreshTokenGrant($,X,Q);return dB("unsupported_grant_type","Only authorization_code and refresh_token are supported")}async handleAuthorizationCodeGrant(A,Q,$){let w=A.get("code"),B=A.get("redirect_uri"),X=A.get("code_verifier");if(!w||!B||!X)return dB("invalid_request","code, redirect_uri, and code_verifier are required");let Y=await this.clientStore.getClient(Q);if(!Y||!n0A(Y.redirect_uris,B))return dB("invalid_grant","Unregistered redirect_uri");try{let Z=await this.authCodeStore.consumeCode({code:w,clientId:Q,redirectUri:B,codeVerifier:X});return await this.createTokenResponse({issuer:$,clientId:Q,subject:Z.subject,...Z.scope?{scope:Z.scope}:{}})}catch(Z){if(Z instanceof H3)return dB("invalid_grant",Z.message);throw Z}}async handleRefreshTokenGrant(A,Q,$){let w=A.get("refresh_token");if(!w)return dB("invalid_request","refresh_token is required");try{let B=await this.refreshTokenStore.rotateToken(w,Q);return await this.createTokenResponse({issuer:$,clientId:Q,subject:B.consumed.subject,...B.consumed.scope?{scope:B.consumed.scope}:{},refreshToken:B.replacement.token})}catch(B){if(B instanceof j_)return dB("invalid_grant",B.message);throw B}}async createTokenResponse(A){let Q=Math.floor(Date.now()/1000),$=900,w=await LQA(await this.keyStore.getPrivateJwk(),{iss:A.issuer,sub:A.subject,aud:A.clientId,iat:Q,exp:Q+900,...A.scope?{scope:A.scope}:{}}),B=A.refreshToken??(await this.refreshTokenStore.issueToken({clientId:A.clientId,subject:A.subject,...A.scope?{scope:A.scope}:{}})).token;return hU({access_token:w,token_type:"Bearer",expires_in:900,...A.scope?{scope:A.scope}:{},refresh_token:B})}async handleRevokeRequest(A){let Q=await DQA(A),$=VQA(A,Q),w=$.clientId??Q.get("client_id")??void 0,B=Q.get("token");if($.error)return dB("invalid_client",$.error);if(!B)return dB("invalid_request","token is required");if(w){let X=await this.clientStore.getClient(w),Y=zQA(X,$);if(Y)return dB("invalid_client",Y)}return await this.refreshTokenStore.revokeToken(B,w),new Response(null,{status:200})}}class _QA{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 dB("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return dB("access_denied","Invalid setup token");let Q=await this.passkeyService.generateRegistrationOptions(r30(A));return hU(Q)}async handleRegistrationVerify(A){if(await this.passkeyService.hasCredentials())return dB("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return dB("access_denied","Invalid setup token");let Q=await this.passkeyService.verifyRegistrationResponse(await A.json(),r30(A));if(!Q.verified)return dB("access_denied","Passkey registration failed");await this.setupFlow.clearSetupState();let $=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:KQ0(A)});return hU({verified:!0},200,{"Set-Cookie":$.cookie})}async handleAuthenticationOptions(A){if(!await this.passkeyService.hasCredentials())return dB("access_denied","No passkey registered");let Q=await this.passkeyService.generateAuthenticationOptions(r30(A));return hU(Q)}async handleAuthenticationVerify(A){let Q=await this.passkeyService.verifyAuthenticationResponse(await A.json(),r30(A));if(!Q.verified)return dB("access_denied","Passkey authentication failed");let $=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:KQ0(A)});return hU({verified:!0},200,{"Set-Cookie":$.cookie})}}function r30(A){let Q=Gb(A),$=new URL(Q);return{origin:$.origin,rpID:$.hostname}}import{randomUUID as b86}from"crypto";var zQ0=86400;class PQA{setupStateStore;passkeyService;setupTokenTtlSeconds;setupToken;constructor(A){this.setupStateStore=A.setupStateStore,this.passkeyService=A.passkeyService,this.setupTokenTtlSeconds=A.setupTokenTtlSeconds??zQ0}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_${b86()}`,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 $=new URL(A.url);return($.searchParams.get("setup_token")??$.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 I3(A,`/setup?token=${encodeURIComponent(Q.token)}`)}async getOperatorSetupRequired(A){if(await this.passkeyService.hasCredentials())return;let Q=this.getValidSetupToken();if(!Q)return;return{setupUrl:I3(A,`/setup?token=${encodeURIComponent(Q.token)}`),expiresAt:Q.expiresAt,setupTokenId:n2A(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 rp(nF1(Q))}async hasSetupEmailDelivery(A,Q){return this.setupStateStore.hasDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,$={}){await this.setupStateStore.recordDelivery(A,Q,$)}}class o30{issuer;trustedIssuers;allowLocalhostIssuers;keyStore;a2aKeyStore;clientStore;authCodeStore;sessionStore;peerTrustStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;logger;constructor(A){this.issuer=F3(A.issuer),this.trustedIssuers=new Set([this.issuer,...(A.trustedIssuers??[]).map((Q)=>F3(Q))]),this.allowLocalhostIssuers=A.allowLocalhostIssuers??Ub(this.issuer),this.keyStore=new Wz0({storageDir:A.storageDir}),this.a2aKeyStore=new r0A({storageDir:A.storageDir}),this.clientStore=new Hz0({storageDir:A.storageDir}),this.authCodeStore=new Zz0({storageDir:A.storageDir}),this.sessionStore=new p30({storageDir:A.storageDir}),this.peerTrustStore=new S30({storageDir:A.storageDir}),this.passkeyService=new g30({storageDir:A.storageDir,...A.logger?{logger:A.logger}:{}}),this.setupFlow=new PQA({setupStateStore:new r2A({storageDir:A.storageDir}),passkeyService:this.passkeyService,setupTokenTtlSeconds:A.setupTokenTtlSeconds??zQ0}),this.oauthEndpoints=new NQA({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:new m30({storageDir:A.storageDir}),sessionStore:this.sessionStore,keyStore:this.keyStore}),this.webauthnEndpoints=new _QA({passkeyService:this.passkeyService,sessionStore:this.sessionStore,setupFlow:this.setupFlow}),this.logger=A.logger}getIssuer(){return this.issuer}async initialize(){if(await Promise.all([this.keyStore.getPrivateJwk(),this.a2aKeyStore.getPrivateJwk()]),this.logger?.debug("Auth service signing keys loaded"),!await this.hasPasskeyCredentials()){await this.setupFlow.ensureSetupToken();let A=this.getSetupUrl();if(A)if(Ub(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(){let[A,Q]=await Promise.all([this.keyStore.getPublicJwk(),this.a2aKeyStore.getPublicJwk()]);return{keys:[A,Q]}}async getA2ASigningKey(){let A=await this.a2aKeyStore.getPrivateJwk();return{privateJwk:A,keyId:I3(this.issuer,`/.well-known/jwks.json#${A.kid}`)}}grantA2APeerTrust(A){return this.peerTrustStore.grant(A)}getA2APeerTrust(A){return this.peerTrustStore.get(A)}revokeA2APeerTrust(A){return this.peerTrustStore.revoke(A)}getAuthorizationServerMetadata(A=this.issuer){let Q=F3(A);return{issuer:Q,authorization_endpoint:I3(Q,"/authorize"),token_endpoint:I3(Q,"/token"),registration_endpoint:I3(Q,"/register"),revocation_endpoint:I3(Q,"/revoke"),jwks_uri:I3(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:[F3(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 qQ0(A)}async verifyBearerToken(A,Q={}){let $=GQA(A);if(!$)return;let w=Q.issuer?F3(Q.issuer):this.resolveRequestIssuer(A);return UQA($,await this.getJwks(),{issuer:w,...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,$={}){await this.setupFlow.recordSetupEmailDelivery(A,Q,$)}async handleRequest(A){let Q;try{Q=this.resolveRequestIssuer(A)}catch(w){return this.logger?.warn("Rejected OAuth request from untrusted issuer",{error:w instanceof Error?w.message:String(w)}),new Response("Untrusted OAuth issuer",{status:400})}let $=new URL(A.url).pathname;if(A.method==="OPTIONS"&&lF1($))return dF1();if(A.method==="GET"){if($==="/.well-known/oauth-authorization-server")return Vb(hU(this.getAuthorizationServerMetadata(Q)));if($==="/.well-known/jwks.json")return Vb(hU(await this.getJwks()));if($==="/.well-known/oauth-protected-resource")return Vb(hU(this.getProtectedResourceMetadata(Q,Q)))}if(A.method==="GET"&&$==="/setup")return this.setupFlow.handleSetupPage(A);if(A.method==="GET"&&$==="/login")return this.handleLoginPage(A);if((A.method==="GET"||A.method==="POST")&&$==="/logout")return this.handleLogout(A);if(A.method==="POST"&&$==="/webauthn/register/options")return this.webauthnEndpoints.handleRegistrationOptions(A);if(A.method==="POST"&&$==="/webauthn/register/verify")return this.webauthnEndpoints.handleRegistrationVerify(A);if(A.method==="POST"&&$==="/webauthn/auth/options")return this.webauthnEndpoints.handleAuthenticationOptions(A);if(A.method==="POST"&&$==="/webauthn/auth/verify")return this.webauthnEndpoints.handleAuthenticationVerify(A);if(A.method==="GET"&&$==="/authorize")return this.oauthEndpoints.handleAuthorizePage(A);if(A.method==="POST"&&$==="/authorize")return this.oauthEndpoints.handleAuthorizeApproval(A);if(A.method==="POST"&&$==="/register")return Vb(await this.oauthEndpoints.handleClientRegistration(A));if(A.method==="POST"&&$==="/token")return Vb(await this.oauthEndpoints.handleTokenRequest(A,Q));if(A.method==="POST"&&$==="/revoke")return Vb(await this.oauthEndpoints.handleRevokeRequest(A));return new Response("Not Found",{status:404})}async handleWellKnownRequest(A){return this.handleRequest(A)}resolveRequestIssuer(A){let Q=Gb(A,this.issuer);if(this.trustedIssuers.has(Q)||this.allowLocalhostIssuers&&Ub(Q))return Q;throw Error(`Request issuer ${Q} is not in trusted issuers`)}handleLoginPage(A){let Q=JQA(new URL(A.url).searchParams.get("return_to"));return rp(FQA(Q))}async handleLogout(A){await this.sessionStore.revokeSessionFromRequest(A);let Q=JQA(new URL(A.url).searchParams.get("return_to"));return new Response(null,{status:302,headers:{Location:Q,"Set-Cookie":s2A(KQ0(A)),"Cache-Control":"no-store"}})}}qA0();KA();C0();var tF1={name:"@brains/auth-service",version:"0.2.0-alpha.183",description:"Embedded OAuth/OIDC auth service for brain operator authentication",dependencies:{"@brains/notification-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@simplewebauthn/server":"^13.3.1",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},files:["src"],main:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var f86=H.union([H.string().email(),H.object({to:H.string().email(),subject:H.string().min(1),body:H.string().min(1)}).strict()]),x86=H.object({issuer:H.string().optional(),trustedIssuers:H.array(H.string()).default([]),allowLocalhostIssuers:H.boolean().optional(),storageDir:H.string().default("./data/auth"),setupTokenTtlSeconds:H.number().int().positive().default(zQ0),setupEmail:f86.optional()}),s30;function UY(){return s30}class kQA extends p6{service;constructor(A={}){super("auth-service",tF1,A,x86)}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 o30({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(),s30=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(s30===this.service)s30=void 0;this.service=void 0}async getTools(){return[{name:`${this.id}_get_passkey_setup_url`,description:"Get the first-passkey setup URL when operator setup is required. Anchor-only.",inputSchema:{},visibility:"anchor",handler:async()=>{let A=this.getService();if(await A.hasPasskeyCredentials())return{success:!0,data:{status:"complete"}};let Q=await A.getOperatorSetupRequired();if(Q)return{success:!0,data:{status:"setup_required",setupUrl:Q.setupUrl,expiresAt:Q.expiresAt}};return{success:!0,data:{status:"unavailable",reason:"Passkey setup URL is not available."}}},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 $=await Q.getOperatorSetupRequired();if(!$)return;let w=R86(this.config.setupEmail,$);if(await Q.hasSetupEmailDelivery($.setupTokenId,w.to))return;let B=await A.messaging.send({type:gv,payload:{recipient:{type:"email",address:w.to},title:w.subject,body:w.body,sensitivity:"secret"}});if(!("success"in B)||!B.success||!B.data){A.logger.warn("Passkey setup email delivery was not confirmed");return}let X=DA0.safeParse(B.data);if(!X.success||X.data.status!=="sent"){A.logger.warn("Passkey setup email delivery was not confirmed");return}await Q.recordSetupEmailDelivery($.setupTokenId,w.to,X.data.deliveryId?{deliveryId:X.data.deliveryId}:{})}}function R86(A,Q){if(typeof A==="string"){let $=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return{to:A,subject:"Set up your brain passkey",body:["Set up your brain passkey using this single-use link:","",Q.setupUrl,"",`This link expires at ${$}.`,`Dashboard: ${w}/`,`MCP endpoint: ${w}/mcp`,"The first successful passkey registration completes setup and closes this link."].join(`
2323
- `)}}return{to:A.to,subject:eF1(A.subject,Q),body:eF1(A.body,Q)}}function eF1(A,Q){let $=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return A.replaceAll("{{setupUrl}}",Q.setupUrl).replaceAll("{{expiresAt}}",$).replaceAll("{{origin}}",w)}function VQ0(A={}){return new kQA(A)}C0();var jQA=H.object({transport:H.enum(["stdio","http"]).default("http"),mode:H.enum(["basic","debug"]).default("basic"),httpPort:H.number().describe("Port for HTTP transport (only used when transport is 'http')").default(3333),authToken:H.string().describe("Bearer token for HTTP transport authentication").optional(),sessionIdleTtlMs:H.number().describe("Idle time in ms after which an HTTP session is closed and evicted").default(1800000)});C0();import{createHash as E86,randomUUID as T86}from"crypto";function v86(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function JQ0(A,Q){let $=A?.[Q];return typeof $==="string"&&$.length>0?$:void 0}function C86(A){let Q=v86(A.data)?A.data:void 0,$=A.args,w=JQ0(Q,"entityId")??JQ0(Q,"id"),B=A.jobId??JQ0(Q,"jobId"),X=JQ0($,"entityType")??JQ0($,"type");if(!w&&!B)return;return{toolName:A.toolName,...X?{entityType:X}:{},...w?{entityId:w}:{},...B?{jobId:B}:{}}}function h86(A){return A?.map(C86).filter((Q)=>Q!==void 0)??[]}function MQA(A,Q={}){let $=A.pendingConfirmations?.[0];if($)return{needsConfirmation:!0,toolName:$.toolName,summary:$.summary,...$.completionSummary?{completionSummary:$.completionSummary}:{},...$.preview?{preview:$.preview}:{},args:{approvalId:$.id,...Q.conversationId?{conversationId:Q.conversationId}:{},...$.toolCallId?{toolCallId:$.toolCallId}:{},originalArgs:$.args}};let w=h86(A.toolResults);return{success:!0,data:{text:A.text,...Q.conversationId?{conversationId:Q.conversationId}:{},...A.toolResults?{toolResults:A.toolResults}:{},...w.length>0?{readYourWrites:w}:{}}}}var AI1=H.object({message:H.string().min(1),conversationId:H.string().min(1).optional().describe("Opaque conversation handle returned by a previous chat call. Omit it to start a new isolated conversation.")}),QI1=H.object({approvalId:H.string().min(1),confirmed:H.boolean(),conversationId:H.string().min(1).describe("Exact conversation handle returned by the chat confirmation.")});function $I1(A,Q,$,w){let B=A.conversationId??$??w??`conversation-${T86()}`,X=E86("sha256").update(Q).digest("hex").slice(0,16);return{handle:B,internalId:`mcp:${X}:${B}`}}function wI1(A){return{userPermissionLevel:A.userPermissionLevel??"public",interfaceType:"mcp",...A.channelId?{channelId:A.channelId}:{},...A.channelName?{channelName:A.channelName}:{},actor:{actorId:A.userId,interfaceType:"mcp",role:"user"}}}function BI1(A,Q){return[{name:"chat",description:"Talk to the brain to make changes or get reasoned answers. Use this for any create/update/delete request or questions requiring reasoning across content. For simple lookups, use search/get/list directly.",inputSchema:AI1.shape,visibility:"public",sideEffects:"writes",handler:async($,w)=>{let B=AI1.parse($),X=Q();if(!X)return{success:!1,error:"MCP chat tool is not initialized."};let Y=$I1(B,w.userId,w.conversationId,w.channelId),Z=wI1(w),W=w.signal?await X.agent.chat(B.message,Y.internalId,Z,w.signal):await X.agent.chat(B.message,Y.internalId,Z);return MQA(W,{conversationId:Y.handle})}},{name:"confirm",description:"Resolve a pending confirmation returned by chat. Use this only after chat returns needsConfirmation with an approvalId.",inputSchema:QI1.shape,visibility:"public",sideEffects:"writes",handler:async($,w)=>{let B=QI1.parse($),X=Q();if(!X)return{success:!1,error:"MCP confirm tool is not initialized."};let Y=$I1(B,w.userId,w.conversationId,w.channelId),Z=wI1(w),W=w.signal?await X.agent.confirmPendingAction(Y.internalId,B.confirmed,B.approvalId,Z,w.signal):await X.agent.confirmPendingAction(Y.internalId,B.confirmed,B.approvalId,Z);return MQA(W,{conversationId:Y.handle})}}]}KA();function bQA(A,Q){A.messaging.subscribe("job-progress",async($)=>{let w=bg.safeParse($.payload);if(!w.success)return Q.warn("Received invalid job-progress message",{error:w.error.message}),{success:!1};let B=w.data,X=B.type,Y=B.status,Z=B.id;if(Q.debug(`${X} ${Z} - ${Y}:`,{id:B.id,message:B.message,progress:B.progress,metadata:B.metadata}),B.batchDetails)Q.debug(`Batch details for ${Z}:`,{totalOperations:B.batchDetails.totalOperations,completedOperations:B.batchDetails.completedOperations,failedOperations:B.batchDetails.failedOperations,currentOperation:B.batchDetails.currentOperation,errors:B.batchDetails.errors});if(B.jobDetails)Q.debug(`Job details for ${Z}:`,{jobType:B.jobDetails.jobType,priority:B.jobDetails.priority,retryCount:B.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var XI1={name:"@brains/mcp",version:"0.2.0-alpha.183",dependencies:{"@brains/auth-service":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@modelcontextprotocol/sdk":"^1.29.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.3.14","@types/cors":"^2.8.17",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};class Jb extends RJ{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",XI1,Q,jQA)}async getTools(){return BI1(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"});bQA(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=UY();return this.httpServer=Q_.createFresh({port:this.config.httpPort,logger:this.logger,sessionIdleTtlMs:this.config.sessionIdleTtlMs,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,mode:this.config.mode,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",$=this.context.permissions.getUserLevel("mcp",Q),w=UY(),B=this.config.transport==="http"&&(this.config.authToken?!0:w!==void 0);if(B)$="anchor",this.logger.debug("HTTP authentication configured - authenticated users will have anchor permissions");if(this.config.mode==="debug"){if(this.config.transport==="http"&&!B)throw Error("MCP debug mode requires authenticated HTTP transport; configure authToken or OAuth auth service.");if($!=="anchor")throw Error("MCP debug mode requires anchor permissions.")}if(this.mcpTransport.setProtocolMode(this.config.mode),this.mcpTransport.setPermissionLevel($),this.logger.debug(`Starting MCP ${this.config.transport} transport in ${this.config.mode} mode with ${$} permissions`),this.config.transport==="stdio"){this.stdioServer=Z3.createFresh();let X=this.mcpTransport.getMcpServer();this.stdioServer.connectMCPServer(X),await this.stdioServer.start(),this.logger.debug("MCP STDIO transport started")}else{this.httpServer=this.getOrCreateHttpServer();let X=this.mcpTransport.getMcpServer();this.httpServer.connectMCPServer(X,this.mcpTransport),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(){Z3.resetInstance(),Q_.resetInstance()}}KA();function FQ0(A,Q=2000){if(A.length<=Q)return[A];let $=m86(A),w=[],B="";for(let X of $){let Y=B?`
2322
+ </html>`}function qQ0(A){let Q=`${new URL(A.url).pathname}${new URL(A.url).search}`;return new Response(FQA(Q,"Operator login required"),{status:401,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}function GF(A){return A.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}import{randomUUID as j86}from"crypto";function sF1(A){return Buffer.from(JSON.stringify(A)).toString("base64url")}function k86(A){let Q=new Uint8Array(A);if(Q.length===64)return Q;if(Q[0]!==48)return Q;let $=2;if(Q[1]&&Q[1]>128)$+=Q[1]-128;if(Q[$]!==2)throw Error("Invalid DER ECDSA signature");let w=Q[$+1];if(w===void 0)throw Error("Invalid DER ECDSA signature");let B=$+2,X=Q.slice(B,B+w);if($=B+w,Q[$]!==2)throw Error("Invalid DER ECDSA signature");let Y=Q[$+1];if(Y===void 0)throw Error("Invalid DER ECDSA signature");let Z=$+2,W=Q.slice(Z,Z+Y);return new Uint8Array([...aF1(X),...aF1(W)])}function aF1(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 $=new Uint8Array(32);return $.set(Q,32-Q.length),$}async function LQA(A,Q){let $={typ:"JWT",alg:"ES256",kid:A.kid},w=`${sF1($)}.${sF1(Q)}`,B=await crypto.subtle.importKey("jwk",A,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),X=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},B,new TextEncoder().encode(w));return`${w}.${Buffer.from(k86(X)).toString("base64url")}`}var M86=600;class NQA{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 qQ0(A);let $=await this.validateAuthorizationRequest(new URL(A.url).searchParams);if(!$.success)return new Response($.error,{status:400});let w=this.createAuthorizationApprovalToken(Q,$.params);return rp(oF1($.params,w))}async handleAuthorizeApproval(A){let Q=await this.sessionStore.getSessionFromRequest(A);if(!Q)return qQ0(A);let $=await A.formData(),w=await this.validateAuthorizationRequest(new URLSearchParams(qQA($)));if(!w.success)return new Response(w.error,{status:400});let B=$.get("approval_token"),X=typeof B==="string"?B:void 0;if(!X||!this.consumeAuthorizationApprovalToken(X,Q,w.params))return new Response("Invalid authorization approval token",{status:400});let Y=await this.authCodeStore.createCode({clientId:w.params.clientId,redirectUri:w.params.redirectUri,codeChallenge:w.params.codeChallenge,...w.params.scope?{scope:w.params.scope}:{},subject:Q.subject}),Z=new URL(w.params.redirectUri);if(Z.searchParams.set("code",Y.code),w.params.state)Z.searchParams.set("state",w.params.state);return Response.redirect(Z.toString(),302)}createAuthorizationApprovalToken(A,Q){this.pruneExpiredAuthorizationApprovalTokens();let $=`oat_${j86()}`;return this.authorizationApprovalTokens.set($,{token:$,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)+M86}),$}consumeAuthorizationApprovalToken(A,Q,$){this.pruneExpiredAuthorizationApprovalTokens();let w=this.authorizationApprovalTokens.get(A);if(!w)return!1;return this.authorizationApprovalTokens.delete(A),w.sessionId===Q.id&&w.clientId===$.clientId&&w.redirectUri===$.redirectUri&&w.codeChallenge===$.codeChallenge&&w.scope===$.scope&&w.state===$.state}pruneExpiredAuthorizationApprovalTokens(){let A=Math.floor(Date.now()/1000);for(let[Q,$]of this.authorizationApprovalTokens.entries())if($.expiresAt<=A)this.authorizationApprovalTokens.delete(Q)}async validateAuthorizationRequest(A){let Q=A.get("response_type"),$=A.get("client_id"),w=A.get("redirect_uri"),B=A.get("code_challenge"),X=A.get("code_challenge_method"),Y=A.get("scope")??void 0,Z=A.get("state")??void 0;if(Q!=="code")return{success:!1,error:"Unsupported response_type"};if(!$)return{success:!1,error:"Missing client_id"};if(!w)return{success:!1,error:"Missing redirect_uri"};if(!B)return{success:!1,error:"Missing code_challenge"};if(X!=="S256")return{success:!1,error:"Unsupported code_challenge_method"};let W=await this.clientStore.getClient($);if(!W)return{success:!1,error:"Unknown client_id"};if(!n0A(W.redirect_uris,w))return{success:!1,error:"Unregistered redirect_uri"};let K=Y??W.scope;return{success:!0,params:{clientId:$,redirectUri:w,codeChallenge:B,...K?{scope:K}:{},...Z?{state:Z}:{},clientName:W.client_name??W.client_id}}}async handleClientRegistration(A){let Q;try{Q=await A.json()}catch{return dB("invalid_client_metadata","Request body must be JSON")}try{let $=await this.clientStore.registerClient(Q);return hU($,201)}catch($){if($ instanceof b10)return dB("invalid_client_metadata",$.message);throw $}}async handleTokenRequest(A,Q){let $=await DQA(A),w=$.get("grant_type"),B=VQA(A,$),X=B.clientId??$.get("client_id");if(B.error)return dB("invalid_client",B.error);if(!X)return dB("invalid_request","client_id is required");let Y=await this.clientStore.getClient(X),Z=zQA(Y,B);if(Z)return dB("invalid_client",Z);if(w==="authorization_code")return this.handleAuthorizationCodeGrant($,X,Q);if(w==="refresh_token")return this.handleRefreshTokenGrant($,X,Q);return dB("unsupported_grant_type","Only authorization_code and refresh_token are supported")}async handleAuthorizationCodeGrant(A,Q,$){let w=A.get("code"),B=A.get("redirect_uri"),X=A.get("code_verifier");if(!w||!B||!X)return dB("invalid_request","code, redirect_uri, and code_verifier are required");let Y=await this.clientStore.getClient(Q);if(!Y||!n0A(Y.redirect_uris,B))return dB("invalid_grant","Unregistered redirect_uri");try{let Z=await this.authCodeStore.consumeCode({code:w,clientId:Q,redirectUri:B,codeVerifier:X});return await this.createTokenResponse({issuer:$,clientId:Q,subject:Z.subject,...Z.scope?{scope:Z.scope}:{}})}catch(Z){if(Z instanceof H3)return dB("invalid_grant",Z.message);throw Z}}async handleRefreshTokenGrant(A,Q,$){let w=A.get("refresh_token");if(!w)return dB("invalid_request","refresh_token is required");try{let B=await this.refreshTokenStore.rotateToken(w,Q);return await this.createTokenResponse({issuer:$,clientId:Q,subject:B.consumed.subject,...B.consumed.scope?{scope:B.consumed.scope}:{},refreshToken:B.replacement.token})}catch(B){if(B instanceof j_)return dB("invalid_grant",B.message);throw B}}async createTokenResponse(A){let Q=Math.floor(Date.now()/1000),$=900,w=await LQA(await this.keyStore.getPrivateJwk(),{iss:A.issuer,sub:A.subject,aud:A.clientId,iat:Q,exp:Q+900,...A.scope?{scope:A.scope}:{}}),B=A.refreshToken??(await this.refreshTokenStore.issueToken({clientId:A.clientId,subject:A.subject,...A.scope?{scope:A.scope}:{}})).token;return hU({access_token:w,token_type:"Bearer",expires_in:900,...A.scope?{scope:A.scope}:{},refresh_token:B})}async handleRevokeRequest(A){let Q=await DQA(A),$=VQA(A,Q),w=$.clientId??Q.get("client_id")??void 0,B=Q.get("token");if($.error)return dB("invalid_client",$.error);if(!B)return dB("invalid_request","token is required");if(w){let X=await this.clientStore.getClient(w),Y=zQA(X,$);if(Y)return dB("invalid_client",Y)}return await this.refreshTokenStore.revokeToken(B,w),new Response(null,{status:200})}}class _QA{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 dB("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return dB("access_denied","Invalid setup token");let Q=await this.passkeyService.generateRegistrationOptions(r30(A));return hU(Q)}async handleRegistrationVerify(A){if(await this.passkeyService.hasCredentials())return dB("access_denied","Passkey setup already completed");if(!this.setupFlow.hasValidSetupToken(A))return dB("access_denied","Invalid setup token");let Q=await this.passkeyService.verifyRegistrationResponse(await A.json(),r30(A));if(!Q.verified)return dB("access_denied","Passkey registration failed");await this.setupFlow.clearSetupState();let $=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:KQ0(A)});return hU({verified:!0},200,{"Set-Cookie":$.cookie})}async handleAuthenticationOptions(A){if(!await this.passkeyService.hasCredentials())return dB("access_denied","No passkey registered");let Q=await this.passkeyService.generateAuthenticationOptions(r30(A));return hU(Q)}async handleAuthenticationVerify(A){let Q=await this.passkeyService.verifyAuthenticationResponse(await A.json(),r30(A));if(!Q.verified)return dB("access_denied","Passkey authentication failed");let $=await this.sessionStore.createSession(Q.subject??"single-operator",{secure:KQ0(A)});return hU({verified:!0},200,{"Set-Cookie":$.cookie})}}function r30(A){let Q=Gb(A),$=new URL(Q);return{origin:$.origin,rpID:$.hostname}}import{randomUUID as b86}from"crypto";var zQ0=86400;class PQA{setupStateStore;passkeyService;setupTokenTtlSeconds;setupToken;constructor(A){this.setupStateStore=A.setupStateStore,this.passkeyService=A.passkeyService,this.setupTokenTtlSeconds=A.setupTokenTtlSeconds??zQ0}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_${b86()}`,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 $=new URL(A.url);return($.searchParams.get("setup_token")??$.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 I3(A,`/setup?token=${encodeURIComponent(Q.token)}`)}async getOperatorSetupRequired(A){if(await this.passkeyService.hasCredentials())return;let Q=this.getValidSetupToken();if(!Q)return;return{setupUrl:I3(A,`/setup?token=${encodeURIComponent(Q.token)}`),expiresAt:Q.expiresAt,setupTokenId:n2A(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 rp(nF1(Q))}async hasSetupEmailDelivery(A,Q){return this.setupStateStore.hasDelivery(A,Q)}async recordSetupEmailDelivery(A,Q,$={}){await this.setupStateStore.recordDelivery(A,Q,$)}}class o30{issuer;trustedIssuers;allowLocalhostIssuers;keyStore;a2aKeyStore;clientStore;authCodeStore;sessionStore;peerTrustStore;passkeyService;setupFlow;oauthEndpoints;webauthnEndpoints;logger;constructor(A){this.issuer=F3(A.issuer),this.trustedIssuers=new Set([this.issuer,...(A.trustedIssuers??[]).map((Q)=>F3(Q))]),this.allowLocalhostIssuers=A.allowLocalhostIssuers??Ub(this.issuer),this.keyStore=new Wz0({storageDir:A.storageDir}),this.a2aKeyStore=new r0A({storageDir:A.storageDir}),this.clientStore=new Hz0({storageDir:A.storageDir}),this.authCodeStore=new Zz0({storageDir:A.storageDir}),this.sessionStore=new p30({storageDir:A.storageDir}),this.peerTrustStore=new S30({storageDir:A.storageDir}),this.passkeyService=new g30({storageDir:A.storageDir,...A.logger?{logger:A.logger}:{}}),this.setupFlow=new PQA({setupStateStore:new r2A({storageDir:A.storageDir}),passkeyService:this.passkeyService,setupTokenTtlSeconds:A.setupTokenTtlSeconds??zQ0}),this.oauthEndpoints=new NQA({clientStore:this.clientStore,authCodeStore:this.authCodeStore,refreshTokenStore:new m30({storageDir:A.storageDir}),sessionStore:this.sessionStore,keyStore:this.keyStore}),this.webauthnEndpoints=new _QA({passkeyService:this.passkeyService,sessionStore:this.sessionStore,setupFlow:this.setupFlow}),this.logger=A.logger}getIssuer(){return this.issuer}async initialize(){if(await Promise.all([this.keyStore.getPrivateJwk(),this.a2aKeyStore.getPrivateJwk()]),this.logger?.debug("Auth service signing keys loaded"),!await this.hasPasskeyCredentials()){await this.setupFlow.ensureSetupToken();let A=this.getSetupUrl();if(A)if(Ub(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(){let[A,Q]=await Promise.all([this.keyStore.getPublicJwk(),this.a2aKeyStore.getPublicJwk()]);return{keys:[A,Q]}}async getA2ASigningKey(){let A=await this.a2aKeyStore.getPrivateJwk();return{privateJwk:A,keyId:I3(this.issuer,`/.well-known/jwks.json#${A.kid}`)}}grantA2APeerTrust(A){return this.peerTrustStore.grant(A)}getA2APeerTrust(A){return this.peerTrustStore.get(A)}revokeA2APeerTrust(A){return this.peerTrustStore.revoke(A)}getAuthorizationServerMetadata(A=this.issuer){let Q=F3(A);return{issuer:Q,authorization_endpoint:I3(Q,"/authorize"),token_endpoint:I3(Q,"/token"),registration_endpoint:I3(Q,"/register"),revocation_endpoint:I3(Q,"/revoke"),jwks_uri:I3(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:[F3(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 qQ0(A)}async verifyBearerToken(A,Q={}){let $=GQA(A);if(!$)return;let w=Q.issuer?F3(Q.issuer):this.resolveRequestIssuer(A);return UQA($,await this.getJwks(),{issuer:w,...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,$={}){await this.setupFlow.recordSetupEmailDelivery(A,Q,$)}async handleRequest(A){let Q;try{Q=this.resolveRequestIssuer(A)}catch(w){return this.logger?.warn("Rejected OAuth request from untrusted issuer",{error:w instanceof Error?w.message:String(w)}),new Response("Untrusted OAuth issuer",{status:400})}let $=new URL(A.url).pathname;if(A.method==="OPTIONS"&&lF1($))return dF1();if(A.method==="GET"){if($==="/.well-known/oauth-authorization-server")return Vb(hU(this.getAuthorizationServerMetadata(Q)));if($==="/.well-known/jwks.json")return Vb(hU(await this.getJwks()));if($==="/.well-known/oauth-protected-resource")return Vb(hU(this.getProtectedResourceMetadata(Q,Q)))}if(A.method==="GET"&&$==="/setup")return this.setupFlow.handleSetupPage(A);if(A.method==="GET"&&$==="/login")return this.handleLoginPage(A);if((A.method==="GET"||A.method==="POST")&&$==="/logout")return this.handleLogout(A);if(A.method==="POST"&&$==="/webauthn/register/options")return this.webauthnEndpoints.handleRegistrationOptions(A);if(A.method==="POST"&&$==="/webauthn/register/verify")return this.webauthnEndpoints.handleRegistrationVerify(A);if(A.method==="POST"&&$==="/webauthn/auth/options")return this.webauthnEndpoints.handleAuthenticationOptions(A);if(A.method==="POST"&&$==="/webauthn/auth/verify")return this.webauthnEndpoints.handleAuthenticationVerify(A);if(A.method==="GET"&&$==="/authorize")return this.oauthEndpoints.handleAuthorizePage(A);if(A.method==="POST"&&$==="/authorize")return this.oauthEndpoints.handleAuthorizeApproval(A);if(A.method==="POST"&&$==="/register")return Vb(await this.oauthEndpoints.handleClientRegistration(A));if(A.method==="POST"&&$==="/token")return Vb(await this.oauthEndpoints.handleTokenRequest(A,Q));if(A.method==="POST"&&$==="/revoke")return Vb(await this.oauthEndpoints.handleRevokeRequest(A));return new Response("Not Found",{status:404})}async handleWellKnownRequest(A){return this.handleRequest(A)}resolveRequestIssuer(A){let Q=Gb(A,this.issuer);if(this.trustedIssuers.has(Q)||this.allowLocalhostIssuers&&Ub(Q))return Q;throw Error(`Request issuer ${Q} is not in trusted issuers`)}handleLoginPage(A){let Q=JQA(new URL(A.url).searchParams.get("return_to"));return rp(FQA(Q))}async handleLogout(A){await this.sessionStore.revokeSessionFromRequest(A);let Q=JQA(new URL(A.url).searchParams.get("return_to"));return new Response(null,{status:302,headers:{Location:Q,"Set-Cookie":s2A(KQ0(A)),"Cache-Control":"no-store"}})}}qA0();KA();C0();var tF1={name:"@brains/auth-service",version:"0.2.0-alpha.184",description:"Embedded OAuth/OIDC auth service for brain operator authentication",dependencies:{"@brains/notification-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@simplewebauthn/server":"^13.3.1",jose:"^6.2.3"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},files:["src"],main:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var f86=H.union([H.string().email(),H.object({to:H.string().email(),subject:H.string().min(1),body:H.string().min(1)}).strict()]),x86=H.object({issuer:H.string().optional(),trustedIssuers:H.array(H.string()).default([]),allowLocalhostIssuers:H.boolean().optional(),storageDir:H.string().default("./data/auth"),setupTokenTtlSeconds:H.number().int().positive().default(zQ0),setupEmail:f86.optional()}),s30;function UY(){return s30}class kQA extends p6{service;constructor(A={}){super("auth-service",tF1,A,x86)}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 o30({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(),s30=this.service}async onReady(A){await this.requestSetupEmailIfNeeded(A)}async onShutdown(){if(s30===this.service)s30=void 0;this.service=void 0}async getTools(){return[{name:`${this.id}_get_passkey_setup_url`,description:"Get the first-passkey setup URL when operator setup is required. Anchor-only.",inputSchema:{},visibility:"anchor",handler:async()=>{let A=this.getService();if(await A.hasPasskeyCredentials())return{success:!0,data:{status:"complete"}};let Q=await A.getOperatorSetupRequired();if(Q)return{success:!0,data:{status:"setup_required",setupUrl:Q.setupUrl,expiresAt:Q.expiresAt}};return{success:!0,data:{status:"unavailable",reason:"Passkey setup URL is not available."}}},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 $=await Q.getOperatorSetupRequired();if(!$)return;let w=R86(this.config.setupEmail,$);if(await Q.hasSetupEmailDelivery($.setupTokenId,w.to))return;let B=await A.messaging.send({type:gv,payload:{recipient:{type:"email",address:w.to},title:w.subject,body:w.body,sensitivity:"secret"}});if(!("success"in B)||!B.success||!B.data){A.logger.warn("Passkey setup email delivery was not confirmed");return}let X=DA0.safeParse(B.data);if(!X.success||X.data.status!=="sent"){A.logger.warn("Passkey setup email delivery was not confirmed");return}await Q.recordSetupEmailDelivery($.setupTokenId,w.to,X.data.deliveryId?{deliveryId:X.data.deliveryId}:{})}}function R86(A,Q){if(typeof A==="string"){let $=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return{to:A,subject:"Set up your brain passkey",body:["Set up your brain passkey using this single-use link:","",Q.setupUrl,"",`This link expires at ${$}.`,`Dashboard: ${w}/`,`MCP endpoint: ${w}/mcp`,"The first successful passkey registration completes setup and closes this link."].join(`
2323
+ `)}}return{to:A.to,subject:eF1(A.subject,Q),body:eF1(A.body,Q)}}function eF1(A,Q){let $=new Date(Q.expiresAt*1000).toISOString(),w=new URL(Q.setupUrl).origin;return A.replaceAll("{{setupUrl}}",Q.setupUrl).replaceAll("{{expiresAt}}",$).replaceAll("{{origin}}",w)}function VQ0(A={}){return new kQA(A)}C0();var jQA=H.object({transport:H.enum(["stdio","http"]).default("http"),mode:H.enum(["basic","debug"]).default("basic"),httpPort:H.number().describe("Port for HTTP transport (only used when transport is 'http')").default(3333),authToken:H.string().describe("Bearer token for HTTP transport authentication").optional(),sessionIdleTtlMs:H.number().describe("Idle time in ms after which an HTTP session is closed and evicted").default(1800000)});C0();import{createHash as E86,randomUUID as T86}from"crypto";function v86(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}function JQ0(A,Q){let $=A?.[Q];return typeof $==="string"&&$.length>0?$:void 0}function C86(A){let Q=v86(A.data)?A.data:void 0,$=A.args,w=JQ0(Q,"entityId")??JQ0(Q,"id"),B=A.jobId??JQ0(Q,"jobId"),X=JQ0($,"entityType")??JQ0($,"type");if(!w&&!B)return;return{toolName:A.toolName,...X?{entityType:X}:{},...w?{entityId:w}:{},...B?{jobId:B}:{}}}function h86(A){return A?.map(C86).filter((Q)=>Q!==void 0)??[]}function MQA(A,Q={}){let $=A.pendingConfirmations?.[0];if($)return{needsConfirmation:!0,toolName:$.toolName,summary:$.summary,...$.completionSummary?{completionSummary:$.completionSummary}:{},...$.preview?{preview:$.preview}:{},args:{approvalId:$.id,...Q.conversationId?{conversationId:Q.conversationId}:{},...$.toolCallId?{toolCallId:$.toolCallId}:{},originalArgs:$.args}};let w=h86(A.toolResults);return{success:!0,data:{text:A.text,...Q.conversationId?{conversationId:Q.conversationId}:{},...A.toolResults?{toolResults:A.toolResults}:{},...w.length>0?{readYourWrites:w}:{}}}}var AI1=H.object({message:H.string().min(1),conversationId:H.string().min(1).optional().describe("Opaque conversation handle returned by a previous chat call. Omit it to start a new isolated conversation.")}),QI1=H.object({approvalId:H.string().min(1),confirmed:H.boolean(),conversationId:H.string().min(1).describe("Exact conversation handle returned by the chat confirmation.")});function $I1(A,Q,$,w){let B=A.conversationId??$??w??`conversation-${T86()}`,X=E86("sha256").update(Q).digest("hex").slice(0,16);return{handle:B,internalId:`mcp:${X}:${B}`}}function wI1(A){return{userPermissionLevel:A.userPermissionLevel??"public",interfaceType:"mcp",...A.channelId?{channelId:A.channelId}:{},...A.channelName?{channelName:A.channelName}:{},actor:{actorId:A.userId,interfaceType:"mcp",role:"user"}}}function BI1(A,Q){return[{name:"chat",description:"Talk to the brain to make changes or get reasoned answers. Use this for any create/update/delete request or questions requiring reasoning across content. For simple lookups, use search/get/list directly.",inputSchema:AI1.shape,visibility:"public",sideEffects:"writes",handler:async($,w)=>{let B=AI1.parse($),X=Q();if(!X)return{success:!1,error:"MCP chat tool is not initialized."};let Y=$I1(B,w.userId,w.conversationId,w.channelId),Z=wI1(w),W=w.signal?await X.agent.chat(B.message,Y.internalId,Z,w.signal):await X.agent.chat(B.message,Y.internalId,Z);return MQA(W,{conversationId:Y.handle})}},{name:"confirm",description:"Resolve a pending confirmation returned by chat. Use this only after chat returns needsConfirmation with an approvalId.",inputSchema:QI1.shape,visibility:"public",sideEffects:"writes",handler:async($,w)=>{let B=QI1.parse($),X=Q();if(!X)return{success:!1,error:"MCP confirm tool is not initialized."};let Y=$I1(B,w.userId,w.conversationId,w.channelId),Z=wI1(w),W=w.signal?await X.agent.confirmPendingAction(Y.internalId,B.confirmed,B.approvalId,Z,w.signal):await X.agent.confirmPendingAction(Y.internalId,B.confirmed,B.approvalId,Z);return MQA(W,{conversationId:Y.handle})}}]}KA();function bQA(A,Q){A.messaging.subscribe("job-progress",async($)=>{let w=bg.safeParse($.payload);if(!w.success)return Q.warn("Received invalid job-progress message",{error:w.error.message}),{success:!1};let B=w.data,X=B.type,Y=B.status,Z=B.id;if(Q.debug(`${X} ${Z} - ${Y}:`,{id:B.id,message:B.message,progress:B.progress,metadata:B.metadata}),B.batchDetails)Q.debug(`Batch details for ${Z}:`,{totalOperations:B.batchDetails.totalOperations,completedOperations:B.batchDetails.completedOperations,failedOperations:B.batchDetails.failedOperations,currentOperation:B.batchDetails.currentOperation,errors:B.batchDetails.errors});if(B.jobDetails)Q.debug(`Job details for ${Z}:`,{jobType:B.jobDetails.jobType,priority:B.jobDetails.priority,retryCount:B.jobDetails.retryCount});return{success:!0}}),Q.debug("Subscribed to job progress events")}var XI1={name:"@brains/mcp",version:"0.2.0-alpha.184",dependencies:{"@brains/auth-service":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@modelcontextprotocol/sdk":"^1.29.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.3.14","@types/cors":"^2.8.17",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};class Jb extends RJ{mcpTransport;stdioServer;httpServer;domain;constructor(A={}){let Q={...A,authToken:A.authToken??process.env.MCP_AUTH_TOKEN};super("mcp",XI1,Q,jQA)}async getTools(){return BI1(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"});bQA(A,this.logger)}getOrCreateHttpServer(){if(this.httpServer)return this.httpServer;let A=UY();return this.httpServer=Q_.createFresh({port:this.config.httpPort,logger:this.logger,sessionIdleTtlMs:this.config.sessionIdleTtlMs,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,mode:this.config.mode,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",$=this.context.permissions.getUserLevel("mcp",Q),w=UY(),B=this.config.transport==="http"&&(this.config.authToken?!0:w!==void 0);if(B)$="anchor",this.logger.debug("HTTP authentication configured - authenticated users will have anchor permissions");if(this.config.mode==="debug"){if(this.config.transport==="http"&&!B)throw Error("MCP debug mode requires authenticated HTTP transport; configure authToken or OAuth auth service.");if($!=="anchor")throw Error("MCP debug mode requires anchor permissions.")}if(this.mcpTransport.setProtocolMode(this.config.mode),this.mcpTransport.setPermissionLevel($),this.logger.debug(`Starting MCP ${this.config.transport} transport in ${this.config.mode} mode with ${$} permissions`),this.config.transport==="stdio"){this.stdioServer=Z3.createFresh();let X=this.mcpTransport.getMcpServer();this.stdioServer.connectMCPServer(X),await this.stdioServer.start(),this.logger.debug("MCP STDIO transport started")}else{this.httpServer=this.getOrCreateHttpServer();let X=this.mcpTransport.getMcpServer();this.httpServer.connectMCPServer(X,this.mcpTransport),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(){Z3.resetInstance(),Q_.resetInstance()}}KA();function FQ0(A,Q=2000){if(A.length<=Q)return[A];let $=m86(A),w=[],B="";for(let X of $){let Y=B?`
2324
2324
 
2325
2325
  `:"";if(B.length+Y.length+X.length<=Q){B+=Y+X;continue}if(B)w.push(B),B="";if(X.length<=Q){B=X;continue}g86(X,Q,w,(Z)=>{B=Z})}if(B)w.push(B);return w}function g86(A,Q,$,w){let B="",X=A.split(`
2326
2326
  `);for(let Y of X){let Z=B?`
2327
2327
  `:"";if(B.length+Z.length+Y.length<=Q){B+=Z+Y;continue}if(B)$.push(B),B="";if(Y.length<=Q){B=Y;continue}S86(Y,Q,$,(W)=>{B=W})}w(B)}function S86(A,Q,$,w){let B="",X=A.split(" ");for(let Y of X){let Z=B?" ":"";if(B.length+Z.length+Y.length<=Q){B+=Z+Y;continue}if(B)$.push(B);if(Y.length>Q)for(let W=0;W<Y.length;W+=Q){let K=Y.slice(W,W+Q);if(W+Q>=Y.length)B=K;else $.push(K)}else B=Y}w(B)}function m86(A){let Q=[],$=A.split(`
2328
2328
  `),w="",B=!1;for(let X of $){if(X.startsWith("```"))B=!B;if(!B&&X===""&&w){Q.push(w),w="";continue}w+=(w?`
2329
- `:"")+X}if(w)Q.push(w);return Q}S2();var pU=P1(p9A(),1);KA();C0();var l9A=H.object({botToken:H.string().min(1).describe("Discord bot token"),allowedChannels:H.array(H.string()).default([]),requireMention:H.boolean().default(!0),allowDMs:H.boolean().default(!0),showTypingIndicator:H.boolean().default(!0),statusMessage:H.string().default("Mention me to chat"),useThreads:H.boolean().default(!0),threadAutoArchive:H.union([H.literal(60),H.literal(1440),H.literal(4320),H.literal(10080)]).default(1440),...de.shape,captureUrlEmoji:H.string().default("\uD83D\uDD16")});var Jw2={name:"@brains/discord",version:"0.2.0-alpha.183",description:"Discord interface for Brains",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","discord.js":"^14.26.4"},devDependencies:{"@brains/core":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var w$0=2000,zu6={completed:"Action completed",declined:"Action declined",failed:"Action failed"},Vu6={completed:2278750,declined:9741240,failed:15680580},Ju6=8388608,Fu6=8000,Iu6=100;function VI0(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class $O extends mz{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",Jw2,A,l9A);this.fetchText=Q.fetchText??WY1}async onRegister(A){await super.onRegister(A),this.client=new pU.Client({intents:[pU.GatewayIntentBits.Guilds,pU.GatewayIntentBits.GuildMessages,pU.GatewayIntentBits.MessageContent,pU.GatewayIntentBits.DirectMessages],partials:[pU.Partials.Channel]}),this.client.on(pU.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.on(pU.Events.InteractionCreate,(Q)=>{this.handleInteraction(Q)}),this.client.once(pU.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 $=this.client.channels.cache.get(A);if(!VI0($))return;let w=FQ0(Q,w$0);for(let B of w)$.send(B).catch((X)=>this.logger.error("Failed to send message",{error:X}))}async sendMessageWithId({channelId:A,message:Q,approvalCard:$,approvalCards:w}){let B=w??($?[$]:[]),X=B.length>0?this.buildApprovalMessagePayload(Q,B):Q;return this.sendPayloadWithId(A,X)}async sendPayloadWithId(A,Q){if(!A||!this.client)return;let $=this.client.channels.cache.get(A);if(!VI0($))return;if(typeof Q!=="string")return(await $.send(Q)).id;let w=FQ0(Q,w$0),B;for(let X of w)B=(await $.send(X)).id;return B}async editMessage({channelId:A,messageId:Q,newMessage:$}){if(!A||!this.client)return!1;let w=this.client.channels.cache.get(A);if(!VI0(w))return!1;try{return await(await w.messages.fetch(Q)).edit($.slice(0,w$0)),!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,$=A.channel.isThread();if(Q&&!this.config.allowDMs)return;let w=!!this.client?.user&&A.mentions.has(this.client.user,{ignoreEveryone:!0});if(A.author.bot&&!w)return;let B=$&&"ownerId"in A.channel&&A.channel.ownerId===this.client?.user?.id,X=this.getSpaceChannelId(A),Y=!Q&&this.isConfiguredSpace(X),Z={channelId:X,isBot:A.author.bot};if(this.config.allowedChannels.length>0&&!Q&&!this.isAllowedChannel(A.channel.id,X))return;let W=Q||B||!this.config.requireMention||w;if(Y&&(!W||this.willRouteUseNonSpaceConversation(A)))await this.capturePassiveSpaceMessage(A,X).catch((G)=>this.logger.error("Passive Discord space capture failed",{error:G,channelId:X}));if(!W){if(this.config.captureUrls){let G=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(G.length>0){await A.react(this.config.captureUrlEmoji).catch((D)=>this.logger.debug("React failed",{error:D}));for(let D of G)await this.captureUrlViaAgent(D,A.channel.id,A.author.id,"discord",Z).catch((q)=>this.logger.error("URL capture failed",{error:q,url:D}))}}return}let K=this.stripMention(A.content);if(A.attachments.size>0){let G=this.context.permissions.getUserLevel("discord",A.author.id,Z);if(G==="anchor"||G==="trusted")for(let q of A.attachments.values()){let J=q.name,F=q.contentType??void 0,I=q.size;if(!this.isUploadableTextFile(J,F))continue;if(!this.isFileSizeAllowed(I))continue;try{let P=await this.fetchText(q.url);K+=`
2329
+ `:"")+X}if(w)Q.push(w);return Q}S2();var pU=P1(p9A(),1);KA();C0();var l9A=H.object({botToken:H.string().min(1).describe("Discord bot token"),allowedChannels:H.array(H.string()).default([]),requireMention:H.boolean().default(!0),allowDMs:H.boolean().default(!0),showTypingIndicator:H.boolean().default(!0),statusMessage:H.string().default("Mention me to chat"),useThreads:H.boolean().default(!0),threadAutoArchive:H.union([H.literal(60),H.literal(1440),H.literal(4320),H.literal(10080)]).default(1440),...de.shape,captureUrlEmoji:H.string().default("\uD83D\uDD16")});var Jw2={name:"@brains/discord",version:"0.2.0-alpha.184",description:"Discord interface for Brains",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*","discord.js":"^14.26.4"},devDependencies:{"@brains/core":"workspace:*","@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var w$0=2000,zu6={completed:"Action completed",declined:"Action declined",failed:"Action failed"},Vu6={completed:2278750,declined:9741240,failed:15680580},Ju6=8388608,Fu6=8000,Iu6=100;function VI0(A){return!!A&&typeof A==="object"&&"send"in A&&"sendTyping"in A}class $O extends mz{client=null;fetchText;pendingConfirmations=new Map;typingIntervals=new Map;constructor(A,Q={}){super("discord",Jw2,A,l9A);this.fetchText=Q.fetchText??WY1}async onRegister(A){await super.onRegister(A),this.client=new pU.Client({intents:[pU.GatewayIntentBits.Guilds,pU.GatewayIntentBits.GuildMessages,pU.GatewayIntentBits.MessageContent,pU.GatewayIntentBits.DirectMessages],partials:[pU.Partials.Channel]}),this.client.on(pU.Events.MessageCreate,(Q)=>{this.handleMessage(Q)}),this.client.on(pU.Events.InteractionCreate,(Q)=>{this.handleInteraction(Q)}),this.client.once(pU.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 $=this.client.channels.cache.get(A);if(!VI0($))return;let w=FQ0(Q,w$0);for(let B of w)$.send(B).catch((X)=>this.logger.error("Failed to send message",{error:X}))}async sendMessageWithId({channelId:A,message:Q,approvalCard:$,approvalCards:w}){let B=w??($?[$]:[]),X=B.length>0?this.buildApprovalMessagePayload(Q,B):Q;return this.sendPayloadWithId(A,X)}async sendPayloadWithId(A,Q){if(!A||!this.client)return;let $=this.client.channels.cache.get(A);if(!VI0($))return;if(typeof Q!=="string")return(await $.send(Q)).id;let w=FQ0(Q,w$0),B;for(let X of w)B=(await $.send(X)).id;return B}async editMessage({channelId:A,messageId:Q,newMessage:$}){if(!A||!this.client)return!1;let w=this.client.channels.cache.get(A);if(!VI0(w))return!1;try{return await(await w.messages.fetch(Q)).edit($.slice(0,w$0)),!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,$=A.channel.isThread();if(Q&&!this.config.allowDMs)return;let w=!!this.client?.user&&A.mentions.has(this.client.user,{ignoreEveryone:!0});if(A.author.bot&&!w)return;let B=$&&"ownerId"in A.channel&&A.channel.ownerId===this.client?.user?.id,X=this.getSpaceChannelId(A),Y=!Q&&this.isConfiguredSpace(X),Z={channelId:X,isBot:A.author.bot};if(this.config.allowedChannels.length>0&&!Q&&!this.isAllowedChannel(A.channel.id,X))return;let W=Q||B||!this.config.requireMention||w;if(Y&&(!W||this.willRouteUseNonSpaceConversation(A)))await this.capturePassiveSpaceMessage(A,X).catch((G)=>this.logger.error("Passive Discord space capture failed",{error:G,channelId:X}));if(!W){if(this.config.captureUrls){let G=this.extractCaptureableUrls(A.content,this.config.blockedUrlDomains);if(G.length>0){await A.react(this.config.captureUrlEmoji).catch((D)=>this.logger.debug("React failed",{error:D}));for(let D of G)await this.captureUrlViaAgent(D,A.channel.id,A.author.id,"discord",Z).catch((q)=>this.logger.error("URL capture failed",{error:q,url:D}))}}return}let K=this.stripMention(A.content);if(A.attachments.size>0){let G=this.context.permissions.getUserLevel("discord",A.author.id,Z);if(G==="anchor"||G==="trusted")for(let q of A.attachments.values()){let J=q.name,F=q.contentType??void 0,I=q.size;if(!this.isUploadableTextFile(J,F))continue;if(!this.isFileSizeAllowed(I))continue;try{let P=await this.fetchText(q.url);K+=`
2330
2330
 
2331
2331
  `+this.formatFileUploadMessage(J,P)}catch(P){this.logger.error("Failed to download attachment",{error:P,filename:J})}}}if(K=K.trim(),!K)return;let U=A.channel.id;await this.routeToAgent(K,U,A,Z)}async handleInteraction(A){if(!this.context||!A.isButton())return;let Q=this.parseApprovalButtonCustomId(A.customId);if(!Q)return;let $=`discord-${A.channelId}`;if(!this.pendingConfirmations.get($)?.has(Q.approvalId)){await A.reply({content:"This approval is no longer pending or has changed.",ephemeral:!0}).catch((Y)=>this.logger.debug("Failed to reply to stale approval button",{error:Y}));return}await A.deferUpdate().catch((Y)=>this.logger.debug("Failed to defer approval button",{error:Y})),await this.clearApprovalInteractionComponents(A);let B=this.buildInteractionConfirmationContext(A),X=await this.context.agent.confirmPendingAction($,Q.confirmed,Q.approvalId,B);await this.handleAgentResponseToolStatuses(X,$),this.syncPendingApprovalsAfterResolution($,Q.approvalId,X),await this.sendApprovalResultMessage({channelId:A.channelId,response:X,userPermissionLevel:B.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 $=this.stripMention(A.content).trim();if(!$)return;let w=`discord-${Q}`,B=this.getChannelName(A);await this.context.conversations.start({sessionId:w,interfaceType:"discord",channelId:Q,metadata:{channelName:B,interfaceType:"discord",channelId:Q}}),await this.context.conversations.addMessage({conversationId:w,role:"user",content:$,metadata:this.buildUserMessageMetadata(A,Q,B,{threadId:A.channel.isThread()?A.channel.id:void 0})})}async routeToAgent(A,Q,$,w){if(!this.context)return;let B=this.context.agent,X=Q;if(this.config.useThreads&&$.guild&&!$.channel.isThread())try{X=(await $.startThread({name:GH(A,Iu6),autoArchiveDuration:this.config.threadAutoArchive})).id}catch(K){this.logger.error("Failed to create thread",{error:K})}let Y=`discord-${X}`,Z=this.context.permissions.getUserLevel("discord",$.author.id,w),W=this.getChannelName($);this.startProcessingInput(X);try{let K=this.client?.channels.cache.get(X);if(VI0(K))this.startTypingIndicator(K);if(this.pendingConfirmations.has(Y)){if(await this.handleConfirmationResponse(A,Y,X,$,w))return}let U=await B.chat(A,Y,{userPermissionLevel:Z,interfaceType:"discord",channelId:X,channelName:W,...this.buildUserMessageMetadata($,Q,W,{threadId:X!==Q||$.channel.isThread()?X:void 0})});await this.handleAgentResponseToolStatuses(U,Y);let G=Vv(U.cards);if(G.length>0)this.pendingConfirmations.set(Y,new Set(G.map((q)=>q.id)));else if(U.pendingConfirmations)this.pendingConfirmations.set(Y,new Set(U.pendingConfirmations.map((q)=>q.id)));else this.pendingConfirmations.delete(Y);let D=await this.sendMessageWithId({channelId:X,message:lm(U.text,G),approvalCards:G});if(D&&U.toolResults){for(let q of U.toolResults)if(q.jobId)this.trackAgentResponseForJob(q.jobId,D,X)}}catch(K){this.logger.error("Error handling message",{error:K,channelId:X}),this.sendMessageToChannel({channelId:X,message:`**Error:** ${K instanceof Error?K.message:"Unknown error"}`})}finally{this.endProcessingInput(),this.stopTypingIndicator(X)}}buildApprovalMessagePayload(A,Q){let $=Q.length>1;return{content:GH(A.trim().length>0?`${A}
2332
2332
 
@@ -2396,7 +2396,7 @@ ${A.value}
2396
2396
  `);if(LI0(A))return this.renderList(A,0,(Q)=>this.nodeToDiscordMarkdown(Q));if(A.type==="break")return`
2397
2397
  `;if(A.type==="thematicBreak")return"---";if(Q4A(A))return`\`\`\`
2398
2398
  ${$4A(A)}
2399
- \`\`\``;return this.defaultNodeToText(A,(Q)=>this.nodeToDiscordMarkdown(Q))}};var yK2={DeferredChannelMessageWithSource:5,DeferredUpdateMessage:6},RI0="https://discord.com/api/v10",gK2=2000,er6=/^[0-9a-f]{64}$/,Ao6=/^[0-9a-f]+$/,Qo6=class A{name="discord";userName;botUserId;apiBaseUrl;botToken;publicKey;applicationId;mentionRoleIds;interactionFlags;chat=null;logger;formatConverter=new tr6;requestContext=new cr6;threadParentCache=new Map;static THREAD_PARENT_CACHE_TTL=300000;constructor(Q={}){let $=Q.botToken??process.env.DISCORD_BOT_TOKEN;if(!$)throw new Iq("discord","botToken is required. Set DISCORD_BOT_TOKEN or provide it in config.");let w=Q.publicKey??process.env.DISCORD_PUBLIC_KEY;if(!w)throw new Iq("discord","publicKey is required. Set DISCORD_PUBLIC_KEY or provide it in config.");let B=Q.applicationId??process.env.DISCORD_APPLICATION_ID;if(!B)throw new Iq("discord","applicationId is required. Set DISCORD_APPLICATION_ID or provide it in config.");if(this.apiBaseUrl=Q.apiUrl??process.env.DISCORD_API_URL??RI0,this.botToken=$,this.publicKey=w.trim().toLowerCase(),this.applicationId=B,this.mentionRoleIds=Q.mentionRoleIds??(process.env.DISCORD_MENTION_ROLE_IDS?process.env.DISCORD_MENTION_ROLE_IDS.split(",").map((X)=>X.trim()):[]),this.botUserId=B,this.interactionFlags=Q.interactionFlags,this.logger=Q.logger??new bI0("info").child("discord"),this.userName=Q.userName??"bot",!er6.test(this.publicKey))this.logger.error("Invalid Discord public key format",{length:this.publicKey.length,isHex:Ao6.test(this.publicKey)})}async initialize(Q){this.chat=Q,this.logger.info("Discord adapter initialized")}async getUser(Q){try{let w=await(await this.discordFetch(`/users/${Q}`,"GET")).json();return{avatarUrl:w.avatar?`https://cdn.discordapp.com/avatars/${w.id}/${w.avatar}.png`:void 0,email:void 0,fullName:w.global_name||w.username,isBot:w.bot??!1,userId:w.id,userName:w.username}}catch{return null}}async handleWebhook(Q,$){let w=await Q.arrayBuffer(),B=new Uint8Array(w),X=new TextDecoder().decode(B),Y=Q.headers.get("x-discord-gateway-token");if(Y){if(Y!==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 G=JSON.parse(X);return this.handleForwardedGatewayEvent(G,$)}catch{return new Response("Invalid JSON",{status:400})}}this.logger.info("Discord webhook received",{bodyLength:X.length,bodyBytesLength:B.length,hasSignature:!!Q.headers.get("x-signature-ed25519"),hasTimestamp:!!Q.headers.get("x-signature-timestamp")});let Z=Q.headers.get("x-signature-ed25519"),W=Q.headers.get("x-signature-timestamp");if(!await this.verifySignature(B,Z,W))return this.logger.warn("Discord signature verification failed, returning 401"),new Response("Invalid signature",{status:401});this.logger.info("Discord signature verification passed");let U;try{U=JSON.parse(X)}catch{return new Response("Invalid JSON",{status:400})}if(this.logger.info("Discord interaction parsed",{type:U.type,typeIsPing:U.type===Wd.Ping,expectedPingType:Wd.Ping,id:U.id}),U.type===Wd.Ping){let G=JSON.stringify({type:z$0.InteractionResponseType.PONG});return this.logger.info("Discord PING received, responding with PONG",{responseBody:G,responseType:z$0.InteractionResponseType.PONG}),new Response(G,{status:200,headers:{"Content-Type":"application/json"}})}if(U.type===Wd.MessageComponent)return this.handleComponentInteraction(U,$),this.respondToInteraction({type:yK2.DeferredUpdateMessage});if(U.type===Wd.ApplicationCommand){let G=this.getApplicationCommandContext(U),D=this.getInteractionFlags(G);return this.handleApplicationCommandInteraction(G,$),this.respondToInteraction({...D===void 0?{}:{data:{flags:D}},type:yK2.DeferredChannelMessageWithSource})}return new Response("Unknown interaction type",{status:400})}async verifySignature(Q,$,w){if(!($&&w))return this.logger.warn("Discord signature verification failed: missing headers",{hasSignature:!!$,hasTimestamp:!!w}),!1;try{this.logger.info("Discord signature verification attempt",{bodyBytesLength:Q.length,signatureLength:$.length,timestampLength:w.length,publicKeyLength:this.publicKey.length,timestamp:w,signaturePrefix:$.slice(0,16),publicKey:this.publicKey});let B=await z$0.verifyKey(Q,$,w,this.publicKey);if(!B){let X=new TextDecoder().decode(Q);this.logger.warn("Discord signature verification failed: invalid signature",{publicKeyLength:this.publicKey.length,signatureLength:$.length,publicKeyPrefix:this.publicKey.slice(0,8),publicKeySuffix:this.publicKey.slice(-8),timestamp:w,bodyLength:Q.length,bodyPrefix:X.slice(0,50)})}return B}catch(B){return this.logger.warn("Discord signature verification failed: exception",{error:B}),!1}}respondToInteraction(Q){return Response.json(Q)}handleComponentInteraction(Q,$){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}let w=Q.data?.custom_id;if(!w){this.logger.warn("No custom_id in component interaction");return}let B=Q.member?.user||Q.user;if(!B){this.logger.warn("No user in component interaction");return}let X=Q.channel_id,Y=Q.guild_id||"@me",Z=Q.message?.id;if(!(X&&Z)){this.logger.warn("Missing channel_id or message_id in interaction");return}let W=Q.channel,K=W?.type===11||W?.type===12,U=K&&W?.parent_id?W.parent_id:X,G=K?this.encodeThreadId({guildId:Y,channelId:U,threadId:X}):this.encodeThreadId({guildId:Y,channelId:X}),D=lr6(w),q={actionId:D.actionId,value:D.value??D.actionId,user:{userId:B.id,userName:B.username,fullName:B.global_name||B.username,isBot:B.bot??!1,isMe:!1},messageId:Z,threadId:G,adapter:this,raw:Q};this.logger.debug("Processing Discord button action",{actionId:w,messageId:Z,threadId:G}),this.chat.processAction(q,$)}getApplicationCommandContext(Q){let $=Q.data?.name;if(!$)return this.logger.warn("No command name in application command interaction"),null;let w=Q.member?.user||Q.user;if(!w)return this.logger.warn("No user in application command interaction"),null;let B=Q.channel_id;if(!B)return this.logger.warn("Missing channel_id in application command interaction"),null;let X=Q.guild_id||"@me",Y=Q.channel,Z=Y?.type===11||Y?.type===12,W=Z&&Y?.parent_id?Y.parent_id:B,K=Z?this.encodeThreadId({guildId:X,channelId:W,threadId:B}):this.encodeThreadId({guildId:X,channelId:B}),{command:U,text:G}=this.parseSlashCommand($,Q.data?.options);return{channelId:K,command:U,interaction:Q,text:G,user:w}}getInteractionFlags(Q){if(!(Q&&this.interactionFlags))return;return this.interactionFlags(Q)}handleApplicationCommandInteraction(Q,$){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}if(!Q)return;let{channelId:w,command:B,interaction:X,text:Y,user:Z}=Q;this.logger.debug("Processing Discord slash command",{command:B,text:Y,userId:Z.id,channelId:w}),this.requestContext.run({slashCommand:{channelId:w,interactionToken:X.token,initialResponseSent:!1}},()=>{this.chat?.processSlashCommand({command:B,text:Y,user:{userId:Z.id,userName:Z.username,fullName:Z.global_name||Z.username,isBot:Z.bot??!1,isMe:Z.id===this.applicationId},adapter:this,raw:X,channelId:w},$)})}parseSlashCommand(Q,$){let w=[Q.startsWith("/")?Q:`/${Q}`],B=[],X=(Y)=>{for(let Z of Y){if(Z.value!==void 0){B.push(String(Z.value));continue}if(Z.options&&Z.options.length>0)w.push(Z.name),X(Z.options)}};if($&&$.length>0)X($);return{command:w.join(" "),text:B.join(" ").trim()}}async handleGatewayInteraction(Q){if(Q.isChatInputCommand()){let $=this.getApplicationCommandContext(this.normalizeGatewaySlashCommandInteraction(Q)),w=this.getInteractionFlags($);await Q.deferReply(w===void 0?void 0:{flags:w}),this.handleApplicationCommandInteraction($);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 $="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:$},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 $="parentId"in Q.channel&&typeof Q.channel.parentId==="string"?Q.channel.parentId:void 0;return{id:Q.channel.id,parent_id:$,type:Q.channel.type}}normalizeGatewayCommandOptions(Q){return Q.map(($)=>({name:$.name,options:$.options?this.normalizeGatewayCommandOptions($.options):void 0,type:$.type,value:$.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,$){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,$);break;case"GATEWAY_MESSAGE_REACTION_ADD":await this.handleForwardedReaction(Q.data,!0,$);break;case"GATEWAY_MESSAGE_REACTION_REMOVE":await this.handleForwardedReaction(Q.data,!1,$);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,$){if(!this.chat)return;let w=Q.guild_id||"@me",B=Q.channel_id,X,Y=B;if(Q.thread)X=Q.thread.id,Y=Q.thread.parent_id;else if(Q.channel_type===11||Q.channel_type===12)try{let q=await(await this.discordFetch(`/channels/${B}`,"GET")).json();if(q.parent_id)X=B,Y=q.parent_id,this.logger.debug("Fetched thread parent for forwarded message",{threadId:B,parentId:q.parent_id})}catch(D){this.logger.error("Failed to fetch thread parent",{error:String(D),channelId:B})}let Z=Q.is_mention||Q.mentions.some((D)=>D.id===this.applicationId),W=this.mentionRoleIds.length>0&&Q.mention_roles?.some((D)=>this.mentionRoleIds.includes(D)),K=Z||W;if(!X&&K)try{let D=await this.createDiscordThread(B,Q.id);X=D.id,this.logger.debug("Created Discord thread for forwarded mention",{channelId:B,messageId:Q.id,threadId:D.id})}catch(D){this.logger.error("Failed to create Discord thread for mention",{error:String(D),messageId:Q.id})}let U=this.encodeThreadId({guildId:w,channelId:Y,threadId:X}),G=new n9({id:Q.id,threadId:U,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((D)=>({type:this.getAttachmentType(D.content_type),url:D.url,name:D.filename,mimeType:D.content_type,size:D.size})),raw:Q,isMention:K});try{await this.chat.handleIncomingMessage(this,U,G)}catch(D){this.logger.error("Error handling forwarded message",{error:String(D),messageId:Q.id})}}async handleForwardedReaction(Q,$,w){if(!this.chat)return;let B=Q.guild_id||"@me",X=Q.channel_id,Y,Z=X;if(Q.channel_type===dh.GuildPublicThread||Q.channel_type===dh.GuildPrivateThread){let q=this.threadParentCache.get(X);if(q&&q.expiresAt>Date.now())Y=X,Z=q.parentId;else try{let F=await(await this.discordFetch(`/channels/${X}`,"GET")).json();if(F.parent_id)Y=X,Z=F.parent_id,this.threadParentCache.set(X,{parentId:F.parent_id,expiresAt:Date.now()+A.THREAD_PARENT_CACHE_TTL})}catch(J){this.logger.error("Failed to fetch thread parent for reaction",{error:String(J),channelId:X})}}let W=this.encodeThreadId({guildId:B,channelId:Z,threadId:Y}),K=Q.emoji.name||"unknown",U=this.normalizeDiscordEmoji(K),G=Q.user??Q.member?.user;if(!G){this.logger.warn("Reaction event missing user info",{data:Q});return}let D={adapter:this,threadId:W,messageId:Q.message_id,emoji:U,rawEmoji:Q.emoji.id?`<:${K}:${Q.emoji.id}>`:K,added:$,user:{userId:G.id,userName:G.username,fullName:G.username,isBot:G.bot===!0,isMe:G.id===this.applicationId},raw:Q};this.chat.processReaction(D)}async postMessage(Q,$){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=Q;if(B)w=B;let Y={},Z=[],W=[],K=xI0($);if(K){let J=u4A(K);Z.push(...J.embeds),W.push(...J.components)}else Y.content=this.truncateContent(uh(this.formatConverter.renderPostable($),"discord"));if(Z.length>0)Y.embeds=Z;if(W.length>0)Y.components=W;let U=I4A($),G=this.tryPostSlashResponse(X,Y,U);if(G)return G;if(U.length>0)return this.postMessageWithFiles(w,X,Y,U);this.logger.debug("Discord API: POST message",{channelId:w,contentLength:Y.content?.length||0,embedCount:Z.length,componentCount:W.length});let q=await(await this.discordFetch(`/channels/${w}/messages`,"POST",Y)).json();return this.logger.debug("Discord API: POST message response",{messageId:q.id}),{id:q.id,threadId:X,raw:q}}tryPostSlashResponse(Q,$,w){let B=this.requestContext.getStore()?.slashCommand;if(!B||B.channelId!==Q)return;return this.postSlashCommandResponse(B,Q,$,w)}async postSlashCommandResponse(Q,$,w,B){let X=!Q.initialResponseSent;Q.initialResponseSent=!0;let Y=X?`/webhooks/${this.applicationId}/${Q.interactionToken}/messages/@original`:`/webhooks/${this.applicationId}/${Q.interactionToken}?wait=true`,Z=X?"PATCH":"POST";this.logger.debug("Discord interaction webhook: responding to slash command",{threadId:$,isInitialResponse:X,hasFiles:B.length>0});let K=await(B.length>0?await this.discordInteractionFetchWithFiles(Y,Z,w,B):await this.discordInteractionFetch(Y,Z,w)).json();return{id:K.id,threadId:$,raw:K}}async createDiscordThread(Q,$){let w=`Thread ${new Date().toLocaleString()}`;this.logger.debug("Discord API: POST thread",{channelId:Q,messageId:$,threadName:w});try{let X=await(await this.discordFetch(`/channels/${Q}/messages/${$}/threads`,"POST",{name:w,auto_archive_duration:1440})).json();return this.logger.debug("Discord API: POST thread response",{threadId:X.id,threadName:X.name}),X}catch(B){if(B instanceof YO&&typeof B.message==="string"&&B.message.includes('"code"')&&B.message.includes("160004"))return this.logger.debug("Thread already exists for message, reusing existing thread",{channelId:Q,messageId:$}),{id:$,name:w};throw B}}truncateContent(Q){if(Q.length<=gK2)return Q;return`${Q.slice(0,gK2-3)}...`}async postMessageWithFiles(Q,$,w,B){let X=new FormData;X.append("payload_json",JSON.stringify(w));for(let W=0;W<B.length;W++){let K=B[W];if(!K)continue;let U=await L4A(K.data,{platform:"discord"});if(!U)continue;let G=new Blob([new Uint8Array(U)],{type:K.mimeType||"application/octet-stream"});X.append(`files[${W}]`,G,K.filename)}let Y=await fetch(`${RI0}/channels/${Q}/messages`,{method:"POST",headers:{Authorization:`Bot ${this.botToken}`},body:X});if(!Y.ok){let W=await Y.text();throw new YO("discord",`Failed to post message: ${Y.status} ${W}`)}let Z=await Y.json();return{id:Z.id,threadId:$,raw:Z}}async discordInteractionFetch(Q,$,w){let B=await fetch(`${RI0}${Q}`,{method:$,headers:w?{"Content-Type":"application/json"}:void 0,body:w?JSON.stringify(w):void 0});if(!B.ok){let X=await B.text();throw this.logger.error("Discord interaction API error",{path:Q,method:$,status:B.status,error:X}),new YO("discord",`Discord interaction API error: ${B.status} ${X}`)}return B}async discordInteractionFetchWithFiles(Q,$,w,B){let X=new FormData;X.append("payload_json",JSON.stringify(w));for(let Z=0;Z<B.length;Z++){let W=B[Z];if(!W)continue;let K=await L4A(W.data,{platform:"discord"});if(!K)continue;let U=new Blob([new Uint8Array(K)],{type:W.mimeType||"application/octet-stream"});X.append(`files[${Z}]`,U,W.filename)}let Y=await fetch(`${RI0}${Q}`,{method:$,body:X});if(!Y.ok){let Z=await Y.text();throw this.logger.error("Discord interaction API error",{path:Q,method:$,status:Y.status,error:Z}),new YO("discord",`Discord interaction API error: ${Y.status} ${Z}`)}return Y}async editMessage(Q,$,w){let{channelId:B,threadId:X}=this.decodeThreadId(Q),Y=X||B,Z={},W=[],K=[],U=xI0(w);if(U){let q=u4A(U);W.push(...q.embeds),K.push(...q.components),Z.content=""}else Z.content=this.truncateContent(uh(this.formatConverter.renderPostable(w),"discord"));if(W.length>0)Z.embeds=W;if(K.length>0)Z.components=K;this.logger.debug("Discord API: PATCH message",{channelId:Y,messageId:$,contentLength:Z.content?.length||0});let D=await(await this.discordFetch(`/channels/${Y}/messages/${$}`,"PATCH",Z)).json();return this.logger.debug("Discord API: PATCH message response",{messageId:D.id}),{id:D.id,threadId:Q,raw:D}}async deleteMessage(Q,$){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=B||w;this.logger.debug("Discord API: DELETE message",{channelId:X,messageId:$}),await this.discordFetch(`/channels/${X}/messages/${$}`,"DELETE"),this.logger.debug("Discord API: DELETE message response",{ok:!0})}async addReaction(Q,$,w){let{channelId:B,threadId:X}=this.decodeThreadId(Q),Y=X||B,Z=this.encodeEmoji(w);this.logger.debug("Discord API: PUT reaction",{channelId:Y,messageId:$,emoji:Z}),await this.discordFetch(`/channels/${Y}/messages/${$}/reactions/${Z}/@me`,"PUT"),this.logger.debug("Discord API: PUT reaction response",{ok:!0})}async removeReaction(Q,$,w){let{channelId:B,threadId:X}=this.decodeThreadId(Q),Y=X||B,Z=this.encodeEmoji(w);this.logger.debug("Discord API: DELETE reaction",{channelId:Y,messageId:$,emoji:Z}),await this.discordFetch(`/channels/${Y}/messages/${$}/reactions/${Z}/@me`,"DELETE"),this.logger.debug("Discord API: DELETE reaction response",{ok:!0})}encodeEmoji(Q){let $=K$0.toDiscord?K$0.toDiscord(Q):String(Q);return encodeURIComponent($)}async startTyping(Q,$){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=B||w;this.logger.debug("Discord API: POST typing",{channelId:X}),await this.discordFetch(`/channels/${X}/typing`,"POST")}async fetchMessages(Q,$={}){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=B||w,Y=$.limit||50,Z=$.direction??"backward",W=new URLSearchParams;if(W.set("limit",String(Y)),$.cursor)if(Z==="backward")W.set("before",$.cursor);else W.set("after",$.cursor);this.logger.debug("Discord API: GET messages",{channelId:X,limit:Y,direction:Z,cursor:$.cursor});let U=await(await this.discordFetch(`/channels/${X}/messages?${W.toString()}`,"GET")).json();this.logger.debug("Discord API: GET messages response",{messageCount:U.length});let D=[...U].reverse().map((J)=>this.parseDiscordMessage(J,Q)),q;if(U.length===Y)if(Z==="backward")q=U.at(-1)?.id;else q=U[0]?.id;return{messages:D,nextCursor:q}}async fetchThread(Q){let{channelId:$,guildId:w}=this.decodeThreadId(Q);this.logger.debug("Discord API: GET channel",{channelId:$});let X=await(await this.discordFetch(`/channels/${$}`,"GET")).json();return{id:Q,channelId:$,channelName:X.name,isDM:X.type===dh.DM||X.type===dh.GroupDM,metadata:{guildId:w,channelType:X.type,raw:X}}}async openDM(Q){this.logger.debug("Discord API: POST DM channel",{userId:Q});let w=await(await this.discordFetch("/users/@me/channels","POST",{recipient_id:Q})).json();return this.logger.debug("Discord API: POST DM channel response",{channelId:w.id}),this.encodeThreadId({guildId:"@me",channelId:w.id})}isDM(Q){let{guildId:$}=this.decodeThreadId(Q);return $==="@me"}encodeThreadId(Q){let $=Q.threadId?`:${Q.threadId}`:"";return`discord:${Q.guildId}:${Q.channelId}${$}`}decodeThreadId(Q){let $=Q.split(":");if($.length<3||$[0]!=="discord")throw new Iq("discord",`Invalid Discord thread ID: ${Q}`);return{guildId:$[1],channelId:$[2],threadId:$[3]}}parseMessage(Q){let $=Q,w=$.guild_id||"@me",B=this.encodeThreadId({guildId:w,channelId:$.channel_id});return this.parseDiscordMessage($,B)}parseDiscordMessage(Q,$){let w=Q.type===EX2.ThreadStarterMessage&&Q.referenced_message?Q.referenced_message:Q,B=w.author,X=B.bot??!1,Y=B.id===this.botUserId;return new n9({id:w.id,threadId:$,text:this.formatConverter.extractPlainText(w.content),formatted:this.formatConverter.toAst(w.content),raw:Q,author:{userId:B.id,userName:B.username,fullName:B.global_name||B.username,isBot:X,isMe:Y},metadata:{dateSent:new Date(w.timestamp),edited:w.edited_timestamp!==null,editedAt:w.edited_timestamp?new Date(w.edited_timestamp):void 0},attachments:(w.attachments||[]).map((Z)=>({type:this.getAttachmentType(Z.content_type),url:Z.url,name:Z.filename,mimeType:Z.content_type,size:Z.size,width:Z.width??void 0,height:Z.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"}rehydrateAttachment(Q){let $=Q.fetchMetadata?.url??Q.url;if(!$)return Q;return{...Q,fetchData:()=>this.downloadAttachment($)}}async downloadAttachment(Q){let $;try{$=await fetch(Q)}catch(w){throw new YO("discord","Failed to download Discord attachment",w instanceof Error?w:void 0)}if(!$.ok)throw new YO("discord",`Failed to download Discord attachment: ${$.status}`);return Buffer.from(await $.arrayBuffer())}renderFormatted(Q){return this.formatConverter.fromAst(Q)}async discordFetch(Q,$,w){let B=`${this.apiBaseUrl}${Q}`,X={Authorization:`Bot ${this.botToken}`};if(w)X["Content-Type"]="application/json";let Y=await fetch(B,{method:$,headers:X,body:w?JSON.stringify(w):void 0});if(!Y.ok){let Z=await Y.text();throw this.logger.error("Discord API error",{path:Q,method:$,status:Y.status,error:Z}),new YO("discord",`Discord API error: ${Y.status} ${Z}`)}return Y}async startGatewayListener(Q,$=180000,w,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:$,webhookUrl:B?"configured":"not configured"});let X=this.runGatewayListener($,w,B);return Q.waitUntil(X),new Response(JSON.stringify({status:"listening",durationMs:$,message:`Gateway listener started, will run for ${$/1000} seconds`}),{status:200,headers:{"Content-Type":"application/json"}})}async runGatewayListener(Q,$,w){let B=new xX.Client({intents:[xX.GatewayIntentBits.Guilds,xX.GatewayIntentBits.GuildMessages,xX.GatewayIntentBits.MessageContent,xX.GatewayIntentBits.DirectMessages,xX.GatewayIntentBits.GuildMessageReactions,xX.GatewayIntentBits.DirectMessageReactions],partials:[xX.Partials.Channel]}),X=!1;if(w)B.on("raw",async(Y)=>{if(X)return;if(!Y.t)return;this.logger.info("Discord Gateway forwarding event",{type:Y.t}),await this.forwardGatewayEvent(w,{type:`GATEWAY_${Y.t}`,timestamp:Date.now(),data:Y.d})});else this.setupLegacyGatewayHandlers(B,()=>X);B.on(xX.Events.ClientReady,()=>{this.logger.info("Discord Gateway connected",{username:B.user?.username,id:B.user?.id})}),B.on(xX.Events.Error,(Y)=>{this.logger.error("Discord Gateway error",{error:String(Y)})});try{await B.login(this.botToken),await new Promise((Y)=>{let Z=setTimeout(Y,Q);if($){if($.aborted){clearTimeout(Z),Y();return}$.addEventListener("abort",()=>{this.logger.info("Discord Gateway listener received abort signal (new listener started)"),clearTimeout(Z),Y()},{once:!0})}}),this.logger.info("Discord Gateway listener duration elapsed, disconnecting")}catch(Y){this.logger.error("Discord Gateway listener error",{error:String(Y)})}finally{X=!0,B.destroy(),this.logger.info("Discord Gateway listener stopped")}}setupLegacyGatewayHandlers(Q,$){Q.on(xX.Events.MessageCreate,async(w)=>{if($()){this.logger.debug("Ignoring message - Gateway is shutting down");return}if(w.author.bot){this.logger.debug("Ignoring message from bot",{authorId:w.author.id,authorName:w.author.username,isMe:w.author.id===Q.user?.id});return}let B=w.mentions.has(Q.user?.id??""),X=this.mentionRoleIds.length>0&&w.mentions.roles.some((Z)=>this.mentionRoleIds.includes(Z.id)),Y=B||X;this.logger.info("Discord Gateway message received",{channelId:w.channelId,guildId:w.guildId,authorId:w.author.id,isMentioned:Y,isUserMentioned:B,isRoleMentioned:X,content:w.content.slice(0,100)}),await this.handleGatewayMessage(w,Y)}),Q.on(xX.Events.InteractionCreate,async(w)=>{if($()){this.logger.debug("Ignoring interaction - Gateway is shutting down");return}this.logger.info("Discord Gateway interaction received",{id:w.id,type:w.type});try{await this.handleGatewayInteraction(w)}catch(B){this.logger.error("Error handling Gateway interaction",{error:String(B),interactionId:w.id})}}),Q.on(xX.Events.MessageReactionAdd,async(w,B)=>{if($()){this.logger.debug("Ignoring reaction - Gateway is shutting down");return}if(B.bot){this.logger.debug("Ignoring reaction from bot",{userId:B.id,isMe:B.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction added",{emoji:w.emoji.name,messageId:w.message.id,channelId:w.message.channelId,userId:B.id}),B.username)await this.handleGatewayReaction(w,B,!0)}),Q.on(xX.Events.MessageReactionRemove,async(w,B)=>{if($()){this.logger.debug("Ignoring reaction removal - Gateway is shutting down");return}if(B.bot){this.logger.debug("Ignoring reaction removal from bot",{userId:B.id,isMe:B.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction removed",{emoji:w.emoji.name,messageId:w.message.id,channelId:w.message.channelId,userId:B.id}),B.username)await this.handleGatewayReaction(w,B,!1)})}async forwardGatewayEvent(Q,$){try{this.logger.debug("Forwarding Gateway event to webhook",{type:$.type,webhookUrl:Q});let w=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/json","x-discord-gateway-token":this.botToken},body:JSON.stringify($)});if(w.ok)this.logger.debug("Gateway event forwarded successfully",{type:$.type});else{let B=await w.text();this.logger.error("Failed to forward Gateway event",{type:$.type,status:w.status,error:B})}}catch(w){this.logger.error("Error forwarding Gateway event",{type:$.type,error:String(w)})}}async handleGatewayMessage(Q,$){if(!this.chat)return;let w=Q.guildId||"@me",B=Q.channelId,X=Q.channel.isThread(),Y,Z=B;if(X&&"parentId"in Q.channel&&Q.channel.parentId)Y=B,Z=Q.channel.parentId;if(!Y&&$)try{let U=await this.createDiscordThread(B,Q.id);Y=U.id,this.logger.debug("Created Discord thread for incoming mention",{channelId:B,messageId:Q.id,threadId:U.id})}catch(U){this.logger.error("Failed to create Discord thread for mention",{error:String(U),messageId:Q.id})}let W=this.encodeThreadId({guildId:w,channelId:Z,threadId:Y}),K=new n9({id:Q.id,threadId:W,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((U)=>({type:this.getAttachmentType(U.contentType),url:U.url,name:U.name,mimeType:U.contentType??void 0,size:U.size})),raw:{id:Q.id,channel_id:B,guild_id:w,content:Q.content,author:{id:Q.author.id,username:Q.author.username},timestamp:Q.createdAt.toISOString()},isMention:$});try{await this.chat.handleIncomingMessage(this,W,K)}catch(U){this.logger.error("Error handling Gateway message",{error:String(U),messageId:Q.id})}}async handleGatewayReaction(Q,$,w){if(!this.chat)return;let B=Q.message.guildId||"@me",X=Q.message.channelId,Y=Q.message.channel?.isThread?.(),Z=X,W;if(Y&&Q.message.channel?.parentId)W=X,Z=Q.message.channel.parentId;let K=this.encodeThreadId({guildId:B,channelId:Z,threadId:W}),U=Q.emoji.name||"unknown",G=this.normalizeDiscordEmoji(U),D={adapter:this,threadId:K,messageId:Q.message.id,emoji:G,rawEmoji:Q.emoji.id?`<:${U}:${Q.emoji.id}>`:U,added:w,user:{userId:$.id,userName:$.username,fullName:$.username,isBot:$.bot===!0,isMe:$.id===this.applicationId},raw:{emoji:Q.emoji,message_id:Q.message.id,channel_id:Q.message.channelId,guild_id:Q.message.guildId,user_id:$.id}};this.chat.processReaction(D)}channelIdFromThreadId(Q){return Q.split(":").slice(0,3).join(":")}async fetchChannelMessages(Q,$={}){let B=Q.split(":")[2];if(!B)throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);let X=$.limit||50,Y=$.direction??"backward",Z=new URLSearchParams;if(Z.set("limit",String(X)),$.cursor)if(Y==="backward")Z.set("before",$.cursor);else Z.set("after",$.cursor);this.logger.debug("Discord API: GET channel messages",{channelId:B,limit:X,direction:Y,cursor:$.cursor});let K=await(await this.discordFetch(`/channels/${B}/messages?${Z.toString()}`,"GET")).json();this.logger.debug("Discord API: GET channel messages response",{messageCount:K.length});let G=[...K].reverse().map((q)=>this.parseDiscordMessage(q,Q)),D;if(K.length===X)if(Y==="backward")D=K.at(-1)?.id;else D=K[0]?.id;return{messages:G,nextCursor:D}}async listThreads(Q,$={}){let w=Q.split(":"),B=w[1],X=w[2];if(!(B&&X))throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET threads",{guildId:B,channelId:X});let W=((await(await this.discordFetch(`/guilds/${B}/threads/active`,"GET")).json()).threads||[]).filter((I)=>I.parent_id===X),K=[];try{K=(await(await this.discordFetch(`/channels/${X}/threads/archived/public?limit=${$.limit||50}`,"GET")).json()).threads||[]}catch{this.logger.debug("Could not fetch archived threads (may lack permissions)")}let U=[...W,...K],G=new Set,D=U.filter((I)=>{if(G.has(I.id))return!1;return G.add(I.id),!0}),q=$.limit||50,J=D.slice(0,q),F=[];for(let I of J){let P=this.encodeThreadId({guildId:B,channelId:X,threadId:I.id});try{let f=(await(await this.discordFetch(`/channels/${I.id}/messages?limit=1&after=0`,"GET")).json())[0];if(f)F.push({id:P,rootMessage:this.parseDiscordMessage(f,P),replyCount:I.total_message_sent??I.message_count,lastReplyAt:I.thread_metadata?.archive_timestamp?new Date(I.thread_metadata.archive_timestamp):void 0})}catch{F.push({id:P,rootMessage:new n9({id:I.id,threadId:P,text:I.name,formatted:this.formatConverter.toAst(I.name),raw:I,author:{userId:"unknown",userName:"unknown",fullName:"unknown",isBot:!1,isMe:!1},metadata:{dateSent:new Date,edited:!1},attachments:[]}),replyCount:I.total_message_sent??I.message_count})}}return this.logger.debug("Discord API: listThreads result",{threadCount:F.length}),{threads:F,nextCursor:D.length>q?String(q):void 0}}async fetchChannelInfo(Q){let w=Q.split(":")[2];if(!w)throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET channel info",{channelId:w});let X=await(await this.discordFetch(`/channels/${w}`,"GET")).json();return{id:Q,name:X.name,isDM:X.type===dh.DM||X.type===dh.GroupDM,memberCount:X.member_count,metadata:{channelType:X.type,raw:X}}}async postChannelMessage(Q,$){let B=Q.split(":")[2];if(!B)throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);let X={},Y=[],Z=[],W=xI0($);if(W){let q=u4A(W);Y.push(...q.embeds),Z.push(...q.components)}else X.content=this.truncateContent(uh(this.formatConverter.renderPostable($),"discord"));if(Y.length>0)X.embeds=Y;if(Z.length>0)X.components=Z;let K=I4A($),U=this.tryPostSlashResponse(Q,X,K);if(U)return U;if(K.length>0)return this.postMessageWithFiles(B,Q,X,K);this.logger.debug("Discord API: POST channel message",{channelId:B,contentLength:X.content?.length||0});let D=await(await this.discordFetch(`/channels/${B}/messages`,"POST",X)).json();return{id:D.id,threadId:Q,raw:D}}normalizeDiscordEmoji(Q){let w={"\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 XO(w)}};function uK2(A){return new Qo6(A??{})}var $o6=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 $=this.locks.get(A);if($&&$.expiresAt>Date.now())return null;let w={threadId:A,token:wo6(),expiresAt:Date.now()+Q};return this.locks.set(A,w),w}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 $=this.locks.get(A.threadId);if(!$||$.token!==A.token)return!1;if($.expiresAt<Date.now())return this.locks.delete(A.threadId),!1;return $.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,$){this.ensureConnected(),this.cache.set(A,{value:Q,expiresAt:$?Date.now()+$:null})}async setIfNotExists(A,Q,$){this.ensureConnected();let w=this.cache.get(A);if(w)if(w.expiresAt!==null&&w.expiresAt<=Date.now())this.cache.delete(A);else return!1;return this.cache.set(A,{value:Q,expiresAt:$?Date.now()+$:null}),!0}async delete(A){this.ensureConnected(),this.cache.delete(A)}async appendToList(A,Q,$){this.ensureConnected();let w=this.cache.get(A),B;if(w&&w.expiresAt!==null&&w.expiresAt<=Date.now())B=[];else if(w&&Array.isArray(w.value))B=w.value;else B=[];if(B.push(Q),$?.maxLength&&B.length>$.maxLength)B=B.slice(B.length-$.maxLength);this.cache.set(A,{value:B,expiresAt:$?.ttlMs?Date.now()+$.ttlMs:null})}async enqueue(A,Q,$){this.ensureConnected();let w=this.queues.get(A);if(!w)w=[],this.queues.set(A,w);if(w.push(Q),w.length>$)w.splice(0,w.length-$);return w.length}async dequeue(A){this.ensureConnected();let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let $=Q.shift();if(Q.length===0)this.queues.delete(A);return $??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,$]of this.locks)if($.expiresAt<=A)this.locks.delete(Q)}_getSubscriptionCount(){return this.subscriptions.size}_getLockCount(){return this.cleanExpiredLocks(),this.locks.size}};function wo6(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function vI0(A){return new $o6}C0();var Bo6=H.object({subscribedAt:H.string().datetime(),routingMode:H.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:H.boolean().optional()}),Xo6="chat.discord.subscriptions";function c4A(A){return A.scoped({namespace:Xo6,schema:Bo6})}function cK2(A,Q=vI0()){let $=c4A(A);return new pK2(Q,$)}class pK2{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,$){return this.memoryState.appendToList(A,Q,$)}delete(A){return this.memoryState.delete(A)}dequeue(A){return this.memoryState.dequeue(A)}enqueue(A,Q,$){return this.memoryState.enqueue(A,Q,$)}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,$){return this.memoryState.set(A,Q,$)}setIfNotExists(A,Q,$){return this.memoryState.setIfNotExists(A,Q,$)}}function lK2(A){let{discord:Q}=A;if(!Q)return new V4A({userName:A.userName,adapters:{},state:vI0()});let $=uK2({botToken:Q.botToken,publicKey:Q.publicKey,applicationId:Q.applicationId,mentionRoleIds:Q.mentionRoleIds});return A.gatewayLoop.setAdapter($),new V4A({userName:A.userName,adapters:{discord:$},concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"},state:cK2(A.runtimeState)})}class p4A{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($){this.deps.logger.debug("Discord thread subscription failed",{error:$,threadId:A.id})}}async shouldRouteSubscribedMessage(A,Q){if(this.deps.getPlatform(A)!=="discord")return!1;if(A.isDM)return!0;let $=await this.deps.getSubscriptions()?.get(A.id);if(!$)return!1;if($.routingMode==="mention-required"){if(!Q.isMention&&!$.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,$);return Boolean(Q.isMention)}if(!await this.shouldRequireMentionInSubscribedThread(A))return!0;let B={...$,routingMode:"mention-required"};if(!Q.isMention&&!$.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,B);else await this.deps.getSubscriptions()?.set(A.id,B);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((w)=>!w.isBot&&!w.isMe).length>1}catch(Q){return this.deps.logger.debug("Failed to inspect Discord thread participants",{error:Q,threadId:A.id}),!1}}}KA();class l4A{deps;constructor(A){this.deps=A}async build(A,Q,$,w){let B={message:$.text.trim(),attachments:[],notices:[]};if($.attachments.length===0)return B;if(!(w==="anchor"||w==="trusted"))return B;let Y=this.deps.getUploadStore();if(!Y)return B;for(let Z of $.attachments){let W=Z.name;if(!W)continue;let K=vN(W,"upload"),U=BM(K,Z.mimeType),G=Z.size??0,D=CU0(K,U);if(!D){B.notices.push(`Unsupported file upload type: ${K}`);continue}if(!hU0(D,G)){B.notices.push(`File upload too large: ${K}`);continue}try{let q=await this.readAttachmentData(Z);if(!q)continue;let J=CN({filename:K,mediaType:U,content:q,fallbackFilename:"upload"});if(!J.ok){B.notices.push(J.message);continue}let F=await Y.save({filename:J.filename,mediaType:J.mediaType,content:q,metadata:this.buildMetadata(A,Q,$)});B.attachments.push(iK2(F.filename,F.mediaType,q,F.ref,J.kind==="text"))}catch(q){this.deps.logger.error("Failed to read chat attachment",{error:q,filename:K}),B.notices.push(`Could not read file upload: ${K}`)}}return B}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 $=await Q.arrayBuffer();return Buffer.from(new Uint8Array($))}buildMetadata(A,Q,$){let w=this.deps.getThreadIdParts(Q.id);return{interfaceType:A,channelId:Q.id,parentChannelId:Q.channelId,messageId:$.id,uploaderId:$.author.userId,uploaderUsername:$.author.userName,...w.guildId?{guildId:w.guildId}:{},...w.threadId?{threadId:w.threadId}:{}}}}function dK2(A,Q,$,w){return iK2(A,Q,$,w,XM(A,Q))}function iK2(A,Q,$,w,B){if(B)return{kind:"text",filename:A,mediaType:Q,content:$.toString("utf8").replace(/^\uFEFF/,""),sizeBytes:$.byteLength,source:w};return{kind:"file",filename:A,mediaType:Q,data:$,sizeBytes:$.byteLength,source:w}}function V$0(){return{namespace:"discord-chat",refKind:"discord-chat-upload",routePath:"/api/webhooks/chat/discord/uploads"}}function fF(A){let Q=A.split(":");if(Q[0]!=="discord")return{};return{...Q[1]?{guildId:Q[1]}:{},...Q[2]?{channelId:Q[2]}:{},...Q[3]?{threadId:Q[3]}:{}}}function Yo6(A){let Q=A.raw;if(typeof Q!=="object"||Q===null)return;let $=Q.channel_id;return typeof $==="string"?$:void 0}function nK2(A,Q){if(A.isDM)return!1;let $=fF(A.id);if(!$.threadId)return!1;let w=Yo6(Q);return w!==void 0&&w!==$.threadId}function CI0(A,Q){if(Q.allowedChannels.length===0||A.isDM)return!0;let $=fF(A.id);return[A.id,A.channelId,$.channelId,$.threadId].some((w)=>typeof w==="string"&&Q.allowedChannels.includes(w))}function d4A(A,Q,$){if(A.isDM&&!$.allowDMs)return!1;if(Q.author.isMe)return!1;if(Q.author.isBot&&!Q.isMention)return!1;return CI0(A,$)}function i4A(A,Q,$){if(Q!=="discord")return!0;if(!$)return!1;if(A.isDM&&!$.allowDMs)return!1;return CI0(A,$)}function n4A(A,Q){return{channelId:fF(A.id).channelId??A.channelId,isBot:Boolean(Q.author.isBot)}}function Ud(A){return A.isDM?"DM":A.channelId}var Zo6="https://discord.com/api/v10";async function rK2(A){let Q=fF(A.threadId),$=Q.threadId??Q.channelId;if(!$)return;let w=A.fetchFn??fetch;try{let B=await w(`${Zo6}/channels/${$}/messages/${A.messageId}`,{method:"PATCH",headers:{Authorization:`Bot ${A.botToken}`,"Content-Type":"application/json"},body:JSON.stringify({components:[]})});if(!B.ok)A.logger.debug("Failed to clear Discord message components",{messageId:A.messageId,channelId:$,status:B.status})}catch(B){A.logger.debug("Failed to clear Discord message components",{error:B,messageId:A.messageId,channelId:$})}}var oK2={name:"@brains/chat",version:"0.2.0-alpha.183",description:"Discord Chat SDK interface for Brains",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":"^1.3.14"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Wo6=/https?:\/\/\S+/i,Ko6=/[\s\S]+/,Uo6=1000,Go6=H.looseObject({type:H.literal("card"),children:H.array(H.looseObject({type:H.string()})),imageUrl:H.string().optional(),subtitle:H.string().optional(),title:H.string().optional()}),Do6=H.object({card:H.custom((A)=>Go6.safeParse(A).success),fallbackText:H.string().optional()});class hI0 extends mz{threadRegistry=new JI0;pendingApprovals;uploadContinuity;promptActions=new i9A(Uo6);toolStatusMessenger=new n9A(this.threadRegistry);cardBuilder=new a9A({getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),registerPromptAction:(A,Q)=>this.registerPromptAction(A,Q)});artifactDelivery=new e9A({getContext:()=>this.context,getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),logger:this.logger});approvalCards=new A7A({cardBuilder:this.cardBuilder,clearMessageComponents:async(A,Q)=>{let $=this.config.adapters.discord?.botToken;if(!$)return;await rK2({threadId:A,messageId:Q,botToken:$,logger:this.logger})}});subscriptionRouter=new p4A({getSubscriptions:()=>this.discordSubscriptions,getPlatform:(A)=>this.getPlatform(A),isBotCreatedThread:nK2,logger:this.logger});chatInputBuilder=new l4A({getUploadStore:()=>this.context?.uploads.scoped(V$0()),getThreadIdParts:fF,logger:this.logger});gatewayLoop;discordApp;discordSubscriptions;constructor(A={}){super("chat",oK2,A,d9A);this.gatewayLoop=new Q7A({getApp:()=>this.discordApp.instance,gatewayRunMs:this.config.gatewayRunMs,gatewayRestartDelayMs:this.config.gatewayRestartDelayMs,logger:this.logger}),this.discordApp=new $7A({discord:this.config.adapters.discord,getUploadStore:()=>this.context?.uploads.scoped(V$0()),buildApp:(Q)=>lK2({userName:this.config.userName,discord:this.config.adapters.discord,gatewayLoop:this.gatewayLoop,runtimeState:Q})}),this.pendingApprovals=new se({loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},onRestoreError:(Q,$)=>{this.logger.debug("Failed to load pending chat approvals",{error:Q,conversationId:$})}}),this.uploadContinuity=new $00({sourceKind:"discord-chat-upload",loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},restoreAttachment:async(Q)=>{let $=this.context?.uploads.scoped(V$0());if(!$)throw Error("Chat upload store unavailable");let w=await $.read(Q);return dK2(w.record.filename,w.record.mediaType,w.content,w.record.ref)},onLoadError:(Q,$)=>{this.logger.debug("Failed to load prior chat uploads",{error:Q,conversationId:$})},onRestoreError:(Q,$)=>{this.logger.debug("Failed to restore prior chat upload",{error:Q,uploadId:$})}})}async onRegister(A){await super.onRegister(A),this.discordSubscriptions=c4A(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 $=this.threadRegistry.get(A);if(!$)return;let w=this.toDiscordCardOutput(Q);if(w){$.post(w).catch((B)=>this.logger.error("Failed to send chat message",{error:B,channelId:A}));return}if(typeof Q!=="string")return;for(let B of B$0(A,Q))$.post(B).catch((X)=>this.logger.error("Failed to send chat message",{error:X,channelId:A}))}async sendMessageWithId({channelId:A,message:Q}){let $=this.threadRegistry.get(A);if(!$)return;let w=this.toDiscordCardOutput(Q);if(w){let X=await $.post(w);return this.threadRegistry.trackMessage($.id,X),X.id}if(typeof Q!=="string")return;let B;for(let X of B$0(A,Q))B=await $.post(X),this.threadRegistry.trackMessage($.id,B);return B?.id}async editMessage({channelId:A,messageId:Q,newMessage:$}){let w=this.threadRegistry.getMessage(A,Q);if(!w)return!1;try{let B=await w.edit(this.toDiscordCardOutput($)??(typeof $==="string"?$:""));if(A)this.threadRegistry.trackMessage(A,B);return!0}catch{return!1}}supportsMessageEditing(){return!0}toDiscordCardOutput(A){let Q=Do6.safeParse(A);if(!Q.success)return;let{card:$,fallbackText:w}=Q.data;if(w===void 0)return{card:$};return{card:$,fallbackText:w}}formatProgressOutput(A){return s9A(A)}formatCompletionOutput(A){return s9A(A)}async handleProgressEvent(A,Q){let $=A.metadata.interfaceType;if($&&$!==this.id){if(!this.isEnabledPlatform($))return;let w={...A,metadata:{...A.metadata,interfaceType:this.id}};await super.handleProgressEvent(w,w.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 Nw2(A,Boolean(this.config.adapters.discord))}registerChatHandlers(A){if(A.onDirectMessage(async(Q,$,w,B)=>{await this.handleRoutedMessage(Q,$,B)}),A.onNewMention(async(Q,$,w)=>{let B=this.getPlatformConfig(Q);if(B&&d4A(Q,$,B)&&!Q.isDM&&B.useThreads)await this.subscriptionRouter.subscribeOwnedThread(Q,$);await this.handleRoutedMessage(Q,$,w)}),A.onSubscribedMessage(async(Q,$,w)=>{if(!await this.subscriptionRouter.shouldRouteSubscribedMessage(Q,$))return;await this.handleRoutedMessage(Q,$,w)}),this.config.adapters.discord&&!this.config.adapters.discord.requireMention)A.onNewMessage(Ko6,async(Q,$,w)=>{await this.handleRoutedMessage(Q,$,w)});A.onNewMessage(Wo6,async(Q,$)=>{await this.handlePassiveUrlCapture(Q,$)}),A.onAction([FI0,r9A],async(Q)=>{await this.handleApprovalAction(Q)}),A.onAction(o9A,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 $=A.thread;if(!i4A($,Q,this.config.adapters.discord))return;let w=this.promptActions.get(A.value);if(w?.threadId!==$.id){await $.post(this.formatNoticePayload("That suggested action is no longer available.","Action unavailable"));return}this.promptActions.consume(A.value);let B=fF($.id),X=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:B.channelId??$.channelId,isBot:Boolean(A.user.isBot)}),Y=this.getConversationId(Q,$.id),Z=$.id;await this.runAgentTurn({thread:$,channelId:Z,logLabel:"Error handling chat prompt action",body:async()=>{if(!this.context)return;let W=await this.context.agent.chat(w.prompt,Y,{userPermissionLevel:X,interfaceType:Q,channelId:Z,channelName:Ud($),...this.buildActionEventMetadata(Q,$,A)});await this.renderAgentResponse({thread:$,channelId:Z,conversationId:Y,response:W,userPermissionLevel:X})}})}async handleApprovalAction(A){if(!this.context||!A.thread||!A.value)return;let Q=A.adapter.name;if(!this.isEnabledPlatform(Q))return;let $=this.getConversationId(Q,A.thread.id);if(!(await this.getPendingApprovalIds($)).has(A.value)){await A.thread.post(this.formatNoticePayload("That approval is no longer pending."));return}let B=A.thread;if(!i4A(B,Q,this.config.adapters.discord))return;let X=fF(B.id),Y=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:X.channelId??B.channelId,isBot:Boolean(A.user.isBot)});await this.confirmApproval({thread:B,conversationId:$,approvalId:A.value,confirmed:A.actionId===FI0,userPermissionLevel:Y,metadata:this.buildActionEventMetadata(Q,B,A)})}async handleRoutedMessage(A,Q,$){if(!this.context)return;let w=this.getPlatform(A);if(w!=="discord")return;let B=this.getPlatformConfig(A);if(!B)return;if(!d4A(A,Q,B))return;await this.routeToAgent(w,A,Q,$)}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,$){let w=this.formatErrorPayload($),B=this.toDiscordCardOutput(w);if(B){await A.post(B);return}let X=typeof w==="string"?w:"Message failed.";for(let Y of B$0(Q,X))await A.post(Y)}async routeToAgent(A,Q,$,w){if(!this.context)return;this.threadRegistry.set(Q);let B=this.getConversationId(A,Q.id),X=Q.id,Y=n4A(Q,$),Z=this.context.permissions.getUserLevel(A,$.author.userId,Y),W=await this.chatInputBuilder.build(A,Q,$,Z),K=[...W.attachments];if(await this.attachPriorUploads(B,W,Z),await this.postUploadNotices(Q,W.notices),!W.message&&W.attachments.length===0)return;this.rememberUploadAttachments(B,K),await this.runAgentTurn({thread:Q,channelId:X,logLabel:"Error handling chat message",body:async()=>{if(!this.context)return;let U=await this.getPendingApprovalIds(B);if(U.size>0){if(await this.handleConfirmationResponse(W.message,B,Q,U,Z,this.buildUserMessageMetadata(A,Q,$)))return}let G=this.buildCoalescedAgentInput(W.message,w),D=await this.context.agent.chat(G.message,B,{userPermissionLevel:Z,interfaceType:A,channelId:X,channelName:Ud(Q),...this.buildUserMessageMetadata(A,Q,$,G.metadata),...W.attachments.length>0?{attachments:W.attachments}:{}});await this.renderAgentResponse({thread:Q,channelId:X,conversationId:B,response:D,userPermissionLevel:Z})}})}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),$=Jv(A.response,{deniedCardIds:Q.deniedCardIds});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($,Q.deniedCardIds),B=await this.sendAgentResponseWithFiles({thread:A.thread,channelId:A.channelId,message:w,files:Q.files}),X=await this.sendArtifactCards(A.thread,$);await this.sendSupplementalCards(A.thread,$);let Y=$.directives.find((W)=>W.kind==="approvals");await this.approvalCards.trackPendingConfirmations(A.thread,A.conversationId,Y?.confirmations);let Z=X??B;if(Z)for(let W of $.jobIds)this.trackAgentResponseForJob(W,Z,A.channelId)}rememberPendingConfirmationsFromResponse(A,Q){this.pendingApprovals.rememberFromResponse(A,Q)}async getPendingApprovalIds(A){return this.pendingApprovals.getApprovalIds(A)}async handleConfirmationResponse(A,Q,$,w,B,X){if(!ie(A,w))return!1;let Y=LU0({message:A,approvalIds:w});if(Y.kind==="not-confirmation")return this.pendingApprovals.deleteConversation(Q),await $.post(this.formatNoticePayload("No pending approval to resolve.")),!0;if(Y.kind==="notice")return await $.post(this.formatNoticePayload(Y.message)),!0;return await this.confirmApproval({thread:$,conversationId:Q,approvalId:Y.approvalId,confirmed:Y.confirmed,userPermissionLevel:B,...X?{metadata:X}:{}}),!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:Ud(A.thread),...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){return A.directives.flatMap(($)=>{if($.kind==="text")return[$.text];if($.kind==="denied-artifact")return[this.cardBuilder.formatStructuredCard($.card,Q)];return[]}).filter(($)=>$.trim().length>0).join(`
2399
+ \`\`\``;return this.defaultNodeToText(A,(Q)=>this.nodeToDiscordMarkdown(Q))}};var yK2={DeferredChannelMessageWithSource:5,DeferredUpdateMessage:6},RI0="https://discord.com/api/v10",gK2=2000,er6=/^[0-9a-f]{64}$/,Ao6=/^[0-9a-f]+$/,Qo6=class A{name="discord";userName;botUserId;apiBaseUrl;botToken;publicKey;applicationId;mentionRoleIds;interactionFlags;chat=null;logger;formatConverter=new tr6;requestContext=new cr6;threadParentCache=new Map;static THREAD_PARENT_CACHE_TTL=300000;constructor(Q={}){let $=Q.botToken??process.env.DISCORD_BOT_TOKEN;if(!$)throw new Iq("discord","botToken is required. Set DISCORD_BOT_TOKEN or provide it in config.");let w=Q.publicKey??process.env.DISCORD_PUBLIC_KEY;if(!w)throw new Iq("discord","publicKey is required. Set DISCORD_PUBLIC_KEY or provide it in config.");let B=Q.applicationId??process.env.DISCORD_APPLICATION_ID;if(!B)throw new Iq("discord","applicationId is required. Set DISCORD_APPLICATION_ID or provide it in config.");if(this.apiBaseUrl=Q.apiUrl??process.env.DISCORD_API_URL??RI0,this.botToken=$,this.publicKey=w.trim().toLowerCase(),this.applicationId=B,this.mentionRoleIds=Q.mentionRoleIds??(process.env.DISCORD_MENTION_ROLE_IDS?process.env.DISCORD_MENTION_ROLE_IDS.split(",").map((X)=>X.trim()):[]),this.botUserId=B,this.interactionFlags=Q.interactionFlags,this.logger=Q.logger??new bI0("info").child("discord"),this.userName=Q.userName??"bot",!er6.test(this.publicKey))this.logger.error("Invalid Discord public key format",{length:this.publicKey.length,isHex:Ao6.test(this.publicKey)})}async initialize(Q){this.chat=Q,this.logger.info("Discord adapter initialized")}async getUser(Q){try{let w=await(await this.discordFetch(`/users/${Q}`,"GET")).json();return{avatarUrl:w.avatar?`https://cdn.discordapp.com/avatars/${w.id}/${w.avatar}.png`:void 0,email:void 0,fullName:w.global_name||w.username,isBot:w.bot??!1,userId:w.id,userName:w.username}}catch{return null}}async handleWebhook(Q,$){let w=await Q.arrayBuffer(),B=new Uint8Array(w),X=new TextDecoder().decode(B),Y=Q.headers.get("x-discord-gateway-token");if(Y){if(Y!==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 G=JSON.parse(X);return this.handleForwardedGatewayEvent(G,$)}catch{return new Response("Invalid JSON",{status:400})}}this.logger.info("Discord webhook received",{bodyLength:X.length,bodyBytesLength:B.length,hasSignature:!!Q.headers.get("x-signature-ed25519"),hasTimestamp:!!Q.headers.get("x-signature-timestamp")});let Z=Q.headers.get("x-signature-ed25519"),W=Q.headers.get("x-signature-timestamp");if(!await this.verifySignature(B,Z,W))return this.logger.warn("Discord signature verification failed, returning 401"),new Response("Invalid signature",{status:401});this.logger.info("Discord signature verification passed");let U;try{U=JSON.parse(X)}catch{return new Response("Invalid JSON",{status:400})}if(this.logger.info("Discord interaction parsed",{type:U.type,typeIsPing:U.type===Wd.Ping,expectedPingType:Wd.Ping,id:U.id}),U.type===Wd.Ping){let G=JSON.stringify({type:z$0.InteractionResponseType.PONG});return this.logger.info("Discord PING received, responding with PONG",{responseBody:G,responseType:z$0.InteractionResponseType.PONG}),new Response(G,{status:200,headers:{"Content-Type":"application/json"}})}if(U.type===Wd.MessageComponent)return this.handleComponentInteraction(U,$),this.respondToInteraction({type:yK2.DeferredUpdateMessage});if(U.type===Wd.ApplicationCommand){let G=this.getApplicationCommandContext(U),D=this.getInteractionFlags(G);return this.handleApplicationCommandInteraction(G,$),this.respondToInteraction({...D===void 0?{}:{data:{flags:D}},type:yK2.DeferredChannelMessageWithSource})}return new Response("Unknown interaction type",{status:400})}async verifySignature(Q,$,w){if(!($&&w))return this.logger.warn("Discord signature verification failed: missing headers",{hasSignature:!!$,hasTimestamp:!!w}),!1;try{this.logger.info("Discord signature verification attempt",{bodyBytesLength:Q.length,signatureLength:$.length,timestampLength:w.length,publicKeyLength:this.publicKey.length,timestamp:w,signaturePrefix:$.slice(0,16),publicKey:this.publicKey});let B=await z$0.verifyKey(Q,$,w,this.publicKey);if(!B){let X=new TextDecoder().decode(Q);this.logger.warn("Discord signature verification failed: invalid signature",{publicKeyLength:this.publicKey.length,signatureLength:$.length,publicKeyPrefix:this.publicKey.slice(0,8),publicKeySuffix:this.publicKey.slice(-8),timestamp:w,bodyLength:Q.length,bodyPrefix:X.slice(0,50)})}return B}catch(B){return this.logger.warn("Discord signature verification failed: exception",{error:B}),!1}}respondToInteraction(Q){return Response.json(Q)}handleComponentInteraction(Q,$){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}let w=Q.data?.custom_id;if(!w){this.logger.warn("No custom_id in component interaction");return}let B=Q.member?.user||Q.user;if(!B){this.logger.warn("No user in component interaction");return}let X=Q.channel_id,Y=Q.guild_id||"@me",Z=Q.message?.id;if(!(X&&Z)){this.logger.warn("Missing channel_id or message_id in interaction");return}let W=Q.channel,K=W?.type===11||W?.type===12,U=K&&W?.parent_id?W.parent_id:X,G=K?this.encodeThreadId({guildId:Y,channelId:U,threadId:X}):this.encodeThreadId({guildId:Y,channelId:X}),D=lr6(w),q={actionId:D.actionId,value:D.value??D.actionId,user:{userId:B.id,userName:B.username,fullName:B.global_name||B.username,isBot:B.bot??!1,isMe:!1},messageId:Z,threadId:G,adapter:this,raw:Q};this.logger.debug("Processing Discord button action",{actionId:w,messageId:Z,threadId:G}),this.chat.processAction(q,$)}getApplicationCommandContext(Q){let $=Q.data?.name;if(!$)return this.logger.warn("No command name in application command interaction"),null;let w=Q.member?.user||Q.user;if(!w)return this.logger.warn("No user in application command interaction"),null;let B=Q.channel_id;if(!B)return this.logger.warn("Missing channel_id in application command interaction"),null;let X=Q.guild_id||"@me",Y=Q.channel,Z=Y?.type===11||Y?.type===12,W=Z&&Y?.parent_id?Y.parent_id:B,K=Z?this.encodeThreadId({guildId:X,channelId:W,threadId:B}):this.encodeThreadId({guildId:X,channelId:B}),{command:U,text:G}=this.parseSlashCommand($,Q.data?.options);return{channelId:K,command:U,interaction:Q,text:G,user:w}}getInteractionFlags(Q){if(!(Q&&this.interactionFlags))return;return this.interactionFlags(Q)}handleApplicationCommandInteraction(Q,$){if(!this.chat){this.logger.warn("Chat instance not initialized, ignoring interaction");return}if(!Q)return;let{channelId:w,command:B,interaction:X,text:Y,user:Z}=Q;this.logger.debug("Processing Discord slash command",{command:B,text:Y,userId:Z.id,channelId:w}),this.requestContext.run({slashCommand:{channelId:w,interactionToken:X.token,initialResponseSent:!1}},()=>{this.chat?.processSlashCommand({command:B,text:Y,user:{userId:Z.id,userName:Z.username,fullName:Z.global_name||Z.username,isBot:Z.bot??!1,isMe:Z.id===this.applicationId},adapter:this,raw:X,channelId:w},$)})}parseSlashCommand(Q,$){let w=[Q.startsWith("/")?Q:`/${Q}`],B=[],X=(Y)=>{for(let Z of Y){if(Z.value!==void 0){B.push(String(Z.value));continue}if(Z.options&&Z.options.length>0)w.push(Z.name),X(Z.options)}};if($&&$.length>0)X($);return{command:w.join(" "),text:B.join(" ").trim()}}async handleGatewayInteraction(Q){if(Q.isChatInputCommand()){let $=this.getApplicationCommandContext(this.normalizeGatewaySlashCommandInteraction(Q)),w=this.getInteractionFlags($);await Q.deferReply(w===void 0?void 0:{flags:w}),this.handleApplicationCommandInteraction($);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 $="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:$},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 $="parentId"in Q.channel&&typeof Q.channel.parentId==="string"?Q.channel.parentId:void 0;return{id:Q.channel.id,parent_id:$,type:Q.channel.type}}normalizeGatewayCommandOptions(Q){return Q.map(($)=>({name:$.name,options:$.options?this.normalizeGatewayCommandOptions($.options):void 0,type:$.type,value:$.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,$){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,$);break;case"GATEWAY_MESSAGE_REACTION_ADD":await this.handleForwardedReaction(Q.data,!0,$);break;case"GATEWAY_MESSAGE_REACTION_REMOVE":await this.handleForwardedReaction(Q.data,!1,$);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,$){if(!this.chat)return;let w=Q.guild_id||"@me",B=Q.channel_id,X,Y=B;if(Q.thread)X=Q.thread.id,Y=Q.thread.parent_id;else if(Q.channel_type===11||Q.channel_type===12)try{let q=await(await this.discordFetch(`/channels/${B}`,"GET")).json();if(q.parent_id)X=B,Y=q.parent_id,this.logger.debug("Fetched thread parent for forwarded message",{threadId:B,parentId:q.parent_id})}catch(D){this.logger.error("Failed to fetch thread parent",{error:String(D),channelId:B})}let Z=Q.is_mention||Q.mentions.some((D)=>D.id===this.applicationId),W=this.mentionRoleIds.length>0&&Q.mention_roles?.some((D)=>this.mentionRoleIds.includes(D)),K=Z||W;if(!X&&K)try{let D=await this.createDiscordThread(B,Q.id);X=D.id,this.logger.debug("Created Discord thread for forwarded mention",{channelId:B,messageId:Q.id,threadId:D.id})}catch(D){this.logger.error("Failed to create Discord thread for mention",{error:String(D),messageId:Q.id})}let U=this.encodeThreadId({guildId:w,channelId:Y,threadId:X}),G=new n9({id:Q.id,threadId:U,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((D)=>({type:this.getAttachmentType(D.content_type),url:D.url,name:D.filename,mimeType:D.content_type,size:D.size})),raw:Q,isMention:K});try{await this.chat.handleIncomingMessage(this,U,G)}catch(D){this.logger.error("Error handling forwarded message",{error:String(D),messageId:Q.id})}}async handleForwardedReaction(Q,$,w){if(!this.chat)return;let B=Q.guild_id||"@me",X=Q.channel_id,Y,Z=X;if(Q.channel_type===dh.GuildPublicThread||Q.channel_type===dh.GuildPrivateThread){let q=this.threadParentCache.get(X);if(q&&q.expiresAt>Date.now())Y=X,Z=q.parentId;else try{let F=await(await this.discordFetch(`/channels/${X}`,"GET")).json();if(F.parent_id)Y=X,Z=F.parent_id,this.threadParentCache.set(X,{parentId:F.parent_id,expiresAt:Date.now()+A.THREAD_PARENT_CACHE_TTL})}catch(J){this.logger.error("Failed to fetch thread parent for reaction",{error:String(J),channelId:X})}}let W=this.encodeThreadId({guildId:B,channelId:Z,threadId:Y}),K=Q.emoji.name||"unknown",U=this.normalizeDiscordEmoji(K),G=Q.user??Q.member?.user;if(!G){this.logger.warn("Reaction event missing user info",{data:Q});return}let D={adapter:this,threadId:W,messageId:Q.message_id,emoji:U,rawEmoji:Q.emoji.id?`<:${K}:${Q.emoji.id}>`:K,added:$,user:{userId:G.id,userName:G.username,fullName:G.username,isBot:G.bot===!0,isMe:G.id===this.applicationId},raw:Q};this.chat.processReaction(D)}async postMessage(Q,$){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=Q;if(B)w=B;let Y={},Z=[],W=[],K=xI0($);if(K){let J=u4A(K);Z.push(...J.embeds),W.push(...J.components)}else Y.content=this.truncateContent(uh(this.formatConverter.renderPostable($),"discord"));if(Z.length>0)Y.embeds=Z;if(W.length>0)Y.components=W;let U=I4A($),G=this.tryPostSlashResponse(X,Y,U);if(G)return G;if(U.length>0)return this.postMessageWithFiles(w,X,Y,U);this.logger.debug("Discord API: POST message",{channelId:w,contentLength:Y.content?.length||0,embedCount:Z.length,componentCount:W.length});let q=await(await this.discordFetch(`/channels/${w}/messages`,"POST",Y)).json();return this.logger.debug("Discord API: POST message response",{messageId:q.id}),{id:q.id,threadId:X,raw:q}}tryPostSlashResponse(Q,$,w){let B=this.requestContext.getStore()?.slashCommand;if(!B||B.channelId!==Q)return;return this.postSlashCommandResponse(B,Q,$,w)}async postSlashCommandResponse(Q,$,w,B){let X=!Q.initialResponseSent;Q.initialResponseSent=!0;let Y=X?`/webhooks/${this.applicationId}/${Q.interactionToken}/messages/@original`:`/webhooks/${this.applicationId}/${Q.interactionToken}?wait=true`,Z=X?"PATCH":"POST";this.logger.debug("Discord interaction webhook: responding to slash command",{threadId:$,isInitialResponse:X,hasFiles:B.length>0});let K=await(B.length>0?await this.discordInteractionFetchWithFiles(Y,Z,w,B):await this.discordInteractionFetch(Y,Z,w)).json();return{id:K.id,threadId:$,raw:K}}async createDiscordThread(Q,$){let w=`Thread ${new Date().toLocaleString()}`;this.logger.debug("Discord API: POST thread",{channelId:Q,messageId:$,threadName:w});try{let X=await(await this.discordFetch(`/channels/${Q}/messages/${$}/threads`,"POST",{name:w,auto_archive_duration:1440})).json();return this.logger.debug("Discord API: POST thread response",{threadId:X.id,threadName:X.name}),X}catch(B){if(B instanceof YO&&typeof B.message==="string"&&B.message.includes('"code"')&&B.message.includes("160004"))return this.logger.debug("Thread already exists for message, reusing existing thread",{channelId:Q,messageId:$}),{id:$,name:w};throw B}}truncateContent(Q){if(Q.length<=gK2)return Q;return`${Q.slice(0,gK2-3)}...`}async postMessageWithFiles(Q,$,w,B){let X=new FormData;X.append("payload_json",JSON.stringify(w));for(let W=0;W<B.length;W++){let K=B[W];if(!K)continue;let U=await L4A(K.data,{platform:"discord"});if(!U)continue;let G=new Blob([new Uint8Array(U)],{type:K.mimeType||"application/octet-stream"});X.append(`files[${W}]`,G,K.filename)}let Y=await fetch(`${RI0}/channels/${Q}/messages`,{method:"POST",headers:{Authorization:`Bot ${this.botToken}`},body:X});if(!Y.ok){let W=await Y.text();throw new YO("discord",`Failed to post message: ${Y.status} ${W}`)}let Z=await Y.json();return{id:Z.id,threadId:$,raw:Z}}async discordInteractionFetch(Q,$,w){let B=await fetch(`${RI0}${Q}`,{method:$,headers:w?{"Content-Type":"application/json"}:void 0,body:w?JSON.stringify(w):void 0});if(!B.ok){let X=await B.text();throw this.logger.error("Discord interaction API error",{path:Q,method:$,status:B.status,error:X}),new YO("discord",`Discord interaction API error: ${B.status} ${X}`)}return B}async discordInteractionFetchWithFiles(Q,$,w,B){let X=new FormData;X.append("payload_json",JSON.stringify(w));for(let Z=0;Z<B.length;Z++){let W=B[Z];if(!W)continue;let K=await L4A(W.data,{platform:"discord"});if(!K)continue;let U=new Blob([new Uint8Array(K)],{type:W.mimeType||"application/octet-stream"});X.append(`files[${Z}]`,U,W.filename)}let Y=await fetch(`${RI0}${Q}`,{method:$,body:X});if(!Y.ok){let Z=await Y.text();throw this.logger.error("Discord interaction API error",{path:Q,method:$,status:Y.status,error:Z}),new YO("discord",`Discord interaction API error: ${Y.status} ${Z}`)}return Y}async editMessage(Q,$,w){let{channelId:B,threadId:X}=this.decodeThreadId(Q),Y=X||B,Z={},W=[],K=[],U=xI0(w);if(U){let q=u4A(U);W.push(...q.embeds),K.push(...q.components),Z.content=""}else Z.content=this.truncateContent(uh(this.formatConverter.renderPostable(w),"discord"));if(W.length>0)Z.embeds=W;if(K.length>0)Z.components=K;this.logger.debug("Discord API: PATCH message",{channelId:Y,messageId:$,contentLength:Z.content?.length||0});let D=await(await this.discordFetch(`/channels/${Y}/messages/${$}`,"PATCH",Z)).json();return this.logger.debug("Discord API: PATCH message response",{messageId:D.id}),{id:D.id,threadId:Q,raw:D}}async deleteMessage(Q,$){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=B||w;this.logger.debug("Discord API: DELETE message",{channelId:X,messageId:$}),await this.discordFetch(`/channels/${X}/messages/${$}`,"DELETE"),this.logger.debug("Discord API: DELETE message response",{ok:!0})}async addReaction(Q,$,w){let{channelId:B,threadId:X}=this.decodeThreadId(Q),Y=X||B,Z=this.encodeEmoji(w);this.logger.debug("Discord API: PUT reaction",{channelId:Y,messageId:$,emoji:Z}),await this.discordFetch(`/channels/${Y}/messages/${$}/reactions/${Z}/@me`,"PUT"),this.logger.debug("Discord API: PUT reaction response",{ok:!0})}async removeReaction(Q,$,w){let{channelId:B,threadId:X}=this.decodeThreadId(Q),Y=X||B,Z=this.encodeEmoji(w);this.logger.debug("Discord API: DELETE reaction",{channelId:Y,messageId:$,emoji:Z}),await this.discordFetch(`/channels/${Y}/messages/${$}/reactions/${Z}/@me`,"DELETE"),this.logger.debug("Discord API: DELETE reaction response",{ok:!0})}encodeEmoji(Q){let $=K$0.toDiscord?K$0.toDiscord(Q):String(Q);return encodeURIComponent($)}async startTyping(Q,$){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=B||w;this.logger.debug("Discord API: POST typing",{channelId:X}),await this.discordFetch(`/channels/${X}/typing`,"POST")}async fetchMessages(Q,$={}){let{channelId:w,threadId:B}=this.decodeThreadId(Q),X=B||w,Y=$.limit||50,Z=$.direction??"backward",W=new URLSearchParams;if(W.set("limit",String(Y)),$.cursor)if(Z==="backward")W.set("before",$.cursor);else W.set("after",$.cursor);this.logger.debug("Discord API: GET messages",{channelId:X,limit:Y,direction:Z,cursor:$.cursor});let U=await(await this.discordFetch(`/channels/${X}/messages?${W.toString()}`,"GET")).json();this.logger.debug("Discord API: GET messages response",{messageCount:U.length});let D=[...U].reverse().map((J)=>this.parseDiscordMessage(J,Q)),q;if(U.length===Y)if(Z==="backward")q=U.at(-1)?.id;else q=U[0]?.id;return{messages:D,nextCursor:q}}async fetchThread(Q){let{channelId:$,guildId:w}=this.decodeThreadId(Q);this.logger.debug("Discord API: GET channel",{channelId:$});let X=await(await this.discordFetch(`/channels/${$}`,"GET")).json();return{id:Q,channelId:$,channelName:X.name,isDM:X.type===dh.DM||X.type===dh.GroupDM,metadata:{guildId:w,channelType:X.type,raw:X}}}async openDM(Q){this.logger.debug("Discord API: POST DM channel",{userId:Q});let w=await(await this.discordFetch("/users/@me/channels","POST",{recipient_id:Q})).json();return this.logger.debug("Discord API: POST DM channel response",{channelId:w.id}),this.encodeThreadId({guildId:"@me",channelId:w.id})}isDM(Q){let{guildId:$}=this.decodeThreadId(Q);return $==="@me"}encodeThreadId(Q){let $=Q.threadId?`:${Q.threadId}`:"";return`discord:${Q.guildId}:${Q.channelId}${$}`}decodeThreadId(Q){let $=Q.split(":");if($.length<3||$[0]!=="discord")throw new Iq("discord",`Invalid Discord thread ID: ${Q}`);return{guildId:$[1],channelId:$[2],threadId:$[3]}}parseMessage(Q){let $=Q,w=$.guild_id||"@me",B=this.encodeThreadId({guildId:w,channelId:$.channel_id});return this.parseDiscordMessage($,B)}parseDiscordMessage(Q,$){let w=Q.type===EX2.ThreadStarterMessage&&Q.referenced_message?Q.referenced_message:Q,B=w.author,X=B.bot??!1,Y=B.id===this.botUserId;return new n9({id:w.id,threadId:$,text:this.formatConverter.extractPlainText(w.content),formatted:this.formatConverter.toAst(w.content),raw:Q,author:{userId:B.id,userName:B.username,fullName:B.global_name||B.username,isBot:X,isMe:Y},metadata:{dateSent:new Date(w.timestamp),edited:w.edited_timestamp!==null,editedAt:w.edited_timestamp?new Date(w.edited_timestamp):void 0},attachments:(w.attachments||[]).map((Z)=>({type:this.getAttachmentType(Z.content_type),url:Z.url,name:Z.filename,mimeType:Z.content_type,size:Z.size,width:Z.width??void 0,height:Z.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"}rehydrateAttachment(Q){let $=Q.fetchMetadata?.url??Q.url;if(!$)return Q;return{...Q,fetchData:()=>this.downloadAttachment($)}}async downloadAttachment(Q){let $;try{$=await fetch(Q)}catch(w){throw new YO("discord","Failed to download Discord attachment",w instanceof Error?w:void 0)}if(!$.ok)throw new YO("discord",`Failed to download Discord attachment: ${$.status}`);return Buffer.from(await $.arrayBuffer())}renderFormatted(Q){return this.formatConverter.fromAst(Q)}async discordFetch(Q,$,w){let B=`${this.apiBaseUrl}${Q}`,X={Authorization:`Bot ${this.botToken}`};if(w)X["Content-Type"]="application/json";let Y=await fetch(B,{method:$,headers:X,body:w?JSON.stringify(w):void 0});if(!Y.ok){let Z=await Y.text();throw this.logger.error("Discord API error",{path:Q,method:$,status:Y.status,error:Z}),new YO("discord",`Discord API error: ${Y.status} ${Z}`)}return Y}async startGatewayListener(Q,$=180000,w,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:$,webhookUrl:B?"configured":"not configured"});let X=this.runGatewayListener($,w,B);return Q.waitUntil(X),new Response(JSON.stringify({status:"listening",durationMs:$,message:`Gateway listener started, will run for ${$/1000} seconds`}),{status:200,headers:{"Content-Type":"application/json"}})}async runGatewayListener(Q,$,w){let B=new xX.Client({intents:[xX.GatewayIntentBits.Guilds,xX.GatewayIntentBits.GuildMessages,xX.GatewayIntentBits.MessageContent,xX.GatewayIntentBits.DirectMessages,xX.GatewayIntentBits.GuildMessageReactions,xX.GatewayIntentBits.DirectMessageReactions],partials:[xX.Partials.Channel]}),X=!1;if(w)B.on("raw",async(Y)=>{if(X)return;if(!Y.t)return;this.logger.info("Discord Gateway forwarding event",{type:Y.t}),await this.forwardGatewayEvent(w,{type:`GATEWAY_${Y.t}`,timestamp:Date.now(),data:Y.d})});else this.setupLegacyGatewayHandlers(B,()=>X);B.on(xX.Events.ClientReady,()=>{this.logger.info("Discord Gateway connected",{username:B.user?.username,id:B.user?.id})}),B.on(xX.Events.Error,(Y)=>{this.logger.error("Discord Gateway error",{error:String(Y)})});try{await B.login(this.botToken),await new Promise((Y)=>{let Z=setTimeout(Y,Q);if($){if($.aborted){clearTimeout(Z),Y();return}$.addEventListener("abort",()=>{this.logger.info("Discord Gateway listener received abort signal (new listener started)"),clearTimeout(Z),Y()},{once:!0})}}),this.logger.info("Discord Gateway listener duration elapsed, disconnecting")}catch(Y){this.logger.error("Discord Gateway listener error",{error:String(Y)})}finally{X=!0,B.destroy(),this.logger.info("Discord Gateway listener stopped")}}setupLegacyGatewayHandlers(Q,$){Q.on(xX.Events.MessageCreate,async(w)=>{if($()){this.logger.debug("Ignoring message - Gateway is shutting down");return}if(w.author.bot){this.logger.debug("Ignoring message from bot",{authorId:w.author.id,authorName:w.author.username,isMe:w.author.id===Q.user?.id});return}let B=w.mentions.has(Q.user?.id??""),X=this.mentionRoleIds.length>0&&w.mentions.roles.some((Z)=>this.mentionRoleIds.includes(Z.id)),Y=B||X;this.logger.info("Discord Gateway message received",{channelId:w.channelId,guildId:w.guildId,authorId:w.author.id,isMentioned:Y,isUserMentioned:B,isRoleMentioned:X,content:w.content.slice(0,100)}),await this.handleGatewayMessage(w,Y)}),Q.on(xX.Events.InteractionCreate,async(w)=>{if($()){this.logger.debug("Ignoring interaction - Gateway is shutting down");return}this.logger.info("Discord Gateway interaction received",{id:w.id,type:w.type});try{await this.handleGatewayInteraction(w)}catch(B){this.logger.error("Error handling Gateway interaction",{error:String(B),interactionId:w.id})}}),Q.on(xX.Events.MessageReactionAdd,async(w,B)=>{if($()){this.logger.debug("Ignoring reaction - Gateway is shutting down");return}if(B.bot){this.logger.debug("Ignoring reaction from bot",{userId:B.id,isMe:B.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction added",{emoji:w.emoji.name,messageId:w.message.id,channelId:w.message.channelId,userId:B.id}),B.username)await this.handleGatewayReaction(w,B,!0)}),Q.on(xX.Events.MessageReactionRemove,async(w,B)=>{if($()){this.logger.debug("Ignoring reaction removal - Gateway is shutting down");return}if(B.bot){this.logger.debug("Ignoring reaction removal from bot",{userId:B.id,isMe:B.id===Q.user?.id});return}if(this.logger.info("Discord Gateway reaction removed",{emoji:w.emoji.name,messageId:w.message.id,channelId:w.message.channelId,userId:B.id}),B.username)await this.handleGatewayReaction(w,B,!1)})}async forwardGatewayEvent(Q,$){try{this.logger.debug("Forwarding Gateway event to webhook",{type:$.type,webhookUrl:Q});let w=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/json","x-discord-gateway-token":this.botToken},body:JSON.stringify($)});if(w.ok)this.logger.debug("Gateway event forwarded successfully",{type:$.type});else{let B=await w.text();this.logger.error("Failed to forward Gateway event",{type:$.type,status:w.status,error:B})}}catch(w){this.logger.error("Error forwarding Gateway event",{type:$.type,error:String(w)})}}async handleGatewayMessage(Q,$){if(!this.chat)return;let w=Q.guildId||"@me",B=Q.channelId,X=Q.channel.isThread(),Y,Z=B;if(X&&"parentId"in Q.channel&&Q.channel.parentId)Y=B,Z=Q.channel.parentId;if(!Y&&$)try{let U=await this.createDiscordThread(B,Q.id);Y=U.id,this.logger.debug("Created Discord thread for incoming mention",{channelId:B,messageId:Q.id,threadId:U.id})}catch(U){this.logger.error("Failed to create Discord thread for mention",{error:String(U),messageId:Q.id})}let W=this.encodeThreadId({guildId:w,channelId:Z,threadId:Y}),K=new n9({id:Q.id,threadId:W,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((U)=>({type:this.getAttachmentType(U.contentType),url:U.url,name:U.name,mimeType:U.contentType??void 0,size:U.size})),raw:{id:Q.id,channel_id:B,guild_id:w,content:Q.content,author:{id:Q.author.id,username:Q.author.username},timestamp:Q.createdAt.toISOString()},isMention:$});try{await this.chat.handleIncomingMessage(this,W,K)}catch(U){this.logger.error("Error handling Gateway message",{error:String(U),messageId:Q.id})}}async handleGatewayReaction(Q,$,w){if(!this.chat)return;let B=Q.message.guildId||"@me",X=Q.message.channelId,Y=Q.message.channel?.isThread?.(),Z=X,W;if(Y&&Q.message.channel?.parentId)W=X,Z=Q.message.channel.parentId;let K=this.encodeThreadId({guildId:B,channelId:Z,threadId:W}),U=Q.emoji.name||"unknown",G=this.normalizeDiscordEmoji(U),D={adapter:this,threadId:K,messageId:Q.message.id,emoji:G,rawEmoji:Q.emoji.id?`<:${U}:${Q.emoji.id}>`:U,added:w,user:{userId:$.id,userName:$.username,fullName:$.username,isBot:$.bot===!0,isMe:$.id===this.applicationId},raw:{emoji:Q.emoji,message_id:Q.message.id,channel_id:Q.message.channelId,guild_id:Q.message.guildId,user_id:$.id}};this.chat.processReaction(D)}channelIdFromThreadId(Q){return Q.split(":").slice(0,3).join(":")}async fetchChannelMessages(Q,$={}){let B=Q.split(":")[2];if(!B)throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);let X=$.limit||50,Y=$.direction??"backward",Z=new URLSearchParams;if(Z.set("limit",String(X)),$.cursor)if(Y==="backward")Z.set("before",$.cursor);else Z.set("after",$.cursor);this.logger.debug("Discord API: GET channel messages",{channelId:B,limit:X,direction:Y,cursor:$.cursor});let K=await(await this.discordFetch(`/channels/${B}/messages?${Z.toString()}`,"GET")).json();this.logger.debug("Discord API: GET channel messages response",{messageCount:K.length});let G=[...K].reverse().map((q)=>this.parseDiscordMessage(q,Q)),D;if(K.length===X)if(Y==="backward")D=K.at(-1)?.id;else D=K[0]?.id;return{messages:G,nextCursor:D}}async listThreads(Q,$={}){let w=Q.split(":"),B=w[1],X=w[2];if(!(B&&X))throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET threads",{guildId:B,channelId:X});let W=((await(await this.discordFetch(`/guilds/${B}/threads/active`,"GET")).json()).threads||[]).filter((I)=>I.parent_id===X),K=[];try{K=(await(await this.discordFetch(`/channels/${X}/threads/archived/public?limit=${$.limit||50}`,"GET")).json()).threads||[]}catch{this.logger.debug("Could not fetch archived threads (may lack permissions)")}let U=[...W,...K],G=new Set,D=U.filter((I)=>{if(G.has(I.id))return!1;return G.add(I.id),!0}),q=$.limit||50,J=D.slice(0,q),F=[];for(let I of J){let P=this.encodeThreadId({guildId:B,channelId:X,threadId:I.id});try{let f=(await(await this.discordFetch(`/channels/${I.id}/messages?limit=1&after=0`,"GET")).json())[0];if(f)F.push({id:P,rootMessage:this.parseDiscordMessage(f,P),replyCount:I.total_message_sent??I.message_count,lastReplyAt:I.thread_metadata?.archive_timestamp?new Date(I.thread_metadata.archive_timestamp):void 0})}catch{F.push({id:P,rootMessage:new n9({id:I.id,threadId:P,text:I.name,formatted:this.formatConverter.toAst(I.name),raw:I,author:{userId:"unknown",userName:"unknown",fullName:"unknown",isBot:!1,isMe:!1},metadata:{dateSent:new Date,edited:!1},attachments:[]}),replyCount:I.total_message_sent??I.message_count})}}return this.logger.debug("Discord API: listThreads result",{threadCount:F.length}),{threads:F,nextCursor:D.length>q?String(q):void 0}}async fetchChannelInfo(Q){let w=Q.split(":")[2];if(!w)throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);this.logger.debug("Discord API: GET channel info",{channelId:w});let X=await(await this.discordFetch(`/channels/${w}`,"GET")).json();return{id:Q,name:X.name,isDM:X.type===dh.DM||X.type===dh.GroupDM,memberCount:X.member_count,metadata:{channelType:X.type,raw:X}}}async postChannelMessage(Q,$){let B=Q.split(":")[2];if(!B)throw new Iq("discord",`Invalid Discord channel ID: ${Q}`);let X={},Y=[],Z=[],W=xI0($);if(W){let q=u4A(W);Y.push(...q.embeds),Z.push(...q.components)}else X.content=this.truncateContent(uh(this.formatConverter.renderPostable($),"discord"));if(Y.length>0)X.embeds=Y;if(Z.length>0)X.components=Z;let K=I4A($),U=this.tryPostSlashResponse(Q,X,K);if(U)return U;if(K.length>0)return this.postMessageWithFiles(B,Q,X,K);this.logger.debug("Discord API: POST channel message",{channelId:B,contentLength:X.content?.length||0});let D=await(await this.discordFetch(`/channels/${B}/messages`,"POST",X)).json();return{id:D.id,threadId:Q,raw:D}}normalizeDiscordEmoji(Q){let w={"\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 XO(w)}};function uK2(A){return new Qo6(A??{})}var $o6=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 $=this.locks.get(A);if($&&$.expiresAt>Date.now())return null;let w={threadId:A,token:wo6(),expiresAt:Date.now()+Q};return this.locks.set(A,w),w}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 $=this.locks.get(A.threadId);if(!$||$.token!==A.token)return!1;if($.expiresAt<Date.now())return this.locks.delete(A.threadId),!1;return $.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,$){this.ensureConnected(),this.cache.set(A,{value:Q,expiresAt:$?Date.now()+$:null})}async setIfNotExists(A,Q,$){this.ensureConnected();let w=this.cache.get(A);if(w)if(w.expiresAt!==null&&w.expiresAt<=Date.now())this.cache.delete(A);else return!1;return this.cache.set(A,{value:Q,expiresAt:$?Date.now()+$:null}),!0}async delete(A){this.ensureConnected(),this.cache.delete(A)}async appendToList(A,Q,$){this.ensureConnected();let w=this.cache.get(A),B;if(w&&w.expiresAt!==null&&w.expiresAt<=Date.now())B=[];else if(w&&Array.isArray(w.value))B=w.value;else B=[];if(B.push(Q),$?.maxLength&&B.length>$.maxLength)B=B.slice(B.length-$.maxLength);this.cache.set(A,{value:B,expiresAt:$?.ttlMs?Date.now()+$.ttlMs:null})}async enqueue(A,Q,$){this.ensureConnected();let w=this.queues.get(A);if(!w)w=[],this.queues.set(A,w);if(w.push(Q),w.length>$)w.splice(0,w.length-$);return w.length}async dequeue(A){this.ensureConnected();let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let $=Q.shift();if(Q.length===0)this.queues.delete(A);return $??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,$]of this.locks)if($.expiresAt<=A)this.locks.delete(Q)}_getSubscriptionCount(){return this.subscriptions.size}_getLockCount(){return this.cleanExpiredLocks(),this.locks.size}};function wo6(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function vI0(A){return new $o6}C0();var Bo6=H.object({subscribedAt:H.string().datetime(),routingMode:H.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:H.boolean().optional()}),Xo6="chat.discord.subscriptions";function c4A(A){return A.scoped({namespace:Xo6,schema:Bo6})}function cK2(A,Q=vI0()){let $=c4A(A);return new pK2(Q,$)}class pK2{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,$){return this.memoryState.appendToList(A,Q,$)}delete(A){return this.memoryState.delete(A)}dequeue(A){return this.memoryState.dequeue(A)}enqueue(A,Q,$){return this.memoryState.enqueue(A,Q,$)}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,$){return this.memoryState.set(A,Q,$)}setIfNotExists(A,Q,$){return this.memoryState.setIfNotExists(A,Q,$)}}function lK2(A){let{discord:Q}=A;if(!Q)return new V4A({userName:A.userName,adapters:{},state:vI0()});let $=uK2({botToken:Q.botToken,publicKey:Q.publicKey,applicationId:Q.applicationId,mentionRoleIds:Q.mentionRoleIds});return A.gatewayLoop.setAdapter($),new V4A({userName:A.userName,adapters:{discord:$},concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"},state:cK2(A.runtimeState)})}class p4A{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($){this.deps.logger.debug("Discord thread subscription failed",{error:$,threadId:A.id})}}async shouldRouteSubscribedMessage(A,Q){if(this.deps.getPlatform(A)!=="discord")return!1;if(A.isDM)return!0;let $=await this.deps.getSubscriptions()?.get(A.id);if(!$)return!1;if($.routingMode==="mention-required"){if(!Q.isMention&&!$.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,$);return Boolean(Q.isMention)}if(!await this.shouldRequireMentionInSubscribedThread(A))return!0;let B={...$,routingMode:"mention-required"};if(!Q.isMention&&!$.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(A,B);else await this.deps.getSubscriptions()?.set(A.id,B);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((w)=>!w.isBot&&!w.isMe).length>1}catch(Q){return this.deps.logger.debug("Failed to inspect Discord thread participants",{error:Q,threadId:A.id}),!1}}}KA();class l4A{deps;constructor(A){this.deps=A}async build(A,Q,$,w){let B={message:$.text.trim(),attachments:[],notices:[]};if($.attachments.length===0)return B;if(!(w==="anchor"||w==="trusted"))return B;let Y=this.deps.getUploadStore();if(!Y)return B;for(let Z of $.attachments){let W=Z.name;if(!W)continue;let K=vN(W,"upload"),U=BM(K,Z.mimeType),G=Z.size??0,D=CU0(K,U);if(!D){B.notices.push(`Unsupported file upload type: ${K}`);continue}if(!hU0(D,G)){B.notices.push(`File upload too large: ${K}`);continue}try{let q=await this.readAttachmentData(Z);if(!q)continue;let J=CN({filename:K,mediaType:U,content:q,fallbackFilename:"upload"});if(!J.ok){B.notices.push(J.message);continue}let F=await Y.save({filename:J.filename,mediaType:J.mediaType,content:q,metadata:this.buildMetadata(A,Q,$)});B.attachments.push(iK2(F.filename,F.mediaType,q,F.ref,J.kind==="text"))}catch(q){this.deps.logger.error("Failed to read chat attachment",{error:q,filename:K}),B.notices.push(`Could not read file upload: ${K}`)}}return B}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 $=await Q.arrayBuffer();return Buffer.from(new Uint8Array($))}buildMetadata(A,Q,$){let w=this.deps.getThreadIdParts(Q.id);return{interfaceType:A,channelId:Q.id,parentChannelId:Q.channelId,messageId:$.id,uploaderId:$.author.userId,uploaderUsername:$.author.userName,...w.guildId?{guildId:w.guildId}:{},...w.threadId?{threadId:w.threadId}:{}}}}function dK2(A,Q,$,w){return iK2(A,Q,$,w,XM(A,Q))}function iK2(A,Q,$,w,B){if(B)return{kind:"text",filename:A,mediaType:Q,content:$.toString("utf8").replace(/^\uFEFF/,""),sizeBytes:$.byteLength,source:w};return{kind:"file",filename:A,mediaType:Q,data:$,sizeBytes:$.byteLength,source:w}}function V$0(){return{namespace:"discord-chat",refKind:"discord-chat-upload",routePath:"/api/webhooks/chat/discord/uploads"}}function fF(A){let Q=A.split(":");if(Q[0]!=="discord")return{};return{...Q[1]?{guildId:Q[1]}:{},...Q[2]?{channelId:Q[2]}:{},...Q[3]?{threadId:Q[3]}:{}}}function Yo6(A){let Q=A.raw;if(typeof Q!=="object"||Q===null)return;let $=Q.channel_id;return typeof $==="string"?$:void 0}function nK2(A,Q){if(A.isDM)return!1;let $=fF(A.id);if(!$.threadId)return!1;let w=Yo6(Q);return w!==void 0&&w!==$.threadId}function CI0(A,Q){if(Q.allowedChannels.length===0||A.isDM)return!0;let $=fF(A.id);return[A.id,A.channelId,$.channelId,$.threadId].some((w)=>typeof w==="string"&&Q.allowedChannels.includes(w))}function d4A(A,Q,$){if(A.isDM&&!$.allowDMs)return!1;if(Q.author.isMe)return!1;if(Q.author.isBot&&!Q.isMention)return!1;return CI0(A,$)}function i4A(A,Q,$){if(Q!=="discord")return!0;if(!$)return!1;if(A.isDM&&!$.allowDMs)return!1;return CI0(A,$)}function n4A(A,Q){return{channelId:fF(A.id).channelId??A.channelId,isBot:Boolean(Q.author.isBot)}}function Ud(A){return A.isDM?"DM":A.channelId}var Zo6="https://discord.com/api/v10";async function rK2(A){let Q=fF(A.threadId),$=Q.threadId??Q.channelId;if(!$)return;let w=A.fetchFn??fetch;try{let B=await w(`${Zo6}/channels/${$}/messages/${A.messageId}`,{method:"PATCH",headers:{Authorization:`Bot ${A.botToken}`,"Content-Type":"application/json"},body:JSON.stringify({components:[]})});if(!B.ok)A.logger.debug("Failed to clear Discord message components",{messageId:A.messageId,channelId:$,status:B.status})}catch(B){A.logger.debug("Failed to clear Discord message components",{error:B,messageId:A.messageId,channelId:$})}}var oK2={name:"@brains/chat",version:"0.2.0-alpha.184",description:"Discord Chat SDK interface for Brains",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":"^1.3.14"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Wo6=/https?:\/\/\S+/i,Ko6=/[\s\S]+/,Uo6=1000,Go6=H.looseObject({type:H.literal("card"),children:H.array(H.looseObject({type:H.string()})),imageUrl:H.string().optional(),subtitle:H.string().optional(),title:H.string().optional()}),Do6=H.object({card:H.custom((A)=>Go6.safeParse(A).success),fallbackText:H.string().optional()});class hI0 extends mz{threadRegistry=new JI0;pendingApprovals;uploadContinuity;promptActions=new i9A(Uo6);toolStatusMessenger=new n9A(this.threadRegistry);cardBuilder=new a9A({getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),registerPromptAction:(A,Q)=>this.registerPromptAction(A,Q)});artifactDelivery=new e9A({getContext:()=>this.context,getDisplayBaseUrl:()=>this.getPreferredDisplayBaseUrl(),logger:this.logger});approvalCards=new A7A({cardBuilder:this.cardBuilder,clearMessageComponents:async(A,Q)=>{let $=this.config.adapters.discord?.botToken;if(!$)return;await rK2({threadId:A,messageId:Q,botToken:$,logger:this.logger})}});subscriptionRouter=new p4A({getSubscriptions:()=>this.discordSubscriptions,getPlatform:(A)=>this.getPlatform(A),isBotCreatedThread:nK2,logger:this.logger});chatInputBuilder=new l4A({getUploadStore:()=>this.context?.uploads.scoped(V$0()),getThreadIdParts:fF,logger:this.logger});gatewayLoop;discordApp;discordSubscriptions;constructor(A={}){super("chat",oK2,A,d9A);this.gatewayLoop=new Q7A({getApp:()=>this.discordApp.instance,gatewayRunMs:this.config.gatewayRunMs,gatewayRestartDelayMs:this.config.gatewayRestartDelayMs,logger:this.logger}),this.discordApp=new $7A({discord:this.config.adapters.discord,getUploadStore:()=>this.context?.uploads.scoped(V$0()),buildApp:(Q)=>lK2({userName:this.config.userName,discord:this.config.adapters.discord,gatewayLoop:this.gatewayLoop,runtimeState:Q})}),this.pendingApprovals=new se({loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},onRestoreError:(Q,$)=>{this.logger.debug("Failed to load pending chat approvals",{error:Q,conversationId:$})}}),this.uploadContinuity=new $00({sourceKind:"discord-chat-upload",loadMessages:async(Q)=>{return await this.context?.conversations.getMessages(Q,{limit:50})??[]},restoreAttachment:async(Q)=>{let $=this.context?.uploads.scoped(V$0());if(!$)throw Error("Chat upload store unavailable");let w=await $.read(Q);return dK2(w.record.filename,w.record.mediaType,w.content,w.record.ref)},onLoadError:(Q,$)=>{this.logger.debug("Failed to load prior chat uploads",{error:Q,conversationId:$})},onRestoreError:(Q,$)=>{this.logger.debug("Failed to restore prior chat upload",{error:Q,uploadId:$})}})}async onRegister(A){await super.onRegister(A),this.discordSubscriptions=c4A(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 $=this.threadRegistry.get(A);if(!$)return;let w=this.toDiscordCardOutput(Q);if(w){$.post(w).catch((B)=>this.logger.error("Failed to send chat message",{error:B,channelId:A}));return}if(typeof Q!=="string")return;for(let B of B$0(A,Q))$.post(B).catch((X)=>this.logger.error("Failed to send chat message",{error:X,channelId:A}))}async sendMessageWithId({channelId:A,message:Q}){let $=this.threadRegistry.get(A);if(!$)return;let w=this.toDiscordCardOutput(Q);if(w){let X=await $.post(w);return this.threadRegistry.trackMessage($.id,X),X.id}if(typeof Q!=="string")return;let B;for(let X of B$0(A,Q))B=await $.post(X),this.threadRegistry.trackMessage($.id,B);return B?.id}async editMessage({channelId:A,messageId:Q,newMessage:$}){let w=this.threadRegistry.getMessage(A,Q);if(!w)return!1;try{let B=await w.edit(this.toDiscordCardOutput($)??(typeof $==="string"?$:""));if(A)this.threadRegistry.trackMessage(A,B);return!0}catch{return!1}}supportsMessageEditing(){return!0}toDiscordCardOutput(A){let Q=Do6.safeParse(A);if(!Q.success)return;let{card:$,fallbackText:w}=Q.data;if(w===void 0)return{card:$};return{card:$,fallbackText:w}}formatProgressOutput(A){return s9A(A)}formatCompletionOutput(A){return s9A(A)}async handleProgressEvent(A,Q){let $=A.metadata.interfaceType;if($&&$!==this.id){if(!this.isEnabledPlatform($))return;let w={...A,metadata:{...A.metadata,interfaceType:this.id}};await super.handleProgressEvent(w,w.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 Nw2(A,Boolean(this.config.adapters.discord))}registerChatHandlers(A){if(A.onDirectMessage(async(Q,$,w,B)=>{await this.handleRoutedMessage(Q,$,B)}),A.onNewMention(async(Q,$,w)=>{let B=this.getPlatformConfig(Q);if(B&&d4A(Q,$,B)&&!Q.isDM&&B.useThreads)await this.subscriptionRouter.subscribeOwnedThread(Q,$);await this.handleRoutedMessage(Q,$,w)}),A.onSubscribedMessage(async(Q,$,w)=>{if(!await this.subscriptionRouter.shouldRouteSubscribedMessage(Q,$))return;await this.handleRoutedMessage(Q,$,w)}),this.config.adapters.discord&&!this.config.adapters.discord.requireMention)A.onNewMessage(Ko6,async(Q,$,w)=>{await this.handleRoutedMessage(Q,$,w)});A.onNewMessage(Wo6,async(Q,$)=>{await this.handlePassiveUrlCapture(Q,$)}),A.onAction([FI0,r9A],async(Q)=>{await this.handleApprovalAction(Q)}),A.onAction(o9A,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 $=A.thread;if(!i4A($,Q,this.config.adapters.discord))return;let w=this.promptActions.get(A.value);if(w?.threadId!==$.id){await $.post(this.formatNoticePayload("That suggested action is no longer available.","Action unavailable"));return}this.promptActions.consume(A.value);let B=fF($.id),X=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:B.channelId??$.channelId,isBot:Boolean(A.user.isBot)}),Y=this.getConversationId(Q,$.id),Z=$.id;await this.runAgentTurn({thread:$,channelId:Z,logLabel:"Error handling chat prompt action",body:async()=>{if(!this.context)return;let W=await this.context.agent.chat(w.prompt,Y,{userPermissionLevel:X,interfaceType:Q,channelId:Z,channelName:Ud($),...this.buildActionEventMetadata(Q,$,A)});await this.renderAgentResponse({thread:$,channelId:Z,conversationId:Y,response:W,userPermissionLevel:X})}})}async handleApprovalAction(A){if(!this.context||!A.thread||!A.value)return;let Q=A.adapter.name;if(!this.isEnabledPlatform(Q))return;let $=this.getConversationId(Q,A.thread.id);if(!(await this.getPendingApprovalIds($)).has(A.value)){await A.thread.post(this.formatNoticePayload("That approval is no longer pending."));return}let B=A.thread;if(!i4A(B,Q,this.config.adapters.discord))return;let X=fF(B.id),Y=this.context.permissions.getUserLevel(Q,A.user.userId,{channelId:X.channelId??B.channelId,isBot:Boolean(A.user.isBot)});await this.confirmApproval({thread:B,conversationId:$,approvalId:A.value,confirmed:A.actionId===FI0,userPermissionLevel:Y,metadata:this.buildActionEventMetadata(Q,B,A)})}async handleRoutedMessage(A,Q,$){if(!this.context)return;let w=this.getPlatform(A);if(w!=="discord")return;let B=this.getPlatformConfig(A);if(!B)return;if(!d4A(A,Q,B))return;await this.routeToAgent(w,A,Q,$)}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,$){let w=this.formatErrorPayload($),B=this.toDiscordCardOutput(w);if(B){await A.post(B);return}let X=typeof w==="string"?w:"Message failed.";for(let Y of B$0(Q,X))await A.post(Y)}async routeToAgent(A,Q,$,w){if(!this.context)return;this.threadRegistry.set(Q);let B=this.getConversationId(A,Q.id),X=Q.id,Y=n4A(Q,$),Z=this.context.permissions.getUserLevel(A,$.author.userId,Y),W=await this.chatInputBuilder.build(A,Q,$,Z),K=[...W.attachments];if(await this.attachPriorUploads(B,W,Z),await this.postUploadNotices(Q,W.notices),!W.message&&W.attachments.length===0)return;this.rememberUploadAttachments(B,K),await this.runAgentTurn({thread:Q,channelId:X,logLabel:"Error handling chat message",body:async()=>{if(!this.context)return;let U=await this.getPendingApprovalIds(B);if(U.size>0){if(await this.handleConfirmationResponse(W.message,B,Q,U,Z,this.buildUserMessageMetadata(A,Q,$)))return}let G=this.buildCoalescedAgentInput(W.message,w),D=await this.context.agent.chat(G.message,B,{userPermissionLevel:Z,interfaceType:A,channelId:X,channelName:Ud(Q),...this.buildUserMessageMetadata(A,Q,$,G.metadata),...W.attachments.length>0?{attachments:W.attachments}:{}});await this.renderAgentResponse({thread:Q,channelId:X,conversationId:B,response:D,userPermissionLevel:Z})}})}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),$=Jv(A.response,{deniedCardIds:Q.deniedCardIds});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($,Q.deniedCardIds),B=await this.sendAgentResponseWithFiles({thread:A.thread,channelId:A.channelId,message:w,files:Q.files}),X=await this.sendArtifactCards(A.thread,$);await this.sendSupplementalCards(A.thread,$);let Y=$.directives.find((W)=>W.kind==="approvals");await this.approvalCards.trackPendingConfirmations(A.thread,A.conversationId,Y?.confirmations);let Z=X??B;if(Z)for(let W of $.jobIds)this.trackAgentResponseForJob(W,Z,A.channelId)}rememberPendingConfirmationsFromResponse(A,Q){this.pendingApprovals.rememberFromResponse(A,Q)}async getPendingApprovalIds(A){return this.pendingApprovals.getApprovalIds(A)}async handleConfirmationResponse(A,Q,$,w,B,X){if(!ie(A,w))return!1;let Y=LU0({message:A,approvalIds:w});if(Y.kind==="not-confirmation")return this.pendingApprovals.deleteConversation(Q),await $.post(this.formatNoticePayload("No pending approval to resolve.")),!0;if(Y.kind==="notice")return await $.post(this.formatNoticePayload(Y.message)),!0;return await this.confirmApproval({thread:$,conversationId:Q,approvalId:Y.approvalId,confirmed:Y.confirmed,userPermissionLevel:B,...X?{metadata:X}:{}}),!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:Ud(A.thread),...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){return A.directives.flatMap(($)=>{if($.kind==="text")return[$.text];if($.kind==="denied-artifact")return[this.cardBuilder.formatStructuredCard($.card,Q)];return[]}).filter(($)=>$.trim().length>0).join(`
2400
2400
 
2401
2401
  `)}formatConfirmationResponsePayload(A,Q,$,w){let B=fU0({response:A,confirmed:Q,remainingApprovalHelp:$,deniedCardIds:w,formatCard:(X)=>this.cardBuilder.formatStructuredCard(X,w),formatPendingConfirmationHelp:nm});return{card:{type:"card",title:bU0(B.variant),children:B.parts.map((X)=>({type:"text",content:X}))},fallbackText:B.parts.join(`
2402
2402
 
@@ -2468,7 +2468,7 @@ ${$4A(A)}
2468
2468
  <p>Once built, this page will be replaced with your actual website.</p>
2469
2469
  </div>
2470
2470
  </body>
2471
- </html>`;var vU2={name:"@brains/webserver",version:"0.2.0-alpha.183",dependencies:{"@brains/plugins":"workspace:*","@hono/bun-compress":"^0.1.1",hono:"^4.12.25"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/messaging-service":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/node":"^20.19.43",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class HO extends RJ{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",vU2,A,UXA)}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 iI0({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,$=this.siteUrl??A?.productionUrl??`http://localhost:${this.config.productionPort}`,w=this.previewUrl??A?.previewUrl??`http://localhost:${this.config.previewPort}`,B=[];if(Q){if(B.push(`Production: ${$}`),A?.previewUrl)B.push(`Preview: ${w}`)}return{status:Q?"healthy":"error",message:Q?B.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!A?.previewUrl,production:Q,previewUrl:A?.previewUrl?w:void 0,productionUrl:Q?$:void 0}}}}}async handleProgressEvent(A,Q){}async ensureDistDirectories(){let{mkdir:A,writeFile:Q}=await import("fs/promises");if(this.config.enablePreview&&this.config.previewDistDir&&!CU2(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(hU2(this.config.previewDistDir,"index.html"),GXA),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!CU2(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(hU2(this.config.productionDistDir,"index.html"),GXA),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}e8();KA();C0();Cv();var EU2={name:"@brains/web-chat",version:"0.2.0-alpha.183",description:"Web chat interface for Brains",dependencies:{"@ai-sdk/react":"^3.0.208","@brains/auth-service":"workspace:*","@brains/console-theme":"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","@tanstack/react-query":"^5.0.0",ai:"^6.0.206","class-variance-authority":"^0.7.0",cmdk:"^1.1.1","lucide-react":"^1.20.0",nanoid:"^5.0.4","radix-ui":"^1.6.0",react:"^19.2.7","react-dom":"^19.2.7",shiki:"^4.2.0",streamdown:"^2.5.0","tailwind-merge":"^3.6.0","use-stick-to-bottom":"^1.1.6"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/react":"^19.2.17","@types/react-dom":"^19.0.3",typescript:"^7.0.2",vite:"^8.0.16"},exports:{".":"./src/index.ts"},files:["src","dist","package.json"],private:!0,scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json"},type:"module"};KA();async function TU2(A,Q){let $=await Q.resolvePermissionLevel(A);if($==="public")return Q.createOperatorLoginRequiredResponse(A);let w=new URL(A.url),B=w.searchParams.get("id")?.trim();if(!B)return new Response("Missing document id",{status:400});let X=await gU2({entityType:"document",id:B,permissionLevel:$,entityService:Q.entityService});if(!X)return new Response("Document not found",{status:404});if(typeof X.content!=="string")return new Response("Document content is not a PDF",{status:415});let Y=ON("document",X.content);if(!Y)return new Response("Document content is not a PDF",{status:415});let Z=fN(X.metadata,B,"document",Y.mimeType);return SU2({requestUrl:w,data:Y.data,mediaType:Y.mimeType,filename:Z})}async function yU2(A,Q){let $=await Q.resolvePermissionLevel(A);if($==="public")return Q.createOperatorLoginRequiredResponse(A);let w=new URL(A.url),B=w.searchParams.get("id")?.trim();if(!B)return new Response("Missing image id",{status:400});let X=await gU2({entityType:"image",id:B,permissionLevel:$,entityService:Q.entityService});if(!X)return new Response("Image not found",{status:404});if(typeof X.content!=="string")return new Response("Image content is not an image",{status:415});let Y=ON("image",X.content);if(!Y)return new Response("Image content is not an image",{status:415});let Z=fN(X.metadata,B,"image",Y.mimeType);return SU2({requestUrl:w,data:Y.data,mediaType:Y.mimeType,filename:Z})}async function gU2(A){let Q={entityType:A.entityType,id:A.id},$=await xN({entityRef:Q,userLevel:A.permissionLevel,getEntity:(w)=>A.entityService.getEntity(w),getVisibleEntity:(w,B)=>A.entityService.getEntity({...w,visibilityScope:B})});return $.status==="visible"?$.entity:void 0}function SU2(A){let Q=new Headers({"Content-Type":A.mediaType,"Content-Length":String(A.data.byteLength),"Content-Disposition":$M({disposition:A.requestUrl.searchParams.has("download")?"attachment":"inline",filename:A.filename})});return new Response(A.data,{headers:Q})}C0();KA();var P$0="upload",mU2=Tm;var Hs6={namespace:"upload",refKind:P$0,routePath:"/api/chat/uploads"};function nI0(){return Hs6}KA();mn0();var uU2=RU0;var cU2=vU0;var Ws6="file",Ks6=16384;async function pU2(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let $=Number(A.headers.get("content-length"));if(Number.isFinite($)&&$>cU2+Ks6)return new Response("File upload too large",{status:400});let w;try{w=await A.formData()}catch{return new Response("Invalid multipart upload",{status:400})}let B=w.get(Ws6);if(!(B instanceof File))return new Response("Missing upload file",{status:400});let X=Buffer.from(await B.arrayBuffer()),Y=CN({filename:B.name,mediaType:B.type,content:X});if(!Y.ok)return new Response(Y.message,{status:400});let Z=Q.getUploadStore(),W=await Z.save({filename:Y.filename,mediaType:Y.mediaType,content:X});return Response.json(Z.toResponseBody(W),{status:201})}async function lU2(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let $=new URL(A.url).searchParams.get("id")?.trim();if(!$)return new Response("Missing upload id",{status:400});let w=await nU2($,Q.getUploadStore());if(w instanceof Response)return w;let{record:B,content:X}=w,Y=rU2(B,X);if(Y instanceof Response)return Y;let Z=new URL(A.url).searchParams.has("download")?"attachment":"inline",W=new Uint8Array(X).buffer;return new Response(W,{headers:{"Content-Type":B.mediaType,"Content-Length":String(X.byteLength),"Content-Disposition":$M({disposition:Z,filename:B.filename})}})}function dU2(A){let Q=vN(A.filename??uU2),$=Gs6(A.url);if(!$)return new Response(`Unsupported file upload URL: ${Q}`,{status:400});let w=CN({filename:Q,mediaType:A.mediaType,content:$.buffer});if(!w.ok)return new Response(w.message,{status:400});return oU2(w,$.buffer)}async function iU2(A,Q){let $=await nU2(A,Q);if($ instanceof Response)return $;let{record:w,content:B}=$,X=rU2(w,B);if(X instanceof Response)return X;return oU2(X,B,{kind:P$0,id:A})}async function nU2(A,Q){try{return await Q.read(A)}catch($){if($ instanceof vJ)return Us6($);throw $}}function rU2(A,Q){let $=CN({filename:A.filename,mediaType:A.mediaType,content:Q});if(!$.ok)return new Response($.message,{status:400});return $}function oU2(A,Q,$){if(A.kind==="text")return{kind:"text",filename:A.filename,mediaType:A.mediaType,content:A.text,sizeBytes:A.sizeBytes,...$!==void 0?{source:$}:{}};return{kind:"file",filename:A.filename,mediaType:A.mediaType,data:new Uint8Array(Q),sizeBytes:A.sizeBytes,...$!==void 0?{source:$}:{}}}function Us6(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 Gs6(A){let Q=/^data:[^,]*,(.*)$/s.exec(A);if(!Q)return null;let w=A.slice(5,A.indexOf(",")).split(";").some((B)=>B.toLowerCase()==="base64");try{let B=w?Buffer.from(Q[1]??"","base64"):Buffer.from(decodeURIComponent(Q[1]??""),"utf8");return{buffer:B,byteLength:B.byteLength}}catch{return null}}var Ds6=H.object({type:H.literal("text"),text:H.string()}),qs6=H.object({type:H.literal("file"),mediaType:H.string().optional(),filename:H.string().optional(),url:H.string()}),zs6=H.looseObject({state:H.literal("approval-responded"),approval:H.object({id:H.string(),approved:H.boolean()})}),Vs6=H.object({id:H.string().optional(),role:H.string(),parts:H.array(H.unknown()).optional(),content:H.string().optional()}),sU2=H.object({id:H.string().optional(),messages:H.array(Vs6).min(1),trigger:H.string().optional()}),Js6=H.object({kind:H.literal(P$0),id:H.string().regex(mU2)}),Fs6=H.object({type:H.literal("data-upload"),data:H.object({ref:Js6})});async function aU2(A,Q){let $=Is6(A);if(!$)return{message:"",attachments:[]};let w=[],B=[];for(let Y of $.parts??[]){let Z=Ds6.safeParse(Y);if(Z.success){if(Z.data.text.length>0)w.push(Z.data.text);continue}let W=qs6.safeParse(Y);if(W.success){let U=dU2(W.data);if(U instanceof Response)return U;B.push(U);continue}let K=Fs6.safeParse(Y);if(K.success){let U=await iU2(K.data.data.ref.id,Q.uploadStore);if(U instanceof Response)return U;B.push(U);continue}if(Ls6(Y)==="data-upload")return new Response("Invalid upload ref",{status:400})}return{message:w.length>0?w.join(`
2471
+ </html>`;var vU2={name:"@brains/webserver",version:"0.2.0-alpha.184",dependencies:{"@brains/plugins":"workspace:*","@hono/bun-compress":"^0.1.1",hono:"^4.12.25"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/messaging-service":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/node":"^20.19.43",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class HO extends RJ{serverManager;siteUrl;previewUrl;constructor(A={}){super("webserver",vU2,A,UXA)}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 iI0({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,$=this.siteUrl??A?.productionUrl??`http://localhost:${this.config.productionPort}`,w=this.previewUrl??A?.previewUrl??`http://localhost:${this.config.previewPort}`,B=[];if(Q){if(B.push(`Production: ${$}`),A?.previewUrl)B.push(`Preview: ${w}`)}return{status:Q?"healthy":"error",message:Q?B.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!A?.previewUrl,production:Q,previewUrl:A?.previewUrl?w:void 0,productionUrl:Q?$:void 0}}}}}async handleProgressEvent(A,Q){}async ensureDistDirectories(){let{mkdir:A,writeFile:Q}=await import("fs/promises");if(this.config.enablePreview&&this.config.previewDistDir&&!CU2(this.config.previewDistDir))await A(this.config.previewDistDir,{recursive:!0}),await Q(hU2(this.config.previewDistDir,"index.html"),GXA),this.logger.debug(`Created preview directory at ${this.config.previewDistDir}`);if(!CU2(this.config.productionDistDir))await A(this.config.productionDistDir,{recursive:!0}),await Q(hU2(this.config.productionDistDir,"index.html"),GXA),this.logger.debug(`Created production directory at ${this.config.productionDistDir}`)}}e8();KA();C0();Cv();var EU2={name:"@brains/web-chat",version:"0.2.0-alpha.184",description:"Web chat interface for Brains",dependencies:{"@ai-sdk/react":"^3.0.208","@brains/auth-service":"workspace:*","@brains/console-theme":"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","@tanstack/react-query":"^5.0.0",ai:"^6.0.206","class-variance-authority":"^0.7.0",cmdk:"^1.1.1","lucide-react":"^1.20.0",nanoid:"^5.0.4","radix-ui":"^1.6.0",react:"^19.2.7","react-dom":"^19.2.7",shiki:"^4.2.0",streamdown:"^2.5.0","tailwind-merge":"^3.6.0","use-stick-to-bottom":"^1.1.6"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/react":"^19.2.17","@types/react-dom":"^19.0.3",typescript:"^7.0.2",vite:"^8.0.16"},exports:{".":"./src/index.ts"},files:["src","dist","package.json"],private:!0,scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json"},type:"module"};KA();async function TU2(A,Q){let $=await Q.resolvePermissionLevel(A);if($==="public")return Q.createOperatorLoginRequiredResponse(A);let w=new URL(A.url),B=w.searchParams.get("id")?.trim();if(!B)return new Response("Missing document id",{status:400});let X=await gU2({entityType:"document",id:B,permissionLevel:$,entityService:Q.entityService});if(!X)return new Response("Document not found",{status:404});if(typeof X.content!=="string")return new Response("Document content is not a PDF",{status:415});let Y=ON("document",X.content);if(!Y)return new Response("Document content is not a PDF",{status:415});let Z=fN(X.metadata,B,"document",Y.mimeType);return SU2({requestUrl:w,data:Y.data,mediaType:Y.mimeType,filename:Z})}async function yU2(A,Q){let $=await Q.resolvePermissionLevel(A);if($==="public")return Q.createOperatorLoginRequiredResponse(A);let w=new URL(A.url),B=w.searchParams.get("id")?.trim();if(!B)return new Response("Missing image id",{status:400});let X=await gU2({entityType:"image",id:B,permissionLevel:$,entityService:Q.entityService});if(!X)return new Response("Image not found",{status:404});if(typeof X.content!=="string")return new Response("Image content is not an image",{status:415});let Y=ON("image",X.content);if(!Y)return new Response("Image content is not an image",{status:415});let Z=fN(X.metadata,B,"image",Y.mimeType);return SU2({requestUrl:w,data:Y.data,mediaType:Y.mimeType,filename:Z})}async function gU2(A){let Q={entityType:A.entityType,id:A.id},$=await xN({entityRef:Q,userLevel:A.permissionLevel,getEntity:(w)=>A.entityService.getEntity(w),getVisibleEntity:(w,B)=>A.entityService.getEntity({...w,visibilityScope:B})});return $.status==="visible"?$.entity:void 0}function SU2(A){let Q=new Headers({"Content-Type":A.mediaType,"Content-Length":String(A.data.byteLength),"Content-Disposition":$M({disposition:A.requestUrl.searchParams.has("download")?"attachment":"inline",filename:A.filename})});return new Response(A.data,{headers:Q})}C0();KA();var P$0="upload",mU2=Tm;var Hs6={namespace:"upload",refKind:P$0,routePath:"/api/chat/uploads"};function nI0(){return Hs6}KA();mn0();var uU2=RU0;var cU2=vU0;var Ws6="file",Ks6=16384;async function pU2(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let $=Number(A.headers.get("content-length"));if(Number.isFinite($)&&$>cU2+Ks6)return new Response("File upload too large",{status:400});let w;try{w=await A.formData()}catch{return new Response("Invalid multipart upload",{status:400})}let B=w.get(Ws6);if(!(B instanceof File))return new Response("Missing upload file",{status:400});let X=Buffer.from(await B.arrayBuffer()),Y=CN({filename:B.name,mediaType:B.type,content:X});if(!Y.ok)return new Response(Y.message,{status:400});let Z=Q.getUploadStore(),W=await Z.save({filename:Y.filename,mediaType:Y.mediaType,content:X});return Response.json(Z.toResponseBody(W),{status:201})}async function lU2(A,Q){if(!await Q.resolveOperatorSession(A))return new Response("Forbidden",{status:403});let $=new URL(A.url).searchParams.get("id")?.trim();if(!$)return new Response("Missing upload id",{status:400});let w=await nU2($,Q.getUploadStore());if(w instanceof Response)return w;let{record:B,content:X}=w,Y=rU2(B,X);if(Y instanceof Response)return Y;let Z=new URL(A.url).searchParams.has("download")?"attachment":"inline",W=new Uint8Array(X).buffer;return new Response(W,{headers:{"Content-Type":B.mediaType,"Content-Length":String(X.byteLength),"Content-Disposition":$M({disposition:Z,filename:B.filename})}})}function dU2(A){let Q=vN(A.filename??uU2),$=Gs6(A.url);if(!$)return new Response(`Unsupported file upload URL: ${Q}`,{status:400});let w=CN({filename:Q,mediaType:A.mediaType,content:$.buffer});if(!w.ok)return new Response(w.message,{status:400});return oU2(w,$.buffer)}async function iU2(A,Q){let $=await nU2(A,Q);if($ instanceof Response)return $;let{record:w,content:B}=$,X=rU2(w,B);if(X instanceof Response)return X;return oU2(X,B,{kind:P$0,id:A})}async function nU2(A,Q){try{return await Q.read(A)}catch($){if($ instanceof vJ)return Us6($);throw $}}function rU2(A,Q){let $=CN({filename:A.filename,mediaType:A.mediaType,content:Q});if(!$.ok)return new Response($.message,{status:400});return $}function oU2(A,Q,$){if(A.kind==="text")return{kind:"text",filename:A.filename,mediaType:A.mediaType,content:A.text,sizeBytes:A.sizeBytes,...$!==void 0?{source:$}:{}};return{kind:"file",filename:A.filename,mediaType:A.mediaType,data:new Uint8Array(Q),sizeBytes:A.sizeBytes,...$!==void 0?{source:$}:{}}}function Us6(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 Gs6(A){let Q=/^data:[^,]*,(.*)$/s.exec(A);if(!Q)return null;let w=A.slice(5,A.indexOf(",")).split(";").some((B)=>B.toLowerCase()==="base64");try{let B=w?Buffer.from(Q[1]??"","base64"):Buffer.from(decodeURIComponent(Q[1]??""),"utf8");return{buffer:B,byteLength:B.byteLength}}catch{return null}}var Ds6=H.object({type:H.literal("text"),text:H.string()}),qs6=H.object({type:H.literal("file"),mediaType:H.string().optional(),filename:H.string().optional(),url:H.string()}),zs6=H.looseObject({state:H.literal("approval-responded"),approval:H.object({id:H.string(),approved:H.boolean()})}),Vs6=H.object({id:H.string().optional(),role:H.string(),parts:H.array(H.unknown()).optional(),content:H.string().optional()}),sU2=H.object({id:H.string().optional(),messages:H.array(Vs6).min(1),trigger:H.string().optional()}),Js6=H.object({kind:H.literal(P$0),id:H.string().regex(mU2)}),Fs6=H.object({type:H.literal("data-upload"),data:H.object({ref:Js6})});async function aU2(A,Q){let $=Is6(A);if(!$)return{message:"",attachments:[]};let w=[],B=[];for(let Y of $.parts??[]){let Z=Ds6.safeParse(Y);if(Z.success){if(Z.data.text.length>0)w.push(Z.data.text);continue}let W=qs6.safeParse(Y);if(W.success){let U=dU2(W.data);if(U instanceof Response)return U;B.push(U);continue}let K=Fs6.safeParse(Y);if(K.success){let U=await iU2(K.data.data.ref.id,Q.uploadStore);if(U instanceof Response)return U;B.push(U);continue}if(Ls6(Y)==="data-upload")return new Response("Invalid upload ref",{status:400})}return{message:w.length>0?w.join(`
2472
2472
 
2473
2473
  `):$.content??"",attachments:B,...$.id?{messageId:$.id}:{}}}function tU2(A){let Q=A.messages.at(-1);if(!Q||Q.role==="user")return[];return(Q.parts??[]).map(($)=>zs6.safeParse($)).filter(($)=>$.success).map(($)=>$.data.approval)}function Is6(A){for(let Q=A.messages.length-1;Q>=0;Q-=1){let $=A.messages[Q];if($?.role==="user")return $}return}function Ls6(A){if(typeof A!=="object"||A===null||!("type"in A))return;let Q=A.type;return typeof Q==="string"?Q:void 0}KA();var Ns6=/\n{0,2}\[Entities affected this turn: [\s\S]*? Reference these IDs directly in follow-ups instead of searching for them\.\]\s*$/;function rI0(A){return A.replace(Ns6,"").trimEnd()}KA();function eU2(A,Q,$){A.write({type:"text-start",id:Q}),A.write({type:"text-delta",id:Q,delta:$}),A.write({type:"text-end",id:Q})}function DXA(A,Q){let $=Q.directives.flatMap((w)=>{switch(w.kind){case"artifact":case"supplemental":return[w.card];case"approvals":return w.cards;default:return[]}});for(let w of $){let B=gU0(w);if(B.kind==="attachment"){A.write({type:"data-attachment",id:B.id,data:B});continue}if(B.kind==="sources"){A.write({type:"data-sources",id:B.id,data:B});continue}if(B.kind==="actions"){A.write({type:"data-actions",id:B.id,data:B});continue}let X=B.toolCallId??B.id,Y=B.input??{};switch(A.write({type:"tool-input-available",toolCallId:X,toolName:B.toolName,input:Y,dynamic:!0,title:B.preview?`${B.summary}
2474
2474
 
@@ -5759,7 +5759,7 @@ ${KG2}</style></head><body>${j$0(A)}<main id="root" data-web-chat-root>Brain Cha
5759
5759
  `);B=Y.pop()??"";for(let Z of Y){let W=Z.split(`
5760
5760
  `).find((F)=>F.startsWith("data: "));if(!W)continue;let K;try{let F=Da6.safeParse(JSON.parse(W.slice(6)));if(!F.success)continue;K=F.data}catch{return $.cancel().catch(()=>{}),{success:!1,error:"Malformed SSE event from remote agent"}}let U=K.result;if(!U?.final)continue;$.cancel().catch(()=>{});let G=U.status,D=G?.state??"unknown",J=(G?.message?.parts??[]).filter((F)=>F.kind==="text"&&typeof F.text==="string").map((F)=>F.text).join(`
5761
5761
  `)||"No response text";return{success:!0,data:{state:D,response:J}}}X=await mG2($,Q)}return{success:!1,error:"Stream ended without a terminal event"}}class M$0 extends Error{timeoutMs;constructor(A){super(`request timed out after ${A}ms`);this.timeoutMs=A,this.name="A2ARequestTimeoutError"}}class b$0 extends Error{timeoutMs;constructor(A){super(`A2A stream stalled waiting for final event after ${A}ms`);this.timeoutMs=A,this.name="A2AStreamIdleTimeoutError"}}async function _a6(A,Q,$,w){let B=new AbortController,X;try{return await Promise.race([A(Q,{...$,signal:B.signal}),new Promise((Y,Z)=>{X=setTimeout(()=>{B.abort(),Z(new M$0(w))},w)})])}catch(Y){if(Y instanceof M$0)throw Y;if(B.signal.aborted)throw new M$0(w);throw Y}finally{if(X)clearTimeout(X)}}async function mG2(A,Q){let $;try{return await Promise.race([A.read(),new Promise((w,B)=>{$=setTimeout(()=>B(new b$0(Q)),Q)})])}catch(w){if(w instanceof b$0)A.cancel().catch(()=>{});throw w}finally{if($)clearTimeout($)}}function Pa6(A){if(A instanceof M$0||A instanceof b$0)return!1;return A instanceof Error}function kXA(A,Q){let $=Q>1?` after ${Q} attempts`:"";if(A instanceof b$0)return`${A.message}${$}`;let w=A instanceof Error?A.message:"Unknown network error";return`Failed to reach remote agent${$}: ${w}`}async function jXA(A,Q={},$={}){let w=Q.fetch??globalThis.fetch,B={requestTimeoutMs:Q.requestTimeoutMs??qa6,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??za6,maxNetworkAttempts:Q.maxNetworkAttempts??Va6},X=Ia6(A.agent);if(!X.ok)return{success:!1,error:X.error};let{agentId:Y}=X;if(!Q.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let Z=await Q.entityService.getEntity({entityType:"agent",id:Y,visibilityScope:M7("agent_call is anchor-only and resolves saved remote agents at any visibility")});if(!Z){if($.requireSaved)return{success:!1,error:`Agent ${Y} is not saved or approved.`,code:"agent_not_saved"};if(!La6(Y))return{success:!1,error:`Agent ${A.agent} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let G=`https://${Y}`,D=await gG2(G,w);if(!D)return{success:!1,error:`Could not verify an A2A Agent Card for ${Y}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"};let q=yG2(D.url,Y);if(!q.ok)return{success:!1,error:q.error};let J=await SG2(D.url,A.message,w,Q.requestSigner,B);if("success"in J&&J.success===!0){let F=typeof J.data==="object"&&J.data!==null?J.data:{};return{...J,data:{...F,agentCall:{mode:"one-shot",agent:Y},agentContactCandidate:{source:{kind:"url",url:X.sourceUrl??Y}}}}}return J}if(Z.metadata.status==="archived")return{success:!1,error:`Agent ${Y} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(Z.metadata.status!=="approved")return{success:!1,error:`Agent ${Y} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let W=`https://${Y}`,K=await gG2(W,w);if(!K)return{success:!1,error:`Could not fetch Agent Card from ${W}`};let U=yG2(K.url,Y);if(!U.ok)return{success:!1,error:U.error};return SG2(K.url,A.message,w,Q.requestSigner,B)}function cG2(A={}){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:Ja6,visibility:"trusted",sideEffects:"external",handler:async(Q)=>{let $=Fa6.safeParse(Q);if(!$.success)return{success:!1,error:`Invalid input: ${$.error.message}`};return jXA($.data,A)}}}KA();C0();var ka6=H.object({agent:H.string().trim().min(1).max(253),instruction:H.string().trim().min(1).max(2000),selection:H.string().min(1).max(8000)});function pG2(A,Q){A.messaging.subscribe("a2a:call:request",async($)=>{let w=ka6.safeParse($.payload);if(!w.success)return{success:!1,error:"Invalid A2A call request"};let{agent:B,instruction:X,selection:Y}=w.data,Z=await jXA({agent:B,message:["A CMS author is asking about selected markdown.",`Instruction: ${X}`,"","Selected markdown:",Y].join(`
5762
- `)},Q,{requireSaved:!0});if("success"in Z&&Z.success===!0)return{success:!0,data:Z.data};return{success:!1,error:"error"in Z?Z.error:"Agent call failed"}}),A.messaging.subscribe("a2a:call:agents",async()=>{if(!A.entityService.hasEntityType("agent"))return{success:!0,data:{agents:[]}};return{success:!0,data:{agents:(await A.entityService.listEntities({entityType:"agent",options:{filter:{visibilityScope:M7("operator CMS lists approved A2A contacts at any visibility")}}})).filter((B)=>B.metadata.status==="approved").map((B)=>{let X=B.metadata.name;return{id:B.id,label:typeof X==="string"&&X.length>0?X:B.id}}).sort((B,X)=>B.label.localeCompare(X.label))}}})}var MXA={name:"@brains/a2a",version:"0.2.0-alpha.183",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/auth-service":"workspace:*","@brains/http-signatures":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",hono:"^4.12.25"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var Ma6={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"};class Fd extends RJ{agentCard;taskManager=new PXA;agentService;jwksResolver=new NXA;app;hasWebserver=!1;constructor(A={}){if(Object.prototype.hasOwnProperty.call(A,"trustedTokens"))throw Error("trustedTokens legacy config is no longer supported");if(Object.prototype.hasOwnProperty.call(A,"outboundTokens"))throw Error("outboundTokens legacy config is no longer supported");super("a2a",MXA,A,bG2)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agent,pG2(A,this.createClientDeps(A)),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(),$=A.identity.getProfile(),w=A.tools.listForPermissionLevel("public"),B;if(A.entityService.hasEntityType("skill"))try{let X=await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}});if(X.length>0)B=X.map((Y)=>X00.safeParse(Y.metadata)).filter((Y)=>Y.success).map((Y)=>Y.data)}catch{}this.agentCard=OG2({character:Q,profile:$,version:MXA.version,domain:A.domain,organization:this.config.organization,tools:w,skills:B,authEnabled:!1}),this.logger.debug("Agent Card rebuilt",{skills:this.agentCard.skills.length})}getAgentCard(){return this.agentCard}async resolveCaller(A,Q){let $=new URL(A.url),w=new URL(`${$.pathname}${$.search}`,Gb(A)),B=await kG2({method:A.method,url:w.toString(),headers:A.headers,body:Q},this.jwksResolver);if(B){let X=await UY()?.getA2APeerTrust(B.domain);return{permissionLevel:X?.keyFingerprint===B.keyFingerprint?X.grantedLevel:"public",callerDomain:B.domain}}return{permissionLevel:"public",callerDomain:null}}withCors(A){let Q=new Headers(A.headers);for(let[$,w]of Object.entries(Ma6))Q.set($,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}getOrCreateApp(){if(this.app)return this.app;let A=new Dd;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("/.well-known/agent-directory.json",async(Q)=>{let $=await fG2(this.getContext().entityService);return this.withCors(Q.json($))}),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 $=await Q.req.text(),w;try{w=await this.resolveCaller(Q.req.raw,$)}catch{return this.withCors(Q.json({error:"Invalid HTTP signature"},401))}let B;try{B=JSON.parse($)}catch{return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let X=vG2.safeParse(B);if(!X.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(X.data.method==="message/stream"){let Z=hG2.safeParse(X.data.params??{});if(!Z.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${Z.error.message}`},id:X.data.id}));let W=EG2(X.data.id,Z.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:w.permissionLevel,callerDomain:w.callerDomain});if("error"in W)return this.withCors(Q.json(W));let{stream:K}=W;return this.withCors(new Response(K,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let Y=await CG2(X.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:w.permissionLevel,callerDomain:w.callerDomain});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:"/.well-known/agent-directory.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}]}createRequestSigner(){let A=UY();if(!A)return;let Q=A.getIssuer();if(Ub(Q)||new URL(Q).protocol!=="https:")return;return async($)=>{let w=await A.getA2ASigningKey();await PG2($,w.privateJwk,w.keyId)}}createClientDeps(A){return{requestSigner:this.createRequestSigner(),requestTimeoutMs:this.config.requestTimeoutMs,streamIdleTimeoutMs:this.config.streamIdleTimeoutMs,maxNetworkAttempts:this.config.maxNetworkAttempts,entityService:A.entityService}}async getTools(){return[cG2(this.createClientDeps(this.getContext()))]}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")}}}}KA();C0();var lG2={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 dG2={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 iG2={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 nG2={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 rG2={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 oG2={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 sG2={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 aG2={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 tG2={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 Ta6=H.object({type:H.string()}).catchall(H.unknown()),ya6=H.object({lexicon:H.literal(1),id:H.string(),defs:H.object({main:H.object({type:H.literal("record"),key:H.string().min(1),record:H.object({type:H.literal("object"),required:H.array(H.string()).optional(),properties:H.record(H.string(),Ta6)})})})});function R3(A){return ya6.parse(A)}var E8={"ai.rizom.brain.card":R3(lG2),"ai.rizom.brain.deck":R3(dG2),"ai.rizom.brain.link":R3(iG2),"ai.rizom.brain.note":R3(nG2),"ai.rizom.brain.post":R3(rG2),"ai.rizom.brain.project":R3(oG2),"ai.rizom.brain.series":R3(sG2),"ai.rizom.brain.socialPost":R3(aG2),"ai.rizom.brain.topic":R3(tG2)},ga6="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function r_(A){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:A,compatibility:ga6}}var eG2={"ai.rizom.brain.card":r_("@brains/atproto"),"ai.rizom.brain.deck":r_("@brains/decks"),"ai.rizom.brain.link":r_("@brains/link"),"ai.rizom.brain.note":r_("@brains/note"),"ai.rizom.brain.post":r_("@brains/blog"),"ai.rizom.brain.project":r_("@brains/portfolio"),"ai.rizom.brain.series":r_("@brains/series"),"ai.rizom.brain.socialPost":r_("@brains/social-media"),"ai.rizom.brain.topic":r_("@brains/topics")};function Id(){return Object.values(E8)}function AL0(A){if(!(A in E8))return;return E8[A]}function QL0(){return Object.entries(eG2).map(([A,Q])=>({id:A,...Q}))}C0();function $L0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var Sa6=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ma6(A){let Q=H.string(),$=A.maxLength!==void 0?Q.max(A.maxLength):Q;if(A.knownValues)$=$.refine((w)=>A.knownValues?.includes(w),{message:`expected one of ${A.knownValues.join(", ")}`});if(A.format==="datetime")$=$.refine((w)=>Sa6.test(w)&&!Number.isNaN(Date.parse(w)),{message:"expected datetime"});if(A.format==="uri")$=$.refine((w)=>{try{return new URL(w),!0}catch{return!1}},{message:"expected uri"});return $}function AD2(A){switch(A.type){case"string":return ma6(A);case"integer":return H.number().int();case"boolean":return H.boolean();case"array":{let Q=A.items?AD2(A.items):H.unknown(),$=H.array(Q);if(A.maxLength!==void 0)$=$.max(A.maxLength);return $}case"object":return ua6(A);case"blob":return H.custom($L0,{message:"expected blob"});default:return H.unknown()}}function QD2(A){let Q=new Set(A.required??[]),$={};for(let[w,B]of Object.entries(A.properties??{})){let X=AD2(B);$[w]=Q.has(w)?X:X.optional()}return $}function ua6(A){return H.object(QD2(A)).passthrough()}function bXA(A,Q,$,w=[]){let B=Object.keys(A).filter((X)=>!Q.has(X));if(B.length===0)return;$.addIssue({code:H.ZodIssueCode.custom,path:w,message:`unrecognized field(s): ${B.join(", ")}`})}function ca6(A,Q){if(bXA(A,new Set(["$type","siteUrl","brain","anchor","skills","model","version","createdAt","updatedAt"]),Q),$L0(A.brain))bXA(A.brain,new Set(["did","name","role","purpose","values"]),Q,["brain"]);if($L0(A.anchor))bXA(A.anchor,new Set(["did","name","kind"]),Q,["anchor"])}function v3(A){let Q=H.object({...QD2(A.defs.main.record),$type:H.literal(A.id).optional()}).passthrough();return A.id==="ai.rizom.brain.card"?Q.superRefine(ca6):Q}var OXA={"ai.rizom.brain.card":v3(E8["ai.rizom.brain.card"]),"ai.rizom.brain.deck":v3(E8["ai.rizom.brain.deck"]),"ai.rizom.brain.link":v3(E8["ai.rizom.brain.link"]),"ai.rizom.brain.note":v3(E8["ai.rizom.brain.note"]),"ai.rizom.brain.post":v3(E8["ai.rizom.brain.post"]),"ai.rizom.brain.project":v3(E8["ai.rizom.brain.project"]),"ai.rizom.brain.series":v3(E8["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":v3(E8["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":v3(E8["ai.rizom.brain.topic"])};function pa6(A,Q){let $=A;for(let w of Q){if(typeof w==="symbol")return;if(Array.isArray($)){$=$[Number(w)];continue}if(!$L0($))return;$=$[String(w)]}return $}function la6(A,Q,$){let w=$.path.join(".");if(w==="$type")return`AT Protocol record $type must match lexicon id: ${String(Q.$type)} !== ${A.id}`;if($.code==="invalid_type"&&pa6(Q,$.path)===void 0)return`Missing required AT Protocol record field: ${w}`;if($.code==="invalid_type")return`Invalid AT Protocol record field ${w}: expected ${$.expected}`;if($.code==="too_big")return`Invalid AT Protocol record field ${w}: exceeds maxLength ${$.maximum}`;if($.code==="custom")return`Invalid AT Protocol record field ${w}: ${$.message}`;if($.code==="unrecognized_keys")return`Unrecognized AT Protocol record field(s): ${$.keys.join(", ")}`;return`Invalid AT Protocol record field ${w}: ${$.message}`}function o_(A,Q){let $=v3(A).safeParse(Q);if($.success)return;let w=$.error.issues[0];if(!w)throw $.error;throw Error(la6(A,Q,w))}C0();var O$0="atproto:brain-card-discovered",fXA="atproto:brain-discovered",xXA="atproto:brain-card-refreshed",da6=H.custom((A)=>OXA["ai.rizom.brain.card"].safeParse(A).success),RXA=H.object({repoDid:H.string().min(1),uri:H.string().min(1),cid:H.string().min(1),record:da6}).strict(),ia6=H.object({agentId:H.string().min(1),name:H.string().min(1),url:H.string().url(),status:H.enum(["discovered","approved","archived"]),repoDid:H.string().min(1).optional(),brainDid:H.string().min(1).optional(),anchorDid:H.string().min(1).optional(),cardUri:H.string().min(1).optional(),cardCid:H.string().min(1).optional()}).strict();class aB{static instance;projections=new Map;static getInstance(){return this.instance??=new aB,this.instance}static createFresh(){return new aB}static resetInstance(){this.instance=void 0}register(A){this.validateProjection(A);let Q=this.get(A.entityType);if(Q&&!this.isEquivalentProjection(Q,A))throw Error(`AT Protocol projection already registered for entity type ${A.entityType}`);let $=this.projections.get(A.entityType)??[];return $.push(A),this.projections.set(A.entityType,$),this.createUnregister(A.entityType,A)}get(A){let Q=this.projections.get(A);return Q?.[Q.length-1]}has(A){return this.get(A)!==void 0}list(){let A=[];for(let Q of this.projections.keys()){let $=this.get(Q);if($)A.push($)}return A}listLexicons(){return this.list().map((A)=>A.lexicon)}createUnregister(A,Q){let $=!0;return()=>{if(!$)return;$=!1;let w=this.projections.get(A);if(!w)return;let B=w.lastIndexOf(Q);if(B!==-1)w.splice(B,1);if(w.length===0)this.projections.delete(A)}}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}`)}}C0();var $D2={name:"@brains/atproto-registry",version:"0.2.0-alpha.183",description:"Canonical Rizom AT Protocol lexicon registry",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var BD2=H.object({enabled:H.boolean().default(!0)}),vXA="/atproto/lexicons",ra6=H.strictObject({nsid:H.string(),record:H.record(H.string(),H.unknown())});function wD2(A){return new Response(`${JSON.stringify(A,null,2)}
5762
+ `)},Q,{requireSaved:!0});if("success"in Z&&Z.success===!0)return{success:!0,data:Z.data};return{success:!1,error:"error"in Z?Z.error:"Agent call failed"}}),A.messaging.subscribe("a2a:call:agents",async()=>{if(!A.entityService.hasEntityType("agent"))return{success:!0,data:{agents:[]}};return{success:!0,data:{agents:(await A.entityService.listEntities({entityType:"agent",options:{filter:{visibilityScope:M7("operator CMS lists approved A2A contacts at any visibility")}}})).filter((B)=>B.metadata.status==="approved").map((B)=>{let X=B.metadata.name;return{id:B.id,label:typeof X==="string"&&X.length>0?X:B.id}}).sort((B,X)=>B.label.localeCompare(X.label))}}})}var MXA={name:"@brains/a2a",version:"0.2.0-alpha.184",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/auth-service":"workspace:*","@brains/http-signatures":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",hono:"^4.12.25"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var Ma6={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"};class Fd extends RJ{agentCard;taskManager=new PXA;agentService;jwksResolver=new NXA;app;hasWebserver=!1;constructor(A={}){if(Object.prototype.hasOwnProperty.call(A,"trustedTokens"))throw Error("trustedTokens legacy config is no longer supported");if(Object.prototype.hasOwnProperty.call(A,"outboundTokens"))throw Error("outboundTokens legacy config is no longer supported");super("a2a",MXA,A,bG2)}async onRegister(A){if(await super.onRegister(A),this.hasWebserver=A.plugins.has("webserver"),this.agentService=A.agent,pG2(A,this.createClientDeps(A)),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(),$=A.identity.getProfile(),w=A.tools.listForPermissionLevel("public"),B;if(A.entityService.hasEntityType("skill"))try{let X=await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}});if(X.length>0)B=X.map((Y)=>X00.safeParse(Y.metadata)).filter((Y)=>Y.success).map((Y)=>Y.data)}catch{}this.agentCard=OG2({character:Q,profile:$,version:MXA.version,domain:A.domain,organization:this.config.organization,tools:w,skills:B,authEnabled:!1}),this.logger.debug("Agent Card rebuilt",{skills:this.agentCard.skills.length})}getAgentCard(){return this.agentCard}async resolveCaller(A,Q){let $=new URL(A.url),w=new URL(`${$.pathname}${$.search}`,Gb(A)),B=await kG2({method:A.method,url:w.toString(),headers:A.headers,body:Q},this.jwksResolver);if(B){let X=await UY()?.getA2APeerTrust(B.domain);return{permissionLevel:X?.keyFingerprint===B.keyFingerprint?X.grantedLevel:"public",callerDomain:B.domain}}return{permissionLevel:"public",callerDomain:null}}withCors(A){let Q=new Headers(A.headers);for(let[$,w]of Object.entries(Ma6))Q.set($,w);return new Response(A.body,{status:A.status,statusText:A.statusText,headers:Q})}getOrCreateApp(){if(this.app)return this.app;let A=new Dd;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("/.well-known/agent-directory.json",async(Q)=>{let $=await fG2(this.getContext().entityService);return this.withCors(Q.json($))}),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 $=await Q.req.text(),w;try{w=await this.resolveCaller(Q.req.raw,$)}catch{return this.withCors(Q.json({error:"Invalid HTTP signature"},401))}let B;try{B=JSON.parse($)}catch{return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let X=vG2.safeParse(B);if(!X.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(X.data.method==="message/stream"){let Z=hG2.safeParse(X.data.params??{});if(!Z.success)return this.withCors(Q.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${Z.error.message}`},id:X.data.id}));let W=EG2(X.data.id,Z.data.message,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:w.permissionLevel,callerDomain:w.callerDomain});if("error"in W)return this.withCors(Q.json(W));let{stream:K}=W;return this.withCors(new Response(K,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let Y=await CG2(X.data,{taskManager:this.taskManager,agentService:this.agentService,callerPermissionLevel:w.permissionLevel,callerDomain:w.callerDomain});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:"/.well-known/agent-directory.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}]}createRequestSigner(){let A=UY();if(!A)return;let Q=A.getIssuer();if(Ub(Q)||new URL(Q).protocol!=="https:")return;return async($)=>{let w=await A.getA2ASigningKey();await PG2($,w.privateJwk,w.keyId)}}createClientDeps(A){return{requestSigner:this.createRequestSigner(),requestTimeoutMs:this.config.requestTimeoutMs,streamIdleTimeoutMs:this.config.streamIdleTimeoutMs,maxNetworkAttempts:this.config.maxNetworkAttempts,entityService:A.entityService}}async getTools(){return[cG2(this.createClientDeps(this.getContext()))]}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")}}}}KA();C0();var lG2={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 dG2={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 iG2={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 nG2={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 rG2={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 oG2={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 sG2={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 aG2={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 tG2={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 Ta6=H.object({type:H.string()}).catchall(H.unknown()),ya6=H.object({lexicon:H.literal(1),id:H.string(),defs:H.object({main:H.object({type:H.literal("record"),key:H.string().min(1),record:H.object({type:H.literal("object"),required:H.array(H.string()).optional(),properties:H.record(H.string(),Ta6)})})})});function R3(A){return ya6.parse(A)}var E8={"ai.rizom.brain.card":R3(lG2),"ai.rizom.brain.deck":R3(dG2),"ai.rizom.brain.link":R3(iG2),"ai.rizom.brain.note":R3(nG2),"ai.rizom.brain.post":R3(rG2),"ai.rizom.brain.project":R3(oG2),"ai.rizom.brain.series":R3(sG2),"ai.rizom.brain.socialPost":R3(aG2),"ai.rizom.brain.topic":R3(tG2)},ga6="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function r_(A){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:A,compatibility:ga6}}var eG2={"ai.rizom.brain.card":r_("@brains/atproto"),"ai.rizom.brain.deck":r_("@brains/decks"),"ai.rizom.brain.link":r_("@brains/link"),"ai.rizom.brain.note":r_("@brains/note"),"ai.rizom.brain.post":r_("@brains/blog"),"ai.rizom.brain.project":r_("@brains/portfolio"),"ai.rizom.brain.series":r_("@brains/series"),"ai.rizom.brain.socialPost":r_("@brains/social-media"),"ai.rizom.brain.topic":r_("@brains/topics")};function Id(){return Object.values(E8)}function AL0(A){if(!(A in E8))return;return E8[A]}function QL0(){return Object.entries(eG2).map(([A,Q])=>({id:A,...Q}))}C0();function $L0(A){return typeof A==="object"&&A!==null&&!Array.isArray(A)}var Sa6=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ma6(A){let Q=H.string(),$=A.maxLength!==void 0?Q.max(A.maxLength):Q;if(A.knownValues)$=$.refine((w)=>A.knownValues?.includes(w),{message:`expected one of ${A.knownValues.join(", ")}`});if(A.format==="datetime")$=$.refine((w)=>Sa6.test(w)&&!Number.isNaN(Date.parse(w)),{message:"expected datetime"});if(A.format==="uri")$=$.refine((w)=>{try{return new URL(w),!0}catch{return!1}},{message:"expected uri"});return $}function AD2(A){switch(A.type){case"string":return ma6(A);case"integer":return H.number().int();case"boolean":return H.boolean();case"array":{let Q=A.items?AD2(A.items):H.unknown(),$=H.array(Q);if(A.maxLength!==void 0)$=$.max(A.maxLength);return $}case"object":return ua6(A);case"blob":return H.custom($L0,{message:"expected blob"});default:return H.unknown()}}function QD2(A){let Q=new Set(A.required??[]),$={};for(let[w,B]of Object.entries(A.properties??{})){let X=AD2(B);$[w]=Q.has(w)?X:X.optional()}return $}function ua6(A){return H.object(QD2(A)).passthrough()}function bXA(A,Q,$,w=[]){let B=Object.keys(A).filter((X)=>!Q.has(X));if(B.length===0)return;$.addIssue({code:H.ZodIssueCode.custom,path:w,message:`unrecognized field(s): ${B.join(", ")}`})}function ca6(A,Q){if(bXA(A,new Set(["$type","siteUrl","brain","anchor","skills","model","version","createdAt","updatedAt"]),Q),$L0(A.brain))bXA(A.brain,new Set(["did","name","role","purpose","values"]),Q,["brain"]);if($L0(A.anchor))bXA(A.anchor,new Set(["did","name","kind"]),Q,["anchor"])}function v3(A){let Q=H.object({...QD2(A.defs.main.record),$type:H.literal(A.id).optional()}).passthrough();return A.id==="ai.rizom.brain.card"?Q.superRefine(ca6):Q}var OXA={"ai.rizom.brain.card":v3(E8["ai.rizom.brain.card"]),"ai.rizom.brain.deck":v3(E8["ai.rizom.brain.deck"]),"ai.rizom.brain.link":v3(E8["ai.rizom.brain.link"]),"ai.rizom.brain.note":v3(E8["ai.rizom.brain.note"]),"ai.rizom.brain.post":v3(E8["ai.rizom.brain.post"]),"ai.rizom.brain.project":v3(E8["ai.rizom.brain.project"]),"ai.rizom.brain.series":v3(E8["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":v3(E8["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":v3(E8["ai.rizom.brain.topic"])};function pa6(A,Q){let $=A;for(let w of Q){if(typeof w==="symbol")return;if(Array.isArray($)){$=$[Number(w)];continue}if(!$L0($))return;$=$[String(w)]}return $}function la6(A,Q,$){let w=$.path.join(".");if(w==="$type")return`AT Protocol record $type must match lexicon id: ${String(Q.$type)} !== ${A.id}`;if($.code==="invalid_type"&&pa6(Q,$.path)===void 0)return`Missing required AT Protocol record field: ${w}`;if($.code==="invalid_type")return`Invalid AT Protocol record field ${w}: expected ${$.expected}`;if($.code==="too_big")return`Invalid AT Protocol record field ${w}: exceeds maxLength ${$.maximum}`;if($.code==="custom")return`Invalid AT Protocol record field ${w}: ${$.message}`;if($.code==="unrecognized_keys")return`Unrecognized AT Protocol record field(s): ${$.keys.join(", ")}`;return`Invalid AT Protocol record field ${w}: ${$.message}`}function o_(A,Q){let $=v3(A).safeParse(Q);if($.success)return;let w=$.error.issues[0];if(!w)throw $.error;throw Error(la6(A,Q,w))}C0();var O$0="atproto:brain-card-discovered",fXA="atproto:brain-discovered",xXA="atproto:brain-card-refreshed",da6=H.custom((A)=>OXA["ai.rizom.brain.card"].safeParse(A).success),RXA=H.object({repoDid:H.string().min(1),uri:H.string().min(1),cid:H.string().min(1),record:da6}).strict(),ia6=H.object({agentId:H.string().min(1),name:H.string().min(1),url:H.string().url(),status:H.enum(["discovered","approved","archived"]),repoDid:H.string().min(1).optional(),brainDid:H.string().min(1).optional(),anchorDid:H.string().min(1).optional(),cardUri:H.string().min(1).optional(),cardCid:H.string().min(1).optional()}).strict();class aB{static instance;projections=new Map;static getInstance(){return this.instance??=new aB,this.instance}static createFresh(){return new aB}static resetInstance(){this.instance=void 0}register(A){this.validateProjection(A);let Q=this.get(A.entityType);if(Q&&!this.isEquivalentProjection(Q,A))throw Error(`AT Protocol projection already registered for entity type ${A.entityType}`);let $=this.projections.get(A.entityType)??[];return $.push(A),this.projections.set(A.entityType,$),this.createUnregister(A.entityType,A)}get(A){let Q=this.projections.get(A);return Q?.[Q.length-1]}has(A){return this.get(A)!==void 0}list(){let A=[];for(let Q of this.projections.keys()){let $=this.get(Q);if($)A.push($)}return A}listLexicons(){return this.list().map((A)=>A.lexicon)}createUnregister(A,Q){let $=!0;return()=>{if(!$)return;$=!1;let w=this.projections.get(A);if(!w)return;let B=w.lastIndexOf(Q);if(B!==-1)w.splice(B,1);if(w.length===0)this.projections.delete(A)}}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}`)}}C0();var $D2={name:"@brains/atproto-registry",version:"0.2.0-alpha.184",description:"Canonical Rizom AT Protocol lexicon registry",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var BD2=H.object({enabled:H.boolean().default(!0)}),vXA="/atproto/lexicons",ra6=H.strictObject({nsid:H.string(),record:H.record(H.string(),H.unknown())});function wD2(A){return new Response(`${JSON.stringify(A,null,2)}
5763
5763
  `,{headers:{"Content-Type":"application/json"}})}class CXA extends p6{constructor(A={}){super("atproto-registry",$D2,A,BD2)}getWebRoutes(){if(!this.config.enabled)return[];return[{path:`${vXA}/index.json`,method:"GET",public:!0,handler:()=>wD2(this.getIndex())},...Id().map((A)=>({path:`${vXA}/${A.id}.json`,method:"GET",public:!0,handler:()=>wD2(A)}))]}getIndex(){return{lexicons:QL0().map((A)=>({...A,path:`${vXA}/${A.id}.json`}))}}getLexicon(A){return AL0(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:H.string().describe("Canonical lexicon NSID"),record:H.record(H.string(),H.unknown()).describe("Record payload to validate")},handler:async(A)=>{let Q=ra6.safeParse(A);if(!Q.success)return{success:!1,error:`Invalid input: ${Q.error.message}`};let $=this.getLexicon(Q.data.nsid);if(!$)return{success:!1,error:`Unknown AT Protocol lexicon: ${Q.data.nsid}`};try{return o_($,Q.data.record),{success:!0,data:{valid:!0}}}catch(w){return{success:!0,data:{valid:!1,error:w instanceof Error?w.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:Id().length,nsids:Id().map((A)=>A.id),metadata:QL0()}})}}}function f$0(A={}){return new CXA(A)}KA();class hXA{logger;handleImport;handleDelete;deleteOnFileRemoval;fileOperations;constructor(A,Q,$,w,B=!0){if(this.logger=A,this.fileOperations=w,this.deleteOnFileRemoval=B,$)this.handleImport=async(X)=>{let Y=await $({type:"directory-import",data:{paths:[X]}});this.logger.debug("Queued import job for file change",{jobId:Y,path:X})},this.handleDelete=async(X)=>{if(!this.deleteOnFileRemoval){this.logger.warn("File deleted but deleteOnFileRemoval is disabled",{path:X});return}try{let{entityType:Y,id:Z}=this.fileOperations.parseEntityFromPath(X),W=await $({type:"directory-delete",data:{entityId:Z,entityType:Y,filePath:X}});this.logger.info("Queued delete job for removed file",{jobId:W,path:X,entityId:Z,entityType:Y})}catch(Y){this.logger.warn("Could not extract entity info from deleted file",{path:X,error:Y})}};else this.handleImport=async(X)=>{await Q([X])},this.handleDelete=async(X)=>{this.logger.warn("File deleted but no job queue available",{path:X})}}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($){this.logger.error("Failed to handle file change",{event:A,path:Q,error:$})}}}import{EventEmitter as kt6}from"events";import{stat as jt6,Stats as m85}from"fs";import{readdir as Mt6,stat as bt6}from"fs/promises";import*as Z8 from"path";import{lstat as XD2,readdir as oa6,realpath as sa6,stat as aa6}from"fs/promises";import{join as ta6,relative as ea6,resolve as YD2,sep as At6}from"path";import{Readable as Qt6}from"stream";var aU={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},EXA={root:".",fileFilter:(A)=>!0,directoryFilter:(A)=>!0,type:aU.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(EXA);var KD2="READDIRP_RECURSIVE_ERROR",$t6=new Set(["ENOENT","EPERM","EACCES","ELOOP",KD2]),ZD2=[aU.DIR_TYPE,aU.EVERYTHING_TYPE,aU.FILE_DIR_TYPE,aU.FILE_TYPE],wt6=new Set([aU.DIR_TYPE,aU.EVERYTHING_TYPE,aU.FILE_DIR_TYPE]),Bt6=new Set([aU.EVERYTHING_TYPE,aU.FILE_DIR_TYPE,aU.FILE_TYPE]),Xt6=(A)=>$t6.has(A.code),Yt6=process.platform==="win32",HD2=(A)=>!0,WD2=(A)=>{if(A===void 0)return HD2;if(typeof A==="function")return A;if(typeof A==="string"){let Q=A.trim();return($)=>$.basename===Q}if(Array.isArray(A)){let Q=A.map(($)=>$.trim());return($)=>Q.some((w)=>$.basename===w)}return HD2};class TXA extends Qt6{parents;reading;parent;_stat;_maxDepth;_wantsDir;_wantsFile;_wantsEverything;_root;_isDirent;_statsProp;_rdOptions;_fileFilter;_directoryFilter;constructor(A={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:A.highWaterMark});let Q={...EXA,...A},{root:$,type:w}=Q;this._fileFilter=WD2(Q.fileFilter),this._directoryFilter=WD2(Q.directoryFilter);let B=Q.lstat?XD2:aa6;if(Yt6)this._stat=(X)=>B(X,{bigint:!0});else this._stat=B;this._maxDepth=Q.depth!=null&&Number.isSafeInteger(Q.depth)?Q.depth:EXA.depth,this._wantsDir=w?wt6.has(w):!1,this._wantsFile=w?Bt6.has(w):!1,this._wantsEverything=w===aU.EVERYTHING_TYPE,this._root=YD2($),this._isDirent=!Q.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir($,1)],this.reading=!1,this.parent=void 0}async _read(A){if(this.reading)return;this.reading=!0;try{while(!this.destroyed&&A>0){let Q=this.parent,$=Q&&Q.files;if($&&$.length>0){let{path:w,depth:B}=Q,X=$.splice(0,A).map((Z)=>this._formatEntry(Z,w)),Y=await Promise.all(X);for(let Z of Y){if(!Z)continue;if(this.destroyed)return;let W=await this._getEntryType(Z);if(W==="directory"&&this._directoryFilter(Z)){if(B<=this._maxDepth)this.parents.push(this._exploreDir(Z.fullPath,B+1));if(this._wantsDir)this.push(Z),A--}else if((W==="file"||this._includeAsFile(Z))&&this._fileFilter(Z)){if(this._wantsFile)this.push(Z),A--}}}else{let w=this.parents.pop();if(!w){this.push(null);break}if(this.parent=await w,this.destroyed)return}}}catch(Q){this.destroy(Q)}finally{this.reading=!1}}async _exploreDir(A,Q){let $;try{$=await oa6(A,this._rdOptions)}catch(w){this._onError(w)}return{files:$,depth:Q,path:A}}async _formatEntry(A,Q){let $,w=this._isDirent?A.name:A;try{let B=YD2(ta6(Q,w));$={path:ea6(this._root,B),fullPath:B,basename:w},$[this._statsProp]=this._isDirent?A:await this._stat(B)}catch(B){this._onError(B);return}return $}_onError(A){if(Xt6(A)&&!this.destroyed)this.emit("warn",A);else this.destroy(A)}async _getEntryType(A){if(!A&&this._statsProp in A)return"";let Q=A[this._statsProp];if(Q.isFile())return"file";if(Q.isDirectory())return"directory";if(Q&&Q.isSymbolicLink()){let $=A.fullPath;try{let w=await sa6($),B=await XD2(w);if(B.isFile())return"file";if(B.isDirectory()){let X=w.length;if($.startsWith(w)&&$.substr(X,1)===At6){let Y=Error(`Circular symlink detected: "${$}" points to "${w}"`);return Y.code=KD2,this._onError(Y)}return"directory"}}catch(w){return this._onError(w),""}}}_includeAsFile(A){let Q=A&&A[this._statsProp];return Q&&this._wantsEverything&&!Q.isDirectory()}}function UD2(A,Q={}){let $=Q.entryType||Q.type;if($==="both")$=aU.FILE_DIR_TYPE;if($)Q.type=$;if(!A)throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");else if(typeof A!=="string")throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if($&&!ZD2.includes($))throw Error(`readdirp: Invalid type passed. Use one of ${ZD2.join(", ")}`);return Q.root=A,new TXA(Q)}import{watch as Zt6,unwatchFile as GD2,watchFile as Ht6}from"fs";import{realpath as yXA,lstat as Wt6,open as Kt6,stat as qD2}from"fs/promises";import{type as Ut6}from"os";import*as PB from"path";var Gt6="data",mXA="end",zD2="close",YL0=()=>{};var ZL0=process.platform,uXA=ZL0==="win32",Dt6=ZL0==="darwin",qt6=ZL0==="linux",zt6=ZL0==="freebsd",VD2=Ut6()==="OS400",r5={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},C3=r5,Vt6="watch",Jt6={lstat:Wt6,stat:qD2},ah="listeners",wL0="errHandlers",Ld="rawEmitters",Ft6=[ah,wL0,Ld],It6=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Lt6=(A)=>It6.has(PB.extname(A).slice(1).toLowerCase()),SXA=(A,Q)=>{if(A instanceof Set)A.forEach(Q);else Q(A)},x$0=(A,Q,$)=>{let w=A[Q];if(!(w instanceof Set))A[Q]=w=new Set([w]);w.add($)},Nt6=(A)=>(Q)=>{let $=A[Q];if($ instanceof Set)$.clear();else delete A[Q]},R$0=(A,Q,$)=>{let w=A[Q];if(w instanceof Set)w.delete($);else if(w===$)delete A[Q]},JD2=(A)=>A instanceof Set?A.size===0:!A,BL0=new Map;function DD2(A,Q,$,w,B){let X=(Y,Z)=>{if($(A),B(Y,Z,{watchedPath:A}),Z&&A!==Z)XL0(PB.resolve(A,Z),ah,PB.join(A,Z))};try{return Zt6(A,{persistent:Q.persistent},X)}catch(Y){w(Y);return}}var XL0=(A,Q,$,w,B)=>{let X=BL0.get(A);if(!X)return;SXA(X[Q],(Y)=>{Y($,w,B)})},_t6=(A,Q,$,w)=>{let{listener:B,errHandler:X,rawEmitter:Y}=w,Z=BL0.get(Q),W;if(!$.persistent){if(W=DD2(A,$,B,X,Y),!W)return;return W.close.bind(W)}if(Z)x$0(Z,ah,B),x$0(Z,wL0,X),x$0(Z,Ld,Y);else{if(W=DD2(A,$,XL0.bind(null,Q,ah),X,XL0.bind(null,Q,Ld)),!W)return;W.on(C3.ERROR,async(K)=>{let U=XL0.bind(null,Q,wL0);if(Z)Z.watcherUnusable=!0;if(uXA&&K.code==="EPERM")try{await(await Kt6(A,"r")).close(),U(K)}catch(G){}else U(K)}),Z={listeners:B,errHandlers:X,rawEmitters:Y,watcher:W},BL0.set(Q,Z)}return()=>{if(R$0(Z,ah,B),R$0(Z,wL0,X),R$0(Z,Ld,Y),JD2(Z.listeners))Z.watcher.close(),BL0.delete(Q),Ft6.forEach(Nt6(Z)),Z.watcher=void 0,Object.freeze(Z)}},gXA=new Map,Pt6=(A,Q,$,w)=>{let{listener:B,rawEmitter:X}=w,Y=gXA.get(Q),Z=Y&&Y.options;if(Z&&(Z.persistent<$.persistent||Z.interval>$.interval))GD2(Q),Y=void 0;if(Y)x$0(Y,ah,B),x$0(Y,Ld,X);else Y={listeners:B,rawEmitters:X,options:$,watcher:Ht6(Q,$,(W,K)=>{SXA(Y.rawEmitters,(G)=>{G(C3.CHANGE,Q,{curr:W,prev:K})});let U=W.mtimeMs;if(W.size!==K.size||U>K.mtimeMs||U===0)SXA(Y.listeners,(G)=>G(A,W))})},gXA.set(Q,Y);return()=>{if(R$0(Y,ah,B),R$0(Y,Ld,X),JD2(Y.listeners))gXA.delete(Q),GD2(Q),Y.options=Y.watcher=void 0,Object.freeze(Y)}};class cXA{fsw;_boundHandleError;constructor(A){this.fsw=A,this._boundHandleError=(Q)=>A._handleError(Q)}_watchWithNodeFs(A,Q){let $=this.fsw.options,w=PB.dirname(A),B=PB.basename(A);this.fsw._getWatchedDir(w).add(B);let Y=PB.resolve(A),Z={persistent:$.persistent};if(!Q)Q=YL0;let W;if($.usePolling){let K=$.interval!==$.binaryInterval;Z.interval=K&&Lt6(B)?$.binaryInterval:$.interval,W=Pt6(A,Y,Z,{listener:Q,rawEmitter:this.fsw._emitRaw})}else W=_t6(A,Y,Z,{listener:Q,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return W}_handleFile(A,Q,$){if(this.fsw.closed)return;let w=PB.dirname(A),B=PB.basename(A),X=this.fsw._getWatchedDir(w),Y=Q;if(X.has(B))return;let Z=async(K,U)=>{if(!this.fsw._throttle(Vt6,A,5))return;if(!U||U.mtimeMs===0)try{let G=await qD2(A);if(this.fsw.closed)return;let{atimeMs:D,mtimeMs:q}=G;if(!D||D<=q||q!==Y.mtimeMs)this.fsw._emit(C3.CHANGE,A,G);if((Dt6||qt6||zt6)&&Y.ino!==G.ino){this.fsw._closeFile(K),Y=G;let J=this._watchWithNodeFs(A,Z);if(J)this.fsw._addPathCloser(K,J)}else Y=G}catch(G){this.fsw._remove(w,B)}else if(X.has(B)){let{atimeMs:G,mtimeMs:D}=U;if(!G||G<=D||D!==Y.mtimeMs)this.fsw._emit(C3.CHANGE,A,U);Y=U}},W=this._watchWithNodeFs(A,Z);if(!($&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(A)){if(!this.fsw._throttle(C3.ADD,A,0))return;this.fsw._emit(C3.ADD,A,Q)}return W}async _handleSymlink(A,Q,$,w){if(this.fsw.closed)return;let B=A.fullPath,X=this.fsw._getWatchedDir(Q);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let Y;try{Y=await yXA($)}catch(Z){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;if(X.has(w)){if(this.fsw._symlinkPaths.get(B)!==Y)this.fsw._symlinkPaths.set(B,Y),this.fsw._emit(C3.CHANGE,$,A.stats)}else X.add(w),this.fsw._symlinkPaths.set(B,Y),this.fsw._emit(C3.ADD,$,A.stats);return this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(B))return!0;this.fsw._symlinkPaths.set(B,!0)}_handleRead(A,Q,$,w,B,X,Y){A=PB.join(A,"");let Z=w?`${A}:${w}`:A;if(Y=this.fsw._throttle("readdir",Z,1000),!Y)return;let W=this.fsw._getWatchedDir($.path),K=new Set,U=this.fsw._readdirp(A,{fileFilter:(G)=>$.filterPath(G),directoryFilter:(G)=>$.filterDir(G)});if(!U)return;return U.on(Gt6,async(G)=>{if(this.fsw.closed){U=void 0;return}let D=G.path,q=PB.join(A,D);if(K.add(D),G.stats.isSymbolicLink()&&await this._handleSymlink(G,A,q,D))return;if(this.fsw.closed){U=void 0;return}if(D===w||!w&&!W.has(D))this.fsw._incrReadyCount(),q=PB.join(B,PB.relative(B,q)),this._addToNodeFs(q,Q,$,X+1)}).on(C3.ERROR,this._boundHandleError),new Promise((G,D)=>{if(!U)return D();U.once(mXA,()=>{if(this.fsw.closed){U=void 0;return}let q=Y?Y.clear():!1;if(G(void 0),W.getChildren().filter((J)=>{return J!==A&&!K.has(J)}).forEach((J)=>{this.fsw._remove(A,J)}),U=void 0,q)this._handleRead(A,!1,$,w,B,X,Y)})})}async _handleDir(A,Q,$,w,B,X,Y){let Z=this.fsw._getWatchedDir(PB.dirname(A)),W=Z.has(PB.basename(A));if(!($&&this.fsw.options.ignoreInitial)&&!B&&!W)this.fsw._emit(C3.ADD_DIR,A,Q);Z.add(PB.basename(A)),this.fsw._getWatchedDir(A);let K,U,G=this.fsw.options.depth;if((G==null||w<=G)&&!this.fsw._symlinkPaths.has(Y)){if(!B){if(await this._handleRead(A,$,X,B,A,w,K),this.fsw.closed)return}U=this._watchWithNodeFs(A,(D,q)=>{if(q&&q.mtimeMs===0)return;this._handleRead(D,!1,X,B,A,w,K)})}return U}async _addToNodeFs(A,Q,$,w,B){let X=this.fsw._emitReady;if(this.fsw._isIgnored(A)||this.fsw.closed)return X(),!1;let Y=this.fsw._getWatchHelpers(A);if($)Y.filterPath=(Z)=>$.filterPath(Z),Y.filterDir=(Z)=>$.filterDir(Z);try{let Z=await Jt6[Y.statMethod](Y.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(Y.watchPath,Z))return X(),!1;let W=this.fsw.options.followSymlinks,K;if(Z.isDirectory()){let U=PB.resolve(A),G=W?await yXA(A):A;if(this.fsw.closed)return;if(K=await this._handleDir(Y.watchPath,Z,Q,w,B,Y,G),this.fsw.closed)return;if(U!==G&&G!==void 0)this.fsw._symlinkPaths.set(U,G)}else if(Z.isSymbolicLink()){let U=W?await yXA(A):A;if(this.fsw.closed)return;let G=PB.dirname(Y.watchPath);if(this.fsw._getWatchedDir(G).add(Y.watchPath),this.fsw._emit(C3.ADD,Y.watchPath,Z),K=await this._handleDir(G,Z,Q,w,A,Y,U),this.fsw.closed)return;if(U!==void 0)this.fsw._symlinkPaths.set(PB.resolve(A),U)}else K=this._handleFile(Y.watchPath,Z,Q);if(X(),K)this.fsw._addPathCloser(A,K);return!1}catch(Z){if(this.fsw._handleError(Z))return X(),A}}}/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */var pXA="/",Ot6="//",_D2=".",ft6="..",xt6="string",Rt6=/\\/g,PD2=/\/\//g,vt6=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ct6=/^\.[/\\]/;function HL0(A){return Array.isArray(A)?A:[A]}var lXA=(A)=>typeof A==="object"&&A!==null&&!(A instanceof RegExp);function ht6(A){if(typeof A==="function")return A;if(typeof A==="string")return(Q)=>A===Q;if(A instanceof RegExp)return(Q)=>A.test(Q);if(typeof A==="object"&&A!==null)return(Q)=>{if(A.path===Q)return!0;if(A.recursive){let $=Z8.relative(A.path,Q);if(!$)return!1;return!$.startsWith("..")&&!Z8.isAbsolute($)}return!1};return()=>!1}function Et6(A){if(typeof A!=="string")throw Error("string expected");A=Z8.normalize(A),A=A.replace(/\\/g,"/");let Q=!1;if(A.startsWith("//"))Q=!0;if(A=A.replace(PD2,"/"),Q)A="/"+A;return A}function FD2(A,Q,$){let w=Et6(Q);for(let B=0;B<A.length;B++){let X=A[B];if(X(w,$))return!0}return!1}function Tt6(A,Q){if(A==null)throw TypeError("anymatch: specify first argument");let w=HL0(A).map((B)=>ht6(B));if(Q==null)return(B,X)=>{return FD2(w,B,X)};return FD2(w,Q)}var ID2=(A)=>{let Q=HL0(A).flat();if(!Q.every(($)=>typeof $===xt6))throw TypeError(`Non-string provided as watch path: ${Q}`);return Q.map(kD2)},LD2=(A)=>{let Q=A.replace(Rt6,pXA),$=!1;if(Q.startsWith(Ot6))$=!0;if(Q=Q.replace(PD2,pXA),$)Q=pXA+Q;return Q},kD2=(A)=>LD2(Z8.normalize(LD2(A))),ND2=(A="")=>(Q)=>{if(typeof Q==="string")return kD2(Z8.isAbsolute(Q)?Q:Z8.join(A,Q));else return Q},yt6=(A,Q)=>{if(Z8.isAbsolute(A))return A;return Z8.join(Q,A)},gt6=Object.freeze(new Set);class jD2{path;_removeWatcher;items;constructor(A,Q){this.path=A,this._removeWatcher=Q,this.items=new Set}add(A){let{items:Q}=this;if(!Q)return;if(A!==_D2&&A!==ft6)Q.add(A)}async remove(A){let{items:Q}=this;if(!Q)return;if(Q.delete(A),Q.size>0)return;let $=this.path;try{await Mt6($)}catch(w){if(this._removeWatcher)this._removeWatcher(Z8.dirname($),Z8.basename($))}}has(A){let{items:Q}=this;if(!Q)return;return Q.has(A)}getChildren(){let{items:A}=this;if(!A)return[];return[...A.values()]}dispose(){this.items.clear(),this.path="",this._removeWatcher=YL0,this.items=gt6,Object.freeze(this)}}var St6="stat",mt6="lstat";class MD2{fsw;path;watchPath;fullWatchPath;dirParts;followSymlinks;statMethod;constructor(A,Q,$){this.fsw=$;let w=A;this.path=A=A.replace(Ct6,""),this.watchPath=w,this.fullWatchPath=Z8.resolve(w),this.dirParts=[],this.dirParts.forEach((B)=>{if(B.length>1)B.pop()}),this.followSymlinks=Q,this.statMethod=Q?St6:mt6}entryPath(A){return Z8.join(this.watchPath,Z8.relative(this.watchPath,A.fullPath))}filterPath(A){let{stats:Q}=A;if(Q&&Q.isSymbolicLink())return this.filterDir(A);let $=this.entryPath(A);return this.fsw._isntIgnored($,Q)&&this.fsw._hasReadPermissions(Q)}filterDir(A){return this.fsw._isntIgnored(this.entryPath(A),A.stats)}}class dXA extends kt6{closed;options;_closers;_ignoredPaths;_throttled;_streams;_symlinkPaths;_watched;_pendingWrites;_pendingUnlinks;_readyCount;_emitReady;_closePromise;_userIgnored;_readyEmitted;_emitRaw;_boundRemove;_nodeFsHandler;constructor(A={}){super();this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let Q=A.awaitWriteFinish,$={stabilityThreshold:2000,pollInterval:100},w={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...A,ignored:A.ignored?HL0(A.ignored):HL0([]),awaitWriteFinish:Q===!0?$:typeof Q==="object"?{...$,...Q}:!1};if(VD2)w.usePolling=!0;if(w.atomic===void 0)w.atomic=!w.usePolling;let B=process.env.CHOKIDAR_USEPOLLING;if(B!==void 0){let Z=B.toLowerCase();if(Z==="false"||Z==="0")w.usePolling=!1;else if(Z==="true"||Z==="1")w.usePolling=!0;else w.usePolling=!!Z}let X=process.env.CHOKIDAR_INTERVAL;if(X)w.interval=Number.parseInt(X,10);let Y=0;this._emitReady=()=>{if(Y++,Y>=this._readyCount)this._emitReady=YL0,this._readyEmitted=!0,process.nextTick(()=>this.emit(r5.READY))},this._emitRaw=(...Z)=>this.emit(r5.RAW,...Z),this._boundRemove=this._remove.bind(this),this.options=w,this._nodeFsHandler=new cXA(this),Object.freeze(w)}_addIgnoredPath(A){if(lXA(A)){for(let Q of this._ignoredPaths)if(lXA(Q)&&Q.path===A.path&&Q.recursive===A.recursive)return}this._ignoredPaths.add(A)}_removeIgnoredPath(A){if(this._ignoredPaths.delete(A),typeof A==="string"){for(let Q of this._ignoredPaths)if(lXA(Q)&&Q.path===A)this._ignoredPaths.delete(Q)}}add(A,Q,$){let{cwd:w}=this.options;this.closed=!1,this._closePromise=void 0;let B=ID2(A);if(w)B=B.map((X)=>{return yt6(X,w)});if(B.forEach((X)=>{this._removeIgnoredPath(X)}),this._userIgnored=void 0,!this._readyCount)this._readyCount=0;return this._readyCount+=B.length,Promise.all(B.map(async(X)=>{let Y=await this._nodeFsHandler._addToNodeFs(X,!$,void 0,0,Q);if(Y)this._emitReady();return Y})).then((X)=>{if(this.closed)return;X.forEach((Y)=>{if(Y)this.add(Z8.dirname(Y),Z8.basename(Q||Y))})}),this}unwatch(A){if(this.closed)return this;let Q=ID2(A),{cwd:$}=this.options;return Q.forEach((w)=>{if(!Z8.isAbsolute(w)&&!this._closers.has(w)){if($)w=Z8.join($,w);w=Z8.resolve(w)}if(this._closePath(w),this._addIgnoredPath(w),this._watched.has(w))this._addIgnoredPath({path:w,recursive:!0});this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let A=[];return this._closers.forEach((Q)=>Q.forEach(($)=>{let w=$();if(w instanceof Promise)A.push(w)})),this._streams.forEach((Q)=>Q.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach((Q)=>Q.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=A.length?Promise.all(A).then(()=>{return}):Promise.resolve(),this._closePromise}getWatched(){let A={};return this._watched.forEach((Q,$)=>{let B=(this.options.cwd?Z8.relative(this.options.cwd,$):$)||_D2;A[B]=Q.getChildren().sort()}),A}emitWithAll(A,Q){if(this.emit(A,...Q),A!==r5.ERROR)this.emit(r5.ALL,A,...Q)}async _emit(A,Q,$){if(this.closed)return;let w=this.options;if(uXA)Q=Z8.normalize(Q);if(w.cwd)Q=Z8.relative(w.cwd,Q);let B=[Q];if($!=null)B.push($);let X=w.awaitWriteFinish,Y;if(X&&(Y=this._pendingWrites.get(Q)))return Y.lastChange=new Date,this;if(w.atomic){if(A===r5.UNLINK)return this._pendingUnlinks.set(Q,[A,...B]),setTimeout(()=>{this._pendingUnlinks.forEach((Z,W)=>{this.emit(...Z),this.emit(r5.ALL,...Z),this._pendingUnlinks.delete(W)})},typeof w.atomic==="number"?w.atomic:100),this;if(A===r5.ADD&&this._pendingUnlinks.has(Q))A=r5.CHANGE,this._pendingUnlinks.delete(Q)}if(X&&(A===r5.ADD||A===r5.CHANGE)&&this._readyEmitted){let Z=(W,K)=>{if(W)A=r5.ERROR,B[0]=W,this.emitWithAll(A,B);else if(K){if(B.length>1)B[1]=K;else B.push(K);this.emitWithAll(A,B)}};return this._awaitWriteFinish(Q,X.stabilityThreshold,A,Z),this}if(A===r5.CHANGE){if(!this._throttle(r5.CHANGE,Q,50))return this}if(w.alwaysStat&&$===void 0&&(A===r5.ADD||A===r5.ADD_DIR||A===r5.CHANGE)){let Z=w.cwd?Z8.join(w.cwd,Q):Q,W;try{W=await bt6(Z)}catch(K){}if(!W||this.closed)return;B.push(W)}return this.emitWithAll(A,B),this}_handleError(A){let Q=A&&A.code;if(A&&Q!=="ENOENT"&&Q!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||Q!=="EPERM"&&Q!=="EACCES"))this.emit(r5.ERROR,A);return A||this.closed}_throttle(A,Q,$){if(!this._throttled.has(A))this._throttled.set(A,new Map);let w=this._throttled.get(A);if(!w)throw Error("invalid throttle");let B=w.get(Q);if(B)return B.count++,!1;let X,Y=()=>{let W=w.get(Q),K=W?W.count:0;if(w.delete(Q),clearTimeout(X),W)clearTimeout(W.timeoutObject);return K};X=setTimeout(Y,$);let Z={timeoutObject:X,clear:Y,count:0};return w.set(Q,Z),Z}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(A,Q,$,w){let B=this.options.awaitWriteFinish;if(typeof B!=="object")return;let X=B.pollInterval,Y,Z=A;if(this.options.cwd&&!Z8.isAbsolute(A))Z=Z8.join(this.options.cwd,A);let W=new Date,K=this._pendingWrites;function U(G){jt6(Z,(D,q)=>{if(D||!K.has(A)){if(D&&D.code!=="ENOENT")w(D);return}let J=Number(new Date);if(G&&q.size!==G.size)K.get(A).lastChange=J;let F=K.get(A);if(J-F.lastChange>=Q)K.delete(A),w(void 0,q);else Y=setTimeout(U,X,q)})}if(!K.has(A))K.set(A,{lastChange:W,cancelWait:()=>{return K.delete(A),clearTimeout(Y),$}}),Y=setTimeout(U,X)}_isIgnored(A,Q){if(this.options.atomic&&vt6.test(A))return!0;if(!this._userIgnored){let{cwd:$}=this.options,B=(this.options.ignored||[]).map(ND2($)),Y=[...[...this._ignoredPaths].map(ND2($)),...B];this._userIgnored=Tt6(Y,void 0)}return this._userIgnored(A,Q)}_isntIgnored(A,Q){return!this._isIgnored(A,Q)}_getWatchHelpers(A){return new MD2(A,this.options.followSymlinks,this)}_getWatchedDir(A){let Q=Z8.resolve(A);if(!this._watched.has(Q))this._watched.set(Q,new jD2(Q,this._boundRemove));return this._watched.get(Q)}_hasReadPermissions(A){if(this.options.ignorePermissionErrors)return!0;return Boolean(Number(A.mode)&256)}_remove(A,Q,$){let w=Z8.join(A,Q),B=Z8.resolve(w);if($=$!=null?$:this._watched.has(w)||this._watched.has(B),!this._throttle("remove",w,100))return;if(!$&&this._watched.size===1)this.add(A,Q,!0);this._getWatchedDir(w).getChildren().forEach((G)=>this._remove(w,G));let Z=this._getWatchedDir(A),W=Z.has(Q);if(Z.remove(Q),this._symlinkPaths.has(B))this._symlinkPaths.delete(B);let K=w;if(this.options.cwd)K=Z8.relative(this.options.cwd,w);if(this.options.awaitWriteFinish&&this._pendingWrites.has(K)){if(this._pendingWrites.get(K).cancelWait()===r5.ADD)return}this._watched.delete(w),this._watched.delete(B);let U=$?r5.UNLINK_DIR:r5.UNLINK;if(W&&!this._isIgnored(w))this._emit(U,w);this._closePath(w)}_closePath(A){this._closeFile(A);let Q=Z8.dirname(A);this._getWatchedDir(Q).remove(Z8.basename(A))}_closeFile(A){let Q=this._closers.get(A);if(!Q)return;Q.forEach(($)=>$()),this._closers.delete(A)}_addPathCloser(A,Q){if(!Q)return;let $=this._closers.get(A);if(!$)$=[],this._closers.set(A,$);$.push(Q)}_readdirp(A,Q){if(this.closed)return;let $={type:r5.ALL,alwaysStat:!0,lstat:!0,...Q,depth:0},w=UD2(A,$);return this._streams.add(w),w.once(zD2,()=>{w=void 0}),w.once(mXA,()=>{if(w)this._streams.delete(w),w=void 0}),w}}function ut6(A,Q={}){let $=new dXA(Q);return $.add(A),$}var bD2={watch:ut6,FSWatcher:dXA};import{extname as ct6}from"path";var WL0=[".png",".jpg",".jpeg",".webp",".gif",".svg"];function th(A){let Q=ct6(A).toLowerCase();return WL0.includes(Q)}function OD2(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 iXA(A){switch(A.toLowerCase()){case"jpeg":return".jpg";case"svg+xml":return".svg";default:return`.${A.toLowerCase()}`}}import{isAbsolute as pt6,relative as lt6,sep as fD2,join as dt6}from"path";function Nq(A,Q){return pt6(Q)?Q:dt6(A,Q)}function Nd(A,Q){let $=Nq(A,Q),w=lt6(A,$);return fD2==="/"?w:w.split(fD2).join("/")}function it6(A,Q){if(!Nd(Q,A).startsWith("image/"))return!1;return th(A)}function nt6(A,Q){if(Nd(Q,A).split("/")[0]?.startsWith("_"))return!1;if(A.endsWith(".md"))return!0;return it6(A,Q)}class nXA{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=bD2.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(!nt6(Q,this.syncPath))return;this.logger.debug("File change detected",{event:A,path:Q});let $=Nd(this.syncPath,Q);if(this.pendingChanges.set($,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,$]of A){let w=Nq(this.syncPath,Q);try{if(this.onFileChange)await this.onFileChange($,w)}catch(B){this.logger.error("Error processing file change",{path:Q,event:$,error:B})}}}isWatching(){return!!this.watcher}getPendingChangesCount(){return this.pendingChanges.size}}async function xD2(A,Q){if(A?.isWatching())return Q.logger.debug("Already watching directory"),A;return rt6(Q)}function RD2(A){if(A)A.stop();return}function vD2(A,Q){if(A)A.setCallback(Q)}async function rt6(A){let{logger:Q,syncPath:$,watchInterval:w,importEntities:B,jobQueueCallback:X,fileOperations:Y,deleteOnFileRemoval:Z}=A,W=new hXA(Q,B,X,Y,Z),K=new nXA({syncPath:$,watchInterval:w,logger:Q,onFileChange:async(U,G)=>{await W.handleFileChange(U,G)}});return await K.start(),K}async function CD2(A){let Q=Date.now();A.logger.debug("Starting sync (import only)");let $=await A.importEntities(),w=await A.removeOrphanedEntities(),B=Date.now()-Q;return A.markSynced(new Date),A.logger.debug("Sync completed",{duration:B,imported:$.imported,orphansDeleted:w.deleted}),{export:{exported:0,failed:0,errors:[]},import:$,duration:B}}KA();class rXA{logger;syncPath;deleteOnFileRemoval;constructor(A){this.logger=A.logger,this.syncPath=A.syncPath,this.deleteOnFileRemoval=A.deleteOnFileRemoval}prepareBatchOperations(A){let Q=[],$=this.createImportOperations(A);Q.push(...$);let w=$.length;if(this.deleteOnFileRemoval)Q.push({type:"directory-cleanup",data:{}});let B=A.length;return this.logger.debug("Prepared batch operations",{exportOperationsCount:0,importOperationsCount:w,totalFiles:B}),{operations:Q,exportOperationsCount:0,importOperationsCount:w,totalFiles:B}}async queueSyncBatch(A,Q,$,w){let B=this.prepareBatchOperations($);if(B.operations.length===0)return this.logger.debug("No sync operations needed",{source:Q}),null;return{batchId:await A.jobs.enqueueBatch(B.operations,{source:Q,rootJobId:w?.rootJobId??nY(),metadata:{progressToken:w?.progressToken,operationType:"file_operations",operationTarget:this.syncPath,pluginId:w?.pluginId??"directory-sync",interfaceType:w?.interfaceType,channelId:w?.channelId}}),operationCount:B.operations.length,exportOperationsCount:B.exportOperationsCount,importOperationsCount:B.importOperationsCount,totalFiles:B.totalFiles}}createImportOperations(A){if(A.length===0)return[];let Q=50,$=[];for(let w=0;w<A.length;w+=Q){let B=A.slice(w,w+Q);$.push({type:"directory-import",data:{batchIndex:Math.floor(w/Q),paths:B,batchSize:B.length}})}return $}}class oXA{syncInProgress=!1;logger;fileOperations;batchOperationsManager;constructor(A){this.logger=A.logger,this.fileOperations=A.fileOperations,this.batchOperationsManager=new rXA({logger:A.logger,syncPath:A.syncPath,deleteOnFileRemoval:A.deleteOnFileRemoval})}async queueSyncBatch(A,Q,$){if(this.syncInProgress)return this.logger.debug("Sync already in progress, skipping",{source:Q}),null;this.syncInProgress=!0;try{let w=await this.fileOperations.getAllSyncFiles();return await this.batchOperationsManager.queueSyncBatch(A,Q,w,$)}finally{this.syncInProgress=!1}}}class sXA{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 Ae6,dirname as Qe6,extname as $e6}from"path";import{extname as ot6}from"path";var KL0=[".pdf"],hD2=".meta.json";function eh(A){let Q=ot6(A).toLowerCase();return KL0.includes(Q)}function ED2(A){return A.toLowerCase().endsWith(hD2)}function aXA(A){return`${A}${hD2}`}function TD2(A){switch(A.toLowerCase().replace(".","")){case"pdf":default:return"application/pdf"}}import{extname as st6,join as UL0}from"path";function GL0(A,Q){let w=Nd(A,Q).split("/"),B,X;if(w.length===1)B="note",X=w;else if(w.length>1&&w[0])B=w[0],X=w.slice(1);else B="note",X=w;let Y;if(X.length>1){let Z=X[X.length-1];if(Z)X[X.length-1]=yD2(Z);Y=X.join(":")}else Y=yD2(X[0]??"");return{entityType:B,id:Y}}function gD2(A,Q,$,w=".md"){let B=Q.split(":").filter((K)=>K.length>0),X=$==="note";if(B.length===1)return X?UL0(A,`${B[0]}${w}`):UL0(A,$,`${B[0]}${w}`);let Y=B;if(B[0]===$)Y=B.slice(1);let Z=Y[Y.length-1],W=Y.slice(0,-1);if(X)return UL0(A,...W,`${Z}${w}`);return UL0(A,$,...W,`${Z}${w}`)}function SD2(A){if(A.entityType==="document")return".pdf";if(A.entityType!=="image")return".md";let Q=A.metadata.format;if(Q)return iXA(Q);let $=A.content.match(/^data:image\/([a-z+]+);base64,/i);return $?.[1]?iXA($[1]):".md"}function yD2(A){let Q=st6(A).toLowerCase();return Q===".md"||WL0.includes(Q)||KL0.includes(Q)?A.slice(0,-Q.length):A}C0();bH();import{mkdir as we6,readFile as _d,writeFile as eXA,stat as Be6,utimes as Xe6}from"fs/promises";import{join as DL0}from"path";import{mkdir as mD2,readdir as tt6,stat as et6}from"fs/promises";import{access as at6}from"fs/promises";async function s9(A){try{return await at6(A),!0}catch{return!1}}async function tXA(A,Q){return lD2(A,Q,{includeDocuments:!1,includeImages:!1})}async function uD2(A,Q){return lD2(A,Q,{includeDocuments:!0,includeImages:!0})}async function cD2(A,Q){if(!await s9(A))await mD2(A,{recursive:!0});for(let $ of Q)if($!=="note")await mD2(DL0(A,$),{recursive:!0})}async function pD2(A,Q){let $=[],w={totalFiles:0,byEntityType:{}};if(!await s9(A))return{files:$,stats:w};let B=await tXA(A,Q);for(let X of B)try{let Y=DL0(A,X),Z=await et6(Y),{entityType:W}=GL0(A,X);$.push({path:X,entityType:W,modified:Z.mtime}),w.totalFiles++,w.byEntityType[W]=(w.byEntityType[W]??0)+1}catch{continue}return{files:$,stats:w}}async function lD2(A,Q,$){let w=[];if(!await s9(A))return w;let B=async(X,Y="",Z=!1,W=!1)=>{let K=await tt6(X,{withFileTypes:!0});for(let U of K){let G=Y?DL0(Y,U.name):U.name;if(U.isFile()&&!U.name.endsWith(".invalid")&&!ED2(U.name)){if(U.name.endsWith(".md"))w.push(G);else if($.includeImages&&Z&&th(U.name))w.push(G);else if($.includeDocuments&&W&&eh(U.name))w.push(G)}else if(U.isDirectory()&&!U.name.startsWith(".")){if(Y===""&&!Q.hasEntityType(U.name))continue;let D=DL0(X,U.name),q=U.name==="image"&&Y==="",J=U.name==="document"&&Y==="";await B(D,G,Z||q,W||J)}}};return await B(A),w}var Ye6=H.record(H.string(),H.unknown());class AYA{syncPath;entityService;constructor(A,Q){this.syncPath=A,this.entityService=Q}parseEntityFromPath(A){return GL0(this.syncPath,A)}async readEntity(A){let Q=Nq(this.syncPath,A),$=await Be6(Q),{entityType:w,id:B}=this.parseEntityFromPath(A),X=$.birthtime.getTime()>0?$.birthtime:$.mtime,Y=$.mtime,Z,W;if(th(A)||eh(A)){let G=(await _d(Q)).toString("base64"),D=$e6(A);if(Z=`data:${eh(A)?TD2(D):OD2(D)};base64,${G}`,eh(A))W=await this.readDocumentSidecar(Q,A)}else Z=await _d(Q,"utf-8");let K={entityType:w,id:B,content:Z,created:X,updated:Y};if(W)K.metadata=W;return K}async readDocumentSidecar(A,Q){let $={mimeType:"application/pdf",filename:Ae6(Q)},w=aXA(A);if(!await s9(w))return $;try{let B=await _d(w,"utf-8"),X=Ye6.safeParse(JSON.parse(B));return{...$,...X.success?X.data:{}}}catch{return $}}async writeEntity(A){let Q=this.getEntityFilePath(A),$=A.entityType==="image",w=A.entityType==="document";if($||w){let X=$?/^data:image\/[a-z+]+;base64,(.+)$/i:/^data:application\/pdf;base64,(.+)$/i,Y=A.content.match(X),Z=Y?.[1]?Buffer.from(Y[1],"base64"):Buffer.from(A.content,"base64"),W=!1;if(await s9(Q)){let K=await _d(Q),U=e6(K.toString("base64")),G=e6(Z.toString("base64"));if(U===G)W=!0}if(!W)await this.ensureEntityDirectory(A,Q),await eXA(Q,Z);if(w)await this.writeDocumentSidecar(A,Q);if(W)return}else{let X=this.entityService.serializeEntity(A);if(await s9(Q)){let Y=await _d(Q,"utf-8"),Z=e6(Y),W=e6(X);if(Z===W)return}await this.ensureEntityDirectory(A,Q),await eXA(Q,X,"utf-8")}let B=new Date(A.updated);await Xe6(Q,B,B)}async ensureEntityDirectory(A,Q){if(A.entityType!=="note")await we6(Qe6(Q),{recursive:!0})}async writeDocumentSidecar(A,Q){let $=A.metadata,w={};for(let[Y,Z]of Object.entries($)){if(Y==="mimeType")continue;if(Z===void 0)continue;w[Y]=Z}let B=aXA(Q),X=`${JSON.stringify(w,null,2)}
5764
5764
  `;if(await s9(B)){if(await _d(B,"utf-8")===X)return}await this.ensureEntityDirectory(A,B),await eXA(B,X,"utf-8")}getFilePath(A,Q,$=".md"){return gD2(this.syncPath,A,Q,$)}getEntityFilePath(A){return this.getFilePath(A.id,A.entityType,SD2(A))}async getAllMarkdownFiles(){return tXA(this.syncPath,this.entityService)}async getAllSyncFiles(){return uD2(this.syncPath,this.entityService)}async ensureDirectoryStructure(A){await cD2(this.syncPath,A)}shouldUpdateEntity(A,Q){let $=e6(Q.content);return A.contentHash!==$}async gatherFileStatus(){return pD2(this.syncPath,this.entityService)}async syncDirectoryExists(){return s9(this.syncPath)}async fileExists(A){return s9(A)}}JZ();C0();_4();S2();JZ();async function qL0(A,Q,$,w){let{sourceUrl:B}=A,X=await Q.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:B}},limit:1}});if(X[0])return w.debug("Reusing existing image entity",{sourceUrl:B,imageId:X[0].id}),X[0].id;let Y=await $(B),{base64:Z}=JM(Y),W=cv(Z),K=FM(Z);if(!W||!K)throw Error("Could not detect image format or dimensions");let U=await Q.createEntity({entity:{id:A.id,entityType:"image",content:Y,metadata:{title:A.title,alt:A.alt,format:W,width:K.width,height:K.height,sourceUrl:B}}});return w.debug("Created image entity from URL",{sourceUrl:B,imageId:U.entityId}),U.entityId}var dD2=H.object({title:H.string(),slug:H.string().optional(),coverImageUrl:H.url(),coverImageId:H.string().optional(),coverImageAlt:H.string().optional()});class QYA{entityService;fetcher;logger;constructor(A,Q,$=rD){this.entityService=A,this.fetcher=$,this.logger=Q.child("FrontmatterImageConverter")}detectCoverImageUrl(A){let Q;try{Q=c8(A)}catch{return null}let{frontmatter:$}=Q,w=dD2.safeParse($);if(!w.success)return null;if(w.data.coverImageId)return null;let{title:B,slug:X,coverImageUrl:Y,coverImageAlt:Z}=w.data;if(!uv(Y))return null;return{sourceUrl:Y,postTitle:B,postSlug:X??k1(B),customAlt:Z}}async convert(A){let Q;try{Q=c8(A)}catch(K){return this.logger.debug("Parse failed",{error:K}),{content:A,converted:!1}}let{frontmatter:$}=Q,w=dD2.safeParse($);if(!w.success)return{content:A,converted:!1};if(w.data.coverImageId)return{content:A,converted:!1};let{title:B,slug:X,coverImageUrl:Y,coverImageAlt:Z}=w.data;if(!uv(Y))return{content:A,converted:!1};let W={postTitle:B,postSlug:X??k1(B),sourceUrl:Y,customAlt:Z};try{let K=await this.createImageEntity(W),U={...$};return delete U.coverImageUrl,delete U.coverImageAlt,U.coverImageId=K,{content:Wv(U,Q.content),converted:!0,imageId:K}}catch(K){return this.logger.warn("Failed to convert coverImageUrl",{url:Y,error:aA(K)}),{content:A,converted:!1}}}async createImageEntity(A){let{postTitle:Q,postSlug:$,sourceUrl:w,customAlt:B}=A,X=`Cover image for ${Q}`;return qL0({id:`${$}-cover`,title:X,alt:B??X,sourceUrl:w},this.entityService,this.fetcher,this.logger)}}JZ();class v$0{entityService;fetcher;logger;constructor(A,Q,$=rD){this.entityService=A,this.fetcher=$,this.logger=Q.child("MarkdownImageConverter")}detectInlineImages(A,Q){let $=[],w=Ut0(A);for(let B of w){if(!uv(B.url))continue;if(B.url.startsWith("entity://"))continue;let X=this.reconstructMarkdown(B);$.push({sourceUrl:B.url,alt:B.alt,originalMarkdown:X,postSlug:Q})}return $}reconstructMarkdown(A){if(A.title)return`![${A.alt}](${A.url} "${A.title}")`;return`![${A.alt}](${A.url})`}async convert(A,Q){let $=this.detectInlineImages(A,Q);if($.length===0)return{content:A,converted:!1,convertedCount:0};let w=A,B=0,X=0;for(let Y of $)try{let Z=await this.createImageEntity(Y,X++),W=`![${Y.alt}](entity://image/${Z})`;w=w.replace(Y.originalMarkdown,W),B++,this.logger.debug("Converted inline image",{sourceUrl:Y.sourceUrl,imageId:Z})}catch(Z){this.logger.warn("Failed to convert inline image",{sourceUrl:Y.sourceUrl,error:aA(Z)})}return{content:w,converted:B>0,convertedCount:B}}async createImageEntity(A,Q){let{sourceUrl:$,alt:w,postSlug:B}=A;return qL0({id:`${B}-inline-${Q}`,title:w||`Inline image ${Q+1} for ${B}`,alt:w||"",sourceUrl:$},this.entityService,this.fetcher,this.logger)}}class $YA{logger;entityService;fileOperations;constructor(A,Q,$){this.logger=A,this.entityService=Q,this.fileOperations=$}async importEntitiesWithProgress(A,Q,$,w){this.logger.debug("Importing entities with progress reporting");let B={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},X=A??await this.fileOperations.getAllSyncFiles(),Y=X.length;await Q.report({progress:0,message:`Starting import of ${Y} files`});for(let Z=0;Z<Y;Z+=$){let W=X.slice(Z,Z+$),K=await w(W);B.imported+=K.imported,B.skipped+=K.skipped,B.failed+=K.failed,B.quarantined+=K.quarantined,B.errors.push(...K.errors),B.quarantinedFiles.push(...K.quarantinedFiles),B.jobIds.push(...K.jobIds);let U=Math.min(Z+$,Y),G=Math.round(U/Y*40);await Q.report({progress:G,message:`Imported ${U}/${Y} files`})}return B}async exportEntitiesWithProgress(A,Q,$,w){this.logger.debug("Exporting entities with progress reporting");let B=A??this.entityService.getEntityTypes();await Q.report({progress:50,message:`Starting export of ${B.length} entity types`});let X=await w(A);return await Q.report({progress:100,message:`Exported ${X.exported} entities`}),this.logger.debug("Export completed",X),X}}KA();import{rename as Ze6,appendFile as He6,readFile as We6,writeFile as Ke6,access as Ue6}from"fs/promises";import{join as iD2}from"path";class wYA{logger;syncPath;constructor(A,Q){this.logger=A,this.syncPath=Q}isValidationError(A){return HU0(A)}async quarantineInvalidFile(A,Q,$,w){let B=w(A),X=`${B}.invalid`;try{await Ze6(B,X),$.quarantined++,$.quarantinedFiles.push(A);let Y=iD2(this.syncPath,".import-errors.log"),Z=new Date().toISOString(),W=aA(Q),K=`${Z} - ${A}: ${W}
5765
5765
  \u2192 ${A}.invalid
@@ -5788,7 +5788,7 @@ ${KG2}</style></head><body>${j$0(A)}<main id="root" data-web-chat-root>Brain Cha
5788
5788
  *...and ${A.files.length-10} more files*`)}if(A.exists&&A.stats.totalFiles===0)Q.push(`
5789
5789
  ## Getting Started
5790
5790
  `),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(`
5791
- `)}}KA();class SL0 extends X8{directorySync;constructor(A,Q,$){super(A,{schema:XZA,jobTypeName:"directory-export"});this.directorySync=$}async process(A,Q,$){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let w=Date.now();try{let B=await this.directorySync.exportEntitiesWithProgress(A.entityTypes,$,A.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:Q,exported:B.exported,failed:B.failed,duration:Date.now()-w}),B}catch(B){throw this.logger.error("Directory export job failed",{jobId:Q,error:B}),B}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}KA();class mL0 extends X8{directorySync;constructor(A,Q,$){super(A,{schema:BZA,jobTypeName:"directory-import"});this.directorySync=$}async process(A,Q,$){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let w=Date.now();try{let B=await this.directorySync.importEntitiesWithProgress(A.paths,$,A.batchSize??100);return this.logger.debug("Directory import job completed",{jobId:Q,imported:B.imported,skipped:B.skipped,failed:B.failed,quarantined:B.quarantined,duration:Date.now()-w}),B}catch(B){throw this.logger.error("Directory import job failed",{jobId:Q,error:B}),B}}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}KA();class uL0 extends X8{directorySync;context;constructor(A,Q,$){super(A,{schema:$ZA,jobTypeName:"directory-sync"});this.context=Q,this.directorySync=$}async process(A,Q,$){let w=Date.now(),B=A.syncDirection??"both";this.logger.info("Starting directory sync job",{jobId:Q,operation:A.operation,syncDirection:B});let X={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},Y={exported:0,failed:0,errors:[]};if(B!=="export")if(await $.report({progress:10,message:"Scanning directory for changes"}),X=await this.importWithProgress(A.paths,$),B==="import")await this.waitForImportJobs(X.jobIds,$),await $.report({progress:100,message:`Import complete: ${X.imported} imported`});else await $.report({progress:50,message:`Imported ${X.imported} entities`}),await this.waitForImportJobs(X.jobIds,$),await $.report({progress:56,message:"Processing complete, starting export"});if(B!=="import"){let W=B==="export"?10:60;await $.report({progress:W,message:"Exporting entities to directory"}),Y=await this.exportWithProgress(A.entityTypes,$),await $.report({progress:100,message:B==="export"?`Export complete: ${Y.exported} exported`:`Sync complete: ${X.imported} imported, ${Y.exported} exported`})}let Z=Date.now()-w;return this.logger.info("Directory sync job completed",{jobId:Q,duration:Z,imported:X.imported,exported:Y.exported}),{import:X,export:Y,duration:Z}}async importWithProgress(A,Q){try{return await this.directorySync.importEntitiesWithProgress(A,Q,10)}catch($){throw this.logger.error("Import phase failed",{error:$}),$}}async exportWithProgress(A,Q){try{return await this.directorySync.exportEntitiesWithProgress(A,Q,10)}catch($){throw this.logger.error("Export phase failed",{error:$}),$}}async waitForImportJobs(A,Q){if(A.length===0)return;this.logger.debug(`Waiting for ${A.length} import jobs to complete`);let{entityService:$}=this.context,w=300000,B=500,X=Date.now(),Y=async()=>{let W=(await Promise.all(A.map((U)=>$.getAsyncJobStatus(U)))).filter((U)=>U&&(U.status==="completed"||U.status==="failed")).length;if(W===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-X>w){this.logger.warn(`Timeout waiting for import jobs (${W}/${A.length} completed)`);return}let K=Math.round(W/A.length*100);return await Q.report({progress:50+Math.round(K*0.05),message:`Processing ${W}/${A.length} entities`}),await new Promise((U)=>setTimeout(U,B)),Y()};return Y()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}KA();class cL0 extends X8{context;directorySync;gitSync;constructor(A,Q,$,w){super(A,{schema:wZA,jobTypeName:"sync-request"});this.context=Q,this.directorySync=$,this.gitSync=w}async process(A,Q,$){await $.report({progress:5,message:"Pulling latest content from git"});let w=await this.gitSync.withLock(async()=>{return await this.gitSync.pull(),await $.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(!w)return await $.report({progress:100,message:"Sync complete: no files to import"}),{gitPulled:!0,batchQueued:!1};return await $.report({progress:100,message:`Sync queued: ${w.importOperationsCount} import jobs for ${w.totalFiles} files`}),f2$(w)}summarizeDataForLog(A){return{source:A.source,interfaceType:A.interfaceType,channelId:A.channelId}}}function f2$(A){return{gitPulled:!0,batchQueued:!0,batchId:A.batchId,importOperations:A.importOperationsCount,totalFiles:A.totalFiles}}KA();class pL0 extends X8{context;constructor(A,Q,$){super(A,{schema:yL0,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,$){let w=yL0.parse(A);this.logger.info("Processing entity deletion for removed file",{entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}),await $.report({progress:0,total:1,message:`Deleting ${w.entityType}:${w.entityId}`});try{let B=await this.context.entityService.deleteEntity({entityType:w.entityType,id:w.entityId});if(B)this.logger.info("Successfully deleted entity for removed file",{entityId:w.entityId,entityType:w.entityType});else this.logger.warn("Entity not found in database",{entityId:w.entityId,entityType:w.entityType});return await $.report({progress:1,total:1,message:`Deleted ${w.entityType}:${w.entityId}`}),{deleted:B,entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}}catch(B){throw this.logger.error("Failed to delete entity",{entityId:w.entityId,entityType:w.entityType,error:B}),B}}summarizeDataForLog(A){return{entityId:A.entityId,entityType:A.entityType,filePath:A.filePath}}}KA();C0();var x2$=H.object({});class lL0 extends X8{directorySync;constructor(A,Q){super(A,{schema:x2$,jobTypeName:"directory-cleanup"});this.directorySync=Q}async process(A,Q,$){await $.report({progress:0,message:"Removing orphaned entities"});let w=await this.directorySync.removeOrphanedEntities();return await $.report({progress:100,message:`Cleanup complete: ${w.deleted} orphans removed`}),w}}KA();JZ();_4();e8();C0();JZ();import{readFile as R2$,writeFile as v2$}from"fs/promises";var C2$=YZA,h2$=H.record(H.string(),H.unknown());class dL0 extends X8{context;fetcher;constructor(A,Q,$=rD){super(Q,{schema:C2$,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=$}async process(A,Q,$){let{filePath:w,sourceUrl:B,postTitle:X,postSlug:Y,customAlt:Z}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:w,sourceUrl:B,postSlug:Y});try{await this.reportProgress($,{progress:T6.INIT,message:`Reading file: ${w}`});let W;try{W=await R2$(w,"utf-8")}catch(I){return this.logger.error("Failed to read file",{filePath:w,error:aA(I)}),y5.failure(I)}let K;try{K=c8(W)}catch(I){return this.logger.warn("Failed to parse markdown",{filePath:w,error:aA(I)}),y5.failure(I)}let U=h2$.safeParse(K.frontmatter),G=U.success?U.data:{};if(G.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:w}),await this.reportProgress($,{progress:T6.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress($,{progress:T6.FETCH,message:"Checking for existing image"});let D=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:B}},limit:1}}),q;if(D[0])q=D[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:B,imageId:q}),await this.reportProgress($,{progress:T6.EXTRACT,message:`Reusing existing image: ${q}`});else{await this.reportProgress($,{progress:T6.PROCESS,message:`Fetching image from ${B}`});let I;try{I=await this.fetcher(B)}catch(x){return this.logger.error("Failed to fetch image",{sourceUrl:B,error:aA(x)}),y5.failure(x)}await this.reportProgress($,{progress:T6.GENERATE,message:"Creating image entity"});let{base64:P}=JM(I),j=cv(P),k=FM(P);if(!j||!k)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:B}),y5.failure(Error("Could not detect image format or dimensions"));q=`${Y}-cover`;let f=`Cover image for ${X}`,R=Z??f;await this.context.entityService.createEntity({entity:{id:q,entityType:"image",content:I,metadata:{title:f,alt:R,format:j,width:k.width,height:k.height,sourceUrl:B}}}),this.logger.debug("Created image entity",{imageId:q,sourceUrl:B}),await this.reportProgress($,{progress:T6.EXTRACT,message:`Created image: ${q}`})}await this.reportProgress($,{progress:T6.SAVE,message:"Updating file"});let J={...G};delete J.coverImageUrl,delete J.coverImageAlt,J.coverImageId=q;let F=Wv(J,K.content);try{await v2$(w,F,"utf-8")}catch(I){return this.logger.error("Failed to write file",{filePath:w,error:aA(I)}),y5.failure(I)}return await this.reportProgress($,{progress:T6.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:w,imageId:q,sourceUrl:B}),{success:!0,imageId:q}}catch(W){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:w,error:aA(W)}),y5.failure(W)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}KA();JZ();e8();import{readFile as E2$,writeFile as T2$}from"fs/promises";class iL0 extends X8{converter;constructor(A,Q,$=rD){super(Q,{schema:ZZA,jobTypeName:"inline-image-convert"});this.converter=new v$0(A.entityService,Q,$)}async process(A,Q,$){let{filePath:w,postSlug:B}=A;this.logger.debug("Starting inline image conversion job",{jobId:Q,filePath:w,postSlug:B});try{await this.reportProgress($,{progress:T6.INIT,message:`Reading file: ${w}`});let X;try{X=await E2$(w,"utf-8")}catch(W){let K=aA(W);return this.logger.error("Failed to read file",{filePath:w,error:K}),{success:!1,error:K}}await this.reportProgress($,{progress:T6.FETCH,message:"Detecting inline images"});let Y=this.converter.detectInlineImages(X,B);if(Y.length===0)return this.logger.debug("No inline images to convert",{filePath:w}),await this.reportProgress($,{progress:T6.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:w,count:Y.length}),await this.reportProgress($,{progress:T6.PROCESS,message:`Converting ${Y.length} images`});let Z=await this.converter.convert(X,B);if(!Z.converted)return this.logger.debug("No images were converted",{filePath:w}),await this.reportProgress($,{progress:T6.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress($,{progress:T6.SAVE,message:"Writing updated file"});try{await T2$(w,Z.content,"utf-8")}catch(W){let K=aA(W);return this.logger.error("Failed to write file",{filePath:w,error:K}),{success:!1,error:K}}return await this.reportProgress($,{progress:T6.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:w,convertedCount:Z.convertedCount}),{success:!0,convertedCount:Z.convertedCount}}catch(X){let Y=aA(X);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:w,error:Y}),{success:!1,error:Y}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function xV2(A,Q,$){let w=(B)=>$.child(B);A.jobs.registerHandler("directory-sync",new uL0(w("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new SL0(w("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new mL0(w("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new pL0(w("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new lL0(w("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new dL0(A,w("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new iL0(A,w("InlineImageConversionJobHandler"))),$.debug("Registered async job handlers")}KA();C0();import{unlink as y2$,access as g2$}from"fs/promises";var S2$=H.record(H.string(),H.unknown());function RV2(A,Q,$,w){let{subscribe:B}=A.messaging,{entityService:X}=A;B("entity:created",async(Y)=>{let{entity:Z}=Y.payload;try{await Q.fileOps.writeEntity(Z),$.debug("Auto-exported created entity",{id:Z.id,entityType:Z.entityType})}catch(W){$.error("Auto-export FAILED for created entity",{id:Z.id,entityType:Z.entityType,error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0})}return{success:!0}}),B("entity:updated",async(Y)=>{let{entityType:Z,entityId:W}=Y.payload;try{let K=await X.getEntity({entityType:Z,id:W});if(!K)return $.debug("Entity not found in DB, skipping export",{entityType:Z,entityId:W}),{success:!1};await Q.fileOps.writeEntity(K),$.debug("Auto-exported updated entity",{id:K.id,entityType:K.entityType})}catch(K){$.error("Auto-export FAILED for updated entity",{entityType:Z,entityId:W,error:K instanceof Error?K.message:String(K),stack:K instanceof Error?K.stack:void 0})}return{success:!0}}),B("entity:deleted",async(Y)=>{let{entityId:Z,entityType:W}=Y.payload,K=Q.fileOps.getFilePath(Z,W);if(await g2$(K).then(()=>!0,()=>!1))await y2$(K),$.debug("Auto-deleted entity file",{id:Z,entityType:W,path:K});return{success:!0}}),$.debug("Setup auto-sync for entity events",{entityTypes:w})}function vV2(A,Q,$){Q.setJobQueueCallback(async(w)=>{let B=[{type:w.type,data:S2$.parse(w.data)}];return A.jobs.enqueueBatch(B,{priority:5,source:"directory-sync-watcher",rootJobId:nY(),metadata:{operationType:"file_operations",operationTarget:$,pluginId:"directory-sync"}})})}KA();import{readdir as EV2,mkdir as u2$,copyFile as c2$}from"fs/promises";import{join as hV2,resolve as HZA}from"path";import{join as m2$}from"path";async function CV2(A){if(!await s9(m2$(A,".git")))return!1;try{return await h3(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function p2$(A,Q){if(!await s9(A))return!0;if((await EV2(A)).filter((B)=>!B.startsWith(".")&&!B.startsWith("_")).length>0)return!1;if(await CV2(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function TV2(A,Q){let $=await EV2(A,{withFileTypes:!0});for(let w of $){let B=hV2(A,w.name),X=hV2(Q,w.name);if(w.isDirectory()){if(!await s9(X))await u2$(X,{recursive:!0});await TV2(B,X)}else await c2$(B,X)}}async function yV2(A,Q,$){let w=HZA(process.cwd(),A);$=$?HZA($):HZA(process.cwd(),"seed-content");let B=await p2$(w,Q);if(B&&await s9($))Q.debug("Copying seed content to brain-data directory"),await TV2($,w),Q.debug("Seed content copied successfully");else if(B)Q.debug("No seed content directory found, starting with empty brain-data");else Q.debug("brain-data directory not empty, skipping seed content")}function gV2(A,Q,$,w,B){let X=!1,Y=async()=>{if(X)return;X=!0;let Z=Q();if($.seedContent){let W=$.syncPath??A.dataDir;await yV2(W,w,$.seedContentPath)}try{if(B){w.debug("Git enabled \u2014 pulling before import");let K=await B.pull();if(K.files.length>0)w.info("Pulled changes from remote",{filesChanged:K.files.length})}w.debug("Starting initial sync");let W=await Z.sync();w.debug("Initial sync completed",{imported:W.import.imported,failed:W.import.failed,duration:W.duration}),await A.messaging.send({type:Dv.initialSyncCompleted,payload:{success:!0},...{broadcast:!0}})}catch(W){w.error("Initial sync failed",W),await A.messaging.send({type:Dv.initialSyncCompleted,payload:{success:!1,error:aA(W)},...{broadcast:!0}})}};A.messaging.subscribe(Dv.pluginsRegistered,async()=>{return w.debug("Plugins registered, starting initial sync"),await Y(),{success:!0}})}class WZA{fn;delayMs;timeout;pending=!1;constructor(A,Q){this.fn=A,this.delayMs=Q}trigger(){if(!this.timeout){this.fn(),this.timeout=setTimeout(()=>{if(this.timeout=void 0,this.pending)this.pending=!1,this.fn()},this.delayMs);return}this.pending=!0,clearTimeout(this.timeout),this.timeout=setTimeout(()=>{if(this.timeout=void 0,this.pending)this.pending=!1,this.fn()},this.delayMs)}dispose(){if(this.timeout)clearTimeout(this.timeout),this.timeout=void 0;this.pending=!1}}class KZA{fn;delayMs;timeout;constructor(A,Q){this.fn=A,this.delayMs=Q}trigger(){if(this.timeout)clearTimeout(this.timeout);this.timeout=setTimeout(()=>{this.timeout=void 0,this.fn()},this.delayMs)}dispose(){if(this.timeout)clearTimeout(this.timeout),this.timeout=void 0}}function SV2(A,Q,$,w){let B=new KZA(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(Z){w.error("Git auto-commit failed",{error:Z})}})},$),X=["entity:created","entity:updated","entity:deleted"],Y=[];for(let Z of X){let W=A.subscribe(Z,async()=>{return B.trigger(),{success:!0}});Y.push(W)}return()=>{B.dispose();for(let Z of Y)Z()}}function mV2(A,Q,$,w,B){if(w<=0)return()=>{};let X=w*60*1000,Y=!1,Z=async()=>{if(Y)return;Y=!0;try{let{files:K,result:U}=await A.withLock(async()=>{let G=await A.pull();if(G.files.length===0)return{files:[],result:null};let D=await Q.queueSyncBatch($,"periodic-sync");return{files:G.files,result:D}});if(K.length>0)B.info("Periodic sync: pulled changes",{filesChanged:K.length});if(U)B.debug("Periodic sync: queued imports",{importOperations:U.importOperationsCount,totalFiles:U.totalFiles})}catch(K){B.error("Periodic git sync failed",{error:K})}finally{Y=!1}},W=setInterval(()=>{Z()},X);return B.info("Started periodic git sync",{intervalMinutes:w}),()=>{clearInterval(W)}}import{spawnSync as cV2}from"child_process";import{cpSync as l2$,existsSync as uV2,mkdirSync as d2$,mkdtempSync as i2$,rmSync as n2$}from"fs";import{tmpdir as r2$}from"os";import{fileURLToPath as o2$}from"url";import{join as s2$,resolve as a2$}from"path";function GO(A,Q){let $=cV2("git",Q,{cwd:A,stdio:"pipe"});if($.status!==0){let w=$.stderr.toString().trim(),B=$.stdout.toString().trim();throw Error(w||B||`git ${Q.join(" ")} failed`)}}function t2$(A){return A.startsWith("file://")}function e2$(A){return o2$(A)}function AQ$(A,Q){return cV2("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function pV2(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!t2$(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",$=e2$(A.gitUrl),w=a2$(A.seedContentPath);if(!uV2(w))throw Error(`Seed content path not found: ${w}`);if(!uV2($))A.logger.debug("Creating local bare content remote",{remotePath:$,branch:Q}),d2$($,{recursive:!0}),GO(process.cwd(),["init","--bare",`--initial-branch=${Q}`,$]);if(AQ$($,Q)){A.logger.debug("Content remote already initialized",{remotePath:$,branch:Q});return}A.logger.debug("Seeding local content remote",{remotePath:$,seedPath:w,branch:Q});let B=i2$(s2$(r2$(),"directory-sync-seed-"));try{GO(B,["init",`--initial-branch=${Q}`]),GO(B,["config","user.name",A.authorName??"Brain"]),GO(B,["config","user.email",A.authorEmail??"brain@localhost"]),l2$(w,B,{recursive:!0,filter:(X)=>!X.split("/").includes(".git")}),GO(B,["add","."]),GO(B,["commit","-m","seed content remote"]),GO(B,["remote","add","origin",A.gitUrl]),GO(B,["push","-u","origin",Q])}finally{n2$(B,{recursive:!0,force:!0})}}function lV2(A,Q,$,w,B,X){let{subscribe:Y}=A.messaging;Y("entity:export:request",async(Z)=>{try{return{success:!0,data:await Q().exportEntities(Z.payload.entityTypes)}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Export failed"}}}),Y("entity:import:request",async(Z)=>{try{let W=Q(),K=Z.payload.paths,U=await W.importEntities(K);if(K&&K.length>0)await W.removeOrphanedEntities();return{success:!0,data:U}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Import failed"}}}),Y("sync:status:request",async()=>{try{let W=await Q().getStatus();return{success:!0,data:{syncPath:W.syncPath,isInitialized:W.exists,watchEnabled:W.watching,lastSync:W.lastSync?.toISOString()??null,totalFiles:W.stats.totalFiles,byEntityType:W.stats.byEntityType,git:await QQ$(X?.(),w)}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Status check failed"}}}),Y("sync:configure:request",async(Z)=>{try{return await $({syncPath:Z.payload.syncPath}),{success:!0,data:{syncPath:Z.payload.syncPath,configured:!0}}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Configuration failed"}}}),Y("git-sync:get-repo-info",async()=>{if(!B?.repo)return{success:!1,error:"Git not configured"};return{success:!0,data:{repo:B.repo,branch:B.branch??"main"}}}),w.debug("Registered message handlers")}async function QQ$(A,Q){if(!A)return null;try{let $=await A.getStatus();return{branch:$.branch,hasChanges:$.hasChanges,ahead:$.ahead,behind:$.behind,lastCommit:$.lastCommit??null,remote:$.remote??null}}catch($){return Q.debug("Git status unavailable for sync:status:request",{error:$}),null}}KA();C0();KA();C0();function dV2(A,Q){return p8(A,"history","Get version history for an entity from git. Without sha: returns commit list. With sha: returns entity content at that version.",H.object({entityType:H.string().describe("Entity type (e.g. post, note, link)"),id:H.string().describe("Entity ID"),sha:H.string().optional().describe("Commit SHA to retrieve content at. Omit to list commit history."),limit:H.number().int().positive().optional().default(10).describe("Max commits to return (list mode only)")}),async($)=>{let w=`${$.entityType}/${$.id}.md`;try{if($.sha){let X=await Q.show($.sha,w);return f7({sha:$.sha,entityType:$.entityType,id:$.id,content:X},`Content at ${$.sha.slice(0,7)}`)}let B=await Q.log(w,$.limit);if(B.length===0)return f7({commits:[]},`No history found for ${$.entityType}/${$.id}`);return f7({commits:B,entityType:$.entityType,id:$.id},`${B.length} version${B.length===1?"":"s"} found`)}catch(B){return YY(B instanceof Error?B.message:"History lookup failed")}},{visibility:"anchor",sideEffects:"none"})}function iV2(A,Q,$,w){let B=[p8($,"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.",H.object({}),async(X,Y)=>{try{let Z=Y.channelId?`${Y.interfaceType}:${Y.channelId}`:`plugin:${$}`,W={interfaceType:Y.interfaceType,channelId:Y.channelId};if(w){let U=await Q.jobs.enqueue({type:"sync-request",data:{source:Z,interfaceType:W.interfaceType,channelId:W.channelId},toolContext:Y});return f7({jobId:U,status:"queued",gitPulled:!0},"Sync queued: git pull and filesystem scan will run in the background")}let K=await A.queueSyncBatch(Q,Z,W);if(!K)return f7({gitPulled:!1},"No files to sync");return f7({batchId:K.batchId,importOperations:K.importOperationsCount,totalFiles:K.totalFiles,gitPulled:!1},`Sync started: ${K.importOperationsCount} import jobs queued for ${K.totalFiles} files`)}catch(Z){return YY(Z instanceof Error?Z.message:"Sync failed")}},{visibility:"anchor",sideEffects:"external",cli:{name:"sync"}}),p8($,"status","Read directory and git sync status: last sync, watcher state, and pending git changes. Use this for every status follow-up after directory-sync_sync, even when that call returned a jobId; a sync jobId is not a system_job_status batchId.",H.object({}),async()=>{try{let X=await A.getStatus(),Y={syncPath:X.syncPath,lastSync:X.lastSync?.toISOString(),watching:X.watching};if(w){let Z=await w.getStatus();Y.git={isRepo:Z.isRepo,branch:Z.branch,hasChanges:Z.hasChanges,ahead:Z.ahead,behind:Z.behind,remote:Z.remote}}return f7(Y)}catch(X){return YY(X instanceof Error?X.message:"Status check failed")}},{visibility:"anchor",sideEffects:"none"})];if(w)B.push(dV2($,w));return B}var nV2={name:"@brains/directory-sync",version:"0.2.0-alpha.183",description:"Directory-based entity synchronization plugin for Brains",dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chokidar:"^5.0.0","simple-git":"^3.36.0"},devDependencies:{"@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":{types:"./src/index.ts",import:"./src/index.ts"},"./env-schema":"./src/env-schema.ts"},main:"./src/index.ts",peerDependencies:{},private:!0,scripts:{clean:"rm -rf .turbo",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};class UZA extends p6{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",nV2,A,d$0)}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:$}=A;A.templates.register({status:{name:"status",description:"Directory synchronization status",schema:i$0,basePrompt:"",formatter:new gL0,requiredPermission:"anchor"}});let w=this.config.syncPath??A.dataDir;this.directorySync=new C$0({syncPath:w,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,entityService:$,logger:Q});try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:w})}catch(Y){throw this.logger.error("Failed to initialize directory",Y),Y}await this.registerJobHandlers(A);let B=this.requireDirectorySync();if(RV2(A,B,this.logger,this.config.entityTypes),this.config.autoSync)vV2(A,B,this.config.syncPath??A.dataDir);let X=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!X)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(X&&this.config.git){await pV2({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 Y=this.config.syncPath??A.dataDir;if(this.gitSync=new QZA({logger:this.logger.child("GitSync"),dataDir:Y,repo:this.config.git.repo,gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,authToken:this.config.git.authToken,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail}),await this.gitSync.initialize(),this.logger.info("Git integration enabled",{repo:this.config.git.repo}),A.jobs.registerHandler("sync-request",new cL0(this.logger.child("DirectorySyncRequestJobHandler"),A,this.requireDirectorySync(),this.gitSync)),this.gitCleanups.push(SV2(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(mV2(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)gV2(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);lV2(A,()=>this.requireDirectorySync(),(Y)=>this.configure(Y),this.logger,this.config.git,()=>this.gitSync)}async getTools(){let A=this.requireDirectorySync();return iV2(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 C$0({...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){xV2(A,this.requireDirectorySync(),this.logger)}}function wE(A={}){return new UZA(A)}C0();var nL0="email:send",rV2=H.strictObject({to:H.string().email(),subject:H.string().min(1),text:H.string().min(1),html:H.string().min(1).optional(),sensitivity:H.enum(["normal","secret"]).default("normal")});KA();C0();var oV2={name:"@brains/email-resend",version:"0.2.0-alpha.183",description:"Generic email delivery adapter for Resend",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var BQ$=H.object({apiKey:H.string().min(1).optional(),from:H.string().min(1).optional()}),XQ$=H.looseObject({id:H.string().optional()});class sV2 extends p6{fetchImpl;constructor(A={},Q={}){super("email-resend",oV2,A,BQ$);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(nL0,async($)=>{let w=rV2.parse($.payload);try{return{success:!0,data:await this.sendWithResend(w)}}catch(B){if(w.sensitivity==="secret")Q.warn("Email delivery failed for a secret message");else Q.warn("Email delivery failed",{to:w.to,subject:w.subject,error:B instanceof Error?B.message:String(B)});return{success:!1,error:"Email delivery failed"}}})}async sendWithResend(A){let Q=this.config.apiKey,$=this.config.from;if(!Q||!$)return{status:"failed"};let w=await this.fetchImpl("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({from:$,to:A.to,subject:A.subject,text:A.text,...A.html?{html:A.html}:{}})});if(!w.ok)throw Error("Resend email request failed");let B=XQ$.parse(await w.json());return B.id?{status:"sent",id:B.id}:{status:"sent"}}}function rL0(A={}){return new sV2(A)}KA();import{render as Tv2}from"preact-render-to-string";import{h as SE}from"preact";function aV2(A){var Q,$,w="";if(typeof A=="string"||typeof A=="number")w+=A;else if(typeof A=="object")if(Array.isArray(A)){var B=A.length;for(Q=0;Q<B;Q++)A[Q]&&($=aV2(A[Q]))&&(w&&(w+=" "),w+=$)}else for($ in A)A[$]&&(w&&(w+=" "),w+=$);return w}function Cd(){for(var A,Q,$=0,w="",B=arguments.length;$<B;$++)(A=arguments[$])&&(Q=aV2(A))&&(w&&(w+=" "),w+=Q);return w}var YQ$=(A,Q)=>{let $=Array(A.length+Q.length);for(let w=0;w<A.length;w++)$[w]=A[w];for(let w=0;w<Q.length;w++)$[A.length+w]=Q[w];return $},ZQ$=(A,Q)=>({classGroupId:A,validator:Q}),XJ2=(A=new Map,Q=null,$)=>({nextPart:A,validators:Q,classGroupId:$});var tV2=[];var HQ$=(A)=>{let Q=KQ$(A),{conflictingClassGroups:$,conflictingClassGroupModifiers:w}=A;return{getClassGroupId:(Y)=>{if(Y.startsWith("[")&&Y.endsWith("]"))return WQ$(Y);let Z=Y.split("-"),W=Z[0]===""&&Z.length>1?1:0;return YJ2(Z,W,Q)},getConflictingClassGroupIds:(Y,Z)=>{if(Z){let W=w[Y],K=$[Y];if(W){if(K)return YQ$(K,W);return W}return K||tV2}return $[Y]||tV2}}},YJ2=(A,Q,$)=>{if(A.length-Q===0)return $.classGroupId;let B=A[Q],X=$.nextPart.get(B);if(X){let K=YJ2(A,Q+1,X);if(K)return K}let Y=$.validators;if(Y===null)return;let Z=Q===0?A.join("-"):A.slice(Q).join("-"),W=Y.length;for(let K=0;K<W;K++){let U=Y[K];if(U.validator(Z))return U.classGroupId}return},WQ$=(A)=>A.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let Q=A.slice(1,-1),$=Q.indexOf(":"),w=Q.slice(0,$);return w?"arbitrary.."+w:void 0})(),KQ$=(A)=>{let{theme:Q,classGroups:$}=A;return UQ$($,Q)},UQ$=(A,Q)=>{let $=XJ2();for(let w in A){let B=A[w];qZA(B,$,w,Q)}return $},qZA=(A,Q,$,w)=>{let B=A.length;for(let X=0;X<B;X++){let Y=A[X];GQ$(Y,Q,$,w)}},GQ$=(A,Q,$,w)=>{if(typeof A==="string"){DQ$(A,Q,$);return}if(typeof A==="function"){qQ$(A,Q,$,w);return}zQ$(A,Q,$,w)},DQ$=(A,Q,$)=>{let w=A===""?Q:ZJ2(Q,A);w.classGroupId=$},qQ$=(A,Q,$,w)=>{if(VQ$(A)){qZA(A(w),Q,$,w);return}if(Q.validators===null)Q.validators=[];Q.validators.push(ZQ$($,A))},zQ$=(A,Q,$,w)=>{let B=Object.entries(A),X=B.length;for(let Y=0;Y<X;Y++){let[Z,W]=B[Y];qZA(W,ZJ2(Q,Z),$,w)}},ZJ2=(A,Q)=>{let $=A,w=Q.split("-"),B=w.length;for(let X=0;X<B;X++){let Y=w[X],Z=$.nextPart.get(Y);if(!Z)Z=XJ2(),$.nextPart.set(Y,Z);$=Z}return $},VQ$=(A)=>("isThemeGetter"in A)&&A.isThemeGetter===!0,JQ$=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,$=Object.create(null),w=Object.create(null),B=(X,Y)=>{if($[X]=Y,Q++,Q>A)Q=0,w=$,$=Object.create(null)};return{get(X){let Y=$[X];if(Y!==void 0)return Y;if((Y=w[X])!==void 0)return B(X,Y),Y},set(X,Y){if(X in $)$[X]=Y;else B(X,Y)}}};var FQ$=[],eV2=(A,Q,$,w,B)=>({modifiers:A,hasImportantModifier:Q,baseClassName:$,maybePostfixModifierPosition:w,isExternal:B}),IQ$=(A)=>{let{prefix:Q,experimentalParseClassName:$}=A,w=(B)=>{let X=[],Y=0,Z=0,W=0,K,U=B.length;for(let F=0;F<U;F++){let I=B[F];if(Y===0&&Z===0){if(I===":"){X.push(B.slice(W,F)),W=F+1;continue}if(I==="/"){K=F;continue}}if(I==="[")Y++;else if(I==="]")Y--;else if(I==="(")Z++;else if(I===")")Z--}let G=X.length===0?B:B.slice(W),D=G,q=!1;if(G.endsWith("!"))D=G.slice(0,-1),q=!0;else if(G.startsWith("!"))D=G.slice(1),q=!0;let J=K&&K>W?K-W:void 0;return eV2(X,q,D,J)};if(Q){let B=Q+":",X=w;w=(Y)=>Y.startsWith(B)?X(Y.slice(B.length)):eV2(FQ$,!1,Y,void 0,!0)}if($){let B=w;w=(X)=>$({className:X,parseClassName:B})}return w},LQ$=(A)=>{let Q=new Map;return A.orderSensitiveModifiers.forEach(($,w)=>{Q.set($,1e6+w)}),($)=>{let w=[],B=[];for(let X=0;X<$.length;X++){let Y=$[X],Z=Y[0]==="[",W=Q.has(Y);if(Z||W){if(B.length>0)B.sort(),w.push(...B),B=[];w.push(Y)}else B.push(Y)}if(B.length>0)B.sort(),w.push(...B);return w}},NQ$=(A)=>({cache:JQ$(A.cacheSize),parseClassName:IQ$(A),sortModifiers:LQ$(A),postfixLookupClassGroupIds:_Q$(A),...HQ$(A)}),_Q$=(A)=>{let Q=Object.create(null),$=A.postfixLookupClassGroups;if($)for(let w=0;w<$.length;w++)Q[$[w]]=!0;return Q},PQ$=/\s+/,kQ$=(A,Q)=>{let{parseClassName:$,getClassGroupId:w,getConflictingClassGroupIds:B,sortModifiers:X,postfixLookupClassGroupIds:Y}=Q,Z=[],W=A.trim().split(PQ$),K="";for(let U=W.length-1;U>=0;U-=1){let G=W[U],{isExternal:D,modifiers:q,hasImportantModifier:J,baseClassName:F,maybePostfixModifierPosition:I}=$(G);if(D){K=G+(K.length>0?" "+K:K);continue}let P=!!I,j;if(P){let O=F.substring(0,I);j=w(O);let g=j&&Y[j]?w(F):void 0;if(g&&g!==j)j=g,P=!1}else j=w(F);if(!j){if(!P){K=G+(K.length>0?" "+K:K);continue}if(j=w(F),!j){K=G+(K.length>0?" "+K:K);continue}P=!1}let k=q.length===0?"":q.length===1?q[0]:X(q).join(":"),f=J?k+"!":k,R=f+j;if(Z.indexOf(R)>-1)continue;Z.push(R);let x=B(j,P);for(let O=0;O<x.length;++O){let g=x[O];Z.push(f+g)}K=G+(K.length>0?" "+K:K)}return K},jQ$=(...A)=>{let Q=0,$,w,B="";while(Q<A.length)if($=A[Q++]){if(w=HJ2($))B&&(B+=" "),B+=w}return B},HJ2=(A)=>{if(typeof A==="string")return A;let Q,$="";for(let w=0;w<A.length;w++)if(A[w]){if(Q=HJ2(A[w]))$&&($+=" "),$+=Q}return $},AJ2=(A,...Q)=>{let $,w,B,X,Y=(W)=>{let K=Q.reduce((U,G)=>G(U),A());return $=NQ$(K),w=$.cache.get,B=$.cache.set,X=Z,Z(W)},Z=(W)=>{let K=w(W);if(K)return K;let U=kQ$(W,$);return B(W,U),U};return X=Y,(...W)=>X(jQ$(...W))},MQ$=[],S4=(A)=>{let Q=($)=>$[A]||MQ$;return Q.isThemeGetter=!0,Q},WJ2=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,KJ2=/^\((?:(\w[\w-]*):)?(.+)\)$/i,bQ$=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,OQ$=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,fQ$=/\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$/,xQ$=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,RQ$=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,vQ$=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,DO=(A)=>bQ$.test(A),T$=(A)=>!!A&&!Number.isNaN(Number(A)),vF=(A)=>!!A&&Number.isInteger(Number(A)),GZA=(A)=>A.endsWith("%")&&T$(A.slice(0,-1)),a_=(A)=>OQ$.test(A),UJ2=()=>!0,CQ$=(A)=>fQ$.test(A)&&!xQ$.test(A),zZA=()=>!1,hQ$=(A)=>RQ$.test(A),EQ$=(A)=>vQ$.test(A),TQ$=(A)=>!n2(A)&&!t2(A),yQ$=(A)=>A.startsWith("@container")&&(A[10]==="/"&&A[11]!==void 0||A[11]==="s"&&A[16]!==void 0&&A.startsWith("-size/",10)||A[11]==="n"&&A[18]!==void 0&&A.startsWith("-normal/",10)),gQ$=(A)=>qO(A,qJ2,zZA),n2=(A)=>WJ2.test(A),BE=(A)=>qO(A,zJ2,CQ$),QJ2=(A)=>qO(A,iQ$,T$),SQ$=(A)=>qO(A,JJ2,UJ2),mQ$=(A)=>qO(A,VJ2,zZA),$J2=(A)=>qO(A,GJ2,zZA),uQ$=(A)=>qO(A,DJ2,EQ$),oL0=(A)=>qO(A,FJ2,hQ$),t2=(A)=>KJ2.test(A),n$0=(A)=>XE(A,zJ2),cQ$=(A)=>XE(A,VJ2),wJ2=(A)=>XE(A,GJ2),pQ$=(A)=>XE(A,qJ2),lQ$=(A)=>XE(A,DJ2),sL0=(A)=>XE(A,FJ2,!0),dQ$=(A)=>XE(A,JJ2,!0),qO=(A,Q,$)=>{let w=WJ2.exec(A);if(w){if(w[1])return Q(w[1]);return $(w[2])}return!1},XE=(A,Q,$=!1)=>{let w=KJ2.exec(A);if(w){if(w[1])return Q(w[1]);return $}return!1},GJ2=(A)=>A==="position"||A==="percentage",DJ2=(A)=>A==="image"||A==="url",qJ2=(A)=>A==="length"||A==="size"||A==="bg-size",zJ2=(A)=>A==="length",iQ$=(A)=>A==="number",VJ2=(A)=>A==="family-name",JJ2=(A)=>A==="number"||A==="weight",FJ2=(A)=>A==="shadow";var BJ2=()=>{let A=S4("color"),Q=S4("font"),$=S4("text"),w=S4("font-weight"),B=S4("tracking"),X=S4("leading"),Y=S4("breakpoint"),Z=S4("container"),W=S4("spacing"),K=S4("radius"),U=S4("shadow"),G=S4("inset-shadow"),D=S4("text-shadow"),q=S4("drop-shadow"),J=S4("blur"),F=S4("perspective"),I=S4("aspect"),P=S4("ease"),j=S4("animate"),k=()=>["auto","avoid","all","avoid-page","page","left","right","column"],f=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...f(),t2,n2],x=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto","contain","none"],g=()=>[t2,n2,W],u=()=>[DO,"full","auto",...g()],n=()=>[vF,"none","subgrid",t2,n2],t=()=>["auto",{span:["full",vF,t2,n2]},vF,t2,n2],B0=()=>[vF,"auto",t2,n2],l=()=>["auto","min","max","fr",t2,n2],b=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],T=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...g()],o=()=>[DO,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...g()],a=()=>[DO,"screen","full","dvw","lvw","svw","min","max","fit",...g()],q0=()=>[DO,"screen","full","lh","dvh","lvh","svh","min","max","fit",...g()],S=()=>[A,t2,n2],H0=()=>[...f(),wJ2,$J2,{position:[t2,n2]}],N0=()=>["no-repeat",{repeat:["","x","y","space","round"]}],i=()=>["auto","cover","contain",pQ$,gQ$,{size:[t2,n2]}],u0=()=>[GZA,n$0,BE],i0=()=>["","none","full",K,t2,n2],k0=()=>["",T$,n$0,BE],j0=()=>["solid","dashed","dotted","double"],h0=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],m0=()=>[T$,GZA,wJ2,$J2],b0=()=>["","none",J,t2,n2],O0=()=>["none",T$,t2,n2],g0=()=>["none",T$,t2,n2],S0=()=>[T$,t2,n2],r0=()=>[DO,"full",...g()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[a_],breakpoint:[a_],color:[UJ2],container:[a_],"drop-shadow":[a_],ease:["in","out","in-out"],font:[TQ$],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[a_],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[a_],shadow:[a_],spacing:["px",T$],text:[a_],"text-shadow":[a_],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",DO,n2,t2,I]}],container:["container"],"container-type":[{"@container":["","normal","size",t2,n2]}],"container-named":[yQ$],columns:[{columns:[T$,n2,t2,Z]}],"break-after":[{"break-after":k()}],"break-before":[{"break-before":k()}],"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"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:R()}],overflow:[{overflow:x()}],"overflow-x":[{"overflow-x":x()}],"overflow-y":[{"overflow-y":x()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:u()}],"inset-x":[{"inset-x":u()}],"inset-y":[{"inset-y":u()}],start:[{"inset-s":u(),start:u()}],end:[{"inset-e":u(),end:u()}],"inset-bs":[{"inset-bs":u()}],"inset-be":[{"inset-be":u()}],top:[{top:u()}],right:[{right:u()}],bottom:[{bottom:u()}],left:[{left:u()}],visibility:["visible","invisible","collapse"],z:[{z:[vF,"auto",t2,n2]}],basis:[{basis:[DO,"full","auto",Z,...g()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[T$,DO,"auto","initial","none",n2]}],grow:[{grow:["",T$,t2,n2]}],shrink:[{shrink:["",T$,t2,n2]}],order:[{order:[vF,"first","last","none",t2,n2]}],"grid-cols":[{"grid-cols":n()}],"col-start-end":[{col:t()}],"col-start":[{"col-start":B0()}],"col-end":[{"col-end":B0()}],"grid-rows":[{"grid-rows":n()}],"row-start-end":[{row:t()}],"row-start":[{"row-start":B0()}],"row-end":[{"row-end":B0()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":l()}],"auto-rows":[{"auto-rows":l()}],gap:[{gap:g()}],"gap-x":[{"gap-x":g()}],"gap-y":[{"gap-y":g()}],"justify-content":[{justify:[...b(),"normal"]}],"justify-items":[{"justify-items":[...T(),"normal"]}],"justify-self":[{"justify-self":["auto",...T()]}],"align-content":[{content:["normal",...b()]}],"align-items":[{items:[...T(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...T(),{baseline:["","last"]}]}],"place-content":[{"place-content":b()}],"place-items":[{"place-items":[...T(),"baseline"]}],"place-self":[{"place-self":["auto",...T()]}],p:[{p:g()}],px:[{px:g()}],py:[{py:g()}],ps:[{ps:g()}],pe:[{pe:g()}],pbs:[{pbs:g()}],pbe:[{pbe:g()}],pt:[{pt:g()}],pr:[{pr:g()}],pb:[{pb:g()}],pl:[{pl:g()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":g()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":g()}],"space-y-reverse":["space-y-reverse"],size:[{size:o()}],"inline-size":[{inline:["auto",...a()]}],"min-inline-size":[{"min-inline":["auto",...a()]}],"max-inline-size":[{"max-inline":["none",...a()]}],"block-size":[{block:["auto",...q0()]}],"min-block-size":[{"min-block":["auto",...q0()]}],"max-block-size":[{"max-block":["none",...q0()]}],w:[{w:[Z,"screen",...o()]}],"min-w":[{"min-w":[Z,"screen","none",...o()]}],"max-w":[{"max-w":[Z,"screen","none","prose",{screen:[Y]},...o()]}],h:[{h:["screen","lh",...o()]}],"min-h":[{"min-h":["screen","lh","none",...o()]}],"max-h":[{"max-h":["screen","lh",...o()]}],"font-size":[{text:["base",$,n$0,BE]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[w,dQ$,SQ$]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",GZA,n2]}],"font-family":[{font:[cQ$,mQ$,Q]}],"font-features":[{"font-features":[n2]}],"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:[B,t2,n2]}],"line-clamp":[{"line-clamp":[T$,"none",t2,QJ2]}],leading:[{leading:[X,...g()]}],"list-image":[{"list-image":["none",t2,n2]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",t2,n2]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:S()}],"text-color":[{text:S()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...j0(),"wavy"]}],"text-decoration-thickness":[{decoration:[T$,"from-font","auto",t2,BE]}],"text-decoration-color":[{decoration:S()}],"underline-offset":[{"underline-offset":[T$,"auto",t2,n2]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:g()}],"tab-size":[{tab:[vF,t2,n2]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",t2,n2]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",t2,n2]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:H0()}],"bg-repeat":[{bg:N0()}],"bg-size":[{bg:i()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},vF,t2,n2],radial:["",t2,n2],conic:[vF,t2,n2]},lQ$,uQ$]}],"bg-color":[{bg:S()}],"gradient-from-pos":[{from:u0()}],"gradient-via-pos":[{via:u0()}],"gradient-to-pos":[{to:u0()}],"gradient-from":[{from:S()}],"gradient-via":[{via:S()}],"gradient-to":[{to:S()}],rounded:[{rounded:i0()}],"rounded-s":[{"rounded-s":i0()}],"rounded-e":[{"rounded-e":i0()}],"rounded-t":[{"rounded-t":i0()}],"rounded-r":[{"rounded-r":i0()}],"rounded-b":[{"rounded-b":i0()}],"rounded-l":[{"rounded-l":i0()}],"rounded-ss":[{"rounded-ss":i0()}],"rounded-se":[{"rounded-se":i0()}],"rounded-ee":[{"rounded-ee":i0()}],"rounded-es":[{"rounded-es":i0()}],"rounded-tl":[{"rounded-tl":i0()}],"rounded-tr":[{"rounded-tr":i0()}],"rounded-br":[{"rounded-br":i0()}],"rounded-bl":[{"rounded-bl":i0()}],"border-w":[{border:k0()}],"border-w-x":[{"border-x":k0()}],"border-w-y":[{"border-y":k0()}],"border-w-s":[{"border-s":k0()}],"border-w-e":[{"border-e":k0()}],"border-w-bs":[{"border-bs":k0()}],"border-w-be":[{"border-be":k0()}],"border-w-t":[{"border-t":k0()}],"border-w-r":[{"border-r":k0()}],"border-w-b":[{"border-b":k0()}],"border-w-l":[{"border-l":k0()}],"divide-x":[{"divide-x":k0()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":k0()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...j0(),"hidden","none"]}],"divide-style":[{divide:[...j0(),"hidden","none"]}],"border-color":[{border:S()}],"border-color-x":[{"border-x":S()}],"border-color-y":[{"border-y":S()}],"border-color-s":[{"border-s":S()}],"border-color-e":[{"border-e":S()}],"border-color-bs":[{"border-bs":S()}],"border-color-be":[{"border-be":S()}],"border-color-t":[{"border-t":S()}],"border-color-r":[{"border-r":S()}],"border-color-b":[{"border-b":S()}],"border-color-l":[{"border-l":S()}],"divide-color":[{divide:S()}],"outline-style":[{outline:[...j0(),"none","hidden"]}],"outline-offset":[{"outline-offset":[T$,t2,n2]}],"outline-w":[{outline:["",T$,n$0,BE]}],"outline-color":[{outline:S()}],shadow:[{shadow:["","none",U,sL0,oL0]}],"shadow-color":[{shadow:S()}],"inset-shadow":[{"inset-shadow":["none",G,sL0,oL0]}],"inset-shadow-color":[{"inset-shadow":S()}],"ring-w":[{ring:k0()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:S()}],"ring-offset-w":[{"ring-offset":[T$,BE]}],"ring-offset-color":[{"ring-offset":S()}],"inset-ring-w":[{"inset-ring":k0()}],"inset-ring-color":[{"inset-ring":S()}],"text-shadow":[{"text-shadow":["none",D,sL0,oL0]}],"text-shadow-color":[{"text-shadow":S()}],opacity:[{opacity:[T$,t2,n2]}],"mix-blend":[{"mix-blend":[...h0(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":h0()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[T$]}],"mask-image-linear-from-pos":[{"mask-linear-from":m0()}],"mask-image-linear-to-pos":[{"mask-linear-to":m0()}],"mask-image-linear-from-color":[{"mask-linear-from":S()}],"mask-image-linear-to-color":[{"mask-linear-to":S()}],"mask-image-t-from-pos":[{"mask-t-from":m0()}],"mask-image-t-to-pos":[{"mask-t-to":m0()}],"mask-image-t-from-color":[{"mask-t-from":S()}],"mask-image-t-to-color":[{"mask-t-to":S()}],"mask-image-r-from-pos":[{"mask-r-from":m0()}],"mask-image-r-to-pos":[{"mask-r-to":m0()}],"mask-image-r-from-color":[{"mask-r-from":S()}],"mask-image-r-to-color":[{"mask-r-to":S()}],"mask-image-b-from-pos":[{"mask-b-from":m0()}],"mask-image-b-to-pos":[{"mask-b-to":m0()}],"mask-image-b-from-color":[{"mask-b-from":S()}],"mask-image-b-to-color":[{"mask-b-to":S()}],"mask-image-l-from-pos":[{"mask-l-from":m0()}],"mask-image-l-to-pos":[{"mask-l-to":m0()}],"mask-image-l-from-color":[{"mask-l-from":S()}],"mask-image-l-to-color":[{"mask-l-to":S()}],"mask-image-x-from-pos":[{"mask-x-from":m0()}],"mask-image-x-to-pos":[{"mask-x-to":m0()}],"mask-image-x-from-color":[{"mask-x-from":S()}],"mask-image-x-to-color":[{"mask-x-to":S()}],"mask-image-y-from-pos":[{"mask-y-from":m0()}],"mask-image-y-to-pos":[{"mask-y-to":m0()}],"mask-image-y-from-color":[{"mask-y-from":S()}],"mask-image-y-to-color":[{"mask-y-to":S()}],"mask-image-radial":[{"mask-radial":[t2,n2]}],"mask-image-radial-from-pos":[{"mask-radial-from":m0()}],"mask-image-radial-to-pos":[{"mask-radial-to":m0()}],"mask-image-radial-from-color":[{"mask-radial-from":S()}],"mask-image-radial-to-color":[{"mask-radial-to":S()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":f()}],"mask-image-conic-pos":[{"mask-conic":[T$]}],"mask-image-conic-from-pos":[{"mask-conic-from":m0()}],"mask-image-conic-to-pos":[{"mask-conic-to":m0()}],"mask-image-conic-from-color":[{"mask-conic-from":S()}],"mask-image-conic-to-color":[{"mask-conic-to":S()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:H0()}],"mask-repeat":[{mask:N0()}],"mask-size":[{mask:i()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",t2,n2]}],filter:[{filter:["","none",t2,n2]}],blur:[{blur:b0()}],brightness:[{brightness:[T$,t2,n2]}],contrast:[{contrast:[T$,t2,n2]}],"drop-shadow":[{"drop-shadow":["","none",q,sL0,oL0]}],"drop-shadow-color":[{"drop-shadow":S()}],grayscale:[{grayscale:["",T$,t2,n2]}],"hue-rotate":[{"hue-rotate":[T$,t2,n2]}],invert:[{invert:["",T$,t2,n2]}],saturate:[{saturate:[T$,t2,n2]}],sepia:[{sepia:["",T$,t2,n2]}],"backdrop-filter":[{"backdrop-filter":["","none",t2,n2]}],"backdrop-blur":[{"backdrop-blur":b0()}],"backdrop-brightness":[{"backdrop-brightness":[T$,t2,n2]}],"backdrop-contrast":[{"backdrop-contrast":[T$,t2,n2]}],"backdrop-grayscale":[{"backdrop-grayscale":["",T$,t2,n2]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[T$,t2,n2]}],"backdrop-invert":[{"backdrop-invert":["",T$,t2,n2]}],"backdrop-opacity":[{"backdrop-opacity":[T$,t2,n2]}],"backdrop-saturate":[{"backdrop-saturate":[T$,t2,n2]}],"backdrop-sepia":[{"backdrop-sepia":["",T$,t2,n2]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":g()}],"border-spacing-x":[{"border-spacing-x":g()}],"border-spacing-y":[{"border-spacing-y":g()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",t2,n2]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[T$,"initial",t2,n2]}],ease:[{ease:["linear","initial",P,t2,n2]}],delay:[{delay:[T$,t2,n2]}],animate:[{animate:["none",j,t2,n2]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[F,t2,n2]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:O0()}],"rotate-x":[{"rotate-x":O0()}],"rotate-y":[{"rotate-y":O0()}],"rotate-z":[{"rotate-z":O0()}],scale:[{scale:g0()}],"scale-x":[{"scale-x":g0()}],"scale-y":[{"scale-y":g0()}],"scale-z":[{"scale-z":g0()}],"scale-3d":["scale-3d"],skew:[{skew:S0()}],"skew-x":[{"skew-x":S0()}],"skew-y":[{"skew-y":S0()}],transform:[{transform:[t2,n2,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:r0()}],"translate-x":[{"translate-x":r0()}],"translate-y":[{"translate-y":r0()}],"translate-z":[{"translate-z":r0()}],"translate-none":["translate-none"],zoom:[{zoom:[vF,t2,n2]}],accent:[{accent:S()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:S()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],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",t2,n2]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":S()}],"scrollbar-track-color":[{"scrollbar-track":S()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":g()}],"scroll-mx":[{"scroll-mx":g()}],"scroll-my":[{"scroll-my":g()}],"scroll-ms":[{"scroll-ms":g()}],"scroll-me":[{"scroll-me":g()}],"scroll-mbs":[{"scroll-mbs":g()}],"scroll-mbe":[{"scroll-mbe":g()}],"scroll-mt":[{"scroll-mt":g()}],"scroll-mr":[{"scroll-mr":g()}],"scroll-mb":[{"scroll-mb":g()}],"scroll-ml":[{"scroll-ml":g()}],"scroll-p":[{"scroll-p":g()}],"scroll-px":[{"scroll-px":g()}],"scroll-py":[{"scroll-py":g()}],"scroll-ps":[{"scroll-ps":g()}],"scroll-pe":[{"scroll-pe":g()}],"scroll-pbs":[{"scroll-pbs":g()}],"scroll-pbe":[{"scroll-pbe":g()}],"scroll-pt":[{"scroll-pt":g()}],"scroll-pr":[{"scroll-pr":g()}],"scroll-pb":[{"scroll-pb":g()}],"scroll-pl":[{"scroll-pl":g()}],"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",t2,n2]}],fill:[{fill:["none",...S()]}],"stroke-w":[{stroke:[T$,n$0,BE,QJ2]}],stroke:[{stroke:["none",...S()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","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","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","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-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","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-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","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"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","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-pbs","scroll-pbe","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"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},nQ$=(A,{cacheSize:Q,prefix:$,experimentalParseClassName:w,extend:B={},override:X={}})=>{return hd(A,"cacheSize",Q),hd(A,"prefix",$),hd(A,"experimentalParseClassName",w),aL0(A.theme,X.theme),aL0(A.classGroups,X.classGroups),aL0(A.conflictingClassGroups,X.conflictingClassGroups),aL0(A.conflictingClassGroupModifiers,X.conflictingClassGroupModifiers),hd(A,"postfixLookupClassGroups",X.postfixLookupClassGroups),hd(A,"orderSensitiveModifiers",X.orderSensitiveModifiers),tL0(A.theme,B.theme),tL0(A.classGroups,B.classGroups),tL0(A.conflictingClassGroups,B.conflictingClassGroups),tL0(A.conflictingClassGroupModifiers,B.conflictingClassGroupModifiers),DZA(A,B,"postfixLookupClassGroups"),DZA(A,B,"orderSensitiveModifiers"),A},hd=(A,Q,$)=>{if($!==void 0)A[Q]=$},aL0=(A,Q)=>{if(Q)for(let $ in Q)hd(A,$,Q[$])},tL0=(A,Q)=>{if(Q)for(let $ in Q)DZA(A,Q,$)},DZA=(A,Q,$)=>{let w=Q[$];if(w!==void 0)A[$]=A[$]?A[$].concat(w):w},eL0=(A,...Q)=>typeof A==="function"?AJ2(BJ2,A,...Q):AJ2(()=>nQ$(BJ2(),A),...Q);var rQ$=eL0({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 e2(...A){return rQ$(Cd(A))}var IJ2=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,LJ2=Cd,iw=(A,Q)=>($)=>{var w;if((Q===null||Q===void 0?void 0:Q.variants)==null)return LJ2(A,$===null||$===void 0?void 0:$.class,$===null||$===void 0?void 0:$.className);let{variants:B,defaultVariants:X}=Q,Y=Object.keys(B).map((K)=>{let U=$===null||$===void 0?void 0:$[K],G=X===null||X===void 0?void 0:X[K];if(U===null)return null;let D=IJ2(U)||IJ2(G);return B[K][D]}),Z=$&&Object.entries($).reduce((K,U)=>{let[G,D]=U;if(D===void 0)return K;return K[G]=D,K},{}),W=Q===null||Q===void 0?void 0:(w=Q.compoundVariants)===null||w===void 0?void 0:w.reduce((K,U)=>{let{class:G,className:D,...q}=U;return Object.entries(q).every((J)=>{let[F,I]=J;return Array.isArray(I)?I.includes({...X,...Z}[F]):{...X,...Z}[F]===I})?[...K,G,D]:K},[]);return LJ2(A,Y,W,$===null||$===void 0?void 0:$.class,$===null||$===void 0?void 0:$.className)};import{jsxDEV as VZA}from"preact/jsx-dev-runtime";var NJ2=iw("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 JZA({variant:A,title:Q,children:$,className:w}){return VZA("div",{className:e2(NJ2({variant:A}),w),role:"alert",children:[Q&&VZA("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),VZA("div",{className:e2(Q&&"mt-1","text-sm text-current opacity-75"),children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as oQ$}from"preact/jsx-dev-runtime";var _J2=iw("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 YE({variant:A,size:Q,className:$,children:w,ssrOnClick:B,type:X="button",...Y}){return oQ$("button",{type:X,className:e2(_J2({variant:A,size:Q}),$),...Y,...B&&{onclick:B},children:w},void 0,!1,void 0,this)}import{jsxDEV as sQ$}from"preact/jsx-dev-runtime";var PJ2=iw("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 m4({href:A,children:Q,variant:$,size:w,external:B=!1,className:X,"aria-label":Y}){let Z=B?{target:"_blank",rel:"noopener noreferrer"}:{};return sQ$("a",{href:A,className:e2(PJ2({variant:$,size:w}),X),"aria-label":Y,...Z,children:Q},void 0,!1,void 0,this)}import{jsxDEV as AN0}from"preact/jsx-dev-runtime";var kJ2=iw("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"}}),aQ$={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function Ed({variant:A,size:Q,className:$}){let w=aQ$[Q??"md"];return AN0("button",{onclick:"toggleTheme()",type:"button",className:e2(kJ2({variant:A,size:Q}),$),"aria-label":"Toggle dark mode",children:AN0("svg",{className:e2(w,"transition-colors"),fill:"none",stroke:"currentColor",strokeWidth:1.6,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[AN0("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),AN0("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 FZA}from"preact/jsx-dev-runtime";var jJ2=iw("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function QN0({items:A,className:Q,linkClassName:$="hover:text-accent transition-colors",orientation:w,children:B}){if(A.length===0&&!B)return null;let X=[...A].sort((Y,Z)=>Y.priority-Z.priority);return FZA("ul",{className:e2(jJ2({orientation:w}),Q),children:[X.map((Y)=>FZA("li",{children:FZA("a",{href:Y.href,className:$,children:Y.label},void 0,!1,void 0,this)},Y.href,!1,void 0,this)),B]},void 0,!0,void 0,this)}import{jsxDEV as TX5}from"preact/jsx-dev-runtime";import{jsxDEV as SX5}from"preact/jsx-dev-runtime";import{createContext as tQ$,h as eQ$}from"preact";import{useContext as A6$}from"preact/hooks";var IZA=tQ$(null);function Td({headCollector:A,children:Q}){return eQ$(IZA.Provider,{value:A},Q)}function MJ2(){return A6$(IZA)}function C6(A){let Q=MJ2();if(Q)Q.setHeadProps(A);return null}import{createContext as R9$,h as v9$}from"preact";import{useContext as C9$}from"preact/hooks";_0A();var TN2=P1(EN2(),1),f9$=new sq0({gfm:!0,breaks:!0}),x9$={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 lHA(A,Q){let{imageRenderer:$}=Q??{},B=($?new sq0({gfm:!0,breaks:!0}).use({renderer:{image({href:X,title:Y,text:Z}){return $(X,Y,Z)??!1}}}):f9$).parse(A);return B=B.replace(/<\/blockquote>\s*<p>(\u2014|--|\u2013)([\s\S]*?)<\/p>/g,`</blockquote>
5791
+ `)}}KA();class SL0 extends X8{directorySync;constructor(A,Q,$){super(A,{schema:XZA,jobTypeName:"directory-export"});this.directorySync=$}async process(A,Q,$){this.logger.debug("Processing directory export job",{jobId:Q,data:A});let w=Date.now();try{let B=await this.directorySync.exportEntitiesWithProgress(A.entityTypes,$,A.batchSize??100);return this.logger.debug("Directory export job completed",{jobId:Q,exported:B.exported,failed:B.failed,duration:Date.now()-w}),B}catch(B){throw this.logger.error("Directory export job failed",{jobId:Q,error:B}),B}}summarizeDataForLog(A){return{entityTypes:A.entityTypes??"all",batchSize:A.batchSize}}}KA();class mL0 extends X8{directorySync;constructor(A,Q,$){super(A,{schema:BZA,jobTypeName:"directory-import"});this.directorySync=$}async process(A,Q,$){this.logger.debug("Processing directory import job",{jobId:Q,data:A});let w=Date.now();try{let B=await this.directorySync.importEntitiesWithProgress(A.paths,$,A.batchSize??100);return this.logger.debug("Directory import job completed",{jobId:Q,imported:B.imported,skipped:B.skipped,failed:B.failed,quarantined:B.quarantined,duration:Date.now()-w}),B}catch(B){throw this.logger.error("Directory import job failed",{jobId:Q,error:B}),B}}summarizeDataForLog(A){return{pathCount:A.paths?.length??"all",batchSize:A.batchSize}}}KA();class uL0 extends X8{directorySync;context;constructor(A,Q,$){super(A,{schema:$ZA,jobTypeName:"directory-sync"});this.context=Q,this.directorySync=$}async process(A,Q,$){let w=Date.now(),B=A.syncDirection??"both";this.logger.info("Starting directory sync job",{jobId:Q,operation:A.operation,syncDirection:B});let X={imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],jobIds:[]},Y={exported:0,failed:0,errors:[]};if(B!=="export")if(await $.report({progress:10,message:"Scanning directory for changes"}),X=await this.importWithProgress(A.paths,$),B==="import")await this.waitForImportJobs(X.jobIds,$),await $.report({progress:100,message:`Import complete: ${X.imported} imported`});else await $.report({progress:50,message:`Imported ${X.imported} entities`}),await this.waitForImportJobs(X.jobIds,$),await $.report({progress:56,message:"Processing complete, starting export"});if(B!=="import"){let W=B==="export"?10:60;await $.report({progress:W,message:"Exporting entities to directory"}),Y=await this.exportWithProgress(A.entityTypes,$),await $.report({progress:100,message:B==="export"?`Export complete: ${Y.exported} exported`:`Sync complete: ${X.imported} imported, ${Y.exported} exported`})}let Z=Date.now()-w;return this.logger.info("Directory sync job completed",{jobId:Q,duration:Z,imported:X.imported,exported:Y.exported}),{import:X,export:Y,duration:Z}}async importWithProgress(A,Q){try{return await this.directorySync.importEntitiesWithProgress(A,Q,10)}catch($){throw this.logger.error("Import phase failed",{error:$}),$}}async exportWithProgress(A,Q){try{return await this.directorySync.exportEntitiesWithProgress(A,Q,10)}catch($){throw this.logger.error("Export phase failed",{error:$}),$}}async waitForImportJobs(A,Q){if(A.length===0)return;this.logger.debug(`Waiting for ${A.length} import jobs to complete`);let{entityService:$}=this.context,w=300000,B=500,X=Date.now(),Y=async()=>{let W=(await Promise.all(A.map((U)=>$.getAsyncJobStatus(U)))).filter((U)=>U&&(U.status==="completed"||U.status==="failed")).length;if(W===A.length){this.logger.debug("All import jobs completed");return}if(Date.now()-X>w){this.logger.warn(`Timeout waiting for import jobs (${W}/${A.length} completed)`);return}let K=Math.round(W/A.length*100);return await Q.report({progress:50+Math.round(K*0.05),message:`Processing ${W}/${A.length} entities`}),await new Promise((U)=>setTimeout(U,B)),Y()};return Y()}summarizeDataForLog(A){return{operation:A.operation,syncDirection:A.syncDirection}}}KA();class cL0 extends X8{context;directorySync;gitSync;constructor(A,Q,$,w){super(A,{schema:wZA,jobTypeName:"sync-request"});this.context=Q,this.directorySync=$,this.gitSync=w}async process(A,Q,$){await $.report({progress:5,message:"Pulling latest content from git"});let w=await this.gitSync.withLock(async()=>{return await this.gitSync.pull(),await $.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(!w)return await $.report({progress:100,message:"Sync complete: no files to import"}),{gitPulled:!0,batchQueued:!1};return await $.report({progress:100,message:`Sync queued: ${w.importOperationsCount} import jobs for ${w.totalFiles} files`}),f2$(w)}summarizeDataForLog(A){return{source:A.source,interfaceType:A.interfaceType,channelId:A.channelId}}}function f2$(A){return{gitPulled:!0,batchQueued:!0,batchId:A.batchId,importOperations:A.importOperationsCount,totalFiles:A.totalFiles}}KA();class pL0 extends X8{context;constructor(A,Q,$){super(A,{schema:yL0,jobTypeName:"directory-delete"});this.context=Q}async process(A,Q,$){let w=yL0.parse(A);this.logger.info("Processing entity deletion for removed file",{entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}),await $.report({progress:0,total:1,message:`Deleting ${w.entityType}:${w.entityId}`});try{let B=await this.context.entityService.deleteEntity({entityType:w.entityType,id:w.entityId});if(B)this.logger.info("Successfully deleted entity for removed file",{entityId:w.entityId,entityType:w.entityType});else this.logger.warn("Entity not found in database",{entityId:w.entityId,entityType:w.entityType});return await $.report({progress:1,total:1,message:`Deleted ${w.entityType}:${w.entityId}`}),{deleted:B,entityId:w.entityId,entityType:w.entityType,filePath:w.filePath}}catch(B){throw this.logger.error("Failed to delete entity",{entityId:w.entityId,entityType:w.entityType,error:B}),B}}summarizeDataForLog(A){return{entityId:A.entityId,entityType:A.entityType,filePath:A.filePath}}}KA();C0();var x2$=H.object({});class lL0 extends X8{directorySync;constructor(A,Q){super(A,{schema:x2$,jobTypeName:"directory-cleanup"});this.directorySync=Q}async process(A,Q,$){await $.report({progress:0,message:"Removing orphaned entities"});let w=await this.directorySync.removeOrphanedEntities();return await $.report({progress:100,message:`Cleanup complete: ${w.deleted} orphans removed`}),w}}KA();JZ();_4();e8();C0();JZ();import{readFile as R2$,writeFile as v2$}from"fs/promises";var C2$=YZA,h2$=H.record(H.string(),H.unknown());class dL0 extends X8{context;fetcher;constructor(A,Q,$=rD){super(Q,{schema:C2$,jobTypeName:"cover-image-convert"});this.context=A,this.fetcher=$}async process(A,Q,$){let{filePath:w,sourceUrl:B,postTitle:X,postSlug:Y,customAlt:Z}=A;this.logger.debug("Starting image conversion job",{jobId:Q,filePath:w,sourceUrl:B,postSlug:Y});try{await this.reportProgress($,{progress:T6.INIT,message:`Reading file: ${w}`});let W;try{W=await R2$(w,"utf-8")}catch(I){return this.logger.error("Failed to read file",{filePath:w,error:aA(I)}),y5.failure(I)}let K;try{K=c8(W)}catch(I){return this.logger.warn("Failed to parse markdown",{filePath:w,error:aA(I)}),y5.failure(I)}let U=h2$.safeParse(K.frontmatter),G=U.success?U.data:{};if(G.coverImageId)return this.logger.debug("File already has coverImageId, skipping",{filePath:w}),await this.reportProgress($,{progress:T6.COMPLETE,message:"Already converted"}),{success:!0,skipped:!0};await this.reportProgress($,{progress:T6.FETCH,message:"Checking for existing image"});let D=await this.context.entityService.listEntities({entityType:"image",options:{filter:{metadata:{sourceUrl:B}},limit:1}}),q;if(D[0])q=D[0].id,this.logger.debug("Reusing existing image entity",{sourceUrl:B,imageId:q}),await this.reportProgress($,{progress:T6.EXTRACT,message:`Reusing existing image: ${q}`});else{await this.reportProgress($,{progress:T6.PROCESS,message:`Fetching image from ${B}`});let I;try{I=await this.fetcher(B)}catch(x){return this.logger.error("Failed to fetch image",{sourceUrl:B,error:aA(x)}),y5.failure(x)}await this.reportProgress($,{progress:T6.GENERATE,message:"Creating image entity"});let{base64:P}=JM(I),j=cv(P),k=FM(P);if(!j||!k)return this.logger.error("Could not detect image format or dimensions",{sourceUrl:B}),y5.failure(Error("Could not detect image format or dimensions"));q=`${Y}-cover`;let f=`Cover image for ${X}`,R=Z??f;await this.context.entityService.createEntity({entity:{id:q,entityType:"image",content:I,metadata:{title:f,alt:R,format:j,width:k.width,height:k.height,sourceUrl:B}}}),this.logger.debug("Created image entity",{imageId:q,sourceUrl:B}),await this.reportProgress($,{progress:T6.EXTRACT,message:`Created image: ${q}`})}await this.reportProgress($,{progress:T6.SAVE,message:"Updating file"});let J={...G};delete J.coverImageUrl,delete J.coverImageAlt,J.coverImageId=q;let F=Wv(J,K.content);try{await v2$(w,F,"utf-8")}catch(I){return this.logger.error("Failed to write file",{filePath:w,error:aA(I)}),y5.failure(I)}return await this.reportProgress($,{progress:T6.COMPLETE,message:"Conversion complete"}),this.logger.info("Image conversion complete",{filePath:w,imageId:q,sourceUrl:B}),{success:!0,imageId:q}}catch(W){return this.logger.error("Image conversion job failed",{jobId:Q,filePath:w,error:aA(W)}),y5.failure(W)}}summarizeDataForLog(A){return{filePath:A.filePath,sourceUrl:A.sourceUrl,postSlug:A.postSlug}}}KA();JZ();e8();import{readFile as E2$,writeFile as T2$}from"fs/promises";class iL0 extends X8{converter;constructor(A,Q,$=rD){super(Q,{schema:ZZA,jobTypeName:"inline-image-convert"});this.converter=new v$0(A.entityService,Q,$)}async process(A,Q,$){let{filePath:w,postSlug:B}=A;this.logger.debug("Starting inline image conversion job",{jobId:Q,filePath:w,postSlug:B});try{await this.reportProgress($,{progress:T6.INIT,message:`Reading file: ${w}`});let X;try{X=await E2$(w,"utf-8")}catch(W){let K=aA(W);return this.logger.error("Failed to read file",{filePath:w,error:K}),{success:!1,error:K}}await this.reportProgress($,{progress:T6.FETCH,message:"Detecting inline images"});let Y=this.converter.detectInlineImages(X,B);if(Y.length===0)return this.logger.debug("No inline images to convert",{filePath:w}),await this.reportProgress($,{progress:T6.COMPLETE,message:"No images to convert"}),{success:!0,skipped:!0,convertedCount:0};this.logger.debug("Found inline images to convert",{filePath:w,count:Y.length}),await this.reportProgress($,{progress:T6.PROCESS,message:`Converting ${Y.length} images`});let Z=await this.converter.convert(X,B);if(!Z.converted)return this.logger.debug("No images were converted",{filePath:w}),await this.reportProgress($,{progress:T6.COMPLETE,message:"No images converted"}),{success:!0,skipped:!0,convertedCount:0};await this.reportProgress($,{progress:T6.SAVE,message:"Writing updated file"});try{await T2$(w,Z.content,"utf-8")}catch(W){let K=aA(W);return this.logger.error("Failed to write file",{filePath:w,error:K}),{success:!1,error:K}}return await this.reportProgress($,{progress:T6.COMPLETE,message:"Conversion complete"}),this.logger.info("Inline image conversion complete",{filePath:w,convertedCount:Z.convertedCount}),{success:!0,convertedCount:Z.convertedCount}}catch(X){let Y=aA(X);return this.logger.error("Inline image conversion job failed",{jobId:Q,filePath:w,error:Y}),{success:!1,error:Y}}}summarizeDataForLog(A){return{filePath:A.filePath,postSlug:A.postSlug}}}function xV2(A,Q,$){let w=(B)=>$.child(B);A.jobs.registerHandler("directory-sync",new uL0(w("DirectorySyncJobHandler"),A,Q)),A.jobs.registerHandler("directory-export",new SL0(w("DirectoryExportJobHandler"),A,Q)),A.jobs.registerHandler("directory-import",new mL0(w("DirectoryImportJobHandler"),A,Q)),A.jobs.registerHandler("directory-delete",new pL0(w("DirectoryDeleteJobHandler"),A,Q)),A.jobs.registerHandler("directory-cleanup",new lL0(w("DirectoryCleanupJobHandler"),Q)),A.jobs.registerHandler("cover-image-convert",new dL0(A,w("CoverImageConversionJobHandler"))),A.jobs.registerHandler("inline-image-convert",new iL0(A,w("InlineImageConversionJobHandler"))),$.debug("Registered async job handlers")}KA();C0();import{unlink as y2$,access as g2$}from"fs/promises";var S2$=H.record(H.string(),H.unknown());function RV2(A,Q,$,w){let{subscribe:B}=A.messaging,{entityService:X}=A;B("entity:created",async(Y)=>{let{entity:Z}=Y.payload;try{await Q.fileOps.writeEntity(Z),$.debug("Auto-exported created entity",{id:Z.id,entityType:Z.entityType})}catch(W){$.error("Auto-export FAILED for created entity",{id:Z.id,entityType:Z.entityType,error:W instanceof Error?W.message:String(W),stack:W instanceof Error?W.stack:void 0})}return{success:!0}}),B("entity:updated",async(Y)=>{let{entityType:Z,entityId:W}=Y.payload;try{let K=await X.getEntity({entityType:Z,id:W});if(!K)return $.debug("Entity not found in DB, skipping export",{entityType:Z,entityId:W}),{success:!1};await Q.fileOps.writeEntity(K),$.debug("Auto-exported updated entity",{id:K.id,entityType:K.entityType})}catch(K){$.error("Auto-export FAILED for updated entity",{entityType:Z,entityId:W,error:K instanceof Error?K.message:String(K),stack:K instanceof Error?K.stack:void 0})}return{success:!0}}),B("entity:deleted",async(Y)=>{let{entityId:Z,entityType:W}=Y.payload,K=Q.fileOps.getFilePath(Z,W);if(await g2$(K).then(()=>!0,()=>!1))await y2$(K),$.debug("Auto-deleted entity file",{id:Z,entityType:W,path:K});return{success:!0}}),$.debug("Setup auto-sync for entity events",{entityTypes:w})}function vV2(A,Q,$){Q.setJobQueueCallback(async(w)=>{let B=[{type:w.type,data:S2$.parse(w.data)}];return A.jobs.enqueueBatch(B,{priority:5,source:"directory-sync-watcher",rootJobId:nY(),metadata:{operationType:"file_operations",operationTarget:$,pluginId:"directory-sync"}})})}KA();import{readdir as EV2,mkdir as u2$,copyFile as c2$}from"fs/promises";import{join as hV2,resolve as HZA}from"path";import{join as m2$}from"path";async function CV2(A){if(!await s9(m2$(A,".git")))return!1;try{return await h3(A).revparse(["--verify","HEAD"]),!0}catch{return!1}}async function p2$(A,Q){if(!await s9(A))return!0;if((await EV2(A)).filter((B)=>!B.startsWith(".")&&!B.startsWith("_")).length>0)return!1;if(await CV2(A))return Q.debug("Git repository with history detected - skipping seed content",{path:A}),!1;return!0}async function TV2(A,Q){let $=await EV2(A,{withFileTypes:!0});for(let w of $){let B=hV2(A,w.name),X=hV2(Q,w.name);if(w.isDirectory()){if(!await s9(X))await u2$(X,{recursive:!0});await TV2(B,X)}else await c2$(B,X)}}async function yV2(A,Q,$){let w=HZA(process.cwd(),A);$=$?HZA($):HZA(process.cwd(),"seed-content");let B=await p2$(w,Q);if(B&&await s9($))Q.debug("Copying seed content to brain-data directory"),await TV2($,w),Q.debug("Seed content copied successfully");else if(B)Q.debug("No seed content directory found, starting with empty brain-data");else Q.debug("brain-data directory not empty, skipping seed content")}function gV2(A,Q,$,w,B){let X=!1,Y=async()=>{if(X)return;X=!0;let Z=Q();if($.seedContent){let W=$.syncPath??A.dataDir;await yV2(W,w,$.seedContentPath)}try{if(B){w.debug("Git enabled \u2014 pulling before import");let K=await B.pull();if(K.files.length>0)w.info("Pulled changes from remote",{filesChanged:K.files.length})}w.debug("Starting initial sync");let W=await Z.sync();w.debug("Initial sync completed",{imported:W.import.imported,failed:W.import.failed,duration:W.duration}),await A.messaging.send({type:Dv.initialSyncCompleted,payload:{success:!0},...{broadcast:!0}})}catch(W){w.error("Initial sync failed",W),await A.messaging.send({type:Dv.initialSyncCompleted,payload:{success:!1,error:aA(W)},...{broadcast:!0}})}};A.messaging.subscribe(Dv.pluginsRegistered,async()=>{return w.debug("Plugins registered, starting initial sync"),await Y(),{success:!0}})}class WZA{fn;delayMs;timeout;pending=!1;constructor(A,Q){this.fn=A,this.delayMs=Q}trigger(){if(!this.timeout){this.fn(),this.timeout=setTimeout(()=>{if(this.timeout=void 0,this.pending)this.pending=!1,this.fn()},this.delayMs);return}this.pending=!0,clearTimeout(this.timeout),this.timeout=setTimeout(()=>{if(this.timeout=void 0,this.pending)this.pending=!1,this.fn()},this.delayMs)}dispose(){if(this.timeout)clearTimeout(this.timeout),this.timeout=void 0;this.pending=!1}}class KZA{fn;delayMs;timeout;constructor(A,Q){this.fn=A,this.delayMs=Q}trigger(){if(this.timeout)clearTimeout(this.timeout);this.timeout=setTimeout(()=>{this.timeout=void 0,this.fn()},this.delayMs)}dispose(){if(this.timeout)clearTimeout(this.timeout),this.timeout=void 0}}function SV2(A,Q,$,w){let B=new KZA(()=>{Q.withLock(async()=>{try{await Q.commit(),await Q.push()}catch(Z){w.error("Git auto-commit failed",{error:Z})}})},$),X=["entity:created","entity:updated","entity:deleted"],Y=[];for(let Z of X){let W=A.subscribe(Z,async()=>{return B.trigger(),{success:!0}});Y.push(W)}return()=>{B.dispose();for(let Z of Y)Z()}}function mV2(A,Q,$,w,B){if(w<=0)return()=>{};let X=w*60*1000,Y=!1,Z=async()=>{if(Y)return;Y=!0;try{let{files:K,result:U}=await A.withLock(async()=>{let G=await A.pull();if(G.files.length===0)return{files:[],result:null};let D=await Q.queueSyncBatch($,"periodic-sync");return{files:G.files,result:D}});if(K.length>0)B.info("Periodic sync: pulled changes",{filesChanged:K.length});if(U)B.debug("Periodic sync: queued imports",{importOperations:U.importOperationsCount,totalFiles:U.totalFiles})}catch(K){B.error("Periodic git sync failed",{error:K})}finally{Y=!1}},W=setInterval(()=>{Z()},X);return B.info("Started periodic git sync",{intervalMinutes:w}),()=>{clearInterval(W)}}import{spawnSync as cV2}from"child_process";import{cpSync as l2$,existsSync as uV2,mkdirSync as d2$,mkdtempSync as i2$,rmSync as n2$}from"fs";import{tmpdir as r2$}from"os";import{fileURLToPath as o2$}from"url";import{join as s2$,resolve as a2$}from"path";function GO(A,Q){let $=cV2("git",Q,{cwd:A,stdio:"pipe"});if($.status!==0){let w=$.stderr.toString().trim(),B=$.stdout.toString().trim();throw Error(w||B||`git ${Q.join(" ")} failed`)}}function t2$(A){return A.startsWith("file://")}function e2$(A){return o2$(A)}function AQ$(A,Q){return cV2("git",["--git-dir",A,"show-ref","--verify","--quiet",`refs/heads/${Q}`]).status===0}async function pV2(A){if(!A.bootstrapFromSeed)return;if(!A.gitUrl||!t2$(A.gitUrl))return;if(!A.seedContentPath)throw Error("directory-sync git.bootstrapFromSeed requires seedContentPath for local file:// remotes");let Q=A.branch??"main",$=e2$(A.gitUrl),w=a2$(A.seedContentPath);if(!uV2(w))throw Error(`Seed content path not found: ${w}`);if(!uV2($))A.logger.debug("Creating local bare content remote",{remotePath:$,branch:Q}),d2$($,{recursive:!0}),GO(process.cwd(),["init","--bare",`--initial-branch=${Q}`,$]);if(AQ$($,Q)){A.logger.debug("Content remote already initialized",{remotePath:$,branch:Q});return}A.logger.debug("Seeding local content remote",{remotePath:$,seedPath:w,branch:Q});let B=i2$(s2$(r2$(),"directory-sync-seed-"));try{GO(B,["init",`--initial-branch=${Q}`]),GO(B,["config","user.name",A.authorName??"Brain"]),GO(B,["config","user.email",A.authorEmail??"brain@localhost"]),l2$(w,B,{recursive:!0,filter:(X)=>!X.split("/").includes(".git")}),GO(B,["add","."]),GO(B,["commit","-m","seed content remote"]),GO(B,["remote","add","origin",A.gitUrl]),GO(B,["push","-u","origin",Q])}finally{n2$(B,{recursive:!0,force:!0})}}function lV2(A,Q,$,w,B,X){let{subscribe:Y}=A.messaging;Y("entity:export:request",async(Z)=>{try{return{success:!0,data:await Q().exportEntities(Z.payload.entityTypes)}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Export failed"}}}),Y("entity:import:request",async(Z)=>{try{let W=Q(),K=Z.payload.paths,U=await W.importEntities(K);if(K&&K.length>0)await W.removeOrphanedEntities();return{success:!0,data:U}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Import failed"}}}),Y("sync:status:request",async()=>{try{let W=await Q().getStatus();return{success:!0,data:{syncPath:W.syncPath,isInitialized:W.exists,watchEnabled:W.watching,lastSync:W.lastSync?.toISOString()??null,totalFiles:W.stats.totalFiles,byEntityType:W.stats.byEntityType,git:await QQ$(X?.(),w)}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Status check failed"}}}),Y("sync:configure:request",async(Z)=>{try{return await $({syncPath:Z.payload.syncPath}),{success:!0,data:{syncPath:Z.payload.syncPath,configured:!0}}}catch(W){return{success:!1,error:W instanceof Error?W.message:"Configuration failed"}}}),Y("git-sync:get-repo-info",async()=>{if(!B?.repo)return{success:!1,error:"Git not configured"};return{success:!0,data:{repo:B.repo,branch:B.branch??"main"}}}),w.debug("Registered message handlers")}async function QQ$(A,Q){if(!A)return null;try{let $=await A.getStatus();return{branch:$.branch,hasChanges:$.hasChanges,ahead:$.ahead,behind:$.behind,lastCommit:$.lastCommit??null,remote:$.remote??null}}catch($){return Q.debug("Git status unavailable for sync:status:request",{error:$}),null}}KA();C0();KA();C0();function dV2(A,Q){return p8(A,"history","Get version history for an entity from git. Without sha: returns commit list. With sha: returns entity content at that version.",H.object({entityType:H.string().describe("Entity type (e.g. post, note, link)"),id:H.string().describe("Entity ID"),sha:H.string().optional().describe("Commit SHA to retrieve content at. Omit to list commit history."),limit:H.number().int().positive().optional().default(10).describe("Max commits to return (list mode only)")}),async($)=>{let w=`${$.entityType}/${$.id}.md`;try{if($.sha){let X=await Q.show($.sha,w);return f7({sha:$.sha,entityType:$.entityType,id:$.id,content:X},`Content at ${$.sha.slice(0,7)}`)}let B=await Q.log(w,$.limit);if(B.length===0)return f7({commits:[]},`No history found for ${$.entityType}/${$.id}`);return f7({commits:B,entityType:$.entityType,id:$.id},`${B.length} version${B.length===1?"":"s"} found`)}catch(B){return YY(B instanceof Error?B.message:"History lookup failed")}},{visibility:"anchor",sideEffects:"none"})}function iV2(A,Q,$,w){let B=[p8($,"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.",H.object({}),async(X,Y)=>{try{let Z=Y.channelId?`${Y.interfaceType}:${Y.channelId}`:`plugin:${$}`,W={interfaceType:Y.interfaceType,channelId:Y.channelId};if(w){let U=await Q.jobs.enqueue({type:"sync-request",data:{source:Z,interfaceType:W.interfaceType,channelId:W.channelId},toolContext:Y});return f7({jobId:U,status:"queued",gitPulled:!0},"Sync queued: git pull and filesystem scan will run in the background")}let K=await A.queueSyncBatch(Q,Z,W);if(!K)return f7({gitPulled:!1},"No files to sync");return f7({batchId:K.batchId,importOperations:K.importOperationsCount,totalFiles:K.totalFiles,gitPulled:!1},`Sync started: ${K.importOperationsCount} import jobs queued for ${K.totalFiles} files`)}catch(Z){return YY(Z instanceof Error?Z.message:"Sync failed")}},{visibility:"anchor",sideEffects:"external",cli:{name:"sync"}}),p8($,"status","Read directory and git sync status: last sync, watcher state, and pending git changes. Use this for every status follow-up after directory-sync_sync, even when that call returned a jobId; a sync jobId is not a system_job_status batchId.",H.object({}),async()=>{try{let X=await A.getStatus(),Y={syncPath:X.syncPath,lastSync:X.lastSync?.toISOString(),watching:X.watching};if(w){let Z=await w.getStatus();Y.git={isRepo:Z.isRepo,branch:Z.branch,hasChanges:Z.hasChanges,ahead:Z.ahead,behind:Z.behind,remote:Z.remote}}return f7(Y)}catch(X){return YY(X instanceof Error?X.message:"Status check failed")}},{visibility:"anchor",sideEffects:"none"})];if(w)B.push(dV2($,w));return B}var nV2={name:"@brains/directory-sync",version:"0.2.0-alpha.184",description:"Directory-based entity synchronization plugin for Brains",dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/image":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chokidar:"^5.0.0","simple-git":"^3.36.0"},devDependencies:{"@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":{types:"./src/index.ts",import:"./src/index.ts"},"./env-schema":"./src/env-schema.ts"},main:"./src/index.ts",peerDependencies:{},private:!0,scripts:{clean:"rm -rf .turbo",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};class UZA extends p6{directorySync;gitSync;gitCleanups=[];constructor(A={}){super("directory-sync",nV2,A,d$0)}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:$}=A;A.templates.register({status:{name:"status",description:"Directory synchronization status",schema:i$0,basePrompt:"",formatter:new gL0,requiredPermission:"anchor"}});let w=this.config.syncPath??A.dataDir;this.directorySync=new C$0({syncPath:w,autoSync:this.config.autoSync,watchInterval:this.config.watchInterval,includeMetadata:this.config.includeMetadata,entityTypes:this.config.entityTypes,deleteOnFileRemoval:this.config.deleteOnFileRemoval,entityService:$,logger:Q});try{await this.directorySync.initializeDirectory(),this.logger.debug("Directory structure initialized",{path:w})}catch(Y){throw this.logger.error("Failed to initialize directory",Y),Y}await this.registerJobHandlers(A);let B=this.requireDirectorySync();if(RV2(A,B,this.logger,this.config.entityTypes),this.config.autoSync)vV2(A,B,this.config.syncPath??A.dataDir);let X=this.config.git!==void 0&&(this.config.git.repo!==void 0||this.config.git.gitUrl!==void 0);if(this.config.git&&!X)this.logger.debug("Git block present but no repo/gitUrl configured \u2014 git sync disabled");if(X&&this.config.git){await pV2({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 Y=this.config.syncPath??A.dataDir;if(this.gitSync=new QZA({logger:this.logger.child("GitSync"),dataDir:Y,repo:this.config.git.repo,gitUrl:this.config.git.gitUrl,branch:this.config.git.branch,authToken:this.config.git.authToken,authorName:this.config.git.authorName,authorEmail:this.config.git.authorEmail}),await this.gitSync.initialize(),this.logger.info("Git integration enabled",{repo:this.config.git.repo}),A.jobs.registerHandler("sync-request",new cL0(this.logger.child("DirectorySyncRequestJobHandler"),A,this.requireDirectorySync(),this.gitSync)),this.gitCleanups.push(SV2(A.messaging,this.gitSync,this.config.commitDebounce,this.logger.child("GitAutoCommit"))),this.config.autoSync)this.gitCleanups.push(mV2(this.gitSync,this.requireDirectorySync(),A,this.config.syncInterval,this.logger.child("GitPeriodicSync")))}if(this.config.initialSync)gV2(A,()=>this.requireDirectorySync(),this.config,this.logger,this.gitSync);lV2(A,()=>this.requireDirectorySync(),(Y)=>this.configure(Y),this.logger,this.config.git,()=>this.gitSync)}async getTools(){let A=this.requireDirectorySync();return iV2(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 C$0({...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){xV2(A,this.requireDirectorySync(),this.logger)}}function wE(A={}){return new UZA(A)}C0();var nL0="email:send",rV2=H.strictObject({to:H.string().email(),subject:H.string().min(1),text:H.string().min(1),html:H.string().min(1).optional(),sensitivity:H.enum(["normal","secret"]).default("normal")});KA();C0();var oV2={name:"@brains/email-resend",version:"0.2.0-alpha.184",description:"Generic email delivery adapter for Resend",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var BQ$=H.object({apiKey:H.string().min(1).optional(),from:H.string().min(1).optional()}),XQ$=H.looseObject({id:H.string().optional()});class sV2 extends p6{fetchImpl;constructor(A={},Q={}){super("email-resend",oV2,A,BQ$);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(nL0,async($)=>{let w=rV2.parse($.payload);try{return{success:!0,data:await this.sendWithResend(w)}}catch(B){if(w.sensitivity==="secret")Q.warn("Email delivery failed for a secret message");else Q.warn("Email delivery failed",{to:w.to,subject:w.subject,error:B instanceof Error?B.message:String(B)});return{success:!1,error:"Email delivery failed"}}})}async sendWithResend(A){let Q=this.config.apiKey,$=this.config.from;if(!Q||!$)return{status:"failed"};let w=await this.fetchImpl("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json"},body:JSON.stringify({from:$,to:A.to,subject:A.subject,text:A.text,...A.html?{html:A.html}:{}})});if(!w.ok)throw Error("Resend email request failed");let B=XQ$.parse(await w.json());return B.id?{status:"sent",id:B.id}:{status:"sent"}}}function rL0(A={}){return new sV2(A)}KA();import{render as Tv2}from"preact-render-to-string";import{h as SE}from"preact";function aV2(A){var Q,$,w="";if(typeof A=="string"||typeof A=="number")w+=A;else if(typeof A=="object")if(Array.isArray(A)){var B=A.length;for(Q=0;Q<B;Q++)A[Q]&&($=aV2(A[Q]))&&(w&&(w+=" "),w+=$)}else for($ in A)A[$]&&(w&&(w+=" "),w+=$);return w}function Cd(){for(var A,Q,$=0,w="",B=arguments.length;$<B;$++)(A=arguments[$])&&(Q=aV2(A))&&(w&&(w+=" "),w+=Q);return w}var YQ$=(A,Q)=>{let $=Array(A.length+Q.length);for(let w=0;w<A.length;w++)$[w]=A[w];for(let w=0;w<Q.length;w++)$[A.length+w]=Q[w];return $},ZQ$=(A,Q)=>({classGroupId:A,validator:Q}),XJ2=(A=new Map,Q=null,$)=>({nextPart:A,validators:Q,classGroupId:$});var tV2=[];var HQ$=(A)=>{let Q=KQ$(A),{conflictingClassGroups:$,conflictingClassGroupModifiers:w}=A;return{getClassGroupId:(Y)=>{if(Y.startsWith("[")&&Y.endsWith("]"))return WQ$(Y);let Z=Y.split("-"),W=Z[0]===""&&Z.length>1?1:0;return YJ2(Z,W,Q)},getConflictingClassGroupIds:(Y,Z)=>{if(Z){let W=w[Y],K=$[Y];if(W){if(K)return YQ$(K,W);return W}return K||tV2}return $[Y]||tV2}}},YJ2=(A,Q,$)=>{if(A.length-Q===0)return $.classGroupId;let B=A[Q],X=$.nextPart.get(B);if(X){let K=YJ2(A,Q+1,X);if(K)return K}let Y=$.validators;if(Y===null)return;let Z=Q===0?A.join("-"):A.slice(Q).join("-"),W=Y.length;for(let K=0;K<W;K++){let U=Y[K];if(U.validator(Z))return U.classGroupId}return},WQ$=(A)=>A.slice(1,-1).indexOf(":")===-1?void 0:(()=>{let Q=A.slice(1,-1),$=Q.indexOf(":"),w=Q.slice(0,$);return w?"arbitrary.."+w:void 0})(),KQ$=(A)=>{let{theme:Q,classGroups:$}=A;return UQ$($,Q)},UQ$=(A,Q)=>{let $=XJ2();for(let w in A){let B=A[w];qZA(B,$,w,Q)}return $},qZA=(A,Q,$,w)=>{let B=A.length;for(let X=0;X<B;X++){let Y=A[X];GQ$(Y,Q,$,w)}},GQ$=(A,Q,$,w)=>{if(typeof A==="string"){DQ$(A,Q,$);return}if(typeof A==="function"){qQ$(A,Q,$,w);return}zQ$(A,Q,$,w)},DQ$=(A,Q,$)=>{let w=A===""?Q:ZJ2(Q,A);w.classGroupId=$},qQ$=(A,Q,$,w)=>{if(VQ$(A)){qZA(A(w),Q,$,w);return}if(Q.validators===null)Q.validators=[];Q.validators.push(ZQ$($,A))},zQ$=(A,Q,$,w)=>{let B=Object.entries(A),X=B.length;for(let Y=0;Y<X;Y++){let[Z,W]=B[Y];qZA(W,ZJ2(Q,Z),$,w)}},ZJ2=(A,Q)=>{let $=A,w=Q.split("-"),B=w.length;for(let X=0;X<B;X++){let Y=w[X],Z=$.nextPart.get(Y);if(!Z)Z=XJ2(),$.nextPart.set(Y,Z);$=Z}return $},VQ$=(A)=>("isThemeGetter"in A)&&A.isThemeGetter===!0,JQ$=(A)=>{if(A<1)return{get:()=>{return},set:()=>{}};let Q=0,$=Object.create(null),w=Object.create(null),B=(X,Y)=>{if($[X]=Y,Q++,Q>A)Q=0,w=$,$=Object.create(null)};return{get(X){let Y=$[X];if(Y!==void 0)return Y;if((Y=w[X])!==void 0)return B(X,Y),Y},set(X,Y){if(X in $)$[X]=Y;else B(X,Y)}}};var FQ$=[],eV2=(A,Q,$,w,B)=>({modifiers:A,hasImportantModifier:Q,baseClassName:$,maybePostfixModifierPosition:w,isExternal:B}),IQ$=(A)=>{let{prefix:Q,experimentalParseClassName:$}=A,w=(B)=>{let X=[],Y=0,Z=0,W=0,K,U=B.length;for(let F=0;F<U;F++){let I=B[F];if(Y===0&&Z===0){if(I===":"){X.push(B.slice(W,F)),W=F+1;continue}if(I==="/"){K=F;continue}}if(I==="[")Y++;else if(I==="]")Y--;else if(I==="(")Z++;else if(I===")")Z--}let G=X.length===0?B:B.slice(W),D=G,q=!1;if(G.endsWith("!"))D=G.slice(0,-1),q=!0;else if(G.startsWith("!"))D=G.slice(1),q=!0;let J=K&&K>W?K-W:void 0;return eV2(X,q,D,J)};if(Q){let B=Q+":",X=w;w=(Y)=>Y.startsWith(B)?X(Y.slice(B.length)):eV2(FQ$,!1,Y,void 0,!0)}if($){let B=w;w=(X)=>$({className:X,parseClassName:B})}return w},LQ$=(A)=>{let Q=new Map;return A.orderSensitiveModifiers.forEach(($,w)=>{Q.set($,1e6+w)}),($)=>{let w=[],B=[];for(let X=0;X<$.length;X++){let Y=$[X],Z=Y[0]==="[",W=Q.has(Y);if(Z||W){if(B.length>0)B.sort(),w.push(...B),B=[];w.push(Y)}else B.push(Y)}if(B.length>0)B.sort(),w.push(...B);return w}},NQ$=(A)=>({cache:JQ$(A.cacheSize),parseClassName:IQ$(A),sortModifiers:LQ$(A),postfixLookupClassGroupIds:_Q$(A),...HQ$(A)}),_Q$=(A)=>{let Q=Object.create(null),$=A.postfixLookupClassGroups;if($)for(let w=0;w<$.length;w++)Q[$[w]]=!0;return Q},PQ$=/\s+/,kQ$=(A,Q)=>{let{parseClassName:$,getClassGroupId:w,getConflictingClassGroupIds:B,sortModifiers:X,postfixLookupClassGroupIds:Y}=Q,Z=[],W=A.trim().split(PQ$),K="";for(let U=W.length-1;U>=0;U-=1){let G=W[U],{isExternal:D,modifiers:q,hasImportantModifier:J,baseClassName:F,maybePostfixModifierPosition:I}=$(G);if(D){K=G+(K.length>0?" "+K:K);continue}let P=!!I,j;if(P){let O=F.substring(0,I);j=w(O);let g=j&&Y[j]?w(F):void 0;if(g&&g!==j)j=g,P=!1}else j=w(F);if(!j){if(!P){K=G+(K.length>0?" "+K:K);continue}if(j=w(F),!j){K=G+(K.length>0?" "+K:K);continue}P=!1}let k=q.length===0?"":q.length===1?q[0]:X(q).join(":"),f=J?k+"!":k,R=f+j;if(Z.indexOf(R)>-1)continue;Z.push(R);let x=B(j,P);for(let O=0;O<x.length;++O){let g=x[O];Z.push(f+g)}K=G+(K.length>0?" "+K:K)}return K},jQ$=(...A)=>{let Q=0,$,w,B="";while(Q<A.length)if($=A[Q++]){if(w=HJ2($))B&&(B+=" "),B+=w}return B},HJ2=(A)=>{if(typeof A==="string")return A;let Q,$="";for(let w=0;w<A.length;w++)if(A[w]){if(Q=HJ2(A[w]))$&&($+=" "),$+=Q}return $},AJ2=(A,...Q)=>{let $,w,B,X,Y=(W)=>{let K=Q.reduce((U,G)=>G(U),A());return $=NQ$(K),w=$.cache.get,B=$.cache.set,X=Z,Z(W)},Z=(W)=>{let K=w(W);if(K)return K;let U=kQ$(W,$);return B(W,U),U};return X=Y,(...W)=>X(jQ$(...W))},MQ$=[],S4=(A)=>{let Q=($)=>$[A]||MQ$;return Q.isThemeGetter=!0,Q},WJ2=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,KJ2=/^\((?:(\w[\w-]*):)?(.+)\)$/i,bQ$=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,OQ$=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,fQ$=/\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$/,xQ$=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,RQ$=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,vQ$=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,DO=(A)=>bQ$.test(A),T$=(A)=>!!A&&!Number.isNaN(Number(A)),vF=(A)=>!!A&&Number.isInteger(Number(A)),GZA=(A)=>A.endsWith("%")&&T$(A.slice(0,-1)),a_=(A)=>OQ$.test(A),UJ2=()=>!0,CQ$=(A)=>fQ$.test(A)&&!xQ$.test(A),zZA=()=>!1,hQ$=(A)=>RQ$.test(A),EQ$=(A)=>vQ$.test(A),TQ$=(A)=>!n2(A)&&!t2(A),yQ$=(A)=>A.startsWith("@container")&&(A[10]==="/"&&A[11]!==void 0||A[11]==="s"&&A[16]!==void 0&&A.startsWith("-size/",10)||A[11]==="n"&&A[18]!==void 0&&A.startsWith("-normal/",10)),gQ$=(A)=>qO(A,qJ2,zZA),n2=(A)=>WJ2.test(A),BE=(A)=>qO(A,zJ2,CQ$),QJ2=(A)=>qO(A,iQ$,T$),SQ$=(A)=>qO(A,JJ2,UJ2),mQ$=(A)=>qO(A,VJ2,zZA),$J2=(A)=>qO(A,GJ2,zZA),uQ$=(A)=>qO(A,DJ2,EQ$),oL0=(A)=>qO(A,FJ2,hQ$),t2=(A)=>KJ2.test(A),n$0=(A)=>XE(A,zJ2),cQ$=(A)=>XE(A,VJ2),wJ2=(A)=>XE(A,GJ2),pQ$=(A)=>XE(A,qJ2),lQ$=(A)=>XE(A,DJ2),sL0=(A)=>XE(A,FJ2,!0),dQ$=(A)=>XE(A,JJ2,!0),qO=(A,Q,$)=>{let w=WJ2.exec(A);if(w){if(w[1])return Q(w[1]);return $(w[2])}return!1},XE=(A,Q,$=!1)=>{let w=KJ2.exec(A);if(w){if(w[1])return Q(w[1]);return $}return!1},GJ2=(A)=>A==="position"||A==="percentage",DJ2=(A)=>A==="image"||A==="url",qJ2=(A)=>A==="length"||A==="size"||A==="bg-size",zJ2=(A)=>A==="length",iQ$=(A)=>A==="number",VJ2=(A)=>A==="family-name",JJ2=(A)=>A==="number"||A==="weight",FJ2=(A)=>A==="shadow";var BJ2=()=>{let A=S4("color"),Q=S4("font"),$=S4("text"),w=S4("font-weight"),B=S4("tracking"),X=S4("leading"),Y=S4("breakpoint"),Z=S4("container"),W=S4("spacing"),K=S4("radius"),U=S4("shadow"),G=S4("inset-shadow"),D=S4("text-shadow"),q=S4("drop-shadow"),J=S4("blur"),F=S4("perspective"),I=S4("aspect"),P=S4("ease"),j=S4("animate"),k=()=>["auto","avoid","all","avoid-page","page","left","right","column"],f=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...f(),t2,n2],x=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto","contain","none"],g=()=>[t2,n2,W],u=()=>[DO,"full","auto",...g()],n=()=>[vF,"none","subgrid",t2,n2],t=()=>["auto",{span:["full",vF,t2,n2]},vF,t2,n2],B0=()=>[vF,"auto",t2,n2],l=()=>["auto","min","max","fr",t2,n2],b=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],T=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...g()],o=()=>[DO,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...g()],a=()=>[DO,"screen","full","dvw","lvw","svw","min","max","fit",...g()],q0=()=>[DO,"screen","full","lh","dvh","lvh","svh","min","max","fit",...g()],S=()=>[A,t2,n2],H0=()=>[...f(),wJ2,$J2,{position:[t2,n2]}],N0=()=>["no-repeat",{repeat:["","x","y","space","round"]}],i=()=>["auto","cover","contain",pQ$,gQ$,{size:[t2,n2]}],u0=()=>[GZA,n$0,BE],i0=()=>["","none","full",K,t2,n2],k0=()=>["",T$,n$0,BE],j0=()=>["solid","dashed","dotted","double"],h0=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],m0=()=>[T$,GZA,wJ2,$J2],b0=()=>["","none",J,t2,n2],O0=()=>["none",T$,t2,n2],g0=()=>["none",T$,t2,n2],S0=()=>[T$,t2,n2],r0=()=>[DO,"full",...g()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[a_],breakpoint:[a_],color:[UJ2],container:[a_],"drop-shadow":[a_],ease:["in","out","in-out"],font:[TQ$],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[a_],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[a_],shadow:[a_],spacing:["px",T$],text:[a_],"text-shadow":[a_],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",DO,n2,t2,I]}],container:["container"],"container-type":[{"@container":["","normal","size",t2,n2]}],"container-named":[yQ$],columns:[{columns:[T$,n2,t2,Z]}],"break-after":[{"break-after":k()}],"break-before":[{"break-before":k()}],"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"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:R()}],overflow:[{overflow:x()}],"overflow-x":[{"overflow-x":x()}],"overflow-y":[{"overflow-y":x()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:u()}],"inset-x":[{"inset-x":u()}],"inset-y":[{"inset-y":u()}],start:[{"inset-s":u(),start:u()}],end:[{"inset-e":u(),end:u()}],"inset-bs":[{"inset-bs":u()}],"inset-be":[{"inset-be":u()}],top:[{top:u()}],right:[{right:u()}],bottom:[{bottom:u()}],left:[{left:u()}],visibility:["visible","invisible","collapse"],z:[{z:[vF,"auto",t2,n2]}],basis:[{basis:[DO,"full","auto",Z,...g()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[T$,DO,"auto","initial","none",n2]}],grow:[{grow:["",T$,t2,n2]}],shrink:[{shrink:["",T$,t2,n2]}],order:[{order:[vF,"first","last","none",t2,n2]}],"grid-cols":[{"grid-cols":n()}],"col-start-end":[{col:t()}],"col-start":[{"col-start":B0()}],"col-end":[{"col-end":B0()}],"grid-rows":[{"grid-rows":n()}],"row-start-end":[{row:t()}],"row-start":[{"row-start":B0()}],"row-end":[{"row-end":B0()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":l()}],"auto-rows":[{"auto-rows":l()}],gap:[{gap:g()}],"gap-x":[{"gap-x":g()}],"gap-y":[{"gap-y":g()}],"justify-content":[{justify:[...b(),"normal"]}],"justify-items":[{"justify-items":[...T(),"normal"]}],"justify-self":[{"justify-self":["auto",...T()]}],"align-content":[{content:["normal",...b()]}],"align-items":[{items:[...T(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...T(),{baseline:["","last"]}]}],"place-content":[{"place-content":b()}],"place-items":[{"place-items":[...T(),"baseline"]}],"place-self":[{"place-self":["auto",...T()]}],p:[{p:g()}],px:[{px:g()}],py:[{py:g()}],ps:[{ps:g()}],pe:[{pe:g()}],pbs:[{pbs:g()}],pbe:[{pbe:g()}],pt:[{pt:g()}],pr:[{pr:g()}],pb:[{pb:g()}],pl:[{pl:g()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":g()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":g()}],"space-y-reverse":["space-y-reverse"],size:[{size:o()}],"inline-size":[{inline:["auto",...a()]}],"min-inline-size":[{"min-inline":["auto",...a()]}],"max-inline-size":[{"max-inline":["none",...a()]}],"block-size":[{block:["auto",...q0()]}],"min-block-size":[{"min-block":["auto",...q0()]}],"max-block-size":[{"max-block":["none",...q0()]}],w:[{w:[Z,"screen",...o()]}],"min-w":[{"min-w":[Z,"screen","none",...o()]}],"max-w":[{"max-w":[Z,"screen","none","prose",{screen:[Y]},...o()]}],h:[{h:["screen","lh",...o()]}],"min-h":[{"min-h":["screen","lh","none",...o()]}],"max-h":[{"max-h":["screen","lh",...o()]}],"font-size":[{text:["base",$,n$0,BE]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[w,dQ$,SQ$]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",GZA,n2]}],"font-family":[{font:[cQ$,mQ$,Q]}],"font-features":[{"font-features":[n2]}],"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:[B,t2,n2]}],"line-clamp":[{"line-clamp":[T$,"none",t2,QJ2]}],leading:[{leading:[X,...g()]}],"list-image":[{"list-image":["none",t2,n2]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",t2,n2]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:S()}],"text-color":[{text:S()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...j0(),"wavy"]}],"text-decoration-thickness":[{decoration:[T$,"from-font","auto",t2,BE]}],"text-decoration-color":[{decoration:S()}],"underline-offset":[{"underline-offset":[T$,"auto",t2,n2]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:g()}],"tab-size":[{tab:[vF,t2,n2]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",t2,n2]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",t2,n2]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:H0()}],"bg-repeat":[{bg:N0()}],"bg-size":[{bg:i()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},vF,t2,n2],radial:["",t2,n2],conic:[vF,t2,n2]},lQ$,uQ$]}],"bg-color":[{bg:S()}],"gradient-from-pos":[{from:u0()}],"gradient-via-pos":[{via:u0()}],"gradient-to-pos":[{to:u0()}],"gradient-from":[{from:S()}],"gradient-via":[{via:S()}],"gradient-to":[{to:S()}],rounded:[{rounded:i0()}],"rounded-s":[{"rounded-s":i0()}],"rounded-e":[{"rounded-e":i0()}],"rounded-t":[{"rounded-t":i0()}],"rounded-r":[{"rounded-r":i0()}],"rounded-b":[{"rounded-b":i0()}],"rounded-l":[{"rounded-l":i0()}],"rounded-ss":[{"rounded-ss":i0()}],"rounded-se":[{"rounded-se":i0()}],"rounded-ee":[{"rounded-ee":i0()}],"rounded-es":[{"rounded-es":i0()}],"rounded-tl":[{"rounded-tl":i0()}],"rounded-tr":[{"rounded-tr":i0()}],"rounded-br":[{"rounded-br":i0()}],"rounded-bl":[{"rounded-bl":i0()}],"border-w":[{border:k0()}],"border-w-x":[{"border-x":k0()}],"border-w-y":[{"border-y":k0()}],"border-w-s":[{"border-s":k0()}],"border-w-e":[{"border-e":k0()}],"border-w-bs":[{"border-bs":k0()}],"border-w-be":[{"border-be":k0()}],"border-w-t":[{"border-t":k0()}],"border-w-r":[{"border-r":k0()}],"border-w-b":[{"border-b":k0()}],"border-w-l":[{"border-l":k0()}],"divide-x":[{"divide-x":k0()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":k0()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...j0(),"hidden","none"]}],"divide-style":[{divide:[...j0(),"hidden","none"]}],"border-color":[{border:S()}],"border-color-x":[{"border-x":S()}],"border-color-y":[{"border-y":S()}],"border-color-s":[{"border-s":S()}],"border-color-e":[{"border-e":S()}],"border-color-bs":[{"border-bs":S()}],"border-color-be":[{"border-be":S()}],"border-color-t":[{"border-t":S()}],"border-color-r":[{"border-r":S()}],"border-color-b":[{"border-b":S()}],"border-color-l":[{"border-l":S()}],"divide-color":[{divide:S()}],"outline-style":[{outline:[...j0(),"none","hidden"]}],"outline-offset":[{"outline-offset":[T$,t2,n2]}],"outline-w":[{outline:["",T$,n$0,BE]}],"outline-color":[{outline:S()}],shadow:[{shadow:["","none",U,sL0,oL0]}],"shadow-color":[{shadow:S()}],"inset-shadow":[{"inset-shadow":["none",G,sL0,oL0]}],"inset-shadow-color":[{"inset-shadow":S()}],"ring-w":[{ring:k0()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:S()}],"ring-offset-w":[{"ring-offset":[T$,BE]}],"ring-offset-color":[{"ring-offset":S()}],"inset-ring-w":[{"inset-ring":k0()}],"inset-ring-color":[{"inset-ring":S()}],"text-shadow":[{"text-shadow":["none",D,sL0,oL0]}],"text-shadow-color":[{"text-shadow":S()}],opacity:[{opacity:[T$,t2,n2]}],"mix-blend":[{"mix-blend":[...h0(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":h0()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[T$]}],"mask-image-linear-from-pos":[{"mask-linear-from":m0()}],"mask-image-linear-to-pos":[{"mask-linear-to":m0()}],"mask-image-linear-from-color":[{"mask-linear-from":S()}],"mask-image-linear-to-color":[{"mask-linear-to":S()}],"mask-image-t-from-pos":[{"mask-t-from":m0()}],"mask-image-t-to-pos":[{"mask-t-to":m0()}],"mask-image-t-from-color":[{"mask-t-from":S()}],"mask-image-t-to-color":[{"mask-t-to":S()}],"mask-image-r-from-pos":[{"mask-r-from":m0()}],"mask-image-r-to-pos":[{"mask-r-to":m0()}],"mask-image-r-from-color":[{"mask-r-from":S()}],"mask-image-r-to-color":[{"mask-r-to":S()}],"mask-image-b-from-pos":[{"mask-b-from":m0()}],"mask-image-b-to-pos":[{"mask-b-to":m0()}],"mask-image-b-from-color":[{"mask-b-from":S()}],"mask-image-b-to-color":[{"mask-b-to":S()}],"mask-image-l-from-pos":[{"mask-l-from":m0()}],"mask-image-l-to-pos":[{"mask-l-to":m0()}],"mask-image-l-from-color":[{"mask-l-from":S()}],"mask-image-l-to-color":[{"mask-l-to":S()}],"mask-image-x-from-pos":[{"mask-x-from":m0()}],"mask-image-x-to-pos":[{"mask-x-to":m0()}],"mask-image-x-from-color":[{"mask-x-from":S()}],"mask-image-x-to-color":[{"mask-x-to":S()}],"mask-image-y-from-pos":[{"mask-y-from":m0()}],"mask-image-y-to-pos":[{"mask-y-to":m0()}],"mask-image-y-from-color":[{"mask-y-from":S()}],"mask-image-y-to-color":[{"mask-y-to":S()}],"mask-image-radial":[{"mask-radial":[t2,n2]}],"mask-image-radial-from-pos":[{"mask-radial-from":m0()}],"mask-image-radial-to-pos":[{"mask-radial-to":m0()}],"mask-image-radial-from-color":[{"mask-radial-from":S()}],"mask-image-radial-to-color":[{"mask-radial-to":S()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":f()}],"mask-image-conic-pos":[{"mask-conic":[T$]}],"mask-image-conic-from-pos":[{"mask-conic-from":m0()}],"mask-image-conic-to-pos":[{"mask-conic-to":m0()}],"mask-image-conic-from-color":[{"mask-conic-from":S()}],"mask-image-conic-to-color":[{"mask-conic-to":S()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:H0()}],"mask-repeat":[{mask:N0()}],"mask-size":[{mask:i()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",t2,n2]}],filter:[{filter:["","none",t2,n2]}],blur:[{blur:b0()}],brightness:[{brightness:[T$,t2,n2]}],contrast:[{contrast:[T$,t2,n2]}],"drop-shadow":[{"drop-shadow":["","none",q,sL0,oL0]}],"drop-shadow-color":[{"drop-shadow":S()}],grayscale:[{grayscale:["",T$,t2,n2]}],"hue-rotate":[{"hue-rotate":[T$,t2,n2]}],invert:[{invert:["",T$,t2,n2]}],saturate:[{saturate:[T$,t2,n2]}],sepia:[{sepia:["",T$,t2,n2]}],"backdrop-filter":[{"backdrop-filter":["","none",t2,n2]}],"backdrop-blur":[{"backdrop-blur":b0()}],"backdrop-brightness":[{"backdrop-brightness":[T$,t2,n2]}],"backdrop-contrast":[{"backdrop-contrast":[T$,t2,n2]}],"backdrop-grayscale":[{"backdrop-grayscale":["",T$,t2,n2]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[T$,t2,n2]}],"backdrop-invert":[{"backdrop-invert":["",T$,t2,n2]}],"backdrop-opacity":[{"backdrop-opacity":[T$,t2,n2]}],"backdrop-saturate":[{"backdrop-saturate":[T$,t2,n2]}],"backdrop-sepia":[{"backdrop-sepia":["",T$,t2,n2]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":g()}],"border-spacing-x":[{"border-spacing-x":g()}],"border-spacing-y":[{"border-spacing-y":g()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",t2,n2]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[T$,"initial",t2,n2]}],ease:[{ease:["linear","initial",P,t2,n2]}],delay:[{delay:[T$,t2,n2]}],animate:[{animate:["none",j,t2,n2]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[F,t2,n2]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:O0()}],"rotate-x":[{"rotate-x":O0()}],"rotate-y":[{"rotate-y":O0()}],"rotate-z":[{"rotate-z":O0()}],scale:[{scale:g0()}],"scale-x":[{"scale-x":g0()}],"scale-y":[{"scale-y":g0()}],"scale-z":[{"scale-z":g0()}],"scale-3d":["scale-3d"],skew:[{skew:S0()}],"skew-x":[{"skew-x":S0()}],"skew-y":[{"skew-y":S0()}],transform:[{transform:[t2,n2,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:r0()}],"translate-x":[{"translate-x":r0()}],"translate-y":[{"translate-y":r0()}],"translate-z":[{"translate-z":r0()}],"translate-none":["translate-none"],zoom:[{zoom:[vF,t2,n2]}],accent:[{accent:S()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:S()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],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",t2,n2]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":S()}],"scrollbar-track-color":[{"scrollbar-track":S()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":g()}],"scroll-mx":[{"scroll-mx":g()}],"scroll-my":[{"scroll-my":g()}],"scroll-ms":[{"scroll-ms":g()}],"scroll-me":[{"scroll-me":g()}],"scroll-mbs":[{"scroll-mbs":g()}],"scroll-mbe":[{"scroll-mbe":g()}],"scroll-mt":[{"scroll-mt":g()}],"scroll-mr":[{"scroll-mr":g()}],"scroll-mb":[{"scroll-mb":g()}],"scroll-ml":[{"scroll-ml":g()}],"scroll-p":[{"scroll-p":g()}],"scroll-px":[{"scroll-px":g()}],"scroll-py":[{"scroll-py":g()}],"scroll-ps":[{"scroll-ps":g()}],"scroll-pe":[{"scroll-pe":g()}],"scroll-pbs":[{"scroll-pbs":g()}],"scroll-pbe":[{"scroll-pbe":g()}],"scroll-pt":[{"scroll-pt":g()}],"scroll-pr":[{"scroll-pr":g()}],"scroll-pb":[{"scroll-pb":g()}],"scroll-pl":[{"scroll-pl":g()}],"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",t2,n2]}],fill:[{fill:["none",...S()]}],"stroke-w":[{stroke:[T$,n$0,BE,QJ2]}],stroke:[{stroke:["none",...S()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","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","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","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-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","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-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","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"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","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-pbs","scroll-pbe","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"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},nQ$=(A,{cacheSize:Q,prefix:$,experimentalParseClassName:w,extend:B={},override:X={}})=>{return hd(A,"cacheSize",Q),hd(A,"prefix",$),hd(A,"experimentalParseClassName",w),aL0(A.theme,X.theme),aL0(A.classGroups,X.classGroups),aL0(A.conflictingClassGroups,X.conflictingClassGroups),aL0(A.conflictingClassGroupModifiers,X.conflictingClassGroupModifiers),hd(A,"postfixLookupClassGroups",X.postfixLookupClassGroups),hd(A,"orderSensitiveModifiers",X.orderSensitiveModifiers),tL0(A.theme,B.theme),tL0(A.classGroups,B.classGroups),tL0(A.conflictingClassGroups,B.conflictingClassGroups),tL0(A.conflictingClassGroupModifiers,B.conflictingClassGroupModifiers),DZA(A,B,"postfixLookupClassGroups"),DZA(A,B,"orderSensitiveModifiers"),A},hd=(A,Q,$)=>{if($!==void 0)A[Q]=$},aL0=(A,Q)=>{if(Q)for(let $ in Q)hd(A,$,Q[$])},tL0=(A,Q)=>{if(Q)for(let $ in Q)DZA(A,Q,$)},DZA=(A,Q,$)=>{let w=Q[$];if(w!==void 0)A[$]=A[$]?A[$].concat(w):w},eL0=(A,...Q)=>typeof A==="function"?AJ2(BJ2,A,...Q):AJ2(()=>nQ$(BJ2(),A),...Q);var rQ$=eL0({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 e2(...A){return rQ$(Cd(A))}var IJ2=(A)=>typeof A==="boolean"?`${A}`:A===0?"0":A,LJ2=Cd,iw=(A,Q)=>($)=>{var w;if((Q===null||Q===void 0?void 0:Q.variants)==null)return LJ2(A,$===null||$===void 0?void 0:$.class,$===null||$===void 0?void 0:$.className);let{variants:B,defaultVariants:X}=Q,Y=Object.keys(B).map((K)=>{let U=$===null||$===void 0?void 0:$[K],G=X===null||X===void 0?void 0:X[K];if(U===null)return null;let D=IJ2(U)||IJ2(G);return B[K][D]}),Z=$&&Object.entries($).reduce((K,U)=>{let[G,D]=U;if(D===void 0)return K;return K[G]=D,K},{}),W=Q===null||Q===void 0?void 0:(w=Q.compoundVariants)===null||w===void 0?void 0:w.reduce((K,U)=>{let{class:G,className:D,...q}=U;return Object.entries(q).every((J)=>{let[F,I]=J;return Array.isArray(I)?I.includes({...X,...Z}[F]):{...X,...Z}[F]===I})?[...K,G,D]:K},[]);return LJ2(A,Y,W,$===null||$===void 0?void 0:$.class,$===null||$===void 0?void 0:$.className)};import{jsxDEV as VZA}from"preact/jsx-dev-runtime";var NJ2=iw("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 JZA({variant:A,title:Q,children:$,className:w}){return VZA("div",{className:e2(NJ2({variant:A}),w),role:"alert",children:[Q&&VZA("p",{className:"font-medium text-current opacity-90",children:Q},void 0,!1,void 0,this),VZA("div",{className:e2(Q&&"mt-1","text-sm text-current opacity-75"),children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{jsxDEV as oQ$}from"preact/jsx-dev-runtime";var _J2=iw("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 YE({variant:A,size:Q,className:$,children:w,ssrOnClick:B,type:X="button",...Y}){return oQ$("button",{type:X,className:e2(_J2({variant:A,size:Q}),$),...Y,...B&&{onclick:B},children:w},void 0,!1,void 0,this)}import{jsxDEV as sQ$}from"preact/jsx-dev-runtime";var PJ2=iw("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 m4({href:A,children:Q,variant:$,size:w,external:B=!1,className:X,"aria-label":Y}){let Z=B?{target:"_blank",rel:"noopener noreferrer"}:{};return sQ$("a",{href:A,className:e2(PJ2({variant:$,size:w}),X),"aria-label":Y,...Z,children:Q},void 0,!1,void 0,this)}import{jsxDEV as AN0}from"preact/jsx-dev-runtime";var kJ2=iw("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"}}),aQ$={sm:"w-4 h-4",md:"w-5 h-5",lg:"w-6 h-6"};function Ed({variant:A,size:Q,className:$}){let w=aQ$[Q??"md"];return AN0("button",{onclick:"toggleTheme()",type:"button",className:e2(kJ2({variant:A,size:Q}),$),"aria-label":"Toggle dark mode",children:AN0("svg",{className:e2(w,"transition-colors"),fill:"none",stroke:"currentColor",strokeWidth:1.6,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[AN0("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),AN0("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 FZA}from"preact/jsx-dev-runtime";var jJ2=iw("flex flex-wrap",{variants:{orientation:{horizontal:"justify-center gap-6 items-center",vertical:"flex-col gap-2.5"}},defaultVariants:{orientation:"horizontal"}});function QN0({items:A,className:Q,linkClassName:$="hover:text-accent transition-colors",orientation:w,children:B}){if(A.length===0&&!B)return null;let X=[...A].sort((Y,Z)=>Y.priority-Z.priority);return FZA("ul",{className:e2(jJ2({orientation:w}),Q),children:[X.map((Y)=>FZA("li",{children:FZA("a",{href:Y.href,className:$,children:Y.label},void 0,!1,void 0,this)},Y.href,!1,void 0,this)),B]},void 0,!0,void 0,this)}import{jsxDEV as TX5}from"preact/jsx-dev-runtime";import{jsxDEV as SX5}from"preact/jsx-dev-runtime";import{createContext as tQ$,h as eQ$}from"preact";import{useContext as A6$}from"preact/hooks";var IZA=tQ$(null);function Td({headCollector:A,children:Q}){return eQ$(IZA.Provider,{value:A},Q)}function MJ2(){return A6$(IZA)}function C6(A){let Q=MJ2();if(Q)Q.setHeadProps(A);return null}import{createContext as R9$,h as v9$}from"preact";import{useContext as C9$}from"preact/hooks";_0A();var TN2=P1(EN2(),1),f9$=new sq0({gfm:!0,breaks:!0}),x9$={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 lHA(A,Q){let{imageRenderer:$}=Q??{},B=($?new sq0({gfm:!0,breaks:!0}).use({renderer:{image({href:X,title:Y,text:Z}){return $(X,Y,Z)??!1}}}):f9$).parse(A);return B=B.replace(/<\/blockquote>\s*<p>(\u2014|--|\u2013)([\s\S]*?)<\/p>/g,`</blockquote>
5792
5792
  <cite class="block-attribution"><span class="emdash">$1</span>$2</cite>`),TN2.default(B,x9$)}var yN2=R9$(null);function ed({imageRenderer:A,children:Q}){return v9$(yN2.Provider,{value:A??null},Q)}function gN2(){return C9$(yN2)}function XP(){let A=gN2();return(Q)=>lHA(Q,A?{imageRenderer:A}:void 0)}var h9$=/<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,E9$={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},T9$=/&(?:amp|lt|gt|quot|#39);/g;function y9$(A){return A.replace(T9$,(Q)=>E9$[Q]??Q)}function dHA(A){return A.replace(h9$,(Q,$)=>{return`<div class="mermaid">${y9$($)}</div>`})}var SN2=/<!--\s*\.slide:\s*(.*?)\s*-->/g;function mN2(A){let Q={};for(let w of A.matchAll(SN2)){let B=w[1]??"";for(let Y of B.matchAll(/([\w-]+)=["']([^"']*?)["']/g)){let Z=Y[1],W=Y[2];if(Z&&W!==void 0)Q[Z]=W}let X=B.replace(/([\w-]+)=["']([^"']*?)["']/g,"").trim();if(X)for(let Y of X.matchAll(/(?:^|\s)([\w-]+)(?=\s|$)/g)){let Z=Y[1];if(Z)Q[Z]="true"}}let $=A.replace(SN2,"").replace(/^\n+/,"").replace(/\n{3,}/g,`
5793
5793
 
5794
5794
  `).trim();return{attributes:Q,markdown:$}}var g9$=/<!--\s*\.break\s*-->/;function uN2(A){let Q=A.split(g9$);return Q.length>1?Q:null}import{jsxDEV as SF}from"preact/jsx-dev-runtime";var iHA=({markdown:A,deck:Q})=>{let $=XP(),B=A.split(/^---$/gm).map((U)=>U.trim()).map((U)=>{let{attributes:G,markdown:D}=mN2(U),q=uN2(D),J;if(q)J=`<div class="slide-columns">${q.map((I)=>`<div class="slide-column">${dHA($(I.trim()))}</div>`).join("")}</div>`;else J=dHA($(D));return{attributes:G,htmlContent:J}}),X=B.some((U)=>U.htmlContent.includes('class="mermaid"')),Y=Q?.frontmatter?.title??Q?.metadata?.title,Z=Q?.frontmatter?.description??Q?.metadata?.description,W=Q?.ogImageUrl??Q?.coverImageUrl,K=B.map(({attributes:U,htmlContent:G},D)=>SF("section",{...U,dangerouslySetInnerHTML:{__html:G}},D,!1,void 0,this));return SF("section",{className:"presentation-section",children:[Y&&SF(C6,{title:Y,...Z?{description:Z}:{},...W?{ogImage:W}:{},ogType:"article"},void 0,!1,void 0,this),SF("link",{rel:"stylesheet",href:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.css"},void 0,!1,void 0,this),SF("div",{className:"reveal",children:SF("div",{className:"slides",children:K},void 0,!1,void 0,this)},void 0,!1,void 0,this),SF("script",{src:"https://cdn.jsdelivr.net/npm/reveal.js@5.1.0/dist/reveal.min.js",defer:!0},void 0,!1,void 0,this),X&&SF("script",{src:"https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js",defer:!0},void 0,!1,void 0,this),SF("script",{dangerouslySetInnerHTML:{__html:`
@@ -6775,13 +6775,13 @@ ${A.map((X)=>({url:`${Q}${X.path}`,lastmod:$,changefreq:X.path==="/"?"daily":"we
6775
6775
  `+B:$,Y=aF(this.outputDir,"styles","main.css");await this.cssProcessor.process(X,Y,this.workingDir,this.outputDir,this.logger);let Z=await jY.readFile(Y,"utf-8"),W=w.length>0?w:Q;if(W.length>0){let K=W.join(`
6776
6776
  `)+`
6777
6777
 
6778
- `+Z;await jY.writeFile(Y,K,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=aF(process.cwd(),"public");try{await jY.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await jY.readdir(A,{withFileTypes:!0});for(let $ of Q){let w=aF(A,$.name),B=aF(this.outputDir,$.name);if($.isDirectory())await this.copyDirectory(w,B);else await jY.copyFile(w,B),this.logger.debug(`Copied static asset: ${$.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])=>{let B=$.startsWith("/")?$.slice(1):$,X=aF(this.outputDir,B);await jY.mkdir(FI$(X),{recursive:!0}),await jY.writeFile(X,w,"utf-8"),this.logger.debug(`Wrote inline static asset: ${B}`)}))}async copyDirectory(A,Q){await jY.mkdir(Q,{recursive:!0});let $=await jY.readdir(A,{withFileTypes:!0});for(let w of $){let B=aF(A,w.name),X=aF(Q,w.name);if(w.isDirectory())await this.copyDirectory(B,X);else await jY.copyFile(B,X)}}}function dUA(A){return new gv2(A)}XX();C0();C0();var II$=H.object({heading:H.string(),buttonText:H.string(),buttonLink:H.string()}),LI$=H.object({blurb:H.string().optional()}),Ci=H.object({title:H.string(),description:H.string(),url:H.string().optional(),copyright:H.string().optional(),logo:H.boolean().optional(),themeMode:H.enum(["light","dark"]).optional(),analyticsScript:H.string().optional(),cta:II$.optional(),sections:H.record(H.string(),LI$).optional()});var Sv2=H.object({environment:H.enum(["preview","production"]),outputDir:H.string(),workingDir:H.string().optional(),sharedImagesDir:H.string().default("./dist/images"),enableContentGeneration:H.boolean().default(!1),cleanBeforeBuild:H.boolean().default(!0),siteConfig:Ci,layouts:H.record(H.string(),H.any()),themeCSS:H.string().optional()}),jJ5=H.object({success:H.boolean(),outputDir:H.string(),filesGenerated:H.number(),routesBuilt:H.number(),errors:H.array(H.string()).optional(),warnings:H.array(H.string()).optional()});function mv2(A){let Q=A.list(),$=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:$}}function uv2(A,Q,$){let w=Q.getProfile(),B=$.getNavigationItems("primary"),X=$.getNavigationItems("secondary");return{...A,...w.socialLinks!==void 0&&{socialLinks:w.socialLinks},navigation:{primary:B,secondary:X},copyright:A.copyright??"Powered by Rizom"}}XX();JZ();XX();S2();C0();var NI$=H.looseObject({id:H.string(),entityType:H.string(),content:H.string(),metadata:H.looseObject({slug:H.string()})}),_I$=H.looseObject({content:H.string(),metadata:H.looseObject({width:H.number().optional(),height:H.number().optional()})});async function RP0(A,Q){let $=Q.urlGenerator??iY.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((f)=>RP0(f,{...Q,urlGenerator:$})));if(typeof A!=="object")return A;let w={},B=Object.entries(A),X=await Promise.all(B.map(([,f])=>RP0(f,{...Q,urlGenerator:$})));for(let f=0;f<B.length;f++){let R=B[f];if(R)w[R[0]]=X[f]}let Y=NI$.safeParse(A);if(!Y.success)return w;let Z=Y.data,W=Z.entityType,K=Z.metadata.slug,U=Q.pipelineContext.entityDisplay?.[W],G=U?U.label:W.charAt(0).toUpperCase()+W.slice(1),D=U?U.pluralName??U.label.toLowerCase()+"s":Dz(W),q=`/${D}`,J=D.charAt(0).toUpperCase()+D.slice(1),F=PA0(Z),I=await PI$(F,Q),P=kD0(Z)??F,j=await kI$(P,Q);return{...w,...Z,url:$.generateUrl(W,K),typeLabel:G,listUrl:q,listLabel:J,...I,...j&&{ogImageUrl:j}}}async function PI$(A,Q){let $=A?Q.imageBuildService?.get(A):void 0;if($)return{coverImageUrl:$.src,coverImageWidth:$.width,coverImageHeight:$.height,...$.srcset&&{coverImageSrcset:$.srcset,coverImageSizes:$.sizes}};let w=await pv2(A,Q.pipelineContext.services.entityService);if(!w)return{};return{coverImageUrl:w.url,...w.width&&{coverImageWidth:w.width},...w.height&&{coverImageHeight:w.height}}}async function kI$(A,Q){if(!A)return;let $=Q.imageBuildService?.get(A);if($)return cv2($.src,Q.siteUrl);let w=await pv2(A,Q.pipelineContext.services.entityService);if(!w)return;if(w.url.startsWith("data:"))return;return cv2(w.url,Q.siteUrl)}function cv2(A,Q){if(/^https?:\/\//i.test(A)||A.startsWith("data:"))return A;if(!Q)return A;return`${Q.replace(/\/$/,"")}/${A.replace(/^\//,"")}`}async function pv2(A,Q){if(!A)return;let $=await Q.getEntity({entityType:"image",id:A}),w=_I$.safeParse($);if(!w.success)return;return{url:w.data.content,...w.data.metadata.width&&{width:w.data.metadata.width},...w.data.metadata.height&&{height:w.data.metadata.height}}}async function lv2(A,Q){let $=new Set;try{let w=A.getEntityTypes();for(let B of w){if(B==="image")continue;let X=await A.listEntities({entityType:B});for(let Y of X){let Z=PA0(Y);if(Z)$.add(Z);let W=kD0(Y);if(W)$.add(W)}}}catch(w){Q.warn("Failed to collect image IDs for pre-resolution",{error:aA(w)})}return[...$]}async function dv2(A,Q,$,w,B){if(!A.template)return A.content??null;let X=A.template,Y={entityType:"site-content",entityId:`${Q.id}:${A.id}`},Z=A.dataQuery?{dataParams:A.dataQuery,savedContent:Y,fallback:A.content,publishedOnly:$,visibilityScope:w}:{savedContent:Y,fallback:A.content,visibilityScope:w},W=await B.pipelineContext.services.resolveTemplateContent(X,Z);if(!W)return null;return RP0(W,{pipelineContext:B.pipelineContext,imageBuildService:B.imageBuildService,siteUrl:B.siteUrl,urlGenerator:iY.getInstance()})}function iv2(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,$)=>{let w=A.parsedOptions.environment==="production";return dv2($,Q,w,"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 uv2(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 jI$}from"path";async function nv2(A){let Q=A.parsedOptions.workingDir??jI$(A.parsedOptions.outputDir,".preact-work"),$=A.staticSiteBuilderFactory({logger:A.logger.child("StaticSiteBuilder"),workingDir:Q,outputDir:A.parsedOptions.outputDir});if(A.parsedOptions.cleanBeforeBuild)await $.clean();return $}async function rv2(A){await new fP0({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 ov2(A){let Q=new OP0(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),$=await lv2(A.pipelineContext.services.entityService,A.pipelineContext.logger);if($.length>0)await Q.resolveAll($);return Q}async function sv2(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,($)=>{Q?.report($).catch(()=>{})})}function av2(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function tv2(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function ev2(A){let Q=Sv2.parse(A.buildOptions),$=XH.from(A.progress),w=[];try{await $?.report({message:"Starting site build",progress:0,total:100}),await $?.report({message:"Generating dynamic routes",progress:10,total:100}),await rv2({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let B=await nv2({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),X=mv2(A.pipelineContext.routeRegistry);w.push(...X.warnings);let{routes:Y}=X;await $?.report({message:`Building ${Y.length} routes`,progress:20,total:100}),await $?.report({message:"Resolving images",progress:25,total:100});let Z=await ov2({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),W=iv2({routes:Y,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:Z,siteMetadata:Q.siteConfig});return await sv2({staticSiteBuilder:B,buildContext:W,reporter:$}),await $?.report({message:"Site build complete",progress:100,total:100}),av2({outputDir:Q.outputDir,routesBuilt:Y.length,warnings:w})}catch(B){let X=Error("Site build process failed");return A.pipelineContext.logger.error("Site build failed",{error:X,originalError:B}),tv2({outputDir:Q.outputDir,errorMessage:X.message})}}class Rq{static instance=null;static defaultStaticSiteBuilderFactory=dUA;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){Rq.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,$,w,B=void 0){return Rq.instance??=new Rq(A,Rq.defaultStaticSiteBuilderFactory,Q,$,w,B),Rq.instance}static resetInstance(){Rq.instance=null}static createFresh(A,Q,$,w,B,X=void 0){return new Rq(A,B??Rq.defaultStaticSiteBuilderFactory,Q,$,w,X)}constructor(A,Q,$,w,B,X){this.pipelineContext={logger:A,services:$,routeRegistry:w,profileService:B,entityDisplay:X},this.staticSiteBuilderFactory=Q,iY.getInstance().configure(X)}async build(A,Q){return ev2({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}class iUA{config;context;pluginId;logger;debounces=new Map;unsubscribeFunctions=[];constructor(A,Q,$,w){this.config=A,this.context=Q,this.pluginId=$,this.logger=w}requestBuild(A){let Q=A??(this.config.previewOutputDir?"preview":"production"),$=this.debounces.get(Q);if(!$)$=new WZA(()=>{this.enqueueBuild(Q)},this.config.rebuildDebounce),this.debounces.set(Q,$);$.trigger()}setupAutoRebuild(){let A=new Set(["note"]),Q=async(w)=>{let{entityType:B}=w.payload;if(!A.has(B))this.logger.debug(`Entity type ${B} will trigger rebuild`),this.requestBuild();return{success:!0}},$=["entity:created","entity:updated","entity:deleted"];for(let w of $)this.unsubscribeFunctions.push(this.context.messaging.subscribe(w,Q));this.logger.debug(`Auto-rebuild enabled (${this.config.rebuildDebounce}ms debounce), excluding types: ${[...A].join(", ")}`)}dispose(){for(let A of this.debounces.values())A.dispose();this.debounces.clear();for(let A of this.unsubscribeFunctions)A();this.unsubscribeFunctions=[]}async enqueueBuild(A){let Q=A==="production"?this.config.productionOutputDir:this.config.previewOutputDir;this.logger.debug(`Triggering ${A} site rebuild`);try{await this.context.jobs.enqueue({type:"site-build",data:{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:0,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip"}}),this.logger.debug("Site rebuild enqueued")}catch($){this.logger.error("Failed to enqueue site rebuild",{error:$})}}}XX();function MI$(A,Q){return A.map(($)=>({...$,template:$.template.includes(":")?$.template:`${Q}:${$.template}`}))}function vP0(A,Q,$){for(let w of A)$.register({...w,pluginId:Q,sections:w.sections?MI$(w.sections,Q):[]})}function AC2(A,Q,$){A.messaging.subscribe("plugin:site-builder:route:register",async(w)=>{try{let B=y40.parse(w.payload),{routes:X,pluginId:Y}=B;return vP0(X,Y,Q),{success:!0}}catch(B){return $.error("Failed to register routes",{error:B}),{success:!1,error:"Failed to register routes"}}}),A.messaging.subscribe("plugin:site-builder:route:unregister",async(w)=>{try{let B=g40.parse(w.payload),{paths:X,pluginId:Y}=B;if(X)for(let Z of X)Q.unregister(Z);else if(Y)Q.unregisterByPlugin(Y);return{success:!0}}catch(B){return $.error("Failed to unregister routes",{error:B}),{success:!1,error:"Failed to unregister routes"}}}),A.messaging.subscribe("plugin:site-builder:route:list",async(w)=>{try{let B=S40.parse(w.payload);return{success:!0,data:{routes:Q.list(B.pluginId?B:void 0)}}}catch(B){return $.error("Failed to list routes",{error:B}),{success:!1,error:"Failed to list routes"}}}),A.messaging.subscribe("plugin:site-builder:route:get",async(w)=>{try{let B=m40.parse(w.payload);return{success:!0,data:{route:Q.get(B.path)}}}catch(B){return $.error("Failed to get route",{error:B}),{success:!1,error:"Failed to get route"}}}),A.messaging.subscribe("site-builder:routes:list",async()=>{return{success:!0,data:Q.list()}})}import{promises as QC2}from"fs";import{join as $C2}from"path";async function bI$(A,Q,$){let w=A.siteConfig.url??"https://example.com",B=Q.list(),X=pUA(w,A.environment);await QC2.writeFile($C2(A.outputDir,"robots.txt"),X,"utf-8"),$.info(`Generated robots.txt for ${A.environment} environment`);let Y=lUA(B,w);await QC2.writeFile($C2(A.outputDir,"sitemap.xml"),Y,"utf-8"),$.info(`Generated sitemap.xml with ${B.length} URLs`)}function wC2(A){let{context:Q,routeRegistry:$,logger:w}=A;Q.messaging.subscribe("site:build:completed",async(B)=>{try{let X=B.payload;return w.info(`Received site:build:completed event for ${X.environment} environment - generating SEO files`),await bI$(X,$,w),{success:!0}}catch(X){return w.error("Failed to generate SEO files",X),{success:!1}}})}KA();C0();var BC2=H.object({environment:H.enum(["preview","production"]).optional(),outputDir:H.string(),workingDir:H.string().optional(),enableContentGeneration:H.boolean().optional(),siteConfig:Ci.optional()});XX();XX();C0();var OI$=H.object({heading:H.string(),buttonText:H.string(),buttonLink:H.string()}),fI$=H.object({blurb:H.string().optional()}),XC2=H.object({title:H.string(),description:H.string(),url:H.string().optional(),copyright:H.string().optional(),logo:H.boolean().optional(),themeMode:H.enum(["light","dark"]).optional(),analyticsScript:H.string().optional(),cta:OI$.optional(),sections:H.record(H.string(),fI$).optional()});async function Iw0(A,Q){try{let $=await A({type:so,payload:void 0});if("success"in $&&$.success&&$.data){let w=XC2.safeParse($.data);if(w.success)return XC2.parse({...Q,...w.data})}}catch{}return Q}class nUA extends X8{sendMessage;cfg;constructor(A,Q,$){super(A,{schema:BC2,jobTypeName:"site-build"});this.sendMessage=Q,this.cfg=$}async process(A,Q,$){let w=A.environment??"preview",B=A.enableContentGeneration??!1;try{this.logger.debug("Starting site build job",{jobId:Q,environment:w,outputDir:A.outputDir}),await $.report({progress:0,total:100,message:`Starting site build for ${w} environment`});let X=$.createSub({scale:{start:10,end:90}}),Y=await Iw0(this.sendMessage,A.siteConfig??this.cfg.defaultSiteConfig),Z=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:B,environment:w,cleanBeforeBuild:!0,siteConfig:Y,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},X.toCallback());if(await $.report({progress:100,total:100,message:`Site build completed: ${Z.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:Q,environment:w,routesBuilt:Z.routesBuilt,success:Z.success}),Z.success){this.logger.info(`Emitting site:build:completed event for ${w} environment`);let W=w==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage({type:"site:build:completed",payload:{outputDir:A.outputDir,environment:w,routesBuilt:Z.routesBuilt,siteConfig:{...Y,url:W},generateEntityUrl:(K,U)=>iY.getInstance().generateUrl(K,U)},broadcast:!0})}return{success:Z.success,routesBuilt:Z.routesBuilt,outputDir:A.outputDir,environment:w,...Z.errors&&{errors:Z.errors},...Z.warnings&&{warnings:Z.warnings}}}catch(X){throw this.logger.error("Site build job failed",X),X}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}C0();XX();var xI$=H.object({slot:H.enum(Ek).optional().default("primary"),limit:H.number().optional()});class rUA{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,$){let w=xI$.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:w});let B=this.routeRegistry.getNavigationItems(w.slot),X=w.limit?B.slice(0,w.limit):B,Y=X.map((W)=>({label:W.label,href:W.href}));this.logger.debug("NavigationDataSource returning",{slot:w.slot,itemCount:X.length,items:Y});let Z={navigation:Y};return Q.parse(Z)}}XX();KA();C0();var RI$=H.object({environment:H.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function YC2(A,Q){return[p8(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'.",RI$,async($)=>{return Q($.environment),{success:!0,message:`Site build requested${$.environment?` for ${$.environment}`:""} (debounced)`,data:{}}},{sideEffects:"external",cli:{name:"build"}})]}C0();XX();var vI$=H.object({id:H.string(),template:H.string(),content:H.unknown().optional(),dataQuery:H.looseObject({entityType:H.string().optional(),template:H.string().optional(),query:H.looseObject({id:H.string().optional(),limit:H.number().optional(),offset:H.number().optional()}).optional()}).optional(),order:H.number().optional()}),CI$=H.object({show:H.boolean().default(!1),label:H.string().optional(),slot:H.enum(Ek).default("primary"),priority:H.number().min(0).max(100).default(50)}).optional(),hI$=H.object({id:H.string(),path:H.string(),title:H.string().default(""),pageLabel:H.string().optional(),description:H.string().default(""),sections:H.array(vI$).default([]),layout:H.string().default("default"),fullscreen:H.boolean().optional(),pluginId:H.string().optional(),sourceEntityType:H.string().optional(),external:H.boolean().optional(),navigation:CI$}),ZC2=H.object({previewOutputDir:H.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:H.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:H.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:H.string().optional().describe("Working directory for builds").default("./.preact-work"),siteInfo:Ci.default({title:"Brain",description:"A knowledge management system"}),themeCSS:H.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:H.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),templates:H.any().optional().describe("Template definitions to register"),routes:H.array(hI$).optional().describe("Routes to register"),layouts:H.record(H.string(),H.any()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:H.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:H.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),entityDisplay:H.record(H.string(),H.object({label:H.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:H.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')"),layout:H.string().optional().describe("Layout name for this entity type's generated routes (defaults to 'default')"),paginate:H.boolean().optional().describe("Enable pagination for list pages"),pageSize:H.number().optional().describe("Items per page (default: 10)"),navigation:H.object({show:H.boolean().optional().describe("Show in navigation"),slot:H.enum(Ek).optional().describe("Navigation slot (primary or secondary)"),priority:H.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:H.record(H.string(),H.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 HC2={name:"@brains/site-builder-plugin",version:"0.2.0-alpha.183",description:"Static site generation plugin for Brain system",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.20",preact:"^10.27.2","preact-render-to-string":"^6.7.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{clean:"rm -rf dist",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class oUA extends p6{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",HC2,{...A,layouts:Q},ZC2);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new xP0(A.logger),this._slotRegistry=new BP0,A.messaging.subscribe("plugin:site-builder:slot:register",async($)=>{let{slotName:w,pluginId:B,render:X,priority:Y}=$.payload;return this._slotRegistry?.register(w,{pluginId:B,render:X,...Y!==void 0&&{priority:Y}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async($)=>{let{pluginId:w,script:B}=$.payload;return this.headScripts.set(w,B),{success:!0}}),A.entities.registerDataSource(new rUA(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService={getProfile:()=>A.identity.getProfile()},AC2(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)vP0(this.config.routes,this.id,this.routeRegistry);let Q={entityService:A.entityService,sendMessage:A.messaging.send,resolveTemplateContent:($,w)=>A.templates.resolve($,w),getViewTemplate:($)=>A.views.get($),listViewTemplateNames:()=>A.views.list().map(($)=>$.name)};if(this.siteBuilder=Rq.createFresh(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,void 0,this.config.entityDisplay),A.jobs.registerHandler("site-build",new nUA(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 iUA(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe(ao,async()=>{let $=await this.getInstructions();if($)A.registerInstructions($);return{success:!0}}),wC2({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 YC2(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 Iw0(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(($)=>({id:$.id,path:$.path,title:$.title,description:$.description,sections:$.sections.map((w)=>({id:w.id,template:w.template}))})),null,2)}]}}},{uri:"site://templates",name:"View Templates",description:"All registered view templates",mimeType:"application/json",handler:async()=>{let Q=A.views.list();return{contents:[{uri:"site://templates",mimeType:"application/json",text:JSON.stringify(Q.map(($)=>({name:$.name,description:$.description,hasWebRenderer:!!$.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.",$=await Iw0(A.messaging.send,this.config.siteInfo);return`## Your Site
6778
+ `+Z;await jY.writeFile(Y,K,"utf-8")}this.logger.debug("CSS processed successfully with font imports")}async copyStaticAssets(){this.logger.debug("Copying static assets from public/ directory");let A=aF(process.cwd(),"public");try{await jY.access(A)}catch{this.logger.debug("No public/ directory found, skipping static assets");return}let Q=await jY.readdir(A,{withFileTypes:!0});for(let $ of Q){let w=aF(A,$.name),B=aF(this.outputDir,$.name);if($.isDirectory())await this.copyDirectory(w,B);else await jY.copyFile(w,B),this.logger.debug(`Copied static asset: ${$.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])=>{let B=$.startsWith("/")?$.slice(1):$,X=aF(this.outputDir,B);await jY.mkdir(FI$(X),{recursive:!0}),await jY.writeFile(X,w,"utf-8"),this.logger.debug(`Wrote inline static asset: ${B}`)}))}async copyDirectory(A,Q){await jY.mkdir(Q,{recursive:!0});let $=await jY.readdir(A,{withFileTypes:!0});for(let w of $){let B=aF(A,w.name),X=aF(Q,w.name);if(w.isDirectory())await this.copyDirectory(B,X);else await jY.copyFile(B,X)}}}function dUA(A){return new gv2(A)}XX();C0();C0();var II$=H.object({heading:H.string(),buttonText:H.string(),buttonLink:H.string()}),LI$=H.object({blurb:H.string().optional()}),Ci=H.object({title:H.string(),description:H.string(),url:H.string().optional(),copyright:H.string().optional(),logo:H.boolean().optional(),themeMode:H.enum(["light","dark"]).optional(),analyticsScript:H.string().optional(),cta:II$.optional(),sections:H.record(H.string(),LI$).optional()});var Sv2=H.object({environment:H.enum(["preview","production"]),outputDir:H.string(),workingDir:H.string().optional(),sharedImagesDir:H.string().default("./dist/images"),enableContentGeneration:H.boolean().default(!1),cleanBeforeBuild:H.boolean().default(!0),siteConfig:Ci,layouts:H.record(H.string(),H.any()),themeCSS:H.string().optional()}),jJ5=H.object({success:H.boolean(),outputDir:H.string(),filesGenerated:H.number(),routesBuilt:H.number(),errors:H.array(H.string()).optional(),warnings:H.array(H.string()).optional()});function mv2(A){let Q=A.list(),$=Q.length===0?["No routes registered for site build"]:[];return{routes:Q,warnings:$}}function uv2(A,Q,$){let w=Q.getProfile(),B=$.getNavigationItems("primary"),X=$.getNavigationItems("secondary");return{...A,...w.socialLinks!==void 0&&{socialLinks:w.socialLinks},navigation:{primary:B,secondary:X},copyright:A.copyright??"Powered by Rizom"}}XX();JZ();XX();S2();C0();var NI$=H.looseObject({id:H.string(),entityType:H.string(),content:H.string(),metadata:H.looseObject({slug:H.string()})}),_I$=H.looseObject({content:H.string(),metadata:H.looseObject({width:H.number().optional(),height:H.number().optional()})});async function RP0(A,Q){let $=Q.urlGenerator??iY.getInstance();if(A===null||A===void 0)return A;if(Array.isArray(A))return Promise.all(A.map((f)=>RP0(f,{...Q,urlGenerator:$})));if(typeof A!=="object")return A;let w={},B=Object.entries(A),X=await Promise.all(B.map(([,f])=>RP0(f,{...Q,urlGenerator:$})));for(let f=0;f<B.length;f++){let R=B[f];if(R)w[R[0]]=X[f]}let Y=NI$.safeParse(A);if(!Y.success)return w;let Z=Y.data,W=Z.entityType,K=Z.metadata.slug,U=Q.pipelineContext.entityDisplay?.[W],G=U?U.label:W.charAt(0).toUpperCase()+W.slice(1),D=U?U.pluralName??U.label.toLowerCase()+"s":Dz(W),q=`/${D}`,J=D.charAt(0).toUpperCase()+D.slice(1),F=PA0(Z),I=await PI$(F,Q),P=kD0(Z)??F,j=await kI$(P,Q);return{...w,...Z,url:$.generateUrl(W,K),typeLabel:G,listUrl:q,listLabel:J,...I,...j&&{ogImageUrl:j}}}async function PI$(A,Q){let $=A?Q.imageBuildService?.get(A):void 0;if($)return{coverImageUrl:$.src,coverImageWidth:$.width,coverImageHeight:$.height,...$.srcset&&{coverImageSrcset:$.srcset,coverImageSizes:$.sizes}};let w=await pv2(A,Q.pipelineContext.services.entityService);if(!w)return{};return{coverImageUrl:w.url,...w.width&&{coverImageWidth:w.width},...w.height&&{coverImageHeight:w.height}}}async function kI$(A,Q){if(!A)return;let $=Q.imageBuildService?.get(A);if($)return cv2($.src,Q.siteUrl);let w=await pv2(A,Q.pipelineContext.services.entityService);if(!w)return;if(w.url.startsWith("data:"))return;return cv2(w.url,Q.siteUrl)}function cv2(A,Q){if(/^https?:\/\//i.test(A)||A.startsWith("data:"))return A;if(!Q)return A;return`${Q.replace(/\/$/,"")}/${A.replace(/^\//,"")}`}async function pv2(A,Q){if(!A)return;let $=await Q.getEntity({entityType:"image",id:A}),w=_I$.safeParse($);if(!w.success)return;return{url:w.data.content,...w.data.metadata.width&&{width:w.data.metadata.width},...w.data.metadata.height&&{height:w.data.metadata.height}}}async function lv2(A,Q){let $=new Set;try{let w=A.getEntityTypes();for(let B of w){if(B==="image")continue;let X=await A.listEntities({entityType:B});for(let Y of X){let Z=PA0(Y);if(Z)$.add(Z);let W=kD0(Y);if(W)$.add(W)}}}catch(w){Q.warn("Failed to collect image IDs for pre-resolution",{error:aA(w)})}return[...$]}async function dv2(A,Q,$,w,B){if(!A.template)return A.content??null;let X=A.template,Y={entityType:"site-content",entityId:`${Q.id}:${A.id}`},Z=A.dataQuery?{dataParams:A.dataQuery,savedContent:Y,fallback:A.content,publishedOnly:$,visibilityScope:w}:{savedContent:Y,fallback:A.content,visibilityScope:w},W=await B.pipelineContext.services.resolveTemplateContent(X,Z);if(!W)return null;return RP0(W,{pipelineContext:B.pipelineContext,imageBuildService:B.imageBuildService,siteUrl:B.siteUrl,urlGenerator:iY.getInstance()})}function iv2(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,$)=>{let w=A.parsedOptions.environment==="production";return dv2($,Q,w,"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 uv2(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 jI$}from"path";async function nv2(A){let Q=A.parsedOptions.workingDir??jI$(A.parsedOptions.outputDir,".preact-work"),$=A.staticSiteBuilderFactory({logger:A.logger.child("StaticSiteBuilder"),workingDir:Q,outputDir:A.parsedOptions.outputDir});if(A.parsedOptions.cleanBeforeBuild)await $.clean();return $}async function rv2(A){await new fP0({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 ov2(A){let Q=new OP0(A.pipelineContext.services.entityService,A.pipelineContext.logger,A.sharedImagesDir),$=await lv2(A.pipelineContext.services.entityService,A.pipelineContext.logger);if($.length>0)await Q.resolveAll($);return Q}async function sv2(A){let Q=A.reporter?.createSub({scale:{start:85,end:95}});await A.staticSiteBuilder.build(A.buildContext,($)=>{Q?.report($).catch(()=>{})})}function av2(A){return{success:!0,outputDir:A.outputDir,filesGenerated:A.routesBuilt+1,routesBuilt:A.routesBuilt,...A.warnings.length>0&&{warnings:A.warnings}}}function tv2(A){return{success:!1,outputDir:A.outputDir,filesGenerated:0,routesBuilt:0,errors:[A.errorMessage]}}async function ev2(A){let Q=Sv2.parse(A.buildOptions),$=XH.from(A.progress),w=[];try{await $?.report({message:"Starting site build",progress:0,total:100}),await $?.report({message:"Generating dynamic routes",progress:10,total:100}),await rv2({pipelineContext:A.pipelineContext,publishedOnly:Q.environment==="production"});let B=await nv2({logger:A.pipelineContext.logger,parsedOptions:Q,staticSiteBuilderFactory:A.staticSiteBuilderFactory}),X=mv2(A.pipelineContext.routeRegistry);w.push(...X.warnings);let{routes:Y}=X;await $?.report({message:`Building ${Y.length} routes`,progress:20,total:100}),await $?.report({message:"Resolving images",progress:25,total:100});let Z=await ov2({pipelineContext:A.pipelineContext,sharedImagesDir:Q.sharedImagesDir}),W=iv2({routes:Y,parsedOptions:Q,buildOptions:A.buildOptions,pipelineContext:A.pipelineContext,imageBuildService:Z,siteMetadata:Q.siteConfig});return await sv2({staticSiteBuilder:B,buildContext:W,reporter:$}),await $?.report({message:"Site build complete",progress:100,total:100}),av2({outputDir:Q.outputDir,routesBuilt:Y.length,warnings:w})}catch(B){let X=Error("Site build process failed");return A.pipelineContext.logger.error("Site build failed",{error:X,originalError:B}),tv2({outputDir:Q.outputDir,errorMessage:X.message})}}class Rq{static instance=null;static defaultStaticSiteBuilderFactory=dUA;pipelineContext;staticSiteBuilderFactory;static setDefaultStaticSiteBuilderFactory(A){Rq.defaultStaticSiteBuilderFactory=A}static getInstance(A,Q,$,w,B=void 0){return Rq.instance??=new Rq(A,Rq.defaultStaticSiteBuilderFactory,Q,$,w,B),Rq.instance}static resetInstance(){Rq.instance=null}static createFresh(A,Q,$,w,B,X=void 0){return new Rq(A,B??Rq.defaultStaticSiteBuilderFactory,Q,$,w,X)}constructor(A,Q,$,w,B,X){this.pipelineContext={logger:A,services:$,routeRegistry:w,profileService:B,entityDisplay:X},this.staticSiteBuilderFactory=Q,iY.getInstance().configure(X)}async build(A,Q){return ev2({buildOptions:A,progress:Q,pipelineContext:this.pipelineContext,staticSiteBuilderFactory:this.staticSiteBuilderFactory})}}class iUA{config;context;pluginId;logger;debounces=new Map;unsubscribeFunctions=[];constructor(A,Q,$,w){this.config=A,this.context=Q,this.pluginId=$,this.logger=w}requestBuild(A){let Q=A??(this.config.previewOutputDir?"preview":"production"),$=this.debounces.get(Q);if(!$)$=new WZA(()=>{this.enqueueBuild(Q)},this.config.rebuildDebounce),this.debounces.set(Q,$);$.trigger()}setupAutoRebuild(){let A=new Set(["note"]),Q=async(w)=>{let{entityType:B}=w.payload;if(!A.has(B))this.logger.debug(`Entity type ${B} will trigger rebuild`),this.requestBuild();return{success:!0}},$=["entity:created","entity:updated","entity:deleted"];for(let w of $)this.unsubscribeFunctions.push(this.context.messaging.subscribe(w,Q));this.logger.debug(`Auto-rebuild enabled (${this.config.rebuildDebounce}ms debounce), excluding types: ${[...A].join(", ")}`)}dispose(){for(let A of this.debounces.values())A.dispose();this.debounces.clear();for(let A of this.unsubscribeFunctions)A();this.unsubscribeFunctions=[]}async enqueueBuild(A){let Q=A==="production"?this.config.productionOutputDir:this.config.previewOutputDir;this.logger.debug(`Triggering ${A} site rebuild`);try{await this.context.jobs.enqueue({type:"site-build",data:{environment:A,outputDir:Q,workingDir:this.config.workingDir,enableContentGeneration:!0,metadata:{trigger:"debounced-rebuild",timestamp:new Date().toISOString()}},options:{priority:0,source:this.pluginId,metadata:{operationType:"content_operations"},deduplication:"skip"}}),this.logger.debug("Site rebuild enqueued")}catch($){this.logger.error("Failed to enqueue site rebuild",{error:$})}}}XX();function MI$(A,Q){return A.map(($)=>({...$,template:$.template.includes(":")?$.template:`${Q}:${$.template}`}))}function vP0(A,Q,$){for(let w of A)$.register({...w,pluginId:Q,sections:w.sections?MI$(w.sections,Q):[]})}function AC2(A,Q,$){A.messaging.subscribe("plugin:site-builder:route:register",async(w)=>{try{let B=y40.parse(w.payload),{routes:X,pluginId:Y}=B;return vP0(X,Y,Q),{success:!0}}catch(B){return $.error("Failed to register routes",{error:B}),{success:!1,error:"Failed to register routes"}}}),A.messaging.subscribe("plugin:site-builder:route:unregister",async(w)=>{try{let B=g40.parse(w.payload),{paths:X,pluginId:Y}=B;if(X)for(let Z of X)Q.unregister(Z);else if(Y)Q.unregisterByPlugin(Y);return{success:!0}}catch(B){return $.error("Failed to unregister routes",{error:B}),{success:!1,error:"Failed to unregister routes"}}}),A.messaging.subscribe("plugin:site-builder:route:list",async(w)=>{try{let B=S40.parse(w.payload);return{success:!0,data:{routes:Q.list(B.pluginId?B:void 0)}}}catch(B){return $.error("Failed to list routes",{error:B}),{success:!1,error:"Failed to list routes"}}}),A.messaging.subscribe("plugin:site-builder:route:get",async(w)=>{try{let B=m40.parse(w.payload);return{success:!0,data:{route:Q.get(B.path)}}}catch(B){return $.error("Failed to get route",{error:B}),{success:!1,error:"Failed to get route"}}}),A.messaging.subscribe("site-builder:routes:list",async()=>{return{success:!0,data:Q.list()}})}import{promises as QC2}from"fs";import{join as $C2}from"path";async function bI$(A,Q,$){let w=A.siteConfig.url??"https://example.com",B=Q.list(),X=pUA(w,A.environment);await QC2.writeFile($C2(A.outputDir,"robots.txt"),X,"utf-8"),$.info(`Generated robots.txt for ${A.environment} environment`);let Y=lUA(B,w);await QC2.writeFile($C2(A.outputDir,"sitemap.xml"),Y,"utf-8"),$.info(`Generated sitemap.xml with ${B.length} URLs`)}function wC2(A){let{context:Q,routeRegistry:$,logger:w}=A;Q.messaging.subscribe("site:build:completed",async(B)=>{try{let X=B.payload;return w.info(`Received site:build:completed event for ${X.environment} environment - generating SEO files`),await bI$(X,$,w),{success:!0}}catch(X){return w.error("Failed to generate SEO files",X),{success:!1}}})}KA();C0();var BC2=H.object({environment:H.enum(["preview","production"]).optional(),outputDir:H.string(),workingDir:H.string().optional(),enableContentGeneration:H.boolean().optional(),siteConfig:Ci.optional()});XX();XX();C0();var OI$=H.object({heading:H.string(),buttonText:H.string(),buttonLink:H.string()}),fI$=H.object({blurb:H.string().optional()}),XC2=H.object({title:H.string(),description:H.string(),url:H.string().optional(),copyright:H.string().optional(),logo:H.boolean().optional(),themeMode:H.enum(["light","dark"]).optional(),analyticsScript:H.string().optional(),cta:OI$.optional(),sections:H.record(H.string(),fI$).optional()});async function Iw0(A,Q){try{let $=await A({type:so,payload:void 0});if("success"in $&&$.success&&$.data){let w=XC2.safeParse($.data);if(w.success)return XC2.parse({...Q,...w.data})}}catch{}return Q}class nUA extends X8{sendMessage;cfg;constructor(A,Q,$){super(A,{schema:BC2,jobTypeName:"site-build"});this.sendMessage=Q,this.cfg=$}async process(A,Q,$){let w=A.environment??"preview",B=A.enableContentGeneration??!1;try{this.logger.debug("Starting site build job",{jobId:Q,environment:w,outputDir:A.outputDir}),await $.report({progress:0,total:100,message:`Starting site build for ${w} environment`});let X=$.createSub({scale:{start:10,end:90}}),Y=await Iw0(this.sendMessage,A.siteConfig??this.cfg.defaultSiteConfig),Z=await this.cfg.siteBuilder.build({outputDir:A.outputDir,workingDir:A.workingDir,sharedImagesDir:this.cfg.sharedImagesDir,enableContentGeneration:B,environment:w,cleanBeforeBuild:!0,siteConfig:Y,layouts:this.cfg.layouts,themeCSS:this.cfg.themeCSS,slots:this.cfg.slots,headScripts:this.cfg.getHeadScripts?.(),...this.cfg.staticAssets&&{staticAssets:this.cfg.staticAssets}},X.toCallback());if(await $.report({progress:100,total:100,message:`Site build completed: ${Z.routesBuilt} routes built`}),this.logger.debug("Site build job completed",{jobId:Q,environment:w,routesBuilt:Z.routesBuilt,success:Z.success}),Z.success){this.logger.info(`Emitting site:build:completed event for ${w} environment`);let W=w==="preview"?this.cfg.previewUrl??this.cfg.siteUrl:this.cfg.siteUrl;await this.sendMessage({type:"site:build:completed",payload:{outputDir:A.outputDir,environment:w,routesBuilt:Z.routesBuilt,siteConfig:{...Y,url:W},generateEntityUrl:(K,U)=>iY.getInstance().generateUrl(K,U)},broadcast:!0})}return{success:Z.success,routesBuilt:Z.routesBuilt,outputDir:A.outputDir,environment:w,...Z.errors&&{errors:Z.errors},...Z.warnings&&{warnings:Z.warnings}}}catch(X){throw this.logger.error("Site build job failed",X),X}}summarizeDataForLog(A){return{environment:A.environment,outputDir:A.outputDir}}}C0();XX();var xI$=H.object({slot:H.enum(Ek).optional().default("primary"),limit:H.number().optional()});class rUA{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,$){let w=xI$.parse(A??{});this.logger.debug("NavigationDataSource fetch called",{params:w});let B=this.routeRegistry.getNavigationItems(w.slot),X=w.limit?B.slice(0,w.limit):B,Y=X.map((W)=>({label:W.label,href:W.href}));this.logger.debug("NavigationDataSource returning",{slot:w.slot,itemCount:X.length,items:Y});let Z={navigation:Y};return Q.parse(Z)}}XX();KA();C0();var RI$=H.object({environment:H.enum(["preview","production"]).optional().describe("Build environment (defaults to production, or preview if configured)")});function YC2(A,Q){return[p8(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'.",RI$,async($)=>{return Q($.environment),{success:!0,message:`Site build requested${$.environment?` for ${$.environment}`:""} (debounced)`,data:{}}},{sideEffects:"external",cli:{name:"build"}})]}C0();XX();var vI$=H.object({id:H.string(),template:H.string(),content:H.unknown().optional(),dataQuery:H.looseObject({entityType:H.string().optional(),template:H.string().optional(),query:H.looseObject({id:H.string().optional(),limit:H.number().optional(),offset:H.number().optional()}).optional()}).optional(),order:H.number().optional()}),CI$=H.object({show:H.boolean().default(!1),label:H.string().optional(),slot:H.enum(Ek).default("primary"),priority:H.number().min(0).max(100).default(50)}).optional(),hI$=H.object({id:H.string(),path:H.string(),title:H.string().default(""),pageLabel:H.string().optional(),description:H.string().default(""),sections:H.array(vI$).default([]),layout:H.string().default("default"),fullscreen:H.boolean().optional(),pluginId:H.string().optional(),sourceEntityType:H.string().optional(),external:H.boolean().optional(),navigation:CI$}),ZC2=H.object({previewOutputDir:H.string().describe("Output directory for preview builds").default("./dist/site-preview"),productionOutputDir:H.string().describe("Output directory for production builds").default("./dist/site-production"),sharedImagesDir:H.string().describe("Shared directory for optimized images (used by both preview and production)").default("./dist/images"),workingDir:H.string().optional().describe("Working directory for builds").default("./.preact-work"),siteInfo:Ci.default({title:"Brain",description:"A knowledge management system"}),themeCSS:H.string().describe("Custom CSS theme overrides to inject into builds").optional(),analyticsScript:H.string().describe("Analytics tracking script to inject into page head (e.g., Cloudflare Web Analytics)").optional(),templates:H.any().optional().describe("Template definitions to register"),routes:H.array(hI$).optional().describe("Routes to register"),layouts:H.record(H.string(),H.any()).optional().describe("Layout components (at least 'default' required)"),autoRebuild:H.boolean().default(!0).describe("Automatically rebuild site when content changes"),rebuildDebounce:H.number().min(100).describe("Debounce time in ms before triggering site rebuild after content changes").default(5000),entityDisplay:H.record(H.string(),H.object({label:H.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:H.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')"),layout:H.string().optional().describe("Layout name for this entity type's generated routes (defaults to 'default')"),paginate:H.boolean().optional().describe("Enable pagination for list pages"),pageSize:H.number().optional().describe("Items per page (default: 10)"),navigation:H.object({show:H.boolean().optional().describe("Show in navigation"),slot:H.enum(Ek).optional().describe("Navigation slot (primary or secondary)"),priority:H.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:H.record(H.string(),H.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 HC2={name:"@brains/site-builder-plugin",version:"0.2.0-alpha.184",description:"Static site generation plugin for Brain system",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.20",preact:"^10.27.2","preact-render-to-string":"^6.7.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{clean:"rm -rf dist",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class oUA extends p6{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",HC2,{...A,layouts:Q},ZC2);this.layouts=Q}async onRegister(A){if(this.pluginContext=A,this._routeRegistry=new xP0(A.logger),this._slotRegistry=new BP0,A.messaging.subscribe("plugin:site-builder:slot:register",async($)=>{let{slotName:w,pluginId:B,render:X,priority:Y}=$.payload;return this._slotRegistry?.register(w,{pluginId:B,render:X,...Y!==void 0&&{priority:Y}}),{success:!0}}),A.messaging.subscribe("plugin:site-builder:head-script:register",async($)=>{let{pluginId:w,script:B}=$.payload;return this.headScripts.set(w,B),{success:!0}}),A.entities.registerDataSource(new rUA(this._routeRegistry,A.logger.child("NavigationDataSource"))),this.profileService={getProfile:()=>A.identity.getProfile()},AC2(A,this._routeRegistry,this.logger),this.config.templates)A.templates.register(this.config.templates);if(this.config.routes)vP0(this.config.routes,this.id,this.routeRegistry);let Q={entityService:A.entityService,sendMessage:A.messaging.send,resolveTemplateContent:($,w)=>A.templates.resolve($,w),getViewTemplate:($)=>A.views.get($),listViewTemplateNames:()=>A.views.list().map(($)=>$.name)};if(this.siteBuilder=Rq.createFresh(A.logger.child("SiteBuilder"),Q,this.routeRegistry,this.profileService,void 0,this.config.entityDisplay),A.jobs.registerHandler("site-build",new nUA(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 iUA(this.config,A,this.id,this.logger),this.config.autoRebuild)this.logger.debug("Auto-rebuild enabled"),this.rebuildManager.setupAutoRebuild();A.messaging.subscribe(ao,async()=>{let $=await this.getInstructions();if($)A.registerInstructions($);return{success:!0}}),wC2({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 YC2(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 Iw0(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(($)=>({id:$.id,path:$.path,title:$.title,description:$.description,sections:$.sections.map((w)=>({id:w.id,template:w.template}))})),null,2)}]}}},{uri:"site://templates",name:"View Templates",description:"All registered view templates",mimeType:"application/json",handler:async()=>{let Q=A.views.list();return{contents:[{uri:"site://templates",mimeType:"application/json",text:JSON.stringify(Q.map(($)=>({name:$.name,description:$.description,hasWebRenderer:!!$.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.",$=await Iw0(A.messaging.send,this.config.siteInfo);return`## Your Site
6779
6779
  ${[`**Title:** ${$.title}`,`**Description:** ${$.description}`,A.domain&&`**Domain:** ${A.domain}`,A.siteUrl&&`**URL:** ${A.siteUrl}`].filter(Boolean).join(`
6780
6780
  `)}
6781
6781
 
6782
6782
  ## Site Builder Actions
6783
6783
  - When the user asks to build, rebuild, publish, or build the website/site again, call \`site-builder_build-site\` immediately.
6784
- - 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(),delete this.siteBuilder,this.logger.debug("Cleaned up all event subscriptions")}}function mE(A={}){return new oUA(A)}KA();KA();C0();var sUA=H.object({routeId:H.string(),sectionId:H.string()}),TI$=H.object({routeId:H.string(),sectionId:H.string()}),Lw0=H6.extend({entityType:H.literal("site-content"),template:H.string().optional(),content:H.string(),metadata:TI$});KA();class WC2 extends UQ{constructor(){super({entityType:"site-content",purpose:"A content section bound to a route on the published site.",schema:Lw0,frontmatterSchema:sUA})}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 aUA=new WC2;C0();var CP0=H.object({routeId:H.string().optional().describe("Optional: specific route filter"),sectionId:H.string().optional().describe("Optional: specific section filter"),dryRun:H.boolean().optional().default(!1).describe("Optional: preview changes without executing"),force:H.boolean().optional().default(!1).describe("Force regeneration even if content exists")}),qI5=H.object({jobs:H.array(H.object({jobId:H.string(),routeId:H.string(),sectionId:H.string()})),totalSections:H.number(),queuedSections:H.number(),skippedSections:H.number().optional(),batchId:H.string().optional()});C0();var yI$=H.looseObject({id:H.string(),template:H.string().optional(),content:H.unknown().optional()}),gI$=H.looseObject({id:H.string(),title:H.string().optional(),description:H.string().optional(),sections:H.array(yI$)}),SI$=H.array(gI$);class tUA{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");let Q=SI$.safeParse(A.data);if(!Q.success)throw Error("Failed to parse routes from site-builder");return Q.data}async generate(A,Q,$){let w=this.context.logger.child("SiteContentOperations"),B=await this.fetchRoutes(),X=B;if(A.routeId){if(X=B.filter((U)=>U.id===A.routeId),X.length===0)throw Error(`Route not found: ${A.routeId}`)}let Y=[];for(let U of X)for(let G of U.sections){if(A.sectionId&&G.id!==A.sectionId)continue;if(G.content){w.debug("Section has static content, skipping",{routeId:U.id,sectionId:G.id});continue}if(G.template){let D=this.context.templates.getCapabilities(G.template);if(!D){w.warn("Template not found, skipping section",{routeId:U.id,sectionId:G.id,templateName:G.template});continue}if(!D.canGenerate){w.debug("Template doesn't support generation, skipping",{routeId:U.id,sectionId:G.id,templateName:G.template,capabilities:D});continue}}else{w.debug("Section has no template, skipping",{routeId:U.id,sectionId:G.id});continue}if(!A.force&&!A.dryRun){let D=`${U.id}:${G.id}`;if(await this.context.entityService.getEntity({entityType:"site-content",id:D})){w.debug("Content already exists, skipping",{routeId:U.id,sectionId:G.id});continue}}Y.push({route:U,section:G})}let Z=Y.length;if(A.dryRun)return{jobs:[],totalSections:Z,queuedSections:Z,batchId:`dry-run-${Date.now()}`};let W=[],K=[];for(let{route:U,section:G}of Y){let D=`${U.id}:${G.id}`,q=G.template,J={routeId:U.id,sectionId:G.id,entityId:D,entityType:"site-content",templateName:q,context:{prompt:typeof G.content==="string"?G.content:void 0,data:{routeId:U.id,sectionId:G.id,routeTitle:U.title,routeDescription:U.description,sectionContent:G.content},conversationId:"system"},siteConfig:Q};K.push({type:"shell:content-generation",data:J})}if(K.length>0){let U=this.createJobOptions($,"site:content-generation"),G=await this.context.jobs.enqueueBatch(K,U);for(let D=0;D<Y.length;D++){let q=Y[D];if(q)W.push({jobId:`${G}-${D}`,routeId:q.route.id,sectionId:q.section.id})}return{jobs:W,totalSections:Z,queuedSections:W.length,batchId:G}}return{jobs:[],totalSections:Z,queuedSections:0,batchId:`empty-${Date.now()}`}}}class eUA{siteConfig;operations;constructor(A,Q){this.siteConfig=Q,this.operations=new tUA(A)}async generateContent(A,Q){let $=CP0.parse(A);return this.operations.generate($,this.siteConfig,Q)}}XX();C0();var mI$=H.object({namespace:H.string(),sections:H.record(H.string(),H.any())}),KC2=H.custom((A)=>mI$.safeParse(A).success),AGA=H.object({definitions:H.union([KC2,H.array(KC2)]).optional()});KA();function UC2(A,Q){return[p8(Q,"generate","Generate content for all routes, a specific route, or a specific section",CP0,async($,w)=>{let B=A();if(!B)return{success:!1,error:"Site content service not initialized"};if($.sectionId&&!$.routeId)return{success:!1,error:"sectionId requires routeId to be specified"};let X={rootJobId:`generate-${Date.now()}`,progressToken:w.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:w.interfaceType,channelId:w.channelId},Y=await B.generateContent($,X);return{success:!0,message:`Generated ${Y.queuedSections} of ${Y.totalSections} sections. ${Y.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:Y.batchId,jobsQueued:Y.queuedSections,totalSections:Y.totalSections,jobs:Y.jobs}}})]}var GC2={name:"@brains/site-content",version:"0.2.0-alpha.183",description:"Site content entity and generation orchestration",dependencies:{"@brains/content-formatters":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class QGA extends p6{siteContentService;constructor(A={}){super("site-content",GC2,A,AGA)}async onRegister(A){A.entities.register("site-content",Lw0,aUA);for(let Q of CM(this.config.definitions))A.templates.register(lk(Q),Q.namespace);this.siteContentService=new eUA(A)}async getTools(){return UC2(()=>this.siteContentService,this.id)}}function uE(A={}){return new QGA(A)}KA();XX();KA();C0();XX();var cI$=H.object({}),pI$=H.object({}),Nw0=H6.extend({id:H.literal("site-info"),entityType:H.literal("site-info"),metadata:pI$});var hi=DT0.omit({url:!0,analyticsScript:!0});KA();C0();var lI$=H.record(H.string(),H.unknown());class tF extends UQ{constructor(){super({entityType:"site-info",purpose:"Singleton configuration describing the published site.",schema:Nw0,frontmatterSchema:hi,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=hi.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("",lI$.parse(Q))}}class eF{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,$){return eF.instance??=new eF(A,Q,$),eF.instance}static resetInstance(){eF.instance=null}static createFresh(A,Q,$){return new eF(A,Q,$)}constructor(A,Q,$){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new tF;let w=eF.getDefaultSiteInfo();this.defaultSiteInfo={...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 $=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({entity:{id:"site-info",entityType:"site-info",content:$,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}}C0();var dI$=new tF,iI$=H.looseObject({platform:H.string(),url:H.string(),label:H.string().optional()}).transform((A)=>({platform:A.platform,url:A.url,...A.label!==void 0?{label:A.label}:{}})),nI$=H.looseObject({socialLinks:H.array(iI$).optional()});class hP0{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,$){let{entityService:w}=$,B;try{let Z=await w.getEntity({entityType:"site-info",id:"site-info"});B=Z?dI$.parseSiteInfoBody(Z.content):{title:"Brain",description:"A knowledge management system"}}catch{B={title:"Brain",description:"A knowledge management system"}}let X;try{let Z=await w.getEntity({entityType:"anchor-profile",id:"anchor-profile"});if(Z){let W=nI$.safeParse(Z.metadata);X=W.success?W.data.socialLinks:void 0}}catch{}let Y={...B,socialLinks:X,copyright:B.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:Y.title,hasSocialLinks:!!Y.socialLinks}),Q.parse(Y)}}var DC2={name:"@brains/site-info",version:"0.2.0-alpha.183",description:"Site info entity \u2014 site metadata, title, description, CTA",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var oI$=new tF,sI$="site-info";class $GA extends S6{entityType=sI$;schema=Nw0;adapter=oI$;defaultSiteInfo;constructor(A){super("site-info",DC2,{},XY);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new hP0(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=eF.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe(so,async()=>{return{success:!0,data:await Q.getSiteInfo()}}),A.messaging.subscribe("entity:updated",async($)=>{if($.payload.entityType==="site-info"){let B=await Q.getSiteInfo();await A.messaging.send({type:ao,payload:B,broadcast:!0})}return{success:!0}}),A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function cE(A){return new $GA(A)}var aI$=new tF;async function _w0(A){let $=(await A.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!$)throw Error("Site info not found \u2014 create a site-info entity");return aI$.parseSiteInfoBody($.content)}function qC2(A,Q){let $=A.metadata.publishedAt??A.created,w=Q.metadata.publishedAt??Q.created;return new Date(w).getTime()-new Date($).getTime()}async function EP0(A,Q){return(await A.listEntities({entityType:Q.entityType,options:{limit:20}})).sort(qC2).slice(0,Q.count).map(Q.parse)}function wGA(A){if(!A)throw Error("CTA not configured in site-info");return A}C0();var zC2=H.object({label:H.string(),href:H.string(),priority:H.number()}),tI$=H.object({primary:H.array(zC2),secondary:H.array(zC2)}),eI$=H.object({platform:H.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:H.string().describe("Profile or contact URL"),label:H.string().optional().describe("Optional display label")}),AL$=hi.extend({navigation:tI$,copyright:H.string(),socialLinks:H.array(eI$).optional().describe("Social media links from profile entity")});KA();qG();yi();C0();var BGA=H.object({defaultPrompt:H.string().default("Write a blog post about my recent work and insights"),paginate:H.boolean().default(!0),pageSize:H.number().default(10)});KA();e8();S2();C0();var BL$=H.object({prompt:H.string().optional(),title:H.string().optional(),content:H.string().optional(),excerpt:H.string().optional(),coverImageId:H.string().optional(),seriesName:H.string().optional(),seriesIndex:H.number().optional(),skipAi:H.boolean().optional()}),lL5=iK.extend({title:H.string().optional(),slug:H.string().optional()});class XGA extends GZ{constructor(A,Q){super(A,Q,{schema:BL$,jobTypeName:"blog-generation",entityType:"post"})}async generate(A,Q){let{prompt:$,coverImageId:w,seriesName:B,seriesIndex:X,skipAi:Y}=A,{title:Z,content:W,excerpt:K}=A;if(Y){if(!Z)this.failEarly("Title is required when skipAi is true");W=W??`## Introduction
6784
+ - 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(),delete this.siteBuilder,this.logger.debug("Cleaned up all event subscriptions")}}function mE(A={}){return new oUA(A)}KA();KA();C0();var sUA=H.object({routeId:H.string(),sectionId:H.string()}),TI$=H.object({routeId:H.string(),sectionId:H.string()}),Lw0=H6.extend({entityType:H.literal("site-content"),template:H.string().optional(),content:H.string(),metadata:TI$});KA();class WC2 extends UQ{constructor(){super({entityType:"site-content",purpose:"A content section bound to a route on the published site.",schema:Lw0,frontmatterSchema:sUA})}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 aUA=new WC2;C0();var CP0=H.object({routeId:H.string().optional().describe("Optional: specific route filter"),sectionId:H.string().optional().describe("Optional: specific section filter"),dryRun:H.boolean().optional().default(!1).describe("Optional: preview changes without executing"),force:H.boolean().optional().default(!1).describe("Force regeneration even if content exists")}),qI5=H.object({jobs:H.array(H.object({jobId:H.string(),routeId:H.string(),sectionId:H.string()})),totalSections:H.number(),queuedSections:H.number(),skippedSections:H.number().optional(),batchId:H.string().optional()});C0();var yI$=H.looseObject({id:H.string(),template:H.string().optional(),content:H.unknown().optional()}),gI$=H.looseObject({id:H.string(),title:H.string().optional(),description:H.string().optional(),sections:H.array(yI$)}),SI$=H.array(gI$);class tUA{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");let Q=SI$.safeParse(A.data);if(!Q.success)throw Error("Failed to parse routes from site-builder");return Q.data}async generate(A,Q,$){let w=this.context.logger.child("SiteContentOperations"),B=await this.fetchRoutes(),X=B;if(A.routeId){if(X=B.filter((U)=>U.id===A.routeId),X.length===0)throw Error(`Route not found: ${A.routeId}`)}let Y=[];for(let U of X)for(let G of U.sections){if(A.sectionId&&G.id!==A.sectionId)continue;if(G.content){w.debug("Section has static content, skipping",{routeId:U.id,sectionId:G.id});continue}if(G.template){let D=this.context.templates.getCapabilities(G.template);if(!D){w.warn("Template not found, skipping section",{routeId:U.id,sectionId:G.id,templateName:G.template});continue}if(!D.canGenerate){w.debug("Template doesn't support generation, skipping",{routeId:U.id,sectionId:G.id,templateName:G.template,capabilities:D});continue}}else{w.debug("Section has no template, skipping",{routeId:U.id,sectionId:G.id});continue}if(!A.force&&!A.dryRun){let D=`${U.id}:${G.id}`;if(await this.context.entityService.getEntity({entityType:"site-content",id:D})){w.debug("Content already exists, skipping",{routeId:U.id,sectionId:G.id});continue}}Y.push({route:U,section:G})}let Z=Y.length;if(A.dryRun)return{jobs:[],totalSections:Z,queuedSections:Z,batchId:`dry-run-${Date.now()}`};let W=[],K=[];for(let{route:U,section:G}of Y){let D=`${U.id}:${G.id}`,q=G.template,J={routeId:U.id,sectionId:G.id,entityId:D,entityType:"site-content",templateName:q,context:{prompt:typeof G.content==="string"?G.content:void 0,data:{routeId:U.id,sectionId:G.id,routeTitle:U.title,routeDescription:U.description,sectionContent:G.content},conversationId:"system"},siteConfig:Q};K.push({type:"shell:content-generation",data:J})}if(K.length>0){let U=this.createJobOptions($,"site:content-generation"),G=await this.context.jobs.enqueueBatch(K,U);for(let D=0;D<Y.length;D++){let q=Y[D];if(q)W.push({jobId:`${G}-${D}`,routeId:q.route.id,sectionId:q.section.id})}return{jobs:W,totalSections:Z,queuedSections:W.length,batchId:G}}return{jobs:[],totalSections:Z,queuedSections:0,batchId:`empty-${Date.now()}`}}}class eUA{siteConfig;operations;constructor(A,Q){this.siteConfig=Q,this.operations=new tUA(A)}async generateContent(A,Q){let $=CP0.parse(A);return this.operations.generate($,this.siteConfig,Q)}}XX();C0();var mI$=H.object({namespace:H.string(),sections:H.record(H.string(),H.any())}),KC2=H.custom((A)=>mI$.safeParse(A).success),AGA=H.object({definitions:H.union([KC2,H.array(KC2)]).optional()});KA();function UC2(A,Q){return[p8(Q,"generate","Generate content for all routes, a specific route, or a specific section",CP0,async($,w)=>{let B=A();if(!B)return{success:!1,error:"Site content service not initialized"};if($.sectionId&&!$.routeId)return{success:!1,error:"sectionId requires routeId to be specified"};let X={rootJobId:`generate-${Date.now()}`,progressToken:w.progressToken,pluginId:Q,operationType:"content_operations",interfaceType:w.interfaceType,channelId:w.channelId},Y=await B.generateContent($,X);return{success:!0,message:`Generated ${Y.queuedSections} of ${Y.totalSections} sections. ${Y.queuedSections>0?"Jobs are running in the background.":"No new content to generate."}`,data:{batchId:Y.batchId,jobsQueued:Y.queuedSections,totalSections:Y.totalSections,jobs:Y.jobs}}})]}var GC2={name:"@brains/site-content",version:"0.2.0-alpha.184",description:"Site content entity and generation orchestration",dependencies:{"@brains/content-formatters":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class QGA extends p6{siteContentService;constructor(A={}){super("site-content",GC2,A,AGA)}async onRegister(A){A.entities.register("site-content",Lw0,aUA);for(let Q of CM(this.config.definitions))A.templates.register(lk(Q),Q.namespace);this.siteContentService=new eUA(A)}async getTools(){return UC2(()=>this.siteContentService,this.id)}}function uE(A={}){return new QGA(A)}KA();XX();KA();C0();XX();var cI$=H.object({}),pI$=H.object({}),Nw0=H6.extend({id:H.literal("site-info"),entityType:H.literal("site-info"),metadata:pI$});var hi=DT0.omit({url:!0,analyticsScript:!0});KA();C0();var lI$=H.record(H.string(),H.unknown());class tF extends UQ{constructor(){super({entityType:"site-info",purpose:"Singleton configuration describing the published site.",schema:Nw0,frontmatterSchema:hi,isSingleton:!0,hasBody:!1})}createSiteInfoContent(A){let Q=hi.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("",lI$.parse(Q))}}class eF{static instance=null;logger;entityService;adapter;defaultSiteInfo;static getDefaultSiteInfo(){return{title:"Brain",description:"A knowledge management system"}}static getInstance(A,Q,$){return eF.instance??=new eF(A,Q,$),eF.instance}static resetInstance(){eF.instance=null}static createFresh(A,Q,$){return new eF(A,Q,$)}constructor(A,Q,$){this.entityService=A,this.logger=Q.child("SiteInfoService"),this.adapter=new tF;let w=eF.getDefaultSiteInfo();this.defaultSiteInfo={...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 $=this.adapter.createSiteInfoContent(this.defaultSiteInfo);await this.entityService.createEntity({entity:{id:"site-info",entityType:"site-info",content:$,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}}C0();var dI$=new tF,iI$=H.looseObject({platform:H.string(),url:H.string(),label:H.string().optional()}).transform((A)=>({platform:A.platform,url:A.url,...A.label!==void 0?{label:A.label}:{}})),nI$=H.looseObject({socialLinks:H.array(iI$).optional()});class hP0{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,$){let{entityService:w}=$,B;try{let Z=await w.getEntity({entityType:"site-info",id:"site-info"});B=Z?dI$.parseSiteInfoBody(Z.content):{title:"Brain",description:"A knowledge management system"}}catch{B={title:"Brain",description:"A knowledge management system"}}let X;try{let Z=await w.getEntity({entityType:"anchor-profile",id:"anchor-profile"});if(Z){let W=nI$.safeParse(Z.metadata);X=W.success?W.data.socialLinks:void 0}}catch{}let Y={...B,socialLinks:X,copyright:B.copyright??"Powered by Rizom"};return this.logger.debug("SiteInfoDataSource returning",{title:Y.title,hasSocialLinks:!!Y.socialLinks}),Q.parse(Y)}}var DC2={name:"@brains/site-info",version:"0.2.0-alpha.184",description:"Site info entity \u2014 site metadata, title, description, CTA",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var oI$=new tF,sI$="site-info";class $GA extends S6{entityType=sI$;schema=Nw0;adapter=oI$;defaultSiteInfo;constructor(A){super("site-info",DC2,{},XY);this.defaultSiteInfo=A?.siteInfo??{}}getEntityTypeConfig(){return{embeddable:!1}}getDataSources(){return[new hP0(this.logger.child("SiteInfoDataSource"))]}async onRegister(A){let Q=eF.createFresh(A.entityService,this.logger,this.defaultSiteInfo);A.messaging.subscribe(so,async()=>{return{success:!0,data:await Q.getSiteInfo()}}),A.messaging.subscribe("entity:updated",async($)=>{if($.payload.entityType==="site-info"){let B=await Q.getSiteInfo();await A.messaging.send({type:ao,payload:B,broadcast:!0})}return{success:!0}}),A.messaging.subscribe("sync:initial:completed",async()=>{return await Q.initialize(),{success:!0}})}}function cE(A){return new $GA(A)}var aI$=new tF;async function _w0(A){let $=(await A.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!$)throw Error("Site info not found \u2014 create a site-info entity");return aI$.parseSiteInfoBody($.content)}function qC2(A,Q){let $=A.metadata.publishedAt??A.created,w=Q.metadata.publishedAt??Q.created;return new Date(w).getTime()-new Date($).getTime()}async function EP0(A,Q){return(await A.listEntities({entityType:Q.entityType,options:{limit:20}})).sort(qC2).slice(0,Q.count).map(Q.parse)}function wGA(A){if(!A)throw Error("CTA not configured in site-info");return A}C0();var zC2=H.object({label:H.string(),href:H.string(),priority:H.number()}),tI$=H.object({primary:H.array(zC2),secondary:H.array(zC2)}),eI$=H.object({platform:H.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:H.string().describe("Profile or contact URL"),label:H.string().optional().describe("Optional display label")}),AL$=hi.extend({navigation:tI$,copyright:H.string(),socialLinks:H.array(eI$).optional().describe("Social media links from profile entity")});KA();qG();yi();C0();var BGA=H.object({defaultPrompt:H.string().default("Write a blog post about my recent work and insights"),paginate:H.boolean().default(!0),pageSize:H.number().default(10)});KA();e8();S2();C0();var BL$=H.object({prompt:H.string().optional(),title:H.string().optional(),content:H.string().optional(),excerpt:H.string().optional(),coverImageId:H.string().optional(),seriesName:H.string().optional(),seriesIndex:H.number().optional(),skipAi:H.boolean().optional()}),lL5=iK.extend({title:H.string().optional(),slug:H.string().optional()});class XGA extends GZ{constructor(A,Q){super(A,Q,{schema:BL$,jobTypeName:"blog-generation",entityType:"post"})}async generate(A,Q){let{prompt:$,coverImageId:w,seriesName:B,seriesIndex:X,skipAi:Y}=A,{title:Z,content:W,excerpt:K}=A;if(Y){if(!Z)this.failEarly("Title is required when skipAi is true");W=W??`## Introduction
6785
6785
 
6786
6786
  Add your introduction here.
6787
6787
 
@@ -7001,7 +7001,7 @@ ${$.content}`,templateName:"blog:excerpt"})})}KA();yi();qG();function OL$(A){let
7001
7001
  letter-spacing: 0.02em;
7002
7002
  }
7003
7003
  .printable-footer a { color: inherit; text-decoration: none; overflow-wrap: anywhere; }
7004
- `}},void 0,!1,void 0,this),MY("header",{className:"printable-hero",children:[MY("div",{className:"printable-masthead",children:Q.brandLabel&&MY("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this),MY("div",{children:[MY("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.excerpt&&MY("p",{className:"printable-excerpt",children:Q.excerpt},void 0,!1,void 0,this),MY("div",{className:"printable-meta",children:[Q.author&&MY("span",{children:["By ",Q.author]},void 0,!0,void 0,this),$&&MY("span",{children:$},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&&MY("figure",{className:"printable-cover-wrap",children:MY("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this)},void 0,!1,void 0,this),MY(u4,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Boolean(Q.canonicalUrl)||Boolean(Q.brandLabel))&&MY("footer",{className:"printable-footer",children:[MY("span",{children:Q.brandLabel??"Printable PDF"},void 0,!1,void 0,this),Q.canonicalUrl&&MY("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 KN$=26214400,UN$=60000;class VGA{metadata={outputEntityType:"document"};context;renderPdf;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==SP0)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let $=GN$(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),w=await YN$(WN$(HN$(),"brain-blog-printable-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/printable/post/${Q.id}`,template:TC2,format:"pdf",content:$,siteConfig:{title:$.title,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"document",data:await this.renderPdf(X.urlFor(B.urlPath),{maxBytes:KN$,timeoutMs:UN$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${DN$(Q)}-printable.pdf`}}finally{await X.close()}}finally{await ZN$(w,{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}=c8(A.content),$=t5.parse(Q);if(!$.coverImageId)return;let w=await this.context.entityService.getEntity({entityType:"image",id:$.coverImageId});return w?.content.startsWith("data:image/")?w.content:void 0}}function GN$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=t5.parse($);return{title:B.title,body:w,...B.excerpt?{excerpt:B.excerpt}:{},...B.author?{author:B.author}:{},...B.publishedAt?{publishedAt:B.publishedAt}:{},...B.canonicalUrl?{canonicalUrl:B.canonicalUrl}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function DN$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}import{mkdtemp as FN$,rm as IN$}from"fs/promises";import{tmpdir as LN$}from"os";import{join as NN$}from"path";_4();S2();qG();C0();import{jsxDEV as JN$}from"preact/jsx-dev-runtime";var Ow0="og-image",qN$="blog:og-image",yC2=H.object({title:H.string().min(1),excerpt:H.string().optional(),author:H.string().optional(),publishedAt:H.string().optional(),brandLabel:H.string().optional(),coverImageUrl:H.string().optional()}),gC2={name:qN$,pluginId:"blog",schema:yC2,renderers:{image:VN$}};function zN$(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 VN$(A){let Q=yC2.parse(A);return JN$(YP,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Journal",title:Q.title,subtitle:Q.excerpt,meta:[Q.author],tag:zN$(Q.publishedAt)},void 0,!1,void 0,this)}var _N$={width:1200,height:630},PN$=60000;class JGA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;screenshotPng;constructor(A,Q={}){this.context=A,this.screenshotPng=Q.screenshotPng??bw0}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==Ow0)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let $=kN$(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),w=await FN$(NN$(LN$(),"brain-blog-og-image-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/og/post/${Q.id}`,template:gC2,format:"image",content:$,siteConfig:{title:$.title,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"image",data:await this.screenshotPng(X.urlFor(B.urlPath),_N$,{timeoutMs:PN$,fullPage:!1,omitBackground:!1}),mimeType:"image/png",filename:`${jN$(Q)}-og.png`}}finally{await X.close()}}finally{await IN$(w,{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}=c8(A.content),$=t5.parse(Q);if(!$.coverImageId)return;let w=await this.context.entityService.getEntity({entityType:"image",id:$.coverImageId});return w?.content.startsWith("data:image/")?w.content:void 0}}function kN$(A,Q={}){let{frontmatter:$}=c8(A.content),w=t5.parse($);return{title:w.title,...w.excerpt?{excerpt:w.excerpt}:{},...w.author?{author:w.author}:{},...w.publishedAt?{publishedAt:w.publishedAt}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function jN$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}var SC2={name:"@brains/blog",version:"0.2.0-alpha.183",description:"AI-powered blog post generation from existing brain content",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class FGA extends S6{entityType=_P.entityType;schema=Ei;adapter=_P;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("blog",SC2,A,BGA)}getEntityTypeConfig(){return{weight:2,publish:{publishStatuses:["queued","published"]}}}createGenerationHandler(A){return new XGA(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return NC2()}getDataSources(){return[new ZGA(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (cC2(),uC2));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),_C2(A,this.logger),PC2(A,this.logger),jC2(A,this.logger),MC2(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("post",SP0,new VGA(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("post",Ow0,new JGA(A)),this.deferPublishAssetRegistration(A),this.unregisterAtprotoProjection=aB.getInstance().register(KGA()),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:Ow0,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 IGA(A={}){return new FGA(A)}qG();yi();KA();C0();y9();KA();C0();var t3=H.object({title:H.string(),slug:H.string(),coverImageId:H.string().optional()}),ON$=H.object({title:H.string(),slug:H.string()}),fN$=H.object({title:H.string(),slug:H.string()}),SO=H6.extend({entityType:H.literal("series"),metadata:fN$}),mP0=SO.extend({frontmatter:t3}),xN$=mP0.extend({description:H.string().optional(),postCount:H.number(),coverImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()}),pC2=H.object({description:H.string().optional()});function iE(A){return new d$(pC2,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}KA();class LGA extends UQ{constructor(){super({entityType:"series",purpose:"A series grouping related posts or content under one theme.",schema:SO,frontmatterSchema:t3,supportsCoverImage:!0,bodyFormatter:iE("")})}toMarkdown(A){let Q,$={};try{Q=this.parseFrontMatter(A.content,t3).coverImageId,$=iE(A.metadata.title).parse(this.extractBody(A.content))}catch{}let w={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},X=iE(A.metadata.title).format($);return this.buildMarkdown(X,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,t3);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,t3);return iE(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var mO=new LGA;KA();S2();bH();C0();var RN$=H.object({seriesName:H.string().optional(),seriesIndex:H.number().optional()});function uP0(A){let Q=RN$.safeParse(A);return Q.success?Q.data:{}}function nE(A){return uP0(A.metadata).seriesName}function lC2(A){return uP0(A.metadata).seriesIndex}function dC2(A,Q){let $=lC2(A)??Number.MAX_SAFE_INTEGER,w=lC2(Q)??Number.MAX_SAFE_INTEGER;return $-w}class NGA{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"}),$=new Map(Q.map((B)=>[B.id,B])),w=new Set;for(let B of A){let X=k1(B);w.add(X);let Y=$.get(X),Z=Y?.content??this.createSeriesContent(B),W=e6(Z);if(Y?.contentHash===W)continue;let K={id:X,entityType:"series",content:Z,contentHash:W,created:Y?.created??new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:B,slug:k1(B)}};await this.entityService.upsertEntity({entity:K}),this.logger.debug(`Upserted series: ${B}`)}for(let B of Q)if(!w.has(B.id))await this.entityService.deleteEntity({entityType:"series",id:B.id}),this.logger.debug(`Deleted orphaned series: ${B.id}`)}async handleEntityChange(A,Q){let $=nE(A);if($)await this.ensureSeriesExists($);if(Q&&Q!==$)await this.cleanupOrphanedSeries(Q)}async handleEntityDeleted(){await this.syncAllSeries()}async ensureSeriesExists(A){let Q=k1(A);if(await this.entityService.getEntity({entityType:"series",id:Q}))return;let w=this.createSeriesContent(A),B={id:Q,entityType:"series",content:w,contentHash:e6(w),created:new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:A,slug:k1(A)}};await this.entityService.upsertEntity({entity:B}),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=k1(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 $ of Q){if($==="series")continue;if((await this.entityService.listEntities({entityType:$,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 $ of Q){if($==="series")continue;let w=await this.entityService.listEntities({entityType:$});for(let B of w){let X=nE(B);if(X)A.add(X)}}return A}createSeriesContent(A){let Q={title:A,slug:k1(A)};return O7("",Q)}}KA();C0();var vN$=H.object({entityType:H.literal("series"),query:H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional()})}),CN$=H.object({type:H.enum(["list","detail"]),seriesName:H.string().optional()});function hN$(A){let Q=CN$.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let $=vN$.safeParse(A);if($.success){let{query:w}=$.data;if(w.id)return{type:"detail",seriesSlug:w.id};return{type:"list"}}throw Error('Invalid series query format. Expected { type: "list"|"detail" } or { entityType: "series", query: { id?: string } }')}function iC2(A){let Q=_Q(A.content,t3);return mP0.parse({...A,frontmatter:Q.metadata})}class _GA{logger;id="series:entities";name="Series DataSource";description="Fetches series list and detail data";constructor(A){this.logger=A}async fetch(A,Q,$){let w=hN$(A),B=$.entityService;if(w.type==="list")return this.fetchSeriesList(Q,B);if(w.seriesName)return this.fetchSeriesDetail(w.seriesName,Q,B);if(w.seriesSlug)return this.fetchSeriesDetailBySlug(w.seriesSlug,Q,B);throw Error("Invalid series query: must specify seriesName or slug for detail")}async fetchSeriesList(A,Q){let $=await Q.listEntities({entityType:"series"}),w=await this.countEntitiesPerSeries(Q),B=$.map((X)=>{let Y=iC2(X),Z=mO.parseBody(X.content);return{...Y,description:Z.description,postCount:w.get(X.metadata.title)??0}});return this.logger.debug(`Found ${B.length} series entities`),A.parse({series:B})}async fetchSeriesDetail(A,Q,$,w){if(!w)w=(await $.listEntities({entityType:"series",options:{filter:{metadata:{title:A}}}}))[0];if(!w)throw Error(`Series not found: ${A}`);let B=iC2(w),X=mO.parseBody(w.content),Y=await this.getSeriesMembers(A,$);return this.logger.debug(`Found ${Y.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:Y,series:{...B,description:X.description,postCount:Y.length},description:X.description})}async fetchSeriesDetailBySlug(A,Q,$){let B=(await $.listEntities({entityType:"series",options:{filter:{metadata:{slug:A}}}}))[0];if(!B)throw Error(`Series not found with slug: ${A}`);return this.fetchSeriesDetail(B.metadata.title,Q,$,B)}async countEntitiesPerSeries(A){let Q=new Map,$=A.getEntityTypes();for(let w of $){if(w==="series")continue;let B=await A.listEntities({entityType:w});for(let X of B){let Y=nE(X);if(Y)Q.set(Y,(Q.get(Y)??0)+1)}}return Q}async getSeriesMembers(A,Q){let $=[],w=Q.getEntityTypes();for(let B of w){if(B==="series")continue;let X=await Q.listEntities({entityType:B,options:{filter:{metadata:{seriesName:A}}}});$.push(...X)}return $.sort(dC2),$}}KA();C0();bH();var EN$=H.object({prompt:H.string().optional(),title:H.string().optional(),seriesId:H.string().optional()}),TN$=H.object({title:H.string().optional(),excerpt:H.string().optional()});class cP0{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 $=await this.context.entityService.getEntity({entityType:"series",id:Q});if(!$)return{success:!1,error:`Series not found: ${Q}`};let w=await this.gatherMemberSummaries($.metadata.title);if(w.length===0)return{success:!1,error:`No members found in series: ${$.metadata.title}`};let B=A.prompt??`Series name: ${$.metadata.title}
7004
+ `}},void 0,!1,void 0,this),MY("header",{className:"printable-hero",children:[MY("div",{className:"printable-masthead",children:Q.brandLabel&&MY("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this)},void 0,!1,void 0,this),MY("div",{children:[MY("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.excerpt&&MY("p",{className:"printable-excerpt",children:Q.excerpt},void 0,!1,void 0,this),MY("div",{className:"printable-meta",children:[Q.author&&MY("span",{children:["By ",Q.author]},void 0,!0,void 0,this),$&&MY("span",{children:$},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&&MY("figure",{className:"printable-cover-wrap",children:MY("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this)},void 0,!1,void 0,this),MY(u4,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Boolean(Q.canonicalUrl)||Boolean(Q.brandLabel))&&MY("footer",{className:"printable-footer",children:[MY("span",{children:Q.brandLabel??"Printable PDF"},void 0,!1,void 0,this),Q.canonicalUrl&&MY("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 KN$=26214400,UN$=60000;class VGA{metadata={outputEntityType:"document"};context;renderPdf;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==SP0)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let $=GN$(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),w=await YN$(WN$(HN$(),"brain-blog-printable-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/printable/post/${Q.id}`,template:TC2,format:"pdf",content:$,siteConfig:{title:$.title,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"document",data:await this.renderPdf(X.urlFor(B.urlPath),{maxBytes:KN$,timeoutMs:UN$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${DN$(Q)}-printable.pdf`}}finally{await X.close()}}finally{await ZN$(w,{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}=c8(A.content),$=t5.parse(Q);if(!$.coverImageId)return;let w=await this.context.entityService.getEntity({entityType:"image",id:$.coverImageId});return w?.content.startsWith("data:image/")?w.content:void 0}}function GN$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=t5.parse($);return{title:B.title,body:w,...B.excerpt?{excerpt:B.excerpt}:{},...B.author?{author:B.author}:{},...B.publishedAt?{publishedAt:B.publishedAt}:{},...B.canonicalUrl?{canonicalUrl:B.canonicalUrl}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function DN$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}import{mkdtemp as FN$,rm as IN$}from"fs/promises";import{tmpdir as LN$}from"os";import{join as NN$}from"path";_4();S2();qG();C0();import{jsxDEV as JN$}from"preact/jsx-dev-runtime";var Ow0="og-image",qN$="blog:og-image",yC2=H.object({title:H.string().min(1),excerpt:H.string().optional(),author:H.string().optional(),publishedAt:H.string().optional(),brandLabel:H.string().optional(),coverImageUrl:H.string().optional()}),gC2={name:qN$,pluginId:"blog",schema:yC2,renderers:{image:VN$}};function zN$(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 VN$(A){let Q=yC2.parse(A);return JN$(YP,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Journal",title:Q.title,subtitle:Q.excerpt,meta:[Q.author],tag:zN$(Q.publishedAt)},void 0,!1,void 0,this)}var _N$={width:1200,height:630},PN$=60000;class JGA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;screenshotPng;constructor(A,Q={}){this.context=A,this.screenshotPng=Q.screenshotPng??bw0}async resolve(A){if(A.sourceEntityType!=="post"||A.attachmentType!==Ow0)return;let Q=await this.context.entityService.getEntity({entityType:"post",id:A.sourceEntityId});if(!Q)return;let $=kN$(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),w=await FN$(NN$(LN$(),"brain-blog-og-image-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/og/post/${Q.id}`,template:gC2,format:"image",content:$,siteConfig:{title:$.title,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"image",data:await this.screenshotPng(X.urlFor(B.urlPath),_N$,{timeoutMs:PN$,fullPage:!1,omitBackground:!1}),mimeType:"image/png",filename:`${jN$(Q)}-og.png`}}finally{await X.close()}}finally{await IN$(w,{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}=c8(A.content),$=t5.parse(Q);if(!$.coverImageId)return;let w=await this.context.entityService.getEntity({entityType:"image",id:$.coverImageId});return w?.content.startsWith("data:image/")?w.content:void 0}}function kN$(A,Q={}){let{frontmatter:$}=c8(A.content),w=t5.parse($);return{title:w.title,...w.excerpt?{excerpt:w.excerpt}:{},...w.author?{author:w.author}:{},...w.publishedAt?{publishedAt:w.publishedAt}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function jN$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}var SC2={name:"@brains/blog",version:"0.2.0-alpha.184",description:"AI-powered blog post generation from existing brain content",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class FGA extends S6{entityType=_P.entityType;schema=Ei;adapter=_P;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("blog",SC2,A,BGA)}getEntityTypeConfig(){return{weight:2,publish:{publishStatuses:["queued","published"]}}}createGenerationHandler(A){return new XGA(this.logger.child("BlogGenerationJobHandler"),A)}getTemplates(){return NC2()}getDataSources(){return[new ZGA(this.logger.child("BlogDataSource"))]}async onRegister(A){let{RSSDataSource:Q}=await Promise.resolve().then(() => (cC2(),uC2));A.entities.registerDataSource(new Q(this.logger.child("RSSDataSource"))),_C2(A,this.logger),PC2(A,this.logger),jC2(A,this.logger),MC2(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("post",SP0,new VGA(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("post",Ow0,new JGA(A)),this.deferPublishAssetRegistration(A),this.unregisterAtprotoProjection=aB.getInstance().register(KGA()),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:Ow0,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 IGA(A={}){return new FGA(A)}qG();yi();KA();C0();y9();KA();C0();var t3=H.object({title:H.string(),slug:H.string(),coverImageId:H.string().optional()}),ON$=H.object({title:H.string(),slug:H.string()}),fN$=H.object({title:H.string(),slug:H.string()}),SO=H6.extend({entityType:H.literal("series"),metadata:fN$}),mP0=SO.extend({frontmatter:t3}),xN$=mP0.extend({description:H.string().optional(),postCount:H.number(),coverImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()}),pC2=H.object({description:H.string().optional()});function iE(A){return new d$(pC2,{title:A,mappings:[{key:"description",label:"Description",type:"string"}]})}KA();class LGA extends UQ{constructor(){super({entityType:"series",purpose:"A series grouping related posts or content under one theme.",schema:SO,frontmatterSchema:t3,supportsCoverImage:!0,bodyFormatter:iE("")})}toMarkdown(A){let Q,$={};try{Q=this.parseFrontMatter(A.content,t3).coverImageId,$=iE(A.metadata.title).parse(this.extractBody(A.content))}catch{}let w={title:A.metadata.title,slug:A.metadata.slug,...Q&&{coverImageId:Q}},X=iE(A.metadata.title).format($);return this.buildMarkdown(X,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,t3);return{content:A,entityType:"series",metadata:{title:Q.title,slug:Q.slug}}}parseBody(A){try{let Q=this.parseFrontMatter(A,t3);return iE(Q.title).parse(this.extractBody(A))}catch{return{}}}generateFrontMatter(){return""}}var mO=new LGA;KA();S2();bH();C0();var RN$=H.object({seriesName:H.string().optional(),seriesIndex:H.number().optional()});function uP0(A){let Q=RN$.safeParse(A);return Q.success?Q.data:{}}function nE(A){return uP0(A.metadata).seriesName}function lC2(A){return uP0(A.metadata).seriesIndex}function dC2(A,Q){let $=lC2(A)??Number.MAX_SAFE_INTEGER,w=lC2(Q)??Number.MAX_SAFE_INTEGER;return $-w}class NGA{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"}),$=new Map(Q.map((B)=>[B.id,B])),w=new Set;for(let B of A){let X=k1(B);w.add(X);let Y=$.get(X),Z=Y?.content??this.createSeriesContent(B),W=e6(Z);if(Y?.contentHash===W)continue;let K={id:X,entityType:"series",content:Z,contentHash:W,created:Y?.created??new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:B,slug:k1(B)}};await this.entityService.upsertEntity({entity:K}),this.logger.debug(`Upserted series: ${B}`)}for(let B of Q)if(!w.has(B.id))await this.entityService.deleteEntity({entityType:"series",id:B.id}),this.logger.debug(`Deleted orphaned series: ${B.id}`)}async handleEntityChange(A,Q){let $=nE(A);if($)await this.ensureSeriesExists($);if(Q&&Q!==$)await this.cleanupOrphanedSeries(Q)}async handleEntityDeleted(){await this.syncAllSeries()}async ensureSeriesExists(A){let Q=k1(A);if(await this.entityService.getEntity({entityType:"series",id:Q}))return;let w=this.createSeriesContent(A),B={id:Q,entityType:"series",content:w,contentHash:e6(w),created:new Date().toISOString(),updated:new Date().toISOString(),visibility:"public",metadata:{title:A,slug:k1(A)}};await this.entityService.upsertEntity({entity:B}),this.logger.debug(`Created series: ${A}`)}async cleanupOrphanedSeries(A){let Q=k1(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 $ of Q){if($==="series")continue;if((await this.entityService.listEntities({entityType:$,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 $ of Q){if($==="series")continue;let w=await this.entityService.listEntities({entityType:$});for(let B of w){let X=nE(B);if(X)A.add(X)}}return A}createSeriesContent(A){let Q={title:A,slug:k1(A)};return O7("",Q)}}KA();C0();var vN$=H.object({entityType:H.literal("series"),query:H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional()})}),CN$=H.object({type:H.enum(["list","detail"]),seriesName:H.string().optional()});function hN$(A){let Q=CN$.safeParse(A);if(Q.success)return{type:Q.data.type,seriesName:Q.data.seriesName};let $=vN$.safeParse(A);if($.success){let{query:w}=$.data;if(w.id)return{type:"detail",seriesSlug:w.id};return{type:"list"}}throw Error('Invalid series query format. Expected { type: "list"|"detail" } or { entityType: "series", query: { id?: string } }')}function iC2(A){let Q=_Q(A.content,t3);return mP0.parse({...A,frontmatter:Q.metadata})}class _GA{logger;id="series:entities";name="Series DataSource";description="Fetches series list and detail data";constructor(A){this.logger=A}async fetch(A,Q,$){let w=hN$(A),B=$.entityService;if(w.type==="list")return this.fetchSeriesList(Q,B);if(w.seriesName)return this.fetchSeriesDetail(w.seriesName,Q,B);if(w.seriesSlug)return this.fetchSeriesDetailBySlug(w.seriesSlug,Q,B);throw Error("Invalid series query: must specify seriesName or slug for detail")}async fetchSeriesList(A,Q){let $=await Q.listEntities({entityType:"series"}),w=await this.countEntitiesPerSeries(Q),B=$.map((X)=>{let Y=iC2(X),Z=mO.parseBody(X.content);return{...Y,description:Z.description,postCount:w.get(X.metadata.title)??0}});return this.logger.debug(`Found ${B.length} series entities`),A.parse({series:B})}async fetchSeriesDetail(A,Q,$,w){if(!w)w=(await $.listEntities({entityType:"series",options:{filter:{metadata:{title:A}}}}))[0];if(!w)throw Error(`Series not found: ${A}`);let B=iC2(w),X=mO.parseBody(w.content),Y=await this.getSeriesMembers(A,$);return this.logger.debug(`Found ${Y.length} entities in series "${A}"`),Q.parse({seriesName:A,posts:Y,series:{...B,description:X.description,postCount:Y.length},description:X.description})}async fetchSeriesDetailBySlug(A,Q,$){let B=(await $.listEntities({entityType:"series",options:{filter:{metadata:{slug:A}}}}))[0];if(!B)throw Error(`Series not found with slug: ${A}`);return this.fetchSeriesDetail(B.metadata.title,Q,$,B)}async countEntitiesPerSeries(A){let Q=new Map,$=A.getEntityTypes();for(let w of $){if(w==="series")continue;let B=await A.listEntities({entityType:w});for(let X of B){let Y=nE(X);if(Y)Q.set(Y,(Q.get(Y)??0)+1)}}return Q}async getSeriesMembers(A,Q){let $=[],w=Q.getEntityTypes();for(let B of w){if(B==="series")continue;let X=await Q.listEntities({entityType:B,options:{filter:{metadata:{seriesName:A}}}});$.push(...X)}return $.sort(dC2),$}}KA();C0();bH();var EN$=H.object({prompt:H.string().optional(),title:H.string().optional(),seriesId:H.string().optional()}),TN$=H.object({title:H.string().optional(),excerpt:H.string().optional()});class cP0{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 $=await this.context.entityService.getEntity({entityType:"series",id:Q});if(!$)return{success:!1,error:`Series not found: ${Q}`};let w=await this.gatherMemberSummaries($.metadata.title);if(w.length===0)return{success:!1,error:`No members found in series: ${$.metadata.title}`};let B=A.prompt??`Series name: ${$.metadata.title}
7005
7005
 
7006
7006
  Content in this series:
7007
7007
  ${w.join(`
@@ -7013,7 +7013,7 @@ Your task is to write a series description (2-3 sentences) that:
7013
7013
  3. Is engaging and makes readers want to explore the content
7014
7014
  4. Works well as a series overview on a website
7015
7015
 
7016
- Be concise and focus on what makes this series unique and valuable.`});async function Ah2({entity:A,config:Q}){let $=SO.parse(A),w=mO.parseBody($.content);return{$type:"ai.rizom.brain.series",title:$.metadata.title,slug:$.metadata.slug,...w.description&&{description:w.description},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"series",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function PGA(){return{entityType:"series",collection:"ai.rizom.brain.series",lexicon:E8["ai.rizom.brain.series"],validate:!1,buildRecord:Ah2}}var Qh2={name:"@brains/series",version:"0.2.0-alpha.183",description:"Cross-content series \u2014 auto-derived from entities with seriesName metadata",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var $h2=H.discriminatedUnion("mode",[H.object({mode:H.literal("derive"),reason:H.string().optional()}),H.object({mode:H.literal("source"),entityId:H.string(),entityType:H.string(),seriesName:H.string().optional(),previousSeriesName:H.string().optional()})]);class kGA extends S6{entityType="series";schema=SO;adapter=mO;manager;unregisterAtprotoProjection;constructor(){super("series",Qh2,{},XY)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new cP0(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...tC2(),description:eC2}}getDataSources(){return[new _GA(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 $=nE(Q.entity),w=uP0(Q.previousMetadata).seriesName;if(!$&&!w)return null;return{mode:"source",entityId:Q.entity.id,entityType:Q.entity.entityType,...$?{seriesName:$}:{},...w&&w!==$?{previousSeriesName:w}:{}}},jobOptions:(Q)=>{if(!Q.entity)return;return this.getSourceProjectionJobOptions(Q.entity)}}}]}async onRegister(A){this.manager=new NGA(A.entityService,this.logger.child("SeriesManager")),this.unregisterAtprotoProjection=aB.getInstance().register(PGA())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}createSeriesProjectionHandler(A){return{process:async(Q)=>{let $=$h2.parse(Q);if($.mode==="derive")return await this.projectAll(A),{success:!0};let w=await A.entityService.getEntity({entityType:$.entityType,id:$.entityId});if(w)await this.projectSource(w,$.previousSeriesName);else{let B=this.requireManager();for(let X of[$.seriesName,$.previousSeriesName])if(X)await B.cleanupOrphanedSeries(X)}return{success:!0}},validateAndParse:(Q)=>{let $=$h2.safeParse(Q??{});return $.success?$.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 cP0(this.logger.child("SeriesGenerationHandler"),A),$=await A.entityService.listEntities({entityType:"series"});for(let w of $)try{if(!this.adapter.parseBody(w.content).description)this.logger.info(`Generating description for series: ${w.metadata.title}`),await Q.process({seriesId:w.id})}catch(B){this.logger.error(`Failed to generate description for series: ${w.id}`,{error:B})}}}function jGA(){return new kGA}KA();C0();KA();S2();C0();KA();var wh2=H.enum(["generating","draft","queued","published","failed"]),Bh2=H.enum(["generating","draft","queued","published","failed"]),MGA="publishedAt is required when deck status is published",bGA=(A)=>A.status==="published"&&!A.publishedAt,OGA=(A)=>{if(bGA(A))throw Error(MGA)},AI=H.object({title:H.string(),slug:H.string().optional(),description:H.string().optional(),author:H.string().optional(),status:wh2,publishedAt:H.string().datetime().optional(),event:H.string().optional(),coverImageId:H.string().optional(),ogImageId:H.string().optional()}),yk5=H.object({title:H.string(),description:H.string().optional(),status:wh2,publishedAt:H.string().datetime().optional(),coverImageId:H.string().optional(),slug:H.string(),error:H.string().optional()}).superRefine((A,Q)=>{if(!bGA(A))return;Q.addIssue({code:H.ZodIssueCode.custom,path:["publishedAt"],message:MGA})}),dN$=H.object({title:H.string(),description:H.string().optional(),status:Bh2,publishedAt:H.string().datetime().optional(),coverImageId:H.string().optional(),slug:H.string(),error:H.string().optional()}).superRefine((A,Q)=>{if(!bGA(A))return;Q.addIssue({code:"custom",path:["publishedAt"],message:MGA})}),iN$=H.object({title:H.string(),slug:H.string().optional(),description:H.string().optional(),author:H.string().optional(),status:Bh2,publishedAt:H.string().datetime().optional(),event:H.string().optional(),coverImageId:H.string().optional(),ogImageId:H.string().optional()}),Si=H6.extend({entityType:H.literal("deck"),metadata:dN$}),pP0=Si.extend({frontmatter:iN$,body:H.string(),ogImageUrl:H.string().optional()}),fw0=pP0.extend({url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});class fGA extends UQ{constructor(){super({entityType:"deck",purpose:"A slide-deck presentation.",schema:Si,frontmatterSchema:AI,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 $=this.parseFrontMatter(A.content,AI);OGA($);let w={...$,slug:$.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontmatter(A),$=this.extractBody(A);OGA(Q),this.validateSlideStructure($);let w=Q.slug??k1(Q.title),B=Q.status;return{entityType:"deck",content:A,metadata:{slug:w,title:Q.title,description:Q.description,status:B,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(`---
7016
+ Be concise and focus on what makes this series unique and valuable.`});async function Ah2({entity:A,config:Q}){let $=SO.parse(A),w=mO.parseBody($.content);return{$type:"ai.rizom.brain.series",title:$.metadata.title,slug:$.metadata.slug,...w.description&&{description:w.description},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"series",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function PGA(){return{entityType:"series",collection:"ai.rizom.brain.series",lexicon:E8["ai.rizom.brain.series"],validate:!1,buildRecord:Ah2}}var Qh2={name:"@brains/series",version:"0.2.0-alpha.184",description:"Cross-content series \u2014 auto-derived from entities with seriesName metadata",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var $h2=H.discriminatedUnion("mode",[H.object({mode:H.literal("derive"),reason:H.string().optional()}),H.object({mode:H.literal("source"),entityId:H.string(),entityType:H.string(),seriesName:H.string().optional(),previousSeriesName:H.string().optional()})]);class kGA extends S6{entityType="series";schema=SO;adapter=mO;manager;unregisterAtprotoProjection;constructor(){super("series",Qh2,{},XY)}getEntityTypeConfig(){return{weight:0.5}}createGenerationHandler(A){return new cP0(this.logger.child("SeriesGenerationHandler"),A)}getTemplates(){return{...tC2(),description:eC2}}getDataSources(){return[new _GA(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 $=nE(Q.entity),w=uP0(Q.previousMetadata).seriesName;if(!$&&!w)return null;return{mode:"source",entityId:Q.entity.id,entityType:Q.entity.entityType,...$?{seriesName:$}:{},...w&&w!==$?{previousSeriesName:w}:{}}},jobOptions:(Q)=>{if(!Q.entity)return;return this.getSourceProjectionJobOptions(Q.entity)}}}]}async onRegister(A){this.manager=new NGA(A.entityService,this.logger.child("SeriesManager")),this.unregisterAtprotoProjection=aB.getInstance().register(PGA())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}createSeriesProjectionHandler(A){return{process:async(Q)=>{let $=$h2.parse(Q);if($.mode==="derive")return await this.projectAll(A),{success:!0};let w=await A.entityService.getEntity({entityType:$.entityType,id:$.entityId});if(w)await this.projectSource(w,$.previousSeriesName);else{let B=this.requireManager();for(let X of[$.seriesName,$.previousSeriesName])if(X)await B.cleanupOrphanedSeries(X)}return{success:!0}},validateAndParse:(Q)=>{let $=$h2.safeParse(Q??{});return $.success?$.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 cP0(this.logger.child("SeriesGenerationHandler"),A),$=await A.entityService.listEntities({entityType:"series"});for(let w of $)try{if(!this.adapter.parseBody(w.content).description)this.logger.info(`Generating description for series: ${w.metadata.title}`),await Q.process({seriesId:w.id})}catch(B){this.logger.error(`Failed to generate description for series: ${w.id}`,{error:B})}}}function jGA(){return new kGA}KA();C0();KA();S2();C0();KA();var wh2=H.enum(["generating","draft","queued","published","failed"]),Bh2=H.enum(["generating","draft","queued","published","failed"]),MGA="publishedAt is required when deck status is published",bGA=(A)=>A.status==="published"&&!A.publishedAt,OGA=(A)=>{if(bGA(A))throw Error(MGA)},AI=H.object({title:H.string(),slug:H.string().optional(),description:H.string().optional(),author:H.string().optional(),status:wh2,publishedAt:H.string().datetime().optional(),event:H.string().optional(),coverImageId:H.string().optional(),ogImageId:H.string().optional()}),yk5=H.object({title:H.string(),description:H.string().optional(),status:wh2,publishedAt:H.string().datetime().optional(),coverImageId:H.string().optional(),slug:H.string(),error:H.string().optional()}).superRefine((A,Q)=>{if(!bGA(A))return;Q.addIssue({code:H.ZodIssueCode.custom,path:["publishedAt"],message:MGA})}),dN$=H.object({title:H.string(),description:H.string().optional(),status:Bh2,publishedAt:H.string().datetime().optional(),coverImageId:H.string().optional(),slug:H.string(),error:H.string().optional()}).superRefine((A,Q)=>{if(!bGA(A))return;Q.addIssue({code:"custom",path:["publishedAt"],message:MGA})}),iN$=H.object({title:H.string(),slug:H.string().optional(),description:H.string().optional(),author:H.string().optional(),status:Bh2,publishedAt:H.string().datetime().optional(),event:H.string().optional(),coverImageId:H.string().optional(),ogImageId:H.string().optional()}),Si=H6.extend({entityType:H.literal("deck"),metadata:dN$}),pP0=Si.extend({frontmatter:iN$,body:H.string(),ogImageUrl:H.string().optional()}),fw0=pP0.extend({url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});class fGA extends UQ{constructor(){super({entityType:"deck",purpose:"A slide-deck presentation.",schema:Si,frontmatterSchema:AI,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 $=this.parseFrontMatter(A.content,AI);OGA($);let w={...$,slug:$.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}fromMarkdown(A){let Q=this.parseFrontmatter(A),$=this.extractBody(A);OGA(Q),this.validateSlideStructure($);let w=Q.slug??k1(Q.title),B=Q.status;return{entityType:"deck",content:A,metadata:{slug:w,title:Q.title,description:Q.description,status:B,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(`---
7017
7017
  `,Q),metadata:{title:A.title,slug:A.id,status:"generating"}}}}var xw0=new fGA;C0();Q5();var nN$=H.object({markdown:H.string().describe("Markdown content with slide separators (---)"),deck:fw0.optional()}),xGA=K2({name:"deck-detail",description:"Render a presentation deck as Reveal.js slides",schema:nN$,dataSourceId:"decks:entities",requiredPermission:"public",layout:{component:iHA,fullscreen:!0}});Q5();C0();var RGA=H.object({decks:H.array(pP0)}),vGA=H.object({decks:H.array(fw0),pageTitle:H.string().optional(),pageLabel:H.string().optional()});import{jsxDEV as CGA}from"preact/jsx-dev-runtime";var rN$="Presentations",hGA=({decks:A,pageLabel:Q})=>{let $=A.map((B)=>({id:B.id,url:B.url,title:B.frontmatter.title,date:B.frontmatter.publishedAt??B.created,description:B.frontmatter.description}));return CGA("div",{className:"deck-list bg-theme",children:CGA("div",{className:"container mx-auto max-w-[1100px] px-6 py-16 md:px-12 md:py-24",children:CGA(L80,{label:Q&&Q!=="Decks"?Q:rN$,items:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)};y9();class lP0 extends d${constructor(){super(RGA,{title:"Deck List",mappings:[{key:"decks",label:"Decks",type:"array",itemType:"object"}]})}}var EGA=K2({name:"deck-list",description:"List view of all presentation decks",schema:vGA,dataSourceId:"decks:entities",requiredPermission:"public",formatter:new lP0,layout:{component:hGA}});C0();KA();var oN$=H.object({title:H.string().max(80).describe("A short, punchy title (2-5 words) that's memorable and evocative"),content:H.string().describe("Full slide deck content in markdown format with slide separators (---). Each slide should have a header and focused content."),description:H.string().describe("A concise 1-2 sentence summary that captures the essence of the talk")}),Xh2=K2({name:"decks:generation",description:"Template for AI to generate complete slide decks from prompts",schema:oN$,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are creating slide decks in a distinctive voice that blends philosophy, technology, and culture.
7018
7018
 
7019
7019
  Your task is to generate a complete slide deck based on the user's prompt.
@@ -7321,7 +7321,7 @@ ${Z}`,templateName:"decks:description"})).description,await this.reportProgress(
7321
7321
  color: var(--carousel-accent);
7322
7322
  font-weight: 600;
7323
7323
  }
7324
- `}},void 0,!1,void 0,this),B.map((K,U)=>mZ("section",{className:`deck-carousel-slide${U===0?" is-cover":""}`,children:[mZ("header",{className:"deck-carousel-header",children:mZ("span",{className:"deck-carousel-wordmark","aria-label":$??Q,children:[mZ("span",{className:"wm-primary",children:X.primary},void 0,!1,void 0,this),X.secondary!==void 0&&mZ(Q_$,{children:[mZ("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),mZ("span",{className:"wm-secondary",children:X.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),mZ("div",{className:"deck-carousel-body",children:mZ("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:W(K.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),mZ("footer",{className:"deck-carousel-footer",children:[mZ("span",{className:"deck-carousel-footer-meta",children:w??Q},void 0,!1,void 0,this),mZ("span",{className:"deck-carousel-counter","aria-label":`Slide ${U+1} of ${Y}`,children:[mZ("span",{className:"deck-carousel-counter-current",children:String(U+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",mZ("span",{children:Z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},U,!0,void 0,this))]},void 0,!0,void 0,this)}import{mkdtemp as $_$,rm as w_$}from"fs/promises";import{tmpdir as B_$}from"os";import{join as X_$}from"path";_4();S2();var Y_$=26214400,Z_$=60000,Kh2=20;class gGA{metadata={outputEntityType:"document"};context;renderPdf;getThemeMode;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3,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 $=H_$(Q,{brandLabel:this.resolveBrandLabel()});if($.slides.length>Kh2)throw Error(`Refusing to render carousel with ${$.slides.length} slides; maxSlides=${Kh2}`);let w=await this.getThemeMode(),B=await $_$(X_$(B_$(),"brain-deck-carousel-"));try{let X=await VG({outputDir:B,mediaPath:`/_media/carousel/${Q.id}`,template:Wh2,format:"pdf",content:$,siteConfig:{title:$.title,themeMode:w},themeCSS:this.context.themeCSS}),Y=await JG({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor(X.urlPath),{maxBytes:Y_$,timeoutMs:Z_$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${W_$(Q)}-carousel.pdf`}}finally{await Y.close()}}finally{await w_$(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;return Q.length>0?Q:void 0}}function H_$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=typeof $.title==="string"?$.title:A.metadata.title,X=typeof $.event==="string"&&$.event.length>0?$.event:void 0,Y=w.split(/^---$/gm).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>({markdown:Z}));return{title:B,slides:Y,...Q.brandLabel?{brandLabel:Q.brandLabel}:{},...X?{eyebrow:X}:{}}}function W_$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}C0();import{jsxDEV as G_$}from"preact/jsx-dev-runtime";var dP0="og-image",K_$="decks:og-image",Uh2=H.object({title:H.string().min(1),description:H.string().optional(),event:H.string().optional(),brandLabel:H.string().optional(),slideCount:H.number().int().positive().optional(),coverImageUrl:H.string().optional()}),Gh2={name:K_$,pluginId:"decks",schema:Uh2,renderers:{image:U_$}};function U_$(A){let Q=Uh2.parse(A),$=Q.slideCount?`${Q.slideCount} slide${Q.slideCount===1?"":"s"}`:void 0;return G_$(YP,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Deck",title:Q.title,subtitle:Q.description,meta:[Q.event],tag:$},void 0,!1,void 0,this)}_4();S2();class SGA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;deps;constructor(A,Q={}){this.context=A,this.deps=Q}async resolve(A){if(A.sourceEntityType!=="deck"||A.attachmentType!==dP0)return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let{frontmatter:$,content:w}=c8(Q.content),B=AI.parse($),X=D_$(w),Y=this.resolveBrandLabel(),Z=await this.resolveCoverImageUrl(B.coverImageId),W={title:B.title,...B.description?{description:B.description}:{},...B.event?{event:B.event}:{},...X?{slideCount:X}:{},...Z?{coverImageUrl:Z}:{},...Y?{brandLabel:Y}:{}};return{type:"image",data:await dE({mediaPath:`/_media/og/deck/${Q.id}`,template:Gh2,content:W,title:W.title,themeMode:"dark",themeCSS:this.context.themeCSS,tmpPrefix:"brain-deck-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${q_$(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 D_$(A){return A.split(/^---$/gm).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).length}function q_$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}KA();async function Dh2({entity:A,config:Q}){let $=Si.parse(A),w=_Q($.content,AI),B=w.metadata;return{$type:"ai.rizom.brain.deck",title:B.title,...B.slug&&{slug:B.slug},...B.description&&{description:B.description},body:w.content,format:"text/markdown",...B.author&&{author:B.author},...B.event&&{event:B.event},...B.publishedAt&&{publishedAt:B.publishedAt},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"deck",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function mGA(){return{entityType:"deck",collection:"ai.rizom.brain.deck",lexicon:E8["ai.rizom.brain.deck"],validate:!1,buildRecord:Dh2}}var qh2={name:"@brains/decks",version:"0.2.0-alpha.183",description:"Presentation decks plugin for creating and viewing slide presentations",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var V_$=H.object({prompt:H.string(),event:H.string().optional()}),J_$=H.object({title:H.string(),content:H.string()});class uGA extends S6{deps;entityType=xw0.entityType;schema=xw0.schema;adapter=xw0;unregisterCarouselAttachmentProvider;unregisterOgImageAttachmentProvider;unregisterAtprotoProjection;constructor(A={}){super("decks",qh2,{},XY);this.deps=A}createGenerationHandler(A){return new yGA(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":xGA,"deck-list":EGA,generation:Xh2,description:Yh2}}getDataSources(){return[new TGA(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=aB.getInstance().register(mGA()),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:$,entityId:w}=Q.payload;if($!=="deck")return{success:!0};try{let B=await A.entityService.getEntity({entityType:"deck",id:w});if(!B)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:`Deck not found: ${w}`}}),{success:!0};if(B.metadata.status==="published")return{success:!0};let X=new Date().toISOString(),Y={...B,metadata:{...B.metadata,status:"published",publishedAt:X}};await A.entityService.updateEntity({entity:{...Y,content:this.adapter.toMarkdown(Y)}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:$,entityId:w,result:{id:w}}})}catch(B){await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:aA(B)}})}return{success:!0}})}registerCarouselAttachmentProvider(A){let Q={...this.deps,getThemeMode:this.deps.getThemeMode??(async()=>{try{return(await _w0(A.entityService)).themeMode??"dark"}catch{return"dark"}})};this.unregisterCarouselAttachmentProvider=A.attachments.register("deck",Zh2,new gGA(A,Q))}registerOgImageAttachmentProvider(A){this.unregisterOgImageAttachmentProvider=A.attachments.register("deck",dP0,new SGA(A))}registerEvalHandlers(A){A.eval.registerHandler("generateDeck",async(Q)=>{let $=V_$.parse(Q);return A.ai.generate({prompt:`${$.prompt}${$.event?`
7324
+ `}},void 0,!1,void 0,this),B.map((K,U)=>mZ("section",{className:`deck-carousel-slide${U===0?" is-cover":""}`,children:[mZ("header",{className:"deck-carousel-header",children:mZ("span",{className:"deck-carousel-wordmark","aria-label":$??Q,children:[mZ("span",{className:"wm-primary",children:X.primary},void 0,!1,void 0,this),X.secondary!==void 0&&mZ(Q_$,{children:[mZ("span",{className:"wm-dot",children:"."},void 0,!1,void 0,this),mZ("span",{className:"wm-secondary",children:X.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),mZ("div",{className:"deck-carousel-body",children:mZ("div",{className:"deck-carousel-content",dangerouslySetInnerHTML:{__html:W(K.markdown)}},void 0,!1,void 0,this)},void 0,!1,void 0,this),mZ("footer",{className:"deck-carousel-footer",children:[mZ("span",{className:"deck-carousel-footer-meta",children:w??Q},void 0,!1,void 0,this),mZ("span",{className:"deck-carousel-counter","aria-label":`Slide ${U+1} of ${Y}`,children:[mZ("span",{className:"deck-carousel-counter-current",children:String(U+1).padStart(2,"0")},void 0,!1,void 0,this)," / ",mZ("span",{children:Z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},U,!0,void 0,this))]},void 0,!0,void 0,this)}import{mkdtemp as $_$,rm as w_$}from"fs/promises";import{tmpdir as B_$}from"os";import{join as X_$}from"path";_4();S2();var Y_$=26214400,Z_$=60000,Kh2=20;class gGA{metadata={outputEntityType:"document"};context;renderPdf;getThemeMode;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3,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 $=H_$(Q,{brandLabel:this.resolveBrandLabel()});if($.slides.length>Kh2)throw Error(`Refusing to render carousel with ${$.slides.length} slides; maxSlides=${Kh2}`);let w=await this.getThemeMode(),B=await $_$(X_$(B_$(),"brain-deck-carousel-"));try{let X=await VG({outputDir:B,mediaPath:`/_media/carousel/${Q.id}`,template:Wh2,format:"pdf",content:$,siteConfig:{title:$.title,themeMode:w},themeCSS:this.context.themeCSS}),Y=await JG({rootDir:B});try{return{type:"document",data:await this.renderPdf(Y.urlFor(X.urlPath),{maxBytes:Y_$,timeoutMs:Z_$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${W_$(Q)}-carousel.pdf`}}finally{await Y.close()}}finally{await w_$(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;return Q.length>0?Q:void 0}}function H_$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=typeof $.title==="string"?$.title:A.metadata.title,X=typeof $.event==="string"&&$.event.length>0?$.event:void 0,Y=w.split(/^---$/gm).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>({markdown:Z}));return{title:B,slides:Y,...Q.brandLabel?{brandLabel:Q.brandLabel}:{},...X?{eyebrow:X}:{}}}function W_$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}C0();import{jsxDEV as G_$}from"preact/jsx-dev-runtime";var dP0="og-image",K_$="decks:og-image",Uh2=H.object({title:H.string().min(1),description:H.string().optional(),event:H.string().optional(),brandLabel:H.string().optional(),slideCount:H.number().int().positive().optional(),coverImageUrl:H.string().optional()}),Gh2={name:K_$,pluginId:"decks",schema:Uh2,renderers:{image:U_$}};function U_$(A){let Q=Uh2.parse(A),$=Q.slideCount?`${Q.slideCount} slide${Q.slideCount===1?"":"s"}`:void 0;return G_$(YP,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Deck",title:Q.title,subtitle:Q.description,meta:[Q.event],tag:$},void 0,!1,void 0,this)}_4();S2();class SGA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;deps;constructor(A,Q={}){this.context=A,this.deps=Q}async resolve(A){if(A.sourceEntityType!=="deck"||A.attachmentType!==dP0)return;let Q=await this.context.entityService.getEntity({entityType:"deck",id:A.sourceEntityId});if(!Q)return;let{frontmatter:$,content:w}=c8(Q.content),B=AI.parse($),X=D_$(w),Y=this.resolveBrandLabel(),Z=await this.resolveCoverImageUrl(B.coverImageId),W={title:B.title,...B.description?{description:B.description}:{},...B.event?{event:B.event}:{},...X?{slideCount:X}:{},...Z?{coverImageUrl:Z}:{},...Y?{brandLabel:Y}:{}};return{type:"image",data:await dE({mediaPath:`/_media/og/deck/${Q.id}`,template:Gh2,content:W,title:W.title,themeMode:"dark",themeCSS:this.context.themeCSS,tmpPrefix:"brain-deck-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${q_$(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 D_$(A){return A.split(/^---$/gm).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).length}function q_$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}KA();async function Dh2({entity:A,config:Q}){let $=Si.parse(A),w=_Q($.content,AI),B=w.metadata;return{$type:"ai.rizom.brain.deck",title:B.title,...B.slug&&{slug:B.slug},...B.description&&{description:B.description},body:w.content,format:"text/markdown",...B.author&&{author:B.author},...B.event&&{event:B.event},...B.publishedAt&&{publishedAt:B.publishedAt},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"deck",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function mGA(){return{entityType:"deck",collection:"ai.rizom.brain.deck",lexicon:E8["ai.rizom.brain.deck"],validate:!1,buildRecord:Dh2}}var qh2={name:"@brains/decks",version:"0.2.0-alpha.184",description:"Presentation decks plugin for creating and viewing slide presentations",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var V_$=H.object({prompt:H.string(),event:H.string().optional()}),J_$=H.object({title:H.string(),content:H.string()});class uGA extends S6{deps;entityType=xw0.entityType;schema=xw0.schema;adapter=xw0;unregisterCarouselAttachmentProvider;unregisterOgImageAttachmentProvider;unregisterAtprotoProjection;constructor(A={}){super("decks",qh2,{},XY);this.deps=A}createGenerationHandler(A){return new yGA(this.logger.child("DeckGenerationJobHandler"),A)}getTemplates(){return{"deck-detail":xGA,"deck-list":EGA,generation:Xh2,description:Yh2}}getDataSources(){return[new TGA(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=aB.getInstance().register(mGA()),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:$,entityId:w}=Q.payload;if($!=="deck")return{success:!0};try{let B=await A.entityService.getEntity({entityType:"deck",id:w});if(!B)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:`Deck not found: ${w}`}}),{success:!0};if(B.metadata.status==="published")return{success:!0};let X=new Date().toISOString(),Y={...B,metadata:{...B.metadata,status:"published",publishedAt:X}};await A.entityService.updateEntity({entity:{...Y,content:this.adapter.toMarkdown(Y)}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:$,entityId:w,result:{id:w}}})}catch(B){await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:aA(B)}})}return{success:!0}})}registerCarouselAttachmentProvider(A){let Q={...this.deps,getThemeMode:this.deps.getThemeMode??(async()=>{try{return(await _w0(A.entityService)).themeMode??"dark"}catch{return"dark"}})};this.unregisterCarouselAttachmentProvider=A.attachments.register("deck",Zh2,new gGA(A,Q))}registerOgImageAttachmentProvider(A){this.unregisterOgImageAttachmentProvider=A.attachments.register("deck",dP0,new SGA(A))}registerEvalHandlers(A){A.eval.registerHandler("generateDeck",async(Q)=>{let $=V_$.parse(Q);return A.ai.generate({prompt:`${$.prompt}${$.event?`
7325
7325
 
7326
7326
  Note: This presentation is for "${$.event}".`:""}`,templateName:"decks:generation"})}),A.eval.registerHandler("generateDescription",async(Q)=>{let $=J_$.parse(Q);return A.ai.generate({prompt:`Title: ${$.title}
7327
7327
 
@@ -7478,9 +7478,9 @@ ${$.content}`,templateName:"decks:description"})})}}function vw0(){return new uG
7478
7478
  background: transparent;
7479
7479
  }
7480
7480
 
7481
- `,kh2=()=>a7("style",{children:P_$},void 0,!1,void 0,this);import{jsxDEV as HQ,Fragment as k_$}from"preact/jsx-dev-runtime";var sP0=({title:A,description:Q,children:$,detail:w=!1,footer:B=!1,contentClassName:X=""})=>HQ(k_$,{children:[HQ(C6,{title:A,description:Q},void 0,!1,void 0,this),HQ(kh2,{},void 0,!1,void 0,this),HQ("div",{className:`docs-handbook${w?" docs-handbook--detail":""}`,children:[HQ(_h2,{},void 0,!1,void 0,this),HQ("div",{className:`${QI.wrap} ${X}`.trim(),children:[$,B&&HQ(Ph2,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),jh2=({docsCount:A,sectionsCount:Q,startDoc:$})=>HQ("section",{className:"border-b border-[var(--docs-text)] py-14 md:py-24 md:pb-[72px]",children:[HQ("p",{className:`${QI.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),HQ("h1",{className:`${QI.display} m-0 max-w-[16ch] text-5xl leading-[1.05] tracking-[-0.02em] md:text-7xl`,children:["Build, run, and publish"," ",HQ("em",{className:"text-[var(--docs-accent)]",children:"brains."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),HQ("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),HQ("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:[HQ("div",{children:[HQ("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),HQ("div",{children:[HQ("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),HQ("div",{children:[HQ("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),HQ("div",{className:"mt-9 flex flex-wrap gap-3.5",children:[$&&HQ("a",{className:QI.primaryButton,href:ui($),children:"Start reading"},void 0,!1,void 0,this),HQ("a",{className:QI.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Mh2=({groups:A})=>HQ("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:[HQ("p",{className:"m-0 mb-3.5 font-medium text-[var(--docs-text)]",children:"Sections"},void 0,!1,void 0,this),HQ("ol",{className:"m-0 list-none p-0",children:A.map((Q,$)=>HQ("li",{className:"grid grid-cols-[32px_1fr] gap-2 py-1.5",children:[HQ("span",{className:"docs-font-display text-[var(--docs-text-light)] italic",children:[ci($),"."]},void 0,!0,void 0,this),HQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:`#${oP0($)}`,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),bh2=({group:A,index:Q})=>HQ("article",{className:"mb-16 last:mb-0",id:oP0(Q),children:[HQ("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:[HQ("span",{className:"text-right docs-font-display text-3xl leading-[1.1] text-[var(--docs-accent)] italic md:text-4xl",children:[ci(Q),"."]},void 0,!0,void 0,this),HQ("h2",{className:`${QI.display} m-0 text-3xl leading-[1.1] tracking-[-0.015em] md:text-4xl`,children:A.section},void 0,!1,void 0,this),HQ("span",{className:"docs-chapter__leader"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),HQ("ol",{className:"m-0 list-none p-0",children:A.docs.map(($)=>HQ("li",{className:"border-b border-[var(--docs-border-light)] last:border-b-0",children:HQ("a",{className:"group block py-[18px] pl-12 md:pl-[68px]",href:ui($),children:[HQ("p",{className:"m-0 text-[22px] leading-[1.2] tracking-[-0.005em] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:$.metadata.title},void 0,!1,void 0,this),$.metadata.description&&HQ("p",{className:"mt-1.5 mb-0 max-w-[70ch] text-sm leading-[1.55] text-[var(--docs-text-muted)]",children:$.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},$.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Oh2=({title:A})=>HQ("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:[HQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/",children:"Home"},void 0,!1,void 0,this),HQ("span",{children:"/"},void 0,!1,void 0,this),HQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/docs",children:"Docs"},void 0,!1,void 0,this),HQ("span",{children:"/"},void 0,!1,void 0,this),HQ("span",{children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this),fh2=({groups:A,activeGroupIndex:Q,activeSlug:$})=>HQ("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:HQ("nav",{className:"docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)]",children:[HQ("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),HQ("ol",{className:"m-0 list-none p-0",children:A.map((w,B)=>{let X=B===Q;return HQ("li",{className:X?"mb-[22px]":"mb-3.5",children:[HQ("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)] ${X?"text-[var(--docs-text)]":"text-[var(--docs-text-muted)]"}`,href:`/docs#${oP0(B)}`,children:[HQ("span",{className:"docs-font-display text-sm text-[var(--docs-accent)] italic",children:[ci(B),"."]},void 0,!0,void 0,this)," ",w.section]},void 0,!0,void 0,this),X&&HQ("ol",{className:"mt-0.5 list-none p-0",children:w.docs.map((Y)=>{let Z=Y.metadata.slug===$;return HQ("li",{children:HQ("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)] ${Z?"pl-3.5 font-medium text-[var(--docs-accent)]":"text-[var(--docs-text-muted)]"}`,href:ui(Y),"aria-current":Z?"page":void 0,children:Y.metadata.title},void 0,!1,void 0,this)},Y.id,!1,void 0,this)})},void 0,!1,void 0,this)]},w.section,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),xh2=({prevDoc:A,nextDoc:Q})=>{if(!A&&!Q)return null;return HQ("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?HQ("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] transition-colors duration-150 hover:border-[var(--docs-accent)]",href:ui(A),children:[HQ("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),HQ("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):HQ("span",{},void 0,!1,void 0,this),Q&&HQ("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:ui(Q),children:[HQ("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),HQ("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 pi}from"preact/jsx-dev-runtime";var dGA=({docs:A})=>{let Q=Cw0(A),$=rP0(Q),B=Q.filter((X)=>X.metadata.slug!=="index")[0]??Q[0];return pi(sP0,{title:"Documentation",description:"Brains documentation",children:[pi(jh2,{docsCount:A.length,sectionsCount:$.length,startDoc:B},void 0,!1,void 0,this),pi("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:[pi(Mh2,{groups:$},void 0,!1,void 0,this),pi("div",{children:$.map((X,Y)=>pi(bh2,{group:X,index:Y},X.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 FG}from"preact/jsx-dev-runtime";var iGA=({doc:A,docs:Q,prevDoc:$,nextDoc:w})=>{let B=rP0(Q.length>0?Q:[A]),X=Cw0(Q.length>0?Q:[A]),Y=X.findIndex((W)=>W.metadata.slug===A.metadata.slug),Z=Math.max(B.findIndex((W)=>W.docs.some((K)=>K.metadata.slug===A.metadata.slug)),0);return FG(sP0,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[FG(Oh2,{title:A.metadata.title},void 0,!1,void 0,this),FG("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[FG(fh2,{groups:B,activeGroupIndex:Z,activeSlug:A.metadata.slug},void 0,!1,void 0,this),FG("article",{className:"min-w-0",children:[FG("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[FG("p",{className:`${QI.label} m-0 mb-6 flex items-baseline gap-3`,children:[FG("span",{className:"docs-font-display text-lg leading-none tracking-normal normal-case text-[var(--docs-accent)] italic",children:[ci(Z),"."]},void 0,!0,void 0,this)," ",A.metadata.section,Y>=0?` \xB7 ${Y+1}/${X.length}`:""]},void 0,!0,void 0,this),FG("h1",{className:`${QI.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&&FG("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),FG("div",{className:"docs-article__body",children:FG(u4,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),FG(xh2,{prevDoc:$,nextDoc:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};var j_$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),M_$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),b_$=H.object({title:H.string(),section:H.string(),order:H.number().int(),sourcePath:H.string(),description:H.string().optional(),slug:H.string().optional()}),O_$=H.object({title:H.string(),section:H.string(),order:H.number().int(),description:H.string().optional(),slug:H.string()}),hw0=H.object({id:H.string(),entityType:H.literal("doc"),content:H.string(),created:H.string(),updated:H.string(),visibility:M_$,metadata:O_$,contentHash:H.string(),frontmatter:b_$,body:H.string()}),f_$=H.object({docs:H.array(hw0),pagination:j_$.nullable(),baseUrl:H.string().optional()}),x_$=H.object({doc:hw0,docs:H.array(hw0),prevDoc:hw0.nullable(),nextDoc:hw0.nullable()});function Rh2(){return{"doc-list":K2({name:"doc-list",description:"Documentation index template",schema:f_$,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:dGA}}),"doc-detail":K2({name:"doc-detail",description:"Documentation page template",schema:x_$,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:iGA}})}}var vh2={name:"@brains/doc",version:"0.2.0-alpha.183",description:"Documentation entity type \u2014 markdown docs as first-class brain content",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":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class nGA extends S6{entityType=iP0.entityType;schema=mi;adapter=iP0;constructor(){super("docs",vh2,{},XY)}getTemplates(){return Rh2()}getDataSources(){return[new nP0(this.logger.child("DocDataSource"))]}}function Ew0(){return new nGA}KA();S2();C0();p5();C0();var rGA=H.literal("application/pdf"),Ch2=H.enum(["pending","draft","failed"]),oGA=H.object({title:H.string().optional(),mimeType:rGA,filename:H.string().min(1),pageCount:H.number().int().min(0).optional(),status:Ch2.optional(),processingJobId:H.string().optional(),processingError:H.string().optional(),sourceEntityType:H.string().min(1).optional(),sourceEntityId:H.string().min(1).optional(),sourceUploadId:H.string().optional(),sourceFilename:H.string().optional(),sourceMediaType:H.string().optional(),attachmentType:H.string().min(1).optional(),dedupKey:H.string().min(1).optional()}),li=H6.extend({entityType:H.literal("document"),content:H.string().regex(/^data:application\/pdf;base64,.+$/),metadata:oGA});function Tw0(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 aP0(A){return`data:application/pdf;base64,${Buffer.from(A).toString("base64")}`}function sGA(A){let Q=Buffer.from(A).toString("latin1"),$=0,w=/\/Type\s*\/Pages\b[^]*?\/Count\s+(\d+)|\/Count\s+(\d+)[^]*?\/Type\s*\/Pages\b/g;for(let X of Q.matchAll(w)){let Y=parseInt(X[1]??X[2]??"0",10);if(Y>$)$=Y}if($>0)return $;return Q.match(/\/Type\s*\/Page(?!\w)/g)?.length??0}class tP0{entityType="document";purpose="A durable rendered file artifact such as a printable or carousel PDF.";schema=li;toMarkdown(A){return A.content}fromMarkdown(A){return Tw0(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,...$}=A,{mimeType:w}=Tw0(Q);return{entityType:"document",content:Q,metadata:{mimeType:w,...$}}}}var PP=new tP0;async function TDA(A,Q={}){let $=Q.maxBytes??5000000;if(A.byteLength>$)throw Error(`Uploaded PDF is too large for synchronous markdown extraction (${A.byteLength} bytes; max ${$} bytes)`);let B=(await Promise.resolve().then(() => (cT2(),uT2))).getDocument({data:new Uint8Array(A),disableFontFace:!1,useSystemFonts:!0,useWorkerFetch:!1}),X=await B.promise;try{let Y=Q.maxPages??50;if(X.numPages>Y)throw Error(`Uploaded PDF has ${X.numPages} pages; maximum supported for synchronous markdown extraction is ${Y}`);let Z=[];for(let K=1;K<=X.numPages;K+=1){let D=(await(await X.getPage(K)).getTextContent()).items.flatMap((q)=>("str"in q)?[q.str]:[]).join(" ").replace(/\s+/g," ").trim();if(D.length>0)Z.push(D)}let W=Z.join(`
7481
+ `,kh2=()=>a7("style",{children:P_$},void 0,!1,void 0,this);import{jsxDEV as HQ,Fragment as k_$}from"preact/jsx-dev-runtime";var sP0=({title:A,description:Q,children:$,detail:w=!1,footer:B=!1,contentClassName:X=""})=>HQ(k_$,{children:[HQ(C6,{title:A,description:Q},void 0,!1,void 0,this),HQ(kh2,{},void 0,!1,void 0,this),HQ("div",{className:`docs-handbook${w?" docs-handbook--detail":""}`,children:[HQ(_h2,{},void 0,!1,void 0,this),HQ("div",{className:`${QI.wrap} ${X}`.trim(),children:[$,B&&HQ(Ph2,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),jh2=({docsCount:A,sectionsCount:Q,startDoc:$})=>HQ("section",{className:"border-b border-[var(--docs-text)] py-14 md:py-24 md:pb-[72px]",children:[HQ("p",{className:`${QI.label} mb-8`,children:"Handbook \xB7 Brains docs"},void 0,!1,void 0,this),HQ("h1",{className:`${QI.display} m-0 max-w-[16ch] text-5xl leading-[1.05] tracking-[-0.02em] md:text-7xl`,children:["Build, run, and publish"," ",HQ("em",{className:"text-[var(--docs-accent)]",children:"brains."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),HQ("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),HQ("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:[HQ("div",{children:[HQ("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),HQ("div",{children:[HQ("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),HQ("div",{children:[HQ("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),HQ("div",{className:"mt-9 flex flex-wrap gap-3.5",children:[$&&HQ("a",{className:QI.primaryButton,href:ui($),children:"Start reading"},void 0,!1,void 0,this),HQ("a",{className:QI.button,href:"#sections",children:"Browse sections"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Mh2=({groups:A})=>HQ("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:[HQ("p",{className:"m-0 mb-3.5 font-medium text-[var(--docs-text)]",children:"Sections"},void 0,!1,void 0,this),HQ("ol",{className:"m-0 list-none p-0",children:A.map((Q,$)=>HQ("li",{className:"grid grid-cols-[32px_1fr] gap-2 py-1.5",children:[HQ("span",{className:"docs-font-display text-[var(--docs-text-light)] italic",children:[ci($),"."]},void 0,!0,void 0,this),HQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:`#${oP0($)}`,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),bh2=({group:A,index:Q})=>HQ("article",{className:"mb-16 last:mb-0",id:oP0(Q),children:[HQ("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:[HQ("span",{className:"text-right docs-font-display text-3xl leading-[1.1] text-[var(--docs-accent)] italic md:text-4xl",children:[ci(Q),"."]},void 0,!0,void 0,this),HQ("h2",{className:`${QI.display} m-0 text-3xl leading-[1.1] tracking-[-0.015em] md:text-4xl`,children:A.section},void 0,!1,void 0,this),HQ("span",{className:"docs-chapter__leader"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),HQ("ol",{className:"m-0 list-none p-0",children:A.docs.map(($)=>HQ("li",{className:"border-b border-[var(--docs-border-light)] last:border-b-0",children:HQ("a",{className:"group block py-[18px] pl-12 md:pl-[68px]",href:ui($),children:[HQ("p",{className:"m-0 text-[22px] leading-[1.2] tracking-[-0.005em] transition-colors duration-150 group-hover:text-[var(--docs-accent)]",children:$.metadata.title},void 0,!1,void 0,this),$.metadata.description&&HQ("p",{className:"mt-1.5 mb-0 max-w-[70ch] text-sm leading-[1.55] text-[var(--docs-text-muted)]",children:$.metadata.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},$.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Oh2=({title:A})=>HQ("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:[HQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/",children:"Home"},void 0,!1,void 0,this),HQ("span",{children:"/"},void 0,!1,void 0,this),HQ("a",{className:"text-[var(--docs-text-muted)] hover:text-[var(--docs-accent)]",href:"/docs",children:"Docs"},void 0,!1,void 0,this),HQ("span",{children:"/"},void 0,!1,void 0,this),HQ("span",{children:A},void 0,!1,void 0,this)]},void 0,!0,void 0,this),fh2=({groups:A,activeGroupIndex:Q,activeSlug:$})=>HQ("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:HQ("nav",{className:"docs-font-label text-xs tracking-[0.06em] text-[var(--docs-text-light)]",children:[HQ("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),HQ("ol",{className:"m-0 list-none p-0",children:A.map((w,B)=>{let X=B===Q;return HQ("li",{className:X?"mb-[22px]":"mb-3.5",children:[HQ("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)] ${X?"text-[var(--docs-text)]":"text-[var(--docs-text-muted)]"}`,href:`/docs#${oP0(B)}`,children:[HQ("span",{className:"docs-font-display text-sm text-[var(--docs-accent)] italic",children:[ci(B),"."]},void 0,!0,void 0,this)," ",w.section]},void 0,!0,void 0,this),X&&HQ("ol",{className:"mt-0.5 list-none p-0",children:w.docs.map((Y)=>{let Z=Y.metadata.slug===$;return HQ("li",{children:HQ("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)] ${Z?"pl-3.5 font-medium text-[var(--docs-accent)]":"text-[var(--docs-text-muted)]"}`,href:ui(Y),"aria-current":Z?"page":void 0,children:Y.metadata.title},void 0,!1,void 0,this)},Y.id,!1,void 0,this)})},void 0,!1,void 0,this)]},w.section,!0,void 0,this)})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),xh2=({prevDoc:A,nextDoc:Q})=>{if(!A&&!Q)return null;return HQ("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?HQ("a",{className:"group border-t border-[var(--docs-border-light)] pt-[18px] transition-colors duration-150 hover:border-[var(--docs-accent)]",href:ui(A),children:[HQ("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),HQ("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):HQ("span",{},void 0,!1,void 0,this),Q&&HQ("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:ui(Q),children:[HQ("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),HQ("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 pi}from"preact/jsx-dev-runtime";var dGA=({docs:A})=>{let Q=Cw0(A),$=rP0(Q),B=Q.filter((X)=>X.metadata.slug!=="index")[0]??Q[0];return pi(sP0,{title:"Documentation",description:"Brains documentation",children:[pi(jh2,{docsCount:A.length,sectionsCount:$.length,startDoc:B},void 0,!1,void 0,this),pi("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:[pi(Mh2,{groups:$},void 0,!1,void 0,this),pi("div",{children:$.map((X,Y)=>pi(bh2,{group:X,index:Y},X.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 FG}from"preact/jsx-dev-runtime";var iGA=({doc:A,docs:Q,prevDoc:$,nextDoc:w})=>{let B=rP0(Q.length>0?Q:[A]),X=Cw0(Q.length>0?Q:[A]),Y=X.findIndex((W)=>W.metadata.slug===A.metadata.slug),Z=Math.max(B.findIndex((W)=>W.docs.some((K)=>K.metadata.slug===A.metadata.slug)),0);return FG(sP0,{title:A.metadata.title,description:A.metadata.description??A.metadata.section,detail:!0,footer:!0,contentClassName:"pt-16",children:[FG(Oh2,{title:A.metadata.title},void 0,!1,void 0,this),FG("div",{className:"grid items-start gap-10 py-8 pb-24 md:grid-cols-[240px_minmax(0,1fr)] md:gap-20",children:[FG(fh2,{groups:B,activeGroupIndex:Z,activeSlug:A.metadata.slug},void 0,!1,void 0,this),FG("article",{className:"min-w-0",children:[FG("header",{className:"mb-10 border-b border-[var(--docs-border)] pb-8",children:[FG("p",{className:`${QI.label} m-0 mb-6 flex items-baseline gap-3`,children:[FG("span",{className:"docs-font-display text-lg leading-none tracking-normal normal-case text-[var(--docs-accent)] italic",children:[ci(Z),"."]},void 0,!0,void 0,this)," ",A.metadata.section,Y>=0?` \xB7 ${Y+1}/${X.length}`:""]},void 0,!0,void 0,this),FG("h1",{className:`${QI.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&&FG("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),FG("div",{className:"docs-article__body",children:FG(u4,{markdown:A.body},void 0,!1,void 0,this)},void 0,!1,void 0,this),FG(xh2,{prevDoc:$,nextDoc:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};var j_$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),M_$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),b_$=H.object({title:H.string(),section:H.string(),order:H.number().int(),sourcePath:H.string(),description:H.string().optional(),slug:H.string().optional()}),O_$=H.object({title:H.string(),section:H.string(),order:H.number().int(),description:H.string().optional(),slug:H.string()}),hw0=H.object({id:H.string(),entityType:H.literal("doc"),content:H.string(),created:H.string(),updated:H.string(),visibility:M_$,metadata:O_$,contentHash:H.string(),frontmatter:b_$,body:H.string()}),f_$=H.object({docs:H.array(hw0),pagination:j_$.nullable(),baseUrl:H.string().optional()}),x_$=H.object({doc:hw0,docs:H.array(hw0),prevDoc:hw0.nullable(),nextDoc:hw0.nullable()});function Rh2(){return{"doc-list":K2({name:"doc-list",description:"Documentation index template",schema:f_$,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:dGA}}),"doc-detail":K2({name:"doc-detail",description:"Documentation page template",schema:x_$,dataSourceId:"docs:entities",requiredPermission:"public",layout:{component:iGA}})}}var vh2={name:"@brains/doc",version:"0.2.0-alpha.184",description:"Documentation entity type \u2014 markdown docs as first-class brain content",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":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class nGA extends S6{entityType=iP0.entityType;schema=mi;adapter=iP0;constructor(){super("docs",vh2,{},XY)}getTemplates(){return Rh2()}getDataSources(){return[new nP0(this.logger.child("DocDataSource"))]}}function Ew0(){return new nGA}KA();S2();C0();p5();C0();var rGA=H.literal("application/pdf"),Ch2=H.enum(["pending","draft","failed"]),oGA=H.object({title:H.string().optional(),mimeType:rGA,filename:H.string().min(1),pageCount:H.number().int().min(0).optional(),status:Ch2.optional(),processingJobId:H.string().optional(),processingError:H.string().optional(),sourceEntityType:H.string().min(1).optional(),sourceEntityId:H.string().min(1).optional(),sourceUploadId:H.string().optional(),sourceFilename:H.string().optional(),sourceMediaType:H.string().optional(),attachmentType:H.string().min(1).optional(),dedupKey:H.string().min(1).optional()}),li=H6.extend({entityType:H.literal("document"),content:H.string().regex(/^data:application\/pdf;base64,.+$/),metadata:oGA});function Tw0(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 aP0(A){return`data:application/pdf;base64,${Buffer.from(A).toString("base64")}`}function sGA(A){let Q=Buffer.from(A).toString("latin1"),$=0,w=/\/Type\s*\/Pages\b[^]*?\/Count\s+(\d+)|\/Count\s+(\d+)[^]*?\/Type\s*\/Pages\b/g;for(let X of Q.matchAll(w)){let Y=parseInt(X[1]??X[2]??"0",10);if(Y>$)$=Y}if($>0)return $;return Q.match(/\/Type\s*\/Page(?!\w)/g)?.length??0}class tP0{entityType="document";purpose="A durable rendered file artifact such as a printable or carousel PDF.";schema=li;toMarkdown(A){return A.content}fromMarkdown(A){return Tw0(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,...$}=A,{mimeType:w}=Tw0(Q);return{entityType:"document",content:Q,metadata:{mimeType:w,...$}}}}var PP=new tP0;async function TDA(A,Q={}){let $=Q.maxBytes??5000000;if(A.byteLength>$)throw Error(`Uploaded PDF is too large for synchronous markdown extraction (${A.byteLength} bytes; max ${$} bytes)`);let B=(await Promise.resolve().then(() => (cT2(),uT2))).getDocument({data:new Uint8Array(A),disableFontFace:!1,useSystemFonts:!0,useWorkerFetch:!1}),X=await B.promise;try{let Y=Q.maxPages??50;if(X.numPages>Y)throw Error(`Uploaded PDF has ${X.numPages} pages; maximum supported for synchronous markdown extraction is ${Y}`);let Z=[];for(let K=1;K<=X.numPages;K+=1){let D=(await(await X.getPage(K)).getTextContent()).items.flatMap((q)=>("str"in q)?[q.str]:[]).join(" ").replace(/\s+/g," ").trim();if(D.length>0)Z.push(D)}let W=Z.join(`
7482
7482
 
7483
- `).trim();if(!W)throw Error("Could not extract text from the uploaded PDF");return W}finally{await B.destroy()}}KA();_4();S2();C0();import{createHash as JP$}from"crypto";var FP$=26214400,IP$=20,LP$=60000,pT2=80,NP$=10,_P$={renderUrl:H.url().optional(),sourceEntityType:H.string().min(1),sourceEntityId:H.string().min(1),attachmentType:H.string().min(1),documentId:H.string().min(1).optional(),title:H.string().min(1).optional(),filename:H.string().min(1).optional(),dedupKey:H.string().min(1).optional(),replace:H.boolean().optional(),pageCount:H.number().int().min(0).optional(),maxPageCount:H.number().int().positive().optional(),maxBytes:H.number().int().positive().optional(),timeoutMs:H.number().int().positive().optional(),width:H.union([H.string(),H.number()]).optional(),height:H.union([H.string(),H.number()]).optional(),format:H.string().optional(),targetEntityType:H.string().min(1).optional(),targetEntityId:H.string().min(1).optional()},dT2=H.object(_P$),gk0=dT2.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 Sk0 extends X8{context;renderPdf;constructor(A,Q,$={}){super(A,{schema:gk0,jobTypeName:"document-generate"});this.context=Q,this.renderPdf=$.renderPdf??a3}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`,$=await this.context.entityService.getEntity({entityType:A.sourceEntityType,id:A.sourceEntityId});return $?`${Q}:${$.contentHash}`:Q}async process(A,Q,$){this.logger.debug("Starting document generation job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});let w=A.maxPageCount??IP$,B=A.maxBytes??FP$,X=A.timeoutMs??LP$;if(A.pageCount!==void 0&&A.pageCount>w)throw Error(`Refusing to render ${A.pageCount} page PDF; maxPageCount=${w}`);let Y=await this.getDedupKey(A),Z=yDA(A,Y),W=A.documentId!==void 0||A.filename!==void 0;if(A.replace!==!0){let K=await this.findDocumentByDedupKey(Y,W?Z:void 0);if(K&&(!W||K.id===Z)){if(A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,K.id,A);return await this.reportProgress($,{progress:100,message:"Reusing existing generated document"}),{success:!0,documentId:K.id,reused:!0}}}await this.reportProgress($,{progress:20,message:"Rendering PDF document"});try{let K=await this.resolveDocumentAttachment(A,Z,{timeoutMs:X,maxBytes:B}),U=K.data;if(U.byteLength>B)throw Error(`Rendered PDF exceeds maxBytes=${B}: ${U.byteLength} bytes`);let G=sGA(U);if(G>w)throw Error(`Rendered PDF has ${G} pages, exceeding maxPageCount=${w}`);let D=G>0?G:A.pageCount;await this.reportProgress($,{progress:70,message:"Storing PDF document"});let q=A.filename??(A.renderUrl===void 0?K.filename:`${Z}.pdf`),J=PP.createDocumentEntity({dataUrl:aP0(U),filename:q,...A.title&&{title:A.title},...D!==void 0&&{pageCount:D},status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,dedupKey:Y});if(await OH({entityService:this.context.entityService,entity:{...J,id:Z}}),A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,Z,A);return await this.reportProgress($,{progress:100,message:"PDF document generation complete"}),{success:!0,documentId:Z,reused:!1}}catch(K){let U=aA(K);throw this.logger.error("Document generation failed",{jobId:Q,error:U}),await xJ({entityService:this.context.entityService,entityType:"document",id:Z,error:U}),K}}async resolveDocumentAttachment(A,Q,$){if(A.renderUrl!==void 0)return{type:"document",data:await this.renderPdf(A.renderUrl,{timeoutMs:$.timeoutMs,maxBytes:$.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 w=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!w)throw Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`);if(w.type!=="document")throw Error(`Attachment provider returned ${w.type}; expected document`);return w}async findDocumentByDedupKey(A,Q){let $=await this.context.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}});if($.length>1)this.logger.warn("Multiple documents share dedupKey; using first",{dedupKey:A,count:$.length,ids:$.map((B)=>B.id),preferredDocumentId:Q});let w=$.filter((B)=>B.metadata.status!=="pending"&&B.metadata.status!=="failed");return w.find((B)=>B.id===Q)??w[0]}async attachDocumentToTarget(A,Q,$,w){let B=await this.context.entityService.getEntity({entityType:A,id:Q});if(!B)throw Error(`Target entity not found: ${A}/${Q}`);let{frontmatter:X}=c8(B.content),Y=Array.isArray(X.documents)?X.documents.filter(kP$):[],Z=w.replace?await this.removeReferencesForSameSourceAttachment(Y,$,w):Y,W=Z.some((K)=>K.id===$)?Z:[...Z,{id:$}];await this.context.entityService.updateEntity({entity:{...B,content:zX(B.content,"documents",W)}})}async removeReferencesForSameSourceAttachment(A,Q,$){let w=[];for(let B of A){if(B.id===Q){w.push(B);continue}let X=await this.context.entityService.getEntity({entityType:"document",id:B.id});if(!X||!jP$(X,$))w.push(B)}return w}}function yDA(A,Q){let $=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl??"resolved-attachment"}`,w=A.documentId??A.filename?.replace(/\.pdf$/i,"")??Q??$,B=A.replace===!0&&A.documentId===void 0?`${w}-${Date.now()}`:w;return PP$(B)}function PP$(A){let Q=k1(A.replace(/[/:]+/g," "))||`document-${lT2(A)}`;if(Q.length<=pT2)return Q;let $=`-${lT2(A)}`;return`${Q.slice(0,pT2-$.length).replace(/-+$/g,"")}${$}`}function lT2(A){return JP$("sha256").update(A).digest("hex").slice(0,NP$)}function kP$(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}function jP$(A,Q){return A.metadata.sourceEntityType===Q.sourceEntityType&&A.metadata.sourceEntityId===Q.sourceEntityId&&A.metadata.attachmentType===Q.attachmentType}var iT2={name:"@brains/document-plugin",version:"0.2.0-alpha.183",description:"Document entity type for generated PDFs and publishable document attachments",dependencies:{"@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/typescript-config":"workspace:*","bun-types":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var bP$=`data:application/pdf;base64,${Buffer.from(`%PDF-1.4
7483
+ `).trim();if(!W)throw Error("Could not extract text from the uploaded PDF");return W}finally{await B.destroy()}}KA();_4();S2();C0();import{createHash as JP$}from"crypto";var FP$=26214400,IP$=20,LP$=60000,pT2=80,NP$=10,_P$={renderUrl:H.url().optional(),sourceEntityType:H.string().min(1),sourceEntityId:H.string().min(1),attachmentType:H.string().min(1),documentId:H.string().min(1).optional(),title:H.string().min(1).optional(),filename:H.string().min(1).optional(),dedupKey:H.string().min(1).optional(),replace:H.boolean().optional(),pageCount:H.number().int().min(0).optional(),maxPageCount:H.number().int().positive().optional(),maxBytes:H.number().int().positive().optional(),timeoutMs:H.number().int().positive().optional(),width:H.union([H.string(),H.number()]).optional(),height:H.union([H.string(),H.number()]).optional(),format:H.string().optional(),targetEntityType:H.string().min(1).optional(),targetEntityId:H.string().min(1).optional()},dT2=H.object(_P$),gk0=dT2.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 Sk0 extends X8{context;renderPdf;constructor(A,Q,$={}){super(A,{schema:gk0,jobTypeName:"document-generate"});this.context=Q,this.renderPdf=$.renderPdf??a3}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`,$=await this.context.entityService.getEntity({entityType:A.sourceEntityType,id:A.sourceEntityId});return $?`${Q}:${$.contentHash}`:Q}async process(A,Q,$){this.logger.debug("Starting document generation job",{jobId:Q,sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});let w=A.maxPageCount??IP$,B=A.maxBytes??FP$,X=A.timeoutMs??LP$;if(A.pageCount!==void 0&&A.pageCount>w)throw Error(`Refusing to render ${A.pageCount} page PDF; maxPageCount=${w}`);let Y=await this.getDedupKey(A),Z=yDA(A,Y),W=A.documentId!==void 0||A.filename!==void 0;if(A.replace!==!0){let K=await this.findDocumentByDedupKey(Y,W?Z:void 0);if(K&&(!W||K.id===Z)){if(A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,K.id,A);return await this.reportProgress($,{progress:100,message:"Reusing existing generated document"}),{success:!0,documentId:K.id,reused:!0}}}await this.reportProgress($,{progress:20,message:"Rendering PDF document"});try{let K=await this.resolveDocumentAttachment(A,Z,{timeoutMs:X,maxBytes:B}),U=K.data;if(U.byteLength>B)throw Error(`Rendered PDF exceeds maxBytes=${B}: ${U.byteLength} bytes`);let G=sGA(U);if(G>w)throw Error(`Rendered PDF has ${G} pages, exceeding maxPageCount=${w}`);let D=G>0?G:A.pageCount;await this.reportProgress($,{progress:70,message:"Storing PDF document"});let q=A.filename??(A.renderUrl===void 0?K.filename:`${Z}.pdf`),J=PP.createDocumentEntity({dataUrl:aP0(U),filename:q,...A.title&&{title:A.title},...D!==void 0&&{pageCount:D},status:"draft",sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType,dedupKey:Y});if(await OH({entityService:this.context.entityService,entity:{...J,id:Z}}),A.targetEntityType&&A.targetEntityId)await this.attachDocumentToTarget(A.targetEntityType,A.targetEntityId,Z,A);return await this.reportProgress($,{progress:100,message:"PDF document generation complete"}),{success:!0,documentId:Z,reused:!1}}catch(K){let U=aA(K);throw this.logger.error("Document generation failed",{jobId:Q,error:U}),await xJ({entityService:this.context.entityService,entityType:"document",id:Z,error:U}),K}}async resolveDocumentAttachment(A,Q,$){if(A.renderUrl!==void 0)return{type:"document",data:await this.renderPdf(A.renderUrl,{timeoutMs:$.timeoutMs,maxBytes:$.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 w=await this.context.attachments.resolve({sourceEntityType:A.sourceEntityType,sourceEntityId:A.sourceEntityId,attachmentType:A.attachmentType});if(!w)throw Error(`No attachment provider found for ${A.sourceEntityType}/${A.attachmentType}`);if(w.type!=="document")throw Error(`Attachment provider returned ${w.type}; expected document`);return w}async findDocumentByDedupKey(A,Q){let $=await this.context.entityService.listEntities({entityType:"document",options:{filter:{metadata:{dedupKey:A}}}});if($.length>1)this.logger.warn("Multiple documents share dedupKey; using first",{dedupKey:A,count:$.length,ids:$.map((B)=>B.id),preferredDocumentId:Q});let w=$.filter((B)=>B.metadata.status!=="pending"&&B.metadata.status!=="failed");return w.find((B)=>B.id===Q)??w[0]}async attachDocumentToTarget(A,Q,$,w){let B=await this.context.entityService.getEntity({entityType:A,id:Q});if(!B)throw Error(`Target entity not found: ${A}/${Q}`);let{frontmatter:X}=c8(B.content),Y=Array.isArray(X.documents)?X.documents.filter(kP$):[],Z=w.replace?await this.removeReferencesForSameSourceAttachment(Y,$,w):Y,W=Z.some((K)=>K.id===$)?Z:[...Z,{id:$}];await this.context.entityService.updateEntity({entity:{...B,content:zX(B.content,"documents",W)}})}async removeReferencesForSameSourceAttachment(A,Q,$){let w=[];for(let B of A){if(B.id===Q){w.push(B);continue}let X=await this.context.entityService.getEntity({entityType:"document",id:B.id});if(!X||!jP$(X,$))w.push(B)}return w}}function yDA(A,Q){let $=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:${A.renderUrl??"resolved-attachment"}`,w=A.documentId??A.filename?.replace(/\.pdf$/i,"")??Q??$,B=A.replace===!0&&A.documentId===void 0?`${w}-${Date.now()}`:w;return PP$(B)}function PP$(A){let Q=k1(A.replace(/[/:]+/g," "))||`document-${lT2(A)}`;if(Q.length<=pT2)return Q;let $=`-${lT2(A)}`;return`${Q.slice(0,pT2-$.length).replace(/-+$/g,"")}${$}`}function lT2(A){return JP$("sha256").update(A).digest("hex").slice(0,NP$)}function kP$(A){return typeof A==="object"&&A!==null&&"id"in A&&typeof A.id==="string"&&A.id.length>0}function jP$(A,Q){return A.metadata.sourceEntityType===Q.sourceEntityType&&A.metadata.sourceEntityId===Q.sourceEntityId&&A.metadata.attachmentType===Q.attachmentType}var iT2={name:"@brains/document-plugin",version:"0.2.0-alpha.184",description:"Document entity type for generated PDFs and publishable document attachments",dependencies:{"@brains/contracts":"workspace:*","@brains/document":"workspace:*","@brains/media-renderer":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/typescript-config":"workspace:*","bun-types":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var bP$=`data:application/pdf;base64,${Buffer.from(`%PDF-1.4
7484
7484
  % Pending document placeholder
7485
7485
  %%EOF
7486
7486
  `).toString("base64")}`,OP$=H.object({}).catchall(H.unknown()).transform(()=>({})),gDA={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function fP$(A,Q){let $=A.title?.trim();if($)return $;return Q.replace(/\.[^.]+$/,"").trim()||Q}function xP$(A,Q){return`data:${A};base64,${Q.toString("base64")}`}function RP$(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 SDA extends p6{entityType=PP.entityType;schema=li;adapter=PP;pluginContext;constructor(){super("document",iT2,{},OP$)}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 $=await this.promoteUpload({entityType:this.entityType,...Q.title!==void 0?{title:Q.title}:{},from:Q.upload},A);return $.kind==="handled"?$.result:{success:!1,error:"Document upload save was not handled"}}}),A.jobs.registerHandler("generate",new Sk0(this.logger.child("DocumentGenerationJobHandler"),A))}async interceptCreate(A){let Q=this.pluginContext;if(A.from?.kind===gDA.refKind){if(!Q)return{kind:"handled",result:{success:!1,error:"Plugin context not initialized"}};return this.promoteUpload(A,Q)}if(A.from?.kind!=="entity-attachment")return{kind:"continue",input:A};if(!Q)return{kind:"handled",result:{success:!1,error:"Plugin context not initialized"}};let $=gk0.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}}),w=await this.getDedupKey($,Q),B=$.replace===!0?void 0:await this.findExistingDocument(w,Q),X=B?.id??yDA($,w);if(!B)await this.createPendingDocument(Q,{id:X,title:$.title??X,filename:`${X}.pdf`,sourceEntityType:$.sourceEntityType,sourceEntityId:$.sourceEntityId,attachmentType:$.attachmentType,dedupKey:w});let Y=await Q.jobs.enqueue({type:"generate",data:{...$,dedupKey:w,documentId:X}}),Z=`${X}.pdf`;return{kind:"handled",result:{success:!0,data:{entityId:X,jobId:Y,status:"generating",attachment:{mediaType:"application/pdf",url:`/api/chat/attachments/document?id=${encodeURIComponent(X)}`,downloadUrl:`/api/chat/attachments/document?id=${encodeURIComponent(X)}&download=1`,filename:Z,source:{entityType:"document",entityId:X,attachmentType:$.attachmentType}}}}}}async promoteUpload(A,Q){let $=A.from;if($?.kind!==gDA.refKind)return{kind:"handled",result:{success:!1,error:"Unsupported upload ref kind"}};let w;try{w=await Q.uploads.scoped(gDA).read($.id)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}if(w.record.mediaType!=="application/pdf")return{kind:"handled",result:{success:!1,error:"Only PDF uploads can be promoted to document entities"}};let B=fP$(A,w.record.filename),X=k1(B);if(!X)return{kind:"handled",result:{success:!1,error:"Could not derive a document id from the uploaded filename. Provide a title."}};let Y=new Date().toISOString(),Z=PP.createDocumentEntity({dataUrl:xP$(w.record.mediaType,w.content),filename:w.record.filename,title:B,status:"draft",sourceUploadId:$.id,sourceFilename:w.record.filename,sourceMediaType:w.record.mediaType,attachmentType:"uploaded",dedupKey:`upload:${$.kind}:${$.id}`}),W=await Q.entityService.createEntity({entity:{id:X,...Z,created:Y,updated:Y},options:{deduplicateId:!0}});return{kind:"handled",result:{success:!0,data:{entityId:W.entityId,status:"created",attachment:RP$({entityId:W.entityId,filename:w.record.filename})}}}}async createPendingDocument(A,Q){let $=new Date().toISOString(),w=PP.createDocumentEntity({dataUrl:bP$,filename:Q.filename,title:Q.title,status:"pending",sourceEntityType:Q.sourceEntityType,sourceEntityId:Q.sourceEntityId,attachmentType:Q.attachmentType,dedupKey:Q.dedupKey});await Gv({entityService:A.entityService,entity:{id:Q.id,...w,created:$,updated:$}})}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 $=`${A.attachmentType}:${A.sourceEntityType}:${A.sourceEntityId}:resolved-attachment`,w=await Q.entityService.getEntity({entityType:A.sourceEntityType,id:A.sourceEntityId});return w?`${$}:${w.contentHash}`:$}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 mDA(){return new SDA}KA();C0();KA();C0();var nT2=H.enum(["generating","failed"]),vP$=H.enum(["generating","failed"]),nO=H.object({title:H.string().optional(),status:nT2.optional(),error:H.string().optional()}),CP$=H.object({title:H.string(),status:nT2.optional(),error:H.string().optional()}),hP$=H.object({title:H.string(),status:vP$.optional(),error:H.string().optional()}),rO=H6.extend({entityType:H.literal("note"),metadata:hP$}),EP$=rO.extend({frontmatter:nO,body:H.string()});KA();C0();var TP$=H.record(H.string(),H.unknown());class uDA extends UQ{constructor(){super({entityType:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",schema:rO,frontmatterSchema:nO})}toMarkdown(A){let Q=this.extractBody(A.content);try{let $=this.parseFrontMatter(A.content,nO);if(Object.values($).some((w)=>w!==void 0))return this.buildMarkdown(Q,$)}catch{}return Q}fromMarkdown(A){let Q=this.parseMarkdownFrontmatter(A),$=Q.title??this.extractH1(A)??"Untitled";return{content:A,entityType:"note",metadata:{title:$,...Q.status&&{status:Q.status},...Q.error&&{error:Q.error}}}}parseNoteFrontmatter(A){return this.parseMarkdownFrontmatter(A.content)}parseMarkdownFrontmatter(A){try{return this.parseFrontMatter(A,nO)}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 $=this.parseFrontMatter(Q,TP$);if(Object.keys($).length===0)return Q;let w={...$,title:$.title??A},B=this.extractBody(Q);return this.buildMarkdown(B,w)}catch{return Q}}extractH1(A){return A.match(/^#\s+(.+)$/m)?.[1]?.trim()??null}}var bP=new uDA;C0();var cDA=H.object({defaultPrompt:H.string().default("Create a note summarizing key concepts from my knowledge base")});C0();KA();var rT2=H.object({title:H.string().max(80).describe("A clear, descriptive title for the note (3-8 words)"),body:H.string().describe("Note content in markdown format with clear organization and structure")}),pDA=K2({name:"note:generation",description:"Template for AI to generate notes from prompts",schema:rT2,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create personal knowledge notes for research and reference.
@@ -7498,7 +7498,7 @@ title: ${JSON.stringify(A)}
7498
7498
  ---
7499
7499
 
7500
7500
  ${Q.trim()}
7501
- `}var uP$={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},cP$=H.object({uploadId:H.string().min(1),entityId:H.string().min(1),title:H.string().optional()});class dDA extends X8{context;constructor(A,Q){super(A,{schema:cP$,jobTypeName:"upload-import"});this.context=Q}async process(A,Q,$){try{await this.reportProgress($,{progress:10,message:"Reading uploaded file"});let w=await this.context.uploads.scoped(uP$).read(A.uploadId);await this.reportProgress($,{progress:35,message:"Extracting markdown from upload"});let B=await tT2({upload:w,...A.title!==void 0?{title:A.title}:{}});await this.reportProgress($,{progress:80,message:"Saving imported note"});let X=new Date().toISOString(),Y=bP.fromMarkdown(B.content),Z=await OH({entityService:this.context.entityService,entity:{id:A.entityId,entityType:"note",content:B.content,metadata:{title:B.title,...Y.metadata},created:X,updated:X}});return await this.reportProgress($,{progress:100,message:"Upload imported as markdown note"}),{entityId:Z.entityId,status:"created"}}catch(w){return await this.markStubFailed(A.entityId,aA(w)),y5.failure(w)}}async markStubFailed(A,Q){try{let $=await this.context.entityService.getEntity({entityType:"note",id:A});if(!$)return;await this.context.entityService.updateEntity({entity:{...$,content:zX(zX($.content,"status","failed"),"error",Q),metadata:{...$.metadata,status:"failed",error:Q}}})}catch($){this.logger.warn("Failed to mark import stub as failed",{error:$,entityId:A})}}summarizeDataForLog(A){return{uploadId:A.uploadId,entityId:A.entityId,hasTitle:A.title!==void 0}}}KA();async function eT2({entity:A,config:Q}){let $=rO.parse(A),w=_Q($.content,nO);return{$type:"ai.rizom.brain.note",title:$.metadata.title,body:w.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"note",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function iDA(){return{entityType:"note",collection:"ai.rizom.brain.note",lexicon:E8["ai.rizom.brain.note"],validate:!1,buildRecord:eT2}}var Ay2={name:"@brains/note",version:"0.2.0-alpha.183",description:"Personal knowledge capture with markdown-first workflow",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Qy2={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},lP$=H.object({prompt:H.string()});class nDA extends S6{entityType=bP.entityType;schema=rO;adapter=bP;unregisterAtprotoProjection;constructor(A={}){super("note",Ay2,A,cDA)}async interceptCreate(A,Q,$){if(A.from?.kind!==Qy2.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 w=A.from.id,B;try{B=await $.uploads.scoped(Qy2).readRecord(w)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}try{if(!aT2(B.mediaType))return{kind:"handled",result:{success:!1,error:"Only text, JSON, and PDF uploads can be imported as markdown notes"}};let X=lDA({filename:B.filename,...A.title!==void 0?{title:A.title}:{}}),Y=bP.buildStub({id:X.id,title:X.title}),Z=new Date().toISOString(),W=await $.entityService.createEntity({entity:{id:X.id,entityType:"note",content:Y.content,metadata:Y.metadata,created:Z,updated:Z},options:{deduplicateId:!0}}),K=await $.jobs.enqueue({type:"upload-import",data:{uploadId:w,entityId:W.entityId,...A.title!==void 0?{title:A.title}:{}}});return{kind:"handled",result:{success:!0,data:{entityId:W.entityId,status:"generating",jobId:K}}}}catch(X){return{kind:"handled",result:{success:!1,error:X instanceof Error?X.message:"Failed to import upload as markdown"}}}}createGenerationHandler(A){return new mk0(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:pDA}}async onRegister(A){A.jobs.registerHandler("upload-import",new dDA(this.logger.child("UploadMarkdownImportJobHandler"),A)),A.eval.registerHandler("generateNote",async(Q)=>{let $=lP$.parse(Q);return A.ai.generate({prompt:$.prompt,templateName:"note:generation"})}),this.unregisterAtprotoProjection=aB.getInstance().register(iDA())}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 QT(A={}){return new nDA(A)}KA();C0();KA();var $y2=H.object({ref:H.string(),label:H.string()}),wy2=H.enum(["pending","draft","published"]),dP$=H.enum(["pending","draft","published"]),H50=H.object({status:wy2,title:H.string(),url:H.string().url(),description:H.string().optional(),domain:H.string(),capturedAt:H.string().datetime(),source:$y2}),iP$=H50.pick({title:!0,status:!0}),nP$=H.object({title:H.string(),status:dP$}),$T=H6.extend({entityType:H.literal("link"),metadata:nP$});S2();C0();C0();var rDA=H.object({enableSummarization:H.boolean().default(!0).describe("Generate AI summaries for captured links"),jinaApiKey:H.string().optional().describe("Jina Reader API key for higher rate limits (500 RPM vs 20 RPM without key)")});KA();class oO extends UQ{constructor(){super({entityType:"link",purpose:"A saved external URL or web resource captured for later reference.",schema:$T,frontmatterSchema:H50})}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},$=A.summary??"";return this.buildMarkdown($,Q)}parseLinkContent(A){return{frontmatter:this.parseFrontMatter(A,H50),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 Bn=new oO;KA();C0();var rP$=H.object({success:H.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:H.string().describe("If success is false, explain why content could not be extracted. Use an empty string when success is true."),title:H.string().max(80).describe("The page title - extract from the content or create a descriptive one. Leave empty string if success is false."),description:H.string().describe("A one-sentence description of what the page is about. Leave empty string if success is false."),summary:H.string().describe("A 1-2 paragraph summary of the main content. Leave empty string if success is false.")}),By2=K2({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:rP$,basePrompt:`You are an expert at extracting key information from webpage content.
7501
+ `}var uP$={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},cP$=H.object({uploadId:H.string().min(1),entityId:H.string().min(1),title:H.string().optional()});class dDA extends X8{context;constructor(A,Q){super(A,{schema:cP$,jobTypeName:"upload-import"});this.context=Q}async process(A,Q,$){try{await this.reportProgress($,{progress:10,message:"Reading uploaded file"});let w=await this.context.uploads.scoped(uP$).read(A.uploadId);await this.reportProgress($,{progress:35,message:"Extracting markdown from upload"});let B=await tT2({upload:w,...A.title!==void 0?{title:A.title}:{}});await this.reportProgress($,{progress:80,message:"Saving imported note"});let X=new Date().toISOString(),Y=bP.fromMarkdown(B.content),Z=await OH({entityService:this.context.entityService,entity:{id:A.entityId,entityType:"note",content:B.content,metadata:{title:B.title,...Y.metadata},created:X,updated:X}});return await this.reportProgress($,{progress:100,message:"Upload imported as markdown note"}),{entityId:Z.entityId,status:"created"}}catch(w){return await this.markStubFailed(A.entityId,aA(w)),y5.failure(w)}}async markStubFailed(A,Q){try{let $=await this.context.entityService.getEntity({entityType:"note",id:A});if(!$)return;await this.context.entityService.updateEntity({entity:{...$,content:zX(zX($.content,"status","failed"),"error",Q),metadata:{...$.metadata,status:"failed",error:Q}}})}catch($){this.logger.warn("Failed to mark import stub as failed",{error:$,entityId:A})}}summarizeDataForLog(A){return{uploadId:A.uploadId,entityId:A.entityId,hasTitle:A.title!==void 0}}}KA();async function eT2({entity:A,config:Q}){let $=rO.parse(A),w=_Q($.content,nO);return{$type:"ai.rizom.brain.note",title:$.metadata.title,body:w.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"note",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function iDA(){return{entityType:"note",collection:"ai.rizom.brain.note",lexicon:E8["ai.rizom.brain.note"],validate:!1,buildRecord:eT2}}var Ay2={name:"@brains/note",version:"0.2.0-alpha.184",description:"Personal knowledge capture with markdown-first workflow",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Qy2={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"},lP$=H.object({prompt:H.string()});class nDA extends S6{entityType=bP.entityType;schema=rO;adapter=bP;unregisterAtprotoProjection;constructor(A={}){super("note",Ay2,A,cDA)}async interceptCreate(A,Q,$){if(A.from?.kind!==Qy2.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 w=A.from.id,B;try{B=await $.uploads.scoped(Qy2).readRecord(w)}catch{return{kind:"handled",result:{success:!1,error:"Upload ref not found"}}}try{if(!aT2(B.mediaType))return{kind:"handled",result:{success:!1,error:"Only text, JSON, and PDF uploads can be imported as markdown notes"}};let X=lDA({filename:B.filename,...A.title!==void 0?{title:A.title}:{}}),Y=bP.buildStub({id:X.id,title:X.title}),Z=new Date().toISOString(),W=await $.entityService.createEntity({entity:{id:X.id,entityType:"note",content:Y.content,metadata:Y.metadata,created:Z,updated:Z},options:{deduplicateId:!0}}),K=await $.jobs.enqueue({type:"upload-import",data:{uploadId:w,entityId:W.entityId,...A.title!==void 0?{title:A.title}:{}}});return{kind:"handled",result:{success:!0,data:{entityId:W.entityId,status:"generating",jobId:K}}}}catch(X){return{kind:"handled",result:{success:!1,error:X instanceof Error?X.message:"Failed to import upload as markdown"}}}}createGenerationHandler(A){return new mk0(this.logger.child("NoteGenerationJobHandler"),A)}getTemplates(){return{generation:pDA}}async onRegister(A){A.jobs.registerHandler("upload-import",new dDA(this.logger.child("UploadMarkdownImportJobHandler"),A)),A.eval.registerHandler("generateNote",async(Q)=>{let $=lP$.parse(Q);return A.ai.generate({prompt:$.prompt,templateName:"note:generation"})}),this.unregisterAtprotoProjection=aB.getInstance().register(iDA())}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 QT(A={}){return new nDA(A)}KA();C0();KA();var $y2=H.object({ref:H.string(),label:H.string()}),wy2=H.enum(["pending","draft","published"]),dP$=H.enum(["pending","draft","published"]),H50=H.object({status:wy2,title:H.string(),url:H.string().url(),description:H.string().optional(),domain:H.string(),capturedAt:H.string().datetime(),source:$y2}),iP$=H50.pick({title:!0,status:!0}),nP$=H.object({title:H.string(),status:dP$}),$T=H6.extend({entityType:H.literal("link"),metadata:nP$});S2();C0();C0();var rDA=H.object({enableSummarization:H.boolean().default(!0).describe("Generate AI summaries for captured links"),jinaApiKey:H.string().optional().describe("Jina Reader API key for higher rate limits (500 RPM vs 20 RPM without key)")});KA();class oO extends UQ{constructor(){super({entityType:"link",purpose:"A saved external URL or web resource captured for later reference.",schema:$T,frontmatterSchema:H50})}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},$=A.summary??"";return this.buildMarkdown($,Q)}parseLinkContent(A){return{frontmatter:this.parseFrontMatter(A,H50),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 Bn=new oO;KA();C0();var rP$=H.object({success:H.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:H.string().describe("If success is false, explain why content could not be extracted. Use an empty string when success is true."),title:H.string().max(80).describe("The page title - extract from the content or create a descriptive one. Leave empty string if success is false."),description:H.string().describe("A one-sentence description of what the page is about. Leave empty string if success is false."),summary:H.string().describe("A 1-2 paragraph summary of the main content. Leave empty string if success is false.")}),By2=K2({name:"link:extraction",description:"Extract structured content from webpage markdown",dataSourceId:"shell:ai-content",schema:rP$,basePrompt:`You are an expert at extracting key information from webpage content.
7502
7502
 
7503
7503
  You will receive webpage content in markdown format. Your job is to extract structured information from it.
7504
7504
 
@@ -7520,7 +7520,7 @@ Accuracy rules:
7520
7520
 
7521
7521
  `))return{success:!1,error:Y.trim(),errorType:"fetch_failed"};return{success:!0,content:Y}}catch($){return this.handleFetchError($,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 Ak$}from"crypto";class sO{static URL_PATTERN=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi;static extractUrls(A){let Q=A.match(sO.URL_PATTERN)??[];return[...new Set(Q)]}static normalizeUrl(A){try{let Q=new URL(A),$=Q.pathname.replace(/\/$/,"")||"/";return`${Q.protocol}//${Q.host}${$}`}catch{return A}}static generateEntityId(A){let Q=this.normalizeUrl(A),$=Ak$("sha256").update(Q).digest("hex");try{return`${new URL(Q).hostname.replace(/\./g,"-")}-${$.substring(0,6)}`}catch{return $.substring(0,12)}}static isValidUrl(A){try{let Q=new URL(A);return["http:","https:"].includes(Q.protocol)}catch{return!1}}}KA();C0();e8();var Qk$=H.object({interfaceId:H.string().optional(),userId:H.string().optional(),channelId:H.string().optional(),channelName:H.string().optional(),timestamp:H.string().optional()}),$k$=H.object({url:H.url(),metadata:Qk$.optional()}),Sx5=H.object({success:H.boolean(),entityId:H.string().optional(),title:H.string().optional(),url:H.string().optional(),status:H.enum(["pending","draft","published"]).optional(),error:H.string().optional()});class ck0 extends X8{context;linkAdapter;urlFetcher;constructor(A,Q,$){super(A,{schema:$k$,jobTypeName:"link-capture"});this.context=Q,this.linkAdapter=new oO,this.urlFetcher=new Xn($?.jinaApiKey?{jinaApiKey:$.jinaApiKey}:void 0)}async process(A,Q,$){let{url:w,metadata:B}=A;try{await $.report({progress:T6.START,total:100,message:"Starting link capture"});let X=sO.generateEntityId(w);await $.report({progress:T6.INIT,total:100,message:"Checking for existing link"});let Y=await this.context.entityService.getEntity({entityType:"link",id:X});if(Y){let{frontmatter:q}=this.linkAdapter.parseLinkContent(Y.content),J=Y.metadata.status;if(J!=="pending")return this.logger.info("Link already captured, returning existing",{url:w,entityId:X}),{success:!0,entityId:Y.id,title:q.title,url:w,status:J};this.logger.info("Pending link exists, completing extraction",{url:w,entityId:X})}let Z=this.resolveSource(B),W=new Date().toISOString();await $.report({progress:T6.FETCH,total:100,message:"Fetching webpage content"});let K=await this.urlFetcher.fetch(w);if(!K.success){if(K.errorType==="url_not_found"||K.errorType==="url_unreachable"){this.logger.warn("Link URL not accessible",{url:w,errorType:K.errorType,error:K.error});let q=new URL(w).hostname,J=`Could not capture link: ${K.error}`,F=this.linkAdapter.createLinkContent({status:"pending",title:q,url:w,description:J,summary:J,domain:q,capturedAt:W,source:Z});return await OH({entityService:this.context.entityService,entity:{id:X,entityType:"link",content:F,metadata:{status:"pending",title:q}}}),{success:!1,entityId:X,title:q,url:w,status:"pending",error:J}}}await $.report({progress:T6.PROCESS,total:100,message:"Extracting content with AI"});let U=await this.context.ai.generate({templateName:"link:extraction",prompt:K.success?`Extract structured information from this webpage content:
7522
7522
 
7523
- ${K.content}`:`The URL ${w} could not be fetched. Return success: false with error: "${K.error}"`,data:{url:w,hasContent:K.success},interfacePermissionGrant:"public"});if(this.logger.debug("AI extraction result",{result:U}),await $.report({progress:T6.EXTRACT,total:100,message:"Processing extraction results"}),U.success===!1||!U.title||!U.description||!U.summary){let q=U.title||new URL(w).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:w}),await $.report({progress:T6.SAVE,total:100,message:"Saving link as pending"});let J=this.linkAdapter.createLinkContent({status:"pending",title:q,url:w,description:U.description,summary:U.summary,domain:new URL(w).hostname,capturedAt:W,source:Z}),F=await OH({entityService:this.context.entityService,entity:{id:X,entityType:"link",content:J,metadata:{status:"pending",title:q}}});return await $.report({progress:T6.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:F.entityId,title:q,url:w,status:"pending"}}await $.report({progress:T6.SAVE,total:100,message:`Saving link: "${U.title}"`});let G=this.linkAdapter.createLinkContent({status:"draft",title:U.title,url:w,description:U.description,summary:U.summary,domain:new URL(w).hostname,capturedAt:W,source:Z}),D=await OH({entityService:this.context.entityService,entity:{id:X,entityType:"link",content:G,metadata:{status:"draft",title:U.title}}});return await $.report({progress:T6.COMPLETE,total:100,message:`Link captured: "${U.title}"`}),{success:!0,entityId:D.entityId,title:U.title,url:w,status:"draft"}}catch(X){return this.logger.error("Link capture job failed",{error:X,jobId:Q,data:A}),y5.failure(X)}}resolveSource(A){let Q=A?.channelId,$=A?.channelName;if(Q)return{ref:`matrix:${Q}`,label:$??Q};let w=A?.interfaceId??"cli";return{ref:`${w}:local`,label:w.toUpperCase()}}summarizeDataForLog(A){return{url:A.url,interfaceId:A.metadata?.interfaceId}}}async function Zy2({entity:A,config:Q}){let $=$T.parse(A),{frontmatter:w,summary:B}=Bn.parseLinkContent($.content);return{$type:"ai.rizom.brain.link",title:w.title,url:w.url,...w.description&&{description:w.description},...B&&{summary:B},domain:w.domain,capturedAt:w.capturedAt,source:w.source,...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"link",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function AqA(){return{entityType:"link",collection:"ai.rizom.brain.link",lexicon:E8["ai.rizom.brain.link"],validate:!1,buildRecord:Zy2}}var Hy2={name:"@brains/link",version:"0.2.0-alpha.183",description:"Web content capture plugin with AI-powered extraction and structured storage",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Bk$=H.object({url:H.url()});class QqA extends S6{entityType=Bn.entityType;schema=$T;adapter=Bn;shell;unregisterAtprotoProjection;constructor(A={}){super("link",Hy2,A,rDA)}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 ck0(this.logger.child("LinkCaptureJobHandler"),this.context,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0),this.id),Q}async interceptCreate(A,Q,$){if(A.content)try{let X=this.adapter.fromMarkdown(A.content).metadata,Y=typeof X?.title==="string"?X.title:void 0,Z=typeof X?.status==="string"?X.status:void 0,W=this.extractFirstUrl(A.content);if(Y&&Z&&W){let K=k1(W)||k1(Y)||`${A.entityType}-${Date.now()}`,U=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await $.entityService.createEntity({entity:{id:K,entityType:A.entityType,content:A.content,metadata:{title:Y,status:Z},created:U,updated:U}})).entityId,status:"created"}}}}}catch{}let w=A.url??this.extractFirstUrl(A.content,A.prompt,A.title);if(w){if(!this.shell)throw Error("LinkPlugin shell was not initialized during register()");try{let B=await this.createPendingLink(w,A.title,Q,$),X=await this.shell.getJobQueueService().enqueue({type:"link-capture",data:{url:w,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},options:{source:this.id,metadata:{operationType:"data_processing",pluginId:this.id,interfaceType:Q.interfaceType,...Q.channelId?{channelId:Q.channelId}:{}}}});return{kind:"handled",result:{success:!0,data:{entityId:B,status:"generating",jobId:X}}}}catch(B){return{kind:"handled",result:{success:!1,error:B instanceof Error?B.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 ck0(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:By2,"link-list":Xy2,"link-detail":Yy2}}getDataSources(){return[new eDA(this.logger.child("LinksDataSource"))]}async onRegister(A){this.unregisterAtprotoProjection=aB.getInstance().register(AqA()),A.eval.registerHandler("extractContent",async(Q)=>{let{url:$}=Bk$.parse(Q),B=await new Xn(this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0).fetch($);if(!B.success)return{success:!1,error:B.error,errorType:B.errorType};return A.ai.generate({templateName:"link:extraction",prompt:`Extract structured information from this webpage content:
7523
+ ${K.content}`:`The URL ${w} could not be fetched. Return success: false with error: "${K.error}"`,data:{url:w,hasContent:K.success},interfacePermissionGrant:"public"});if(this.logger.debug("AI extraction result",{result:U}),await $.report({progress:T6.EXTRACT,total:100,message:"Processing extraction results"}),U.success===!1||!U.title||!U.description||!U.summary){let q=U.title||new URL(w).hostname;this.logger.info("Incomplete extraction, saving as pending",{url:w}),await $.report({progress:T6.SAVE,total:100,message:"Saving link as pending"});let J=this.linkAdapter.createLinkContent({status:"pending",title:q,url:w,description:U.description,summary:U.summary,domain:new URL(w).hostname,capturedAt:W,source:Z}),F=await OH({entityService:this.context.entityService,entity:{id:X,entityType:"link",content:J,metadata:{status:"pending",title:q}}});return await $.report({progress:T6.COMPLETE,total:100,message:"Link saved (pending)"}),{success:!0,entityId:F.entityId,title:q,url:w,status:"pending"}}await $.report({progress:T6.SAVE,total:100,message:`Saving link: "${U.title}"`});let G=this.linkAdapter.createLinkContent({status:"draft",title:U.title,url:w,description:U.description,summary:U.summary,domain:new URL(w).hostname,capturedAt:W,source:Z}),D=await OH({entityService:this.context.entityService,entity:{id:X,entityType:"link",content:G,metadata:{status:"draft",title:U.title}}});return await $.report({progress:T6.COMPLETE,total:100,message:`Link captured: "${U.title}"`}),{success:!0,entityId:D.entityId,title:U.title,url:w,status:"draft"}}catch(X){return this.logger.error("Link capture job failed",{error:X,jobId:Q,data:A}),y5.failure(X)}}resolveSource(A){let Q=A?.channelId,$=A?.channelName;if(Q)return{ref:`matrix:${Q}`,label:$??Q};let w=A?.interfaceId??"cli";return{ref:`${w}:local`,label:w.toUpperCase()}}summarizeDataForLog(A){return{url:A.url,interfaceId:A.metadata?.interfaceId}}}async function Zy2({entity:A,config:Q}){let $=$T.parse(A),{frontmatter:w,summary:B}=Bn.parseLinkContent($.content);return{$type:"ai.rizom.brain.link",title:w.title,url:w.url,...w.description&&{description:w.description},...B&&{summary:B},domain:w.domain,capturedAt:w.capturedAt,source:w.source,...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"link",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function AqA(){return{entityType:"link",collection:"ai.rizom.brain.link",lexicon:E8["ai.rizom.brain.link"],validate:!1,buildRecord:Zy2}}var Hy2={name:"@brains/link",version:"0.2.0-alpha.184",description:"Web content capture plugin with AI-powered extraction and structured storage",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Bk$=H.object({url:H.url()});class QqA extends S6{entityType=Bn.entityType;schema=$T;adapter=Bn;shell;unregisterAtprotoProjection;constructor(A={}){super("link",Hy2,A,rDA)}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 ck0(this.logger.child("LinkCaptureJobHandler"),this.context,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0),this.id),Q}async interceptCreate(A,Q,$){if(A.content)try{let X=this.adapter.fromMarkdown(A.content).metadata,Y=typeof X?.title==="string"?X.title:void 0,Z=typeof X?.status==="string"?X.status:void 0,W=this.extractFirstUrl(A.content);if(Y&&Z&&W){let K=k1(W)||k1(Y)||`${A.entityType}-${Date.now()}`,U=new Date().toISOString();return{kind:"handled",result:{success:!0,data:{entityId:(await $.entityService.createEntity({entity:{id:K,entityType:A.entityType,content:A.content,metadata:{title:Y,status:Z},created:U,updated:U}})).entityId,status:"created"}}}}}catch{}let w=A.url??this.extractFirstUrl(A.content,A.prompt,A.title);if(w){if(!this.shell)throw Error("LinkPlugin shell was not initialized during register()");try{let B=await this.createPendingLink(w,A.title,Q,$),X=await this.shell.getJobQueueService().enqueue({type:"link-capture",data:{url:w,metadata:{interfaceId:Q.interfaceType,userId:Q.userId,...Q.channelId?{channelId:Q.channelId}:{},...Q.channelName?{channelName:Q.channelName}:{},timestamp:new Date().toISOString()}},options:{source:this.id,metadata:{operationType:"data_processing",pluginId:this.id,interfaceType:Q.interfaceType,...Q.channelId?{channelId:Q.channelId}:{}}}});return{kind:"handled",result:{success:!0,data:{entityId:B,status:"generating",jobId:X}}}}catch(B){return{kind:"handled",result:{success:!1,error:B instanceof Error?B.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 ck0(this.logger.child("LinkCaptureJobHandler"),A,this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0)}getTemplates(){return{extraction:By2,"link-list":Xy2,"link-detail":Yy2}}getDataSources(){return[new eDA(this.logger.child("LinksDataSource"))]}async onRegister(A){this.unregisterAtprotoProjection=aB.getInstance().register(AqA()),A.eval.registerHandler("extractContent",async(Q)=>{let{url:$}=Bk$.parse(Q),B=await new Xn(this.config.jinaApiKey?{jinaApiKey:this.config.jinaApiKey}:void 0).fetch($);if(!B.success)return{success:!1,error:B.error,errorType:B.errorType};return A.ai.generate({templateName:"link:extraction",prompt:`Extract structured information from this webpage content:
7524
7524
 
7525
7525
  ${B.content}`,data:{url:$,hasContent:!0},interfacePermissionGrant:"public"})})}async createPendingLink(A,Q,$,w){let B=sO.generateEntityId(A),X=new URL(A),Y=new Date().toISOString(),Z=Q?.trim()?Q.trim():X.hostname,W=this.adapter.createLinkContent({status:"pending",title:Z,url:A,description:"Link capture is in progress.",summary:`Pending link capture for ${A}.`,domain:X.hostname,capturedAt:Y,source:this.resolveSource($)});return(await Gv({entityService:w.entityService,entity:{id:B,entityType:"link",content:W,metadata:{status:"pending",title:Z},created:Y,updated:Y}})).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[$]=sO.extractUrls(Q);if($)return $}return}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}}function Wy2(A={}){return new QqA(A)}var wT=Wy2;C0();var Xk$=H.object({conversationId:H.string().optional(),interfaceId:H.string().optional(),userId:H.string().optional(),messageId:H.string().optional(),timestamp:H.string().optional()}),DR5=H.object({id:H.string().optional(),metadata:Xk$.optional()});KA();C0();Q5();C0();KA();var Ky2=H.enum(["generating","draft","published","failed"]),Uy2=H.enum(["generating","draft","published","failed"]),SX=H.object({title:H.string(),slug:H.string().optional(),status:Ky2,publishedAt:H.string().datetime().optional(),description:H.string(),year:H.number(),coverImageId:H.string().optional(),ogImageId:H.string().optional(),url:H.string().url().optional()}),Yk$=SX.pick({title:!0,status:!0,publishedAt:!0,year:!0}).extend({slug:H.string(),error:H.string().optional()}),Zk$=H.object({title:H.string(),status:Uy2,publishedAt:H.string().datetime().optional(),year:H.number(),slug:H.string(),error:H.string().optional()}),Hk$=H.object({title:H.string(),slug:H.string().optional(),status:Uy2,publishedAt:H.string().datetime().optional(),description:H.string(),year:H.number(),coverImageId:H.string().optional(),ogImageId:H.string().optional(),url:H.string().url().optional()}),aO=H6.extend({entityType:H.literal("project"),metadata:Zk$}),pk0=H.object({context:H.string(),problem:H.string(),solution:H.string(),outcome:H.string()}),K50=aO.extend({frontmatter:Hk$,body:H.string(),structuredContent:pk0.optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional()}),Wk$=K50.extend({url:H.string().optional(),typeLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()}),Kk$=K50.extend({url:H.string(),typeLabel:H.string(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});KA();S2();y9();class $qA extends d${constructor(){super(pk0,{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 wqA=new $qA;class BqA extends UQ{constructor(){super({entityType:"project",purpose:"A project record in the user's portfolio.",schema:aO,frontmatterSchema:SX,supportsCoverImage:!0,bodyFormatter:wqA})}toMarkdown(A){let Q=this.extractBody(A.content);try{let $=this.parseFrontMatter(A.content,SX),w={...$,slug:$.slug??A.metadata.slug};return this.buildMarkdown(Q,w)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,SX),$=Q.slug??k1(Q.title);return{content:A,entityType:"project",metadata:{title:Q.title,slug:$,status:Q.status,publishedAt:Q.publishedAt,year:Q.year}}}parseProjectFrontmatter(A){return this.parseFrontMatter(A.content,SX)}parseStructuredContent(A){return wqA.parse(this.extractBody(A.content))}createProjectContent(A,Q){let $=wqA.format(Q);return this.buildMarkdown($,A)}buildStub(A){let Q=new Date().getUTCFullYear(),$={title:A.title,slug:A.id,status:"generating",description:"",year:Q};return{content:this.buildMarkdown("",$),metadata:{title:A.title,slug:A.id,status:"generating",year:Q}}}}var BT=new BqA;C0();var XqA=H.looseObject({});import{jsxDEV as MG,Fragment as Gk$}from"preact/jsx-dev-runtime";var Uk$=({project:A})=>{let{frontmatter:Q,url:$,coverImageUrl:w}=A;return MG(j8,{href:$,children:[w&&MG("img",{src:w,alt:Q.title,className:"w-full h-56 object-cover rounded-md mb-4"},void 0,!1,void 0,this),MG(hX,{children:Q.title},void 0,!1,void 0,this),MG("p",{className:"text-theme leading-relaxed",children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},YqA=({projects:A,pageTitle:Q,pagination:$,baseUrl:w="/projects"})=>{let B=Q??"Projects",X=$?.totalItems??A.length,Y=`Browse all ${X} ${X===1?"project":"projects"}`;return MG(Gk$,{children:[MG(C6,{title:B,description:Y},void 0,!1,void 0,this),MG("div",{className:"project-list bg-theme",children:MG("div",{className:"container mx-auto px-6 md:px-12 max-w-5xl py-16 md:py-24",children:[MG("h1",{className:"text-4xl font-bold text-heading mb-12",children:B},void 0,!1,void 0,this),MG("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-8",children:A.map((Z)=>MG(Uk$,{project:Z},Z.id,!1,void 0,this))},void 0,!1,void 0,this),$&&$.totalPages>1&&MG("div",{className:"mt-12",children:MG(WP,{currentPage:$.currentPage,totalPages:$.totalPages,baseUrl:w},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as Kw,Fragment as Gy2}from"preact/jsx-dev-runtime";var Dk$=({prevProject:A,nextProject:Q})=>{if(!A&&!Q)return null;return Kw("nav",{className:"pt-12 mt-12 border-t border-theme-muted",children:Kw("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[A?Kw(j8,{href:A.url,variant:"compact",children:[Kw("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Previous"},void 0,!1,void 0,this),Kw("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):Kw("div",{},void 0,!1,void 0,this),Q&&Kw(j8,{href:Q.url,variant:"compact",className:"md:text-right",children:[Kw("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Next"},void 0,!1,void 0,this),Kw("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)},lk0=({title:A,content:Q})=>{if(!Q)return null;return Kw("section",{className:"mb-12",children:[Kw("h2",{className:"text-2xl font-bold text-heading mb-4",children:A},void 0,!1,void 0,this),Kw(u4,{markdown:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},ZqA=({project:A,prevProject:Q,nextProject:$})=>{let{frontmatter:w,structuredContent:B,metadata:X,coverImageUrl:Y}=A,Z=A.ogImageUrl??Y;return Kw(Gy2,{children:[Kw(C6,{title:w.title,description:w.description,...Z?{ogImage:Z}:{},ogType:"article"},void 0,!1,void 0,this),Kw("article",{className:"project-detail",children:Kw("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:Kw("div",{className:"max-w-3xl mx-auto",children:[Y&&A.coverImageWidth&&A.coverImageHeight&&Kw(ZP,{src:Y,alt:w.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8 shadow-lg"},void 0,!1,void 0,this),Kw("h1",{className:"text-4xl md:text-5xl font-bold text-heading leading-tight tracking-tight mb-4",children:w.title},void 0,!1,void 0,this),Kw("div",{className:"flex flex-wrap items-center gap-4 text-theme-muted mb-8",children:[Kw("span",{className:"text-sm",children:X.year},void 0,!1,void 0,this),w.url&&Kw(Gy2,{children:[Kw("span",{className:"text-theme-muted",children:"|"},void 0,!1,void 0,this),Kw("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",className:"text-brand hover:text-brand-dark transition-colors",children:"View Project"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Kw("p",{className:"text-lg text-theme mb-12 leading-relaxed",children:w.description},void 0,!1,void 0,this),B&&Kw("div",{className:"case-study",children:[Kw(lk0,{title:"Context",content:B.context},void 0,!1,void 0,this),Kw(lk0,{title:"Problem",content:B.problem},void 0,!1,void 0,this),Kw(lk0,{title:"Solution",content:B.solution},void 0,!1,void 0,this),Kw(lk0,{title:"Outcome",content:B.outcome},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Kw(Dk$,{prevProject:Q,nextProject:$},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)};C0();KA();var qk$=H.object({title:H.string().max(80).describe("A clear, compelling project title (3-8 words). Should capture the essence of the project."),description:H.string().describe("A 1-2 sentence summary of the project for portfolio cards. Focus on the core value delivered."),context:H.string().describe("Background information: Who was the client/user? What was the situation? What constraints existed? (2-4 paragraphs)"),problem:H.string().describe("The challenge: What specific problem needed solving? What were the pain points? (2-3 paragraphs)"),solution:H.string().describe("The approach: What was built? What technologies/methods were used? How did it work? (3-5 paragraphs)"),outcome:H.string().describe("The results: What impact did this have? What metrics improved? What was learned? (2-3 paragraphs)")}),HqA=K2({name:"portfolio:generation",description:"Template for AI to generate portfolio project case studies",schema:qk$,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,basePrompt:`You are helping to create a professional portfolio case study based on REAL project information.
7526
7526
 
@@ -7696,7 +7696,7 @@ Use the project request as the primary source of truth. If retrieved knowledge c
7696
7696
  font: 10px/1.45 var(--font-mono, "JetBrains Mono", ui-monospace, monospace);
7697
7697
  }
7698
7698
  .printable-footer a { color: inherit; text-decoration: none; overflow-wrap: anywhere; }
7699
- `}},void 0,!1,void 0,this),n4("section",{className:"project-shell",children:[n4("header",{className:"project-hero",children:[n4("div",{className:"project-index",children:[Q.brandLabel&&n4("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),Q.year&&n4("span",{className:"project-year",children:Q.year},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n4("div",{className:"project-title-panel",children:[n4("span",{className:"printable-kind",children:"Case study dossier"},void 0,!1,void 0,this),n4("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.description&&n4("p",{className:"printable-description",children:Q.description},void 0,!1,void 0,this),n4("div",{className:"printable-meta",children:[Q.year&&n4("span",{children:Q.year},void 0,!1,void 0,this),Q.url&&n4("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&&n4("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this),n4(u4,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Boolean(Q.canonicalUrl)||Boolean(Q.url)||Boolean(Q.brandLabel))&&n4("footer",{className:"printable-footer",children:[n4("span",{children:Q.brandLabel??"Project printable"},void 0,!1,void 0,this),Q.canonicalUrl||Q.url?n4("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 Pk$=26214400,kk$=60000;class UqA{metadata={outputEntityType:"document"};context;renderPdf;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==nk0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let $=jk$(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),w=await Ik$(_k$(Nk$(),"brain-project-printable-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/printable/project/${Q.id}`,template:zy2,format:"pdf",content:$,siteConfig:{title:$.title,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"document",data:await this.renderPdf(X.urlFor(B.urlPath),{maxBytes:Pk$,timeoutMs:kk$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${Mk$(Q)}-printable.pdf`}}finally{await X.close()}}finally{await Lk$(w,{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}=c8(A.content),$=SX.parse(Q);if(!$.coverImageId)return;let w=await this.context.entityService.getEntity({entityType:"image",id:$.coverImageId});return w?.content.startsWith("data:image/")?w.content:void 0}}function jk$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=SX.parse($);return{title:B.title,body:w,...B.description?{description:B.description}:{},year:B.year,...B.publishedAt?{publishedAt:B.publishedAt}:{},...B.url?{url:B.url,canonicalUrl:B.url}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function Mk$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}_4();S2();C0();import{jsxDEV as fk$}from"preact/jsx-dev-runtime";var rk0="og-image",bk$="portfolio:og-image",Vy2=H.object({title:H.string().min(1),description:H.string().optional(),year:H.number().optional(),brandLabel:H.string().optional(),coverImageUrl:H.string().optional()}),Jy2={name:bk$,pluginId:"portfolio",schema:Vy2,renderers:{image:Ok$}};function Ok$(A){let Q=Vy2.parse(A);return fk$(YP,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Project",title:Q.title,subtitle:Q.description,tag:Q.year},void 0,!1,void 0,this)}class GqA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;deps;constructor(A,Q={}){this.context=A,this.deps=Q}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==rk0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let{frontmatter:$}=c8(Q.content),w=SX.parse($),B=this.resolveBrandLabel(),X=await this.resolveCoverImageUrl(w.coverImageId),Y={title:w.title,...w.description?{description:w.description}:{},year:w.year,...X?{coverImageUrl:X}:{},...B?{brandLabel:B}:{}};return{type:"image",data:await dE({mediaPath:`/_media/og/project/${Q.id}`,template:Jy2,content:Y,title:Y.title,themeMode:"light",themeCSS:this.context.themeCSS,tmpPrefix:"brain-project-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${xk$(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 xk$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}var Fy2={name:"@brains/portfolio",version:"0.2.0-alpha.183",description:"Portfolio showcase for projects and case studies",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":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var vk$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),Ck$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),Iy2=H.enum(["generating","draft","published","failed"]),hk$=H.object({title:H.string(),slug:H.string().optional(),status:Iy2,publishedAt:H.string().optional(),description:H.string(),year:H.number(),coverImageId:H.string().optional(),ogImageId:H.string().optional(),url:H.url().optional()}),Ek$=H.object({title:H.string(),status:Iy2,publishedAt:H.string().optional(),year:H.number(),slug:H.string(),error:H.string().optional()}),Tk$=H.object({context:H.string(),problem:H.string(),solution:H.string(),outcome:H.string()}),ok0=H.object({id:H.string(),entityType:H.literal("project"),content:H.string(),created:H.string(),updated:H.string(),visibility:Ck$,metadata:Ek$,contentHash:H.string(),frontmatter:hk$,body:H.string(),structuredContent:Tk$.optional(),url:H.string().optional(),typeLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()}),yk$=H.object({projects:H.array(ok0),pageTitle:H.string().optional(),pagination:vk$.nullable(),baseUrl:H.string().optional()}),gk$=H.object({prompt:H.string(),year:H.number()});function Sk$(A,Q){for(let $ of[A,Q]){let w=$?.match(/\b(19\d{2}|20\d{2})\b/);if(w?.[1])return Number(w[1])}return null}class DqA extends S6{entityType="project";schema=aO;adapter=BT;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("portfolio",Fy2,A,XqA)}async interceptCreate(A,Q,$){if(!A.prompt||A.content)return{kind:"continue",input:A};let w=Sk$(A.title,A.prompt);if(!w)return{kind:"continue",input:A};return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await $.jobs.enqueue({type:"project:generation",data:{prompt:A.prompt,...A.title?{title:A.title}:{},year:w},toolContext:Q,options:{source:this.id,metadata:{operationType:"content_operations"}}})}}}}createGenerationHandler(A){return new dk0(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":K2({name:"project-list",description:"Portfolio project list page template",schema:yk$,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:YqA}}),"project-detail":K2({name:"project-detail",description:"Individual project case study template",schema:H.object({project:ok0,prevProject:ok0.nullable(),nextProject:ok0.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:ZqA}}),generation:HqA}}getDataSources(){return[new ik0(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("project",nk0,new UqA(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("project",rk0,new GqA(A)),this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.unregisterAtprotoProjection=aB.getInstance().register(KqA())}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 $=gk$.parse(Q);return A.ai.generate({prompt:WqA($),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:$,entityId:w}=Q.payload;if($!=="project")return{success:!0};try{let B=await A.entityService.getEntity({entityType:"project",id:w});if(!B)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:`Project not found: ${w}`}}),{success:!0};if(B.metadata.status==="published")return{success:!0};let X=_Q(B.content,SX),Y=new Date().toISOString(),Z=O7(X.content,{...X.metadata,status:"published",publishedAt:Y});await A.entityService.updateEntity({entity:{...B,content:Z,metadata:{...B.metadata,status:"published",publishedAt:Y}}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:$,entityId:w,publishedAt:Y}})}catch(B){await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:aA(B)}})}return{success:!0}})}}function qqA(A={}){return new DqA(A)}KA();C0();Q5();C0();KA();var Ly2=H.enum(["available","early access","coming soon","planned"]),Ny2=H.enum(["available","early access","coming soon","planned"]),_y2=H.object({title:H.string(),description:H.string()}),Eq=H.object({name:H.string(),availability:Ly2,order:H.number(),ogImageId:H.string().optional()}),sk0=H.object({tagline:H.string(),promise:H.string(),role:H.string(),purpose:H.string(),audience:H.string(),values:H.array(H.string()).min(1),features:H.array(_y2).min(1).max(6),story:H.string()}),UC5=Eq.pick({name:!0,availability:!0,order:!0}).extend({slug:H.string()}),mk$=H.object({name:H.string(),availability:Ny2,order:H.number(),slug:H.string()}),uk$=H.object({name:H.string(),availability:Ny2,order:H.number(),ogImageId:H.string().optional()}),Yn=H6.extend({entityType:H.literal("product"),metadata:mk$}),ak0=Yn.extend({frontmatter:uk$,body:sk0,labels:H.record(H.string(),H.string()),ogImageUrl:H.string().optional()}),ck$=ak0.extend({url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),ogImageUrl:H.string().optional()});KA();S2();y9();class Zn extends d${constructor(){super(sk0,{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 zqA extends UQ{constructor(){super({entityType:"product",purpose:"A product entry in the portfolio.",schema:Yn,frontmatterSchema:Eq,bodyFormatter:new Zn})}toMarkdown(A){let Q=this.extractBody(A.content);try{let $=this.parseFrontMatter(A.content,Eq);return this.buildMarkdown(Q,$)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,Eq),$=k1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:$,availability:Q.availability,order:Q.order}}}}var tk0=new zqA;C0();KA();var Py2=H.object({title:H.string(),description:H.string()}),ky2=H.object({title:H.string(),description:H.string()}),pk$=H.object({title:H.string(),description:H.string()}),jy2=H.object({heading:H.string(),buttonText:H.string(),link:H.string()}),tO=H.object({headline:H.string(),tagline:H.string()}),lk$=H.object({title:H.string(),description:H.string()}),ek0=H.object({vision:H.string(),pillars:H.array(Py2).min(1).max(6),approach:H.array(lk$).min(1).max(6),productsIntro:H.string(),technologies:H.array(pk$).min(1).max(6),benefits:H.array(ky2).min(1).max(6),cta:jy2}),dk$=tO.pick({headline:!0}).extend({slug:H.string()}),ik$=H.object({headline:H.string(),slug:H.string()}),nk$=H.object({headline:H.string(),tagline:H.string()}),Hn=H6.extend({entityType:H.literal("products-overview"),metadata:ik$}),VqA=Hn.extend({frontmatter:nk$,body:ek0,labels:H.record(H.string(),H.string())});KA();S2();y9();class Wn extends d${constructor(){super(ek0,{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 JqA extends UQ{constructor(){super({entityType:"products-overview",purpose:"A high-level overview of the product portfolio.",schema:Hn,frontmatterSchema:tO,bodyFormatter:new Wn})}toMarkdown(A){let Q=this.extractBody(A.content);try{let $=this.parseFrontMatter(A.content,tO);return this.buildMarkdown(Q,$)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,tO),$=k1(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:$}}}}var FqA=new JqA;KA();C0();var rk$=H.object({entityType:H.string(),query:H.object({id:H.string().optional()}).optional()});function My2(A,Q){let $=_Q(A.content,Eq),w=Q.parse($.content),B=Q.getLabels();return ak0.parse({...A,frontmatter:$.metadata,body:w,labels:B})}function by2(A,Q){let $=_Q(A.content,tO),w=Q.parse($.content),B=Q.getLabels();return VqA.parse({...A,frontmatter:$.metadata,body:w,labels:B})}class Aj0{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new Wn;productFormatter=new Zn;constructor(A){this.logger=A,this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,$){let w=rk$.parse(A),B=$.entityService;if(w.entityType==="products-overview"){let K=(await B.listEntities({entityType:"products-overview",options:{limit:1}}))[0];if(!K)throw Error("Products overview entity not found");let U=by2(K,this.overviewFormatter);return Q.parse(U)}if(w.query?.id){let K=(await B.listEntities({entityType:"product",options:{filter:{metadata:{slug:w.query.id}},limit:1}}))[0];if(!K)throw Error(`Product not found: ${w.query.id}`);return Q.parse({product:My2(K,this.productFormatter)})}let[X,Y]=await Promise.all([B.listEntities({entityType:"products-overview",options:{limit:1}}),B.listEntities({entityType:"product",options:{sortFields:[{field:"order",direction:"asc"}]}})]),Z=X[0];if(!Z)throw Error("Products overview entity not found");return Q.parse({overview:by2(Z,this.overviewFormatter),products:Y.map((W)=>My2(W,this.productFormatter))})}}import{jsxDEV as f1,Fragment as ak$}from"preact/jsx-dev-runtime";var Oy2=({overview:A,products:Q})=>{let{frontmatter:$,body:w,labels:B}=A;return f1(ak$,{children:[f1(C6,{title:$.headline,description:$.tagline},void 0,!1,void 0,this),f1("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[f1("style",{children:`
7699
+ `}},void 0,!1,void 0,this),n4("section",{className:"project-shell",children:[n4("header",{className:"project-hero",children:[n4("div",{className:"project-index",children:[Q.brandLabel&&n4("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),Q.year&&n4("span",{className:"project-year",children:Q.year},void 0,!1,void 0,this)]},void 0,!0,void 0,this),n4("div",{className:"project-title-panel",children:[n4("span",{className:"printable-kind",children:"Case study dossier"},void 0,!1,void 0,this),n4("h1",{className:"printable-title",children:Q.title},void 0,!1,void 0,this),Q.description&&n4("p",{className:"printable-description",children:Q.description},void 0,!1,void 0,this),n4("div",{className:"printable-meta",children:[Q.year&&n4("span",{children:Q.year},void 0,!1,void 0,this),Q.url&&n4("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&&n4("img",{className:"printable-cover",src:Q.coverImageUrl,alt:""},void 0,!1,void 0,this),n4(u4,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this),(Boolean(Q.canonicalUrl)||Boolean(Q.url)||Boolean(Q.brandLabel))&&n4("footer",{className:"printable-footer",children:[n4("span",{children:Q.brandLabel??"Project printable"},void 0,!1,void 0,this),Q.canonicalUrl||Q.url?n4("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 Pk$=26214400,kk$=60000;class UqA{metadata={outputEntityType:"document"};context;renderPdf;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==nk0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let $=jk$(Q,{brandLabel:this.resolveBrandLabel(),coverImageUrl:await this.resolveCoverImageUrl(Q)}),w=await Ik$(_k$(Nk$(),"brain-project-printable-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/printable/project/${Q.id}`,template:zy2,format:"pdf",content:$,siteConfig:{title:$.title,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"document",data:await this.renderPdf(X.urlFor(B.urlPath),{maxBytes:Pk$,timeoutMs:kk$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${Mk$(Q)}-printable.pdf`}}finally{await X.close()}}finally{await Lk$(w,{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}=c8(A.content),$=SX.parse(Q);if(!$.coverImageId)return;let w=await this.context.entityService.getEntity({entityType:"image",id:$.coverImageId});return w?.content.startsWith("data:image/")?w.content:void 0}}function jk$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=SX.parse($);return{title:B.title,body:w,...B.description?{description:B.description}:{},year:B.year,...B.publishedAt?{publishedAt:B.publishedAt}:{},...B.url?{url:B.url,canonicalUrl:B.url}:{},...Q.coverImageUrl?{coverImageUrl:Q.coverImageUrl}:{},...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function Mk$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}_4();S2();C0();import{jsxDEV as fk$}from"preact/jsx-dev-runtime";var rk0="og-image",bk$="portfolio:og-image",Vy2=H.object({title:H.string().min(1),description:H.string().optional(),year:H.number().optional(),brandLabel:H.string().optional(),coverImageUrl:H.string().optional()}),Jy2={name:bk$,pluginId:"portfolio",schema:Vy2,renderers:{image:Ok$}};function Ok$(A){let Q=Vy2.parse(A);return fk$(YP,{brandLabel:Q.brandLabel??Q.title,eyebrow:"Project",title:Q.title,subtitle:Q.description,tag:Q.year},void 0,!1,void 0,this)}class GqA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;deps;constructor(A,Q={}){this.context=A,this.deps=Q}async resolve(A){if(A.sourceEntityType!=="project"||A.attachmentType!==rk0)return;let Q=await this.context.entityService.getEntity({entityType:"project",id:A.sourceEntityId});if(!Q)return;let{frontmatter:$}=c8(Q.content),w=SX.parse($),B=this.resolveBrandLabel(),X=await this.resolveCoverImageUrl(w.coverImageId),Y={title:w.title,...w.description?{description:w.description}:{},year:w.year,...X?{coverImageUrl:X}:{},...B?{brandLabel:B}:{}};return{type:"image",data:await dE({mediaPath:`/_media/og/project/${Q.id}`,template:Jy2,content:Y,title:Y.title,themeMode:"light",themeCSS:this.context.themeCSS,tmpPrefix:"brain-project-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${xk$(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 xk$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.title)}var Fy2={name:"@brains/portfolio",version:"0.2.0-alpha.184",description:"Portfolio showcase for projects and case studies",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":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var vk$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),Ck$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),Iy2=H.enum(["generating","draft","published","failed"]),hk$=H.object({title:H.string(),slug:H.string().optional(),status:Iy2,publishedAt:H.string().optional(),description:H.string(),year:H.number(),coverImageId:H.string().optional(),ogImageId:H.string().optional(),url:H.url().optional()}),Ek$=H.object({title:H.string(),status:Iy2,publishedAt:H.string().optional(),year:H.number(),slug:H.string(),error:H.string().optional()}),Tk$=H.object({context:H.string(),problem:H.string(),solution:H.string(),outcome:H.string()}),ok0=H.object({id:H.string(),entityType:H.literal("project"),content:H.string(),created:H.string(),updated:H.string(),visibility:Ck$,metadata:Ek$,contentHash:H.string(),frontmatter:hk$,body:H.string(),structuredContent:Tk$.optional(),url:H.string().optional(),typeLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()}),yk$=H.object({projects:H.array(ok0),pageTitle:H.string().optional(),pagination:vk$.nullable(),baseUrl:H.string().optional()}),gk$=H.object({prompt:H.string(),year:H.number()});function Sk$(A,Q){for(let $ of[A,Q]){let w=$?.match(/\b(19\d{2}|20\d{2})\b/);if(w?.[1])return Number(w[1])}return null}class DqA extends S6{entityType="project";schema=aO;adapter=BT;unregisterAtprotoProjection;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("portfolio",Fy2,A,XqA)}async interceptCreate(A,Q,$){if(!A.prompt||A.content)return{kind:"continue",input:A};let w=Sk$(A.title,A.prompt);if(!w)return{kind:"continue",input:A};return{kind:"handled",result:{success:!0,data:{status:"generating",jobId:await $.jobs.enqueue({type:"project:generation",data:{prompt:A.prompt,...A.title?{title:A.title}:{},year:w},toolContext:Q,options:{source:this.id,metadata:{operationType:"content_operations"}}})}}}}createGenerationHandler(A){return new dk0(this.logger.child("ProjectGenerationJobHandler"),A)}getTemplates(){return{"project-list":K2({name:"project-list",description:"Portfolio project list page template",schema:yk$,dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:YqA}}),"project-detail":K2({name:"project-detail",description:"Individual project case study template",schema:H.object({project:ok0,prevProject:ok0.nullable(),nextProject:ok0.nullable()}),dataSourceId:"portfolio:entities",requiredPermission:"public",layout:{component:ZqA}}),generation:HqA}}getDataSources(){return[new ik0(this.logger.child("ProjectDataSource"))]}async onRegister(A){this.registerEvalHandlers(A),this.unregisterPrintableAttachmentProvider=A.attachments.register("project",nk0,new UqA(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("project",rk0,new GqA(A)),this.deferPublishRegistration(A),this.subscribeToPublishExecute(A),this.unregisterAtprotoProjection=aB.getInstance().register(KqA())}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 $=gk$.parse(Q);return A.ai.generate({prompt:WqA($),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:$,entityId:w}=Q.payload;if($!=="project")return{success:!0};try{let B=await A.entityService.getEntity({entityType:"project",id:w});if(!B)return await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:`Project not found: ${w}`}}),{success:!0};if(B.metadata.status==="published")return{success:!0};let X=_Q(B.content,SX),Y=new Date().toISOString(),Z=O7(X.content,{...X.metadata,status:"published",publishedAt:Y});await A.entityService.updateEntity({entity:{...B,content:Z,metadata:{...B.metadata,status:"published",publishedAt:Y}}}),await A.messaging.send({type:"publish:report:success",payload:{entityType:$,entityId:w,publishedAt:Y}})}catch(B){await A.messaging.send({type:"publish:report:failure",payload:{entityType:$,entityId:w,error:aA(B)}})}return{success:!0}})}}function qqA(A={}){return new DqA(A)}KA();C0();Q5();C0();KA();var Ly2=H.enum(["available","early access","coming soon","planned"]),Ny2=H.enum(["available","early access","coming soon","planned"]),_y2=H.object({title:H.string(),description:H.string()}),Eq=H.object({name:H.string(),availability:Ly2,order:H.number(),ogImageId:H.string().optional()}),sk0=H.object({tagline:H.string(),promise:H.string(),role:H.string(),purpose:H.string(),audience:H.string(),values:H.array(H.string()).min(1),features:H.array(_y2).min(1).max(6),story:H.string()}),UC5=Eq.pick({name:!0,availability:!0,order:!0}).extend({slug:H.string()}),mk$=H.object({name:H.string(),availability:Ny2,order:H.number(),slug:H.string()}),uk$=H.object({name:H.string(),availability:Ny2,order:H.number(),ogImageId:H.string().optional()}),Yn=H6.extend({entityType:H.literal("product"),metadata:mk$}),ak0=Yn.extend({frontmatter:uk$,body:sk0,labels:H.record(H.string(),H.string()),ogImageUrl:H.string().optional()}),ck$=ak0.extend({url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),ogImageUrl:H.string().optional()});KA();S2();y9();class Zn extends d${constructor(){super(sk0,{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 zqA extends UQ{constructor(){super({entityType:"product",purpose:"A product entry in the portfolio.",schema:Yn,frontmatterSchema:Eq,bodyFormatter:new Zn})}toMarkdown(A){let Q=this.extractBody(A.content);try{let $=this.parseFrontMatter(A.content,Eq);return this.buildMarkdown(Q,$)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,Eq),$=k1(Q.name);return{content:A,entityType:"product",metadata:{name:Q.name,slug:$,availability:Q.availability,order:Q.order}}}}var tk0=new zqA;C0();KA();var Py2=H.object({title:H.string(),description:H.string()}),ky2=H.object({title:H.string(),description:H.string()}),pk$=H.object({title:H.string(),description:H.string()}),jy2=H.object({heading:H.string(),buttonText:H.string(),link:H.string()}),tO=H.object({headline:H.string(),tagline:H.string()}),lk$=H.object({title:H.string(),description:H.string()}),ek0=H.object({vision:H.string(),pillars:H.array(Py2).min(1).max(6),approach:H.array(lk$).min(1).max(6),productsIntro:H.string(),technologies:H.array(pk$).min(1).max(6),benefits:H.array(ky2).min(1).max(6),cta:jy2}),dk$=tO.pick({headline:!0}).extend({slug:H.string()}),ik$=H.object({headline:H.string(),slug:H.string()}),nk$=H.object({headline:H.string(),tagline:H.string()}),Hn=H6.extend({entityType:H.literal("products-overview"),metadata:ik$}),VqA=Hn.extend({frontmatter:nk$,body:ek0,labels:H.record(H.string(),H.string())});KA();S2();y9();class Wn extends d${constructor(){super(ek0,{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 JqA extends UQ{constructor(){super({entityType:"products-overview",purpose:"A high-level overview of the product portfolio.",schema:Hn,frontmatterSchema:tO,bodyFormatter:new Wn})}toMarkdown(A){let Q=this.extractBody(A.content);try{let $=this.parseFrontMatter(A.content,tO);return this.buildMarkdown(Q,$)}catch{return Q}}fromMarkdown(A){let Q=this.parseFrontMatter(A,tO),$=k1(Q.headline);return{content:A,entityType:"products-overview",metadata:{headline:Q.headline,slug:$}}}}var FqA=new JqA;KA();C0();var rk$=H.object({entityType:H.string(),query:H.object({id:H.string().optional()}).optional()});function My2(A,Q){let $=_Q(A.content,Eq),w=Q.parse($.content),B=Q.getLabels();return ak0.parse({...A,frontmatter:$.metadata,body:w,labels:B})}function by2(A,Q){let $=_Q(A.content,tO),w=Q.parse($.content),B=Q.getLabels();return VqA.parse({...A,frontmatter:$.metadata,body:w,labels:B})}class Aj0{logger;id="products:entities";name="Products Entity DataSource";description="Fetches products and overview for the products page";overviewFormatter=new Wn;productFormatter=new Zn;constructor(A){this.logger=A,this.logger.debug("ProductsDataSource initialized")}async fetch(A,Q,$){let w=rk$.parse(A),B=$.entityService;if(w.entityType==="products-overview"){let K=(await B.listEntities({entityType:"products-overview",options:{limit:1}}))[0];if(!K)throw Error("Products overview entity not found");let U=by2(K,this.overviewFormatter);return Q.parse(U)}if(w.query?.id){let K=(await B.listEntities({entityType:"product",options:{filter:{metadata:{slug:w.query.id}},limit:1}}))[0];if(!K)throw Error(`Product not found: ${w.query.id}`);return Q.parse({product:My2(K,this.productFormatter)})}let[X,Y]=await Promise.all([B.listEntities({entityType:"products-overview",options:{limit:1}}),B.listEntities({entityType:"product",options:{sortFields:[{field:"order",direction:"asc"}]}})]),Z=X[0];if(!Z)throw Error("Products overview entity not found");return Q.parse({overview:by2(Z,this.overviewFormatter),products:Y.map((W)=>My2(W,this.productFormatter))})}}import{jsxDEV as f1,Fragment as ak$}from"preact/jsx-dev-runtime";var Oy2=({overview:A,products:Q})=>{let{frontmatter:$,body:w,labels:B}=A;return f1(ak$,{children:[f1(C6,{title:$.headline,description:$.tagline},void 0,!1,void 0,this),f1("header",{className:"relative w-full min-h-[80vh] flex items-end px-6 md:px-12 bg-brand-dark overflow-hidden",children:[f1("style",{children:`
7700
7700
  @keyframes wave-drift {
7701
7701
  from { transform: translateX(0); }
7702
7702
  to { transform: translateX(-50%); }
@@ -7891,7 +7891,7 @@ Use the project request as the primary source of truth. If retrieved knowledge c
7891
7891
  font: 10px/1.45 var(--font-mono, "JetBrains Mono", ui-monospace, monospace);
7892
7892
  }
7893
7893
  `}},void 0,!1,void 0,this),bG("section",{className:"product-shell",children:[bG("header",{className:"product-hero",children:[Q.brandLabel&&bG("p",{className:"printable-kicker",children:Q.brandLabel},void 0,!1,void 0,this),bG("h1",{className:"printable-title",children:Q.name},void 0,!1,void 0,this),Q.availability&&bG("div",{className:"printable-meta",children:bG("span",{children:Q.availability},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),bG("div",{className:"product-body-wrap",children:[bG("aside",{className:"product-rail","aria-hidden":"true",children:bG("p",{className:"product-rail-label",children:"Product brief / capabilities"},void 0,!1,void 0,this)},void 0,!1,void 0,this),bG(u4,{markdown:Q.body,className:"printable-body"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Q.brandLabel&&bG("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 Xj$=26214400,Yj$=60000;class LqA{metadata={outputEntityType:"document"};context;renderPdf;constructor(A,Q={}){this.context=A,this.renderPdf=Q.renderPdf??a3}async resolve(A){if(A.sourceEntityType!=="product"||A.attachmentType!==Qj0)return;let Q=await this.context.entityService.getEntity({entityType:"product",id:A.sourceEntityId});if(!Q)return;let $=Zj$(Q,{brandLabel:this.resolveBrandLabel()}),w=await Qj$(Bj$(wj$(),"brain-product-printable-"));try{let B=await VG({outputDir:w,mediaPath:`/_media/printable/product/${Q.id}`,template:Ry2,format:"pdf",content:$,siteConfig:{title:$.name,themeMode:"light"},themeCSS:this.context.themeCSS}),X=await JG({rootDir:w});try{return{type:"document",data:await this.renderPdf(X.urlFor(B.urlPath),{maxBytes:Xj$,timeoutMs:Yj$,printBackground:!0,preferCSSPageSize:!0}),mimeType:"application/pdf",filename:`${Hj$(Q)}-printable.pdf`}}finally{await X.close()}}finally{await $j$(w,{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 Zj$(A,Q={}){let{frontmatter:$,content:w}=c8(A.content),B=Eq.parse($);return{name:B.name,body:w,availability:B.availability,...Q.brandLabel?{brandLabel:Q.brandLabel}:{}}}function Hj$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.name)}_4();S2();C0();import{jsxDEV as Uj$}from"preact/jsx-dev-runtime";var $j0="og-image",Wj$="products:og-image",vy2=H.object({name:H.string().min(1),tagline:H.string().optional(),availability:H.string().optional(),brandLabel:H.string().optional()}),Cy2={name:Wj$,pluginId:"products",schema:vy2,renderers:{image:Kj$}};function Kj$(A){let Q=vy2.parse(A);return Uj$(YP,{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 NqA{metadata={outputEntityType:"image",targetField:"ogImageId"};context;deps;constructor(A,Q={}){this.context=A,this.deps=Q}async resolve(A){if(A.sourceEntityType!=="product"||A.attachmentType!==$j0)return;let Q=await this.context.entityService.getEntity({entityType:"product",id:A.sourceEntityId});if(!Q)return;let{frontmatter:$,content:w}=c8(Q.content),B=Eq.parse($),X=Gj$(w,"Tagline"),Y=this.resolveBrandLabel(),Z={name:B.name,availability:B.availability,...X?{tagline:X}:{},...Y?{brandLabel:Y}:{}};return{type:"image",data:await dE({mediaPath:`/_media/og/product/${Q.id}`,template:Cy2,content:Z,title:Z.name,themeMode:"light",themeCSS:this.context.themeCSS,tmpPrefix:"brain-product-og-image-",...this.deps.screenshotPng&&{screenshotPng:this.deps.screenshotPng}}),mimeType:"image/png",filename:`${Dj$(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 Gj$(A,Q){let $=A.split(/\r?\n/),w=$.findIndex((Y)=>Y.trim().toLowerCase()===`## ${Q.toLowerCase()}`);if(w===-1)return;let B=[];for(let Y of $.slice(w+1)){if(Y.trim().startsWith("## "))break;B.push(Y)}let X=B.join(`
7894
- `).trim();return X.length>0?X:void 0}function Dj$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.name)}var hy2={name:"@brains/products",version:"0.2.0-alpha.183",description:"Product entity management and overview page for marketing showcase",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var zj$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),Ey2=H.object({id:H.string(),entityType:H.string(),content:H.string(),created:H.string(),updated:H.string(),visibility:zj$,metadata:H.record(H.string(),H.unknown()),contentHash:H.string()}),Ty2=H.enum(["available","early access","coming soon","planned"]),Vj$=H.object({title:H.string(),description:H.string()}),Jj$=H.object({name:H.string(),availability:Ty2,order:H.number(),ogImageId:H.string().optional()}),Fj$=H.object({tagline:H.string(),promise:H.string(),role:H.string(),purpose:H.string(),audience:H.string(),values:H.array(H.string()).min(1),features:H.array(Vj$).min(1).max(6),story:H.string()}),Ij$=H.object({name:H.string(),availability:Ty2,order:H.number(),slug:H.string()}),yy2=Ey2.extend({entityType:H.literal("product"),metadata:Ij$,frontmatter:Jj$,body:Fj$,labels:H.record(H.string(),H.string()),url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),ogImageUrl:H.string().optional()}),wj0=H.object({title:H.string(),description:H.string()}),Lj$=H.object({heading:H.string(),buttonText:H.string(),link:H.string()}),Nj$=H.object({headline:H.string(),tagline:H.string()}),_j$=H.object({vision:H.string(),pillars:H.array(wj0).min(1).max(6),approach:H.array(wj0).min(1).max(6),productsIntro:H.string(),technologies:H.array(wj0).min(1).max(6),benefits:H.array(wj0).min(1).max(6),cta:Lj$}),Pj$=H.object({headline:H.string(),slug:H.string()}),kj$=Ey2.extend({entityType:H.literal("products-overview"),metadata:Pj$,frontmatter:Nj$,body:_j$,labels:H.record(H.string(),H.string())}),jj$=H.object({overview:kj$,products:H.array(yy2)}),Mj$=H.object({product:yy2});class _qA extends S6{entityType=tk0.entityType;schema=Yn;adapter=tk0;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("products",hy2,A,IqA)}getTemplates(){return{"product-list":K2({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:jj$,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Oy2}}),"product-detail":K2({name:"product-detail",description:"Individual product detail page",schema:Mj$,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:fy2}})}}getDataSources(){return[new Aj0(this.logger.child("ProductsDataSource"))]}async onRegister(A){this.unregisterPrintableAttachmentProvider=A.attachments.register("product",Qj0,new LqA(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("product",$j0,new NqA(A)),A.entities.register("products-overview",Hn,FqA)}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0}}function U50(A={}){return new _qA(A)}KA();C0();C0();var bj$=H.enum(["public","shared","restricted"]),gy2=H.object({includeEntityTypes:H.array(H.string()).default([]),minRelevanceScore:H.number().min(0).max(1).default(0.5),mergeSimilarityThreshold:H.number().min(0).max(1).default(0.85),autoMerge:H.boolean().default(!0),extractableStatuses:H.array(H.string()).default(["published"]),enableAutoExtraction:H.boolean().default(!0),extractionVisibility:bj$.default("public"),sourceChangeBatchDelayMs:H.number().int().min(0).default(1000)});KA();C0();KA();var oh5=H.object({}),Oj$=H.record(H.string(),H.unknown()).transform(()=>({})),Kn=H6.extend({entityType:H.literal("topic"),metadata:Oj$}),sh5=H.object({content:H.string()}),Sy2=H.object({title:H.string().describe("Topic title")});var XT="topics",Uw="topic",PqA="topics-projection",my2="topic:project",Bj0="topics-plugin",uy2="topics:batch-completed",cy2="topics-source-batch";class QV extends UQ{constructor(){super({entityType:Uw,purpose:"A recurring theme or subject derived from the user's content.",schema:Kn,frontmatterSchema:Sy2})}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:Uw}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseTopicBody(A.content),w=this.buildMarkdown("",this.buildFrontmatter(Q.title)).match(/^---\n[\s\S]*?\n---/);return w?w[0]:""}parseTopicBody(A){if(A.startsWith("---"))try{let Q=this.parseFrontmatter(A);return{content:this.extractBody(A).replace(/\n*## Sources[\s\S]*$/,"").trim(),formatted:A,title:Q.title}}catch{return{content:A,formatted:A,title:"Unknown Topic"}}return{content:A,formatted:A,title:"Unknown Topic"}}createTopicBody(A){return this.buildMarkdown(A.content,this.buildFrontmatter(A.title))}}KA();C0();C0();var fj$=H.object({title:H.string().max(100),content:H.string(),relevanceScore:H.number().min(0).max(1)}),py2=H.array(fj$);var xj$=H.object({topics:py2}),ly2=K2({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:xj$,basePrompt:`You are an expert at analyzing content and extracting key topics.
7894
+ `).trim();return X.length>0?X:void 0}function Dj$(A){let Q=A.metadata.slug;return Q.length>0?Q:k1(A.metadata.name)}var hy2={name:"@brains/products",version:"0.2.0-alpha.184",description:"Product entity management and overview page for marketing showcase",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var zj$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),Ey2=H.object({id:H.string(),entityType:H.string(),content:H.string(),created:H.string(),updated:H.string(),visibility:zj$,metadata:H.record(H.string(),H.unknown()),contentHash:H.string()}),Ty2=H.enum(["available","early access","coming soon","planned"]),Vj$=H.object({title:H.string(),description:H.string()}),Jj$=H.object({name:H.string(),availability:Ty2,order:H.number(),ogImageId:H.string().optional()}),Fj$=H.object({tagline:H.string(),promise:H.string(),role:H.string(),purpose:H.string(),audience:H.string(),values:H.array(H.string()).min(1),features:H.array(Vj$).min(1).max(6),story:H.string()}),Ij$=H.object({name:H.string(),availability:Ty2,order:H.number(),slug:H.string()}),yy2=Ey2.extend({entityType:H.literal("product"),metadata:Ij$,frontmatter:Jj$,body:Fj$,labels:H.record(H.string(),H.string()),url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),ogImageUrl:H.string().optional()}),wj0=H.object({title:H.string(),description:H.string()}),Lj$=H.object({heading:H.string(),buttonText:H.string(),link:H.string()}),Nj$=H.object({headline:H.string(),tagline:H.string()}),_j$=H.object({vision:H.string(),pillars:H.array(wj0).min(1).max(6),approach:H.array(wj0).min(1).max(6),productsIntro:H.string(),technologies:H.array(wj0).min(1).max(6),benefits:H.array(wj0).min(1).max(6),cta:Lj$}),Pj$=H.object({headline:H.string(),slug:H.string()}),kj$=Ey2.extend({entityType:H.literal("products-overview"),metadata:Pj$,frontmatter:Nj$,body:_j$,labels:H.record(H.string(),H.string())}),jj$=H.object({overview:kj$,products:H.array(yy2)}),Mj$=H.object({product:yy2});class _qA extends S6{entityType=tk0.entityType;schema=Yn;adapter=tk0;unregisterPrintableAttachmentProvider;unregisterOgImageAttachmentProvider;constructor(A={}){super("products",hy2,A,IqA)}getTemplates(){return{"product-list":K2({name:"product-list",description:"Products page \u2014 overview + brain model cards",schema:jj$,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:Oy2}}),"product-detail":K2({name:"product-detail",description:"Individual product detail page",schema:Mj$,dataSourceId:"products:entities",requiredPermission:"public",layout:{component:fy2}})}}getDataSources(){return[new Aj0(this.logger.child("ProductsDataSource"))]}async onRegister(A){this.unregisterPrintableAttachmentProvider=A.attachments.register("product",Qj0,new LqA(A)),this.unregisterOgImageAttachmentProvider=A.attachments.register("product",$j0,new NqA(A)),A.entities.register("products-overview",Hn,FqA)}async onShutdown(){this.unregisterPrintableAttachmentProvider?.(),this.unregisterPrintableAttachmentProvider=void 0,this.unregisterOgImageAttachmentProvider?.(),this.unregisterOgImageAttachmentProvider=void 0}}function U50(A={}){return new _qA(A)}KA();C0();C0();var bj$=H.enum(["public","shared","restricted"]),gy2=H.object({includeEntityTypes:H.array(H.string()).default([]),minRelevanceScore:H.number().min(0).max(1).default(0.5),mergeSimilarityThreshold:H.number().min(0).max(1).default(0.85),autoMerge:H.boolean().default(!0),extractableStatuses:H.array(H.string()).default(["published"]),enableAutoExtraction:H.boolean().default(!0),extractionVisibility:bj$.default("public"),sourceChangeBatchDelayMs:H.number().int().min(0).default(1000)});KA();C0();KA();var oh5=H.object({}),Oj$=H.record(H.string(),H.unknown()).transform(()=>({})),Kn=H6.extend({entityType:H.literal("topic"),metadata:Oj$}),sh5=H.object({content:H.string()}),Sy2=H.object({title:H.string().describe("Topic title")});var XT="topics",Uw="topic",PqA="topics-projection",my2="topic:project",Bj0="topics-plugin",uy2="topics:batch-completed",cy2="topics-source-batch";class QV extends UQ{constructor(){super({entityType:Uw,purpose:"A recurring theme or subject derived from the user's content.",schema:Kn,frontmatterSchema:Sy2})}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:Uw}}extractMetadata(A){return{}}generateFrontMatter(A){let Q=this.parseTopicBody(A.content),w=this.buildMarkdown("",this.buildFrontmatter(Q.title)).match(/^---\n[\s\S]*?\n---/);return w?w[0]:""}parseTopicBody(A){if(A.startsWith("---"))try{let Q=this.parseFrontmatter(A);return{content:this.extractBody(A).replace(/\n*## Sources[\s\S]*$/,"").trim(),formatted:A,title:Q.title}}catch{return{content:A,formatted:A,title:"Unknown Topic"}}return{content:A,formatted:A,title:"Unknown Topic"}}createTopicBody(A){return this.buildMarkdown(A.content,this.buildFrontmatter(A.title))}}KA();C0();C0();var fj$=H.object({title:H.string().max(100),content:H.string(),relevanceScore:H.number().min(0).max(1)}),py2=H.array(fj$);var xj$=H.object({topics:py2}),ly2=K2({name:"topics:extraction",description:"Extract topics from conversation text",dataSourceId:"shell:ai-content",schema:xj$,basePrompt:`You are an expert at analyzing content and extracting key topics.
7895
7895
 
7896
7896
  Analyze the provided content and extract meaningful topics discussed.
7897
7897
 
@@ -7994,13 +7994,13 @@ ${A.incomingTopic.content}`})}}function cj$(A){if(A.length===0)return"";return A
7994
7994
 
7995
7995
  ${Q.content}`}).join(`
7996
7996
 
7997
- `)}async function YT(A,Q,$,w={}){if(A.length===0)return{created:0,merged:0,skipped:0,batches:0};let B=w.minRelevanceScore??0,X=w.autoMerge??!1,Y=w.mergeSimilarityThreshold??0.85,Z=w.targetVisibility??"public",W=Qg2(A),K=new $V(Q.entityService,$),U=w.topicMergeSynthesizer??new fqA(Q,$),G=await Wj0(Q.entityService,void 0,Z),D=new Map,q=0,J=0,F=0;for(let P of W){$.info(`Processing batch of ${P.length} entities`);let j=cj$(P),k=Kj0({entityTitle:`Batch of ${P.length} entities`,entityType:"batch",content:j,existingTopicTitles:G});try{let R=(await Q.ai.generate({prompt:k,templateName:"topics:extraction"})).topics.filter((x)=>x.relevanceScore>=B);for(let x of R)try{if(X){let u=await K.findMergeCandidate({incoming:x,threshold:Y,additionalCandidates:Array.from(D.values()),targetVisibility:Z});if(u){let n=await U.synthesize({existingTopic:u.topic,incomingTopic:x}),t=await K.applySynthesizedMerge({existingId:u.topic.id,synthesized:{...n,title:u.title},visibility:Z});if(!t)throw Error(`Failed to merge topic: ${x.title}`);D.set(t.id,t),J++;continue}}let O=K.getTopicIdForTitle(x.title,Z);if(D.has(O)){F++;continue}let g=await K.createTopicOptimistic({title:x.title,content:x.content,visibility:Z});if(g.topic)D.set(g.topic.id,g.topic);if(g.created)q++;else F++}catch(O){$.error("Topic batch item failed",{title:x.title,error:aA(O)})}}catch(f){$.error("Batch topic extraction failed",{batchSize:P.length,promptChars:k.length,error:aA(f)})}}let I={created:q,merged:J,skipped:F,batches:W.length};if(q>0||J>0)await Q.messaging.send({type:uy2,payload:I,broadcast:!0});return I}KA();C0();var pj$=H.discriminatedUnion("mode",[H.object({mode:H.literal("derive"),reason:H.string().optional()}),H.object({mode:H.literal("rebuild"),reason:H.string().optional()}),H.object({mode:H.literal("source-batch"),minRelevanceScore:H.number().min(0).max(1).optional()})]);class xqA{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 Zg2(A){let{context:Q,logger:$,config:w}=A;return{process:async(B)=>{if(B.mode==="derive")return await A.extractAllTopics(),{success:!0};if(B.mode==="rebuild")return await A.rebuildAllTopics(),{success:!0};return lj$({context:Q,logger:$,config:w,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:B.minRelevanceScore??w.minRelevanceScore})},validateAndParse:(B)=>{let X=pj$.safeParse(B??{});return X.success?X.data:null}}}async function lj$(A){let Q=A.sourceBatch.drain(),$=await Promise.all(Q.map(async(K)=>({ref:K,entity:await A.context.entityService.getEntity({entityType:K.entityType,id:K.entityId})}))),w=0,B=0,X=0,Y=0,Z=[];for(let{ref:K,entity:U}of $){if(!U){B++;continue}if(U.contentHash!==K.contentHash){w++;continue}if(!A.isEntityPublished(U)){X++;continue}if(!sj(U.visibility,A.config.extractionVisibility)){Y++;continue}Z.push(U)}if(Z.length===0)return{success:!0,sources:Q.length,created:0,merged:0,skipped:0,batches:0,stale:w,missing:B,unpublished:X,hidden:Y};let W=await YT(Z,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,...W,stale:w,missing:B,unpublished:X,hidden:Y}}function Hg2(){return{priority:5,source:Bj0,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:XT}}}async function Wg2(A){let Q=await Ug2(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 $=await YT(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",$)}async function Kg2(A){let Q=await Ug2(A),$=await RqA(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",$)}async function RqA(A,Q,$,w){let B=new $V(Q.entityService,$),X=await B.listTopics({visibility:w.extractionVisibility});for(let Z of X)await B.deleteTopic(Z.id);if(A.length===0)return{deleted:X.length,created:0,merged:0,skipped:0,batches:0};let Y=await YT(A,Q,$,{minRelevanceScore:w.minRelevanceScore,autoMerge:w.autoMerge,mergeSimilarityThreshold:w.mergeSimilarityThreshold,targetVisibility:w.extractionVisibility});return{deleted:X.length,...Y}}async function Ug2(A){let Q=dj$(A),$=[];for(let w of Q){let B=await A.context.entityService.listEntities({entityType:w,options:{filter:{visibilityScope:A.config.extractionVisibility}}});for(let X of B){if(!A.isEntityPublished(X))continue;$.push(X)}}return $}function dj$(A){return A.context.entityService.getEntityTypes().filter(($)=>A.shouldProcessEntityType($))}var Dn=H.object({entityType:H.string(),content:H.string(),metadata:H.record(H.string(),H.unknown()).optional()}),ij$=Dn.extend({minRelevanceScore:H.number().optional()}),nj$=H.object({contentA:Dn,contentB:Dn,minRelevanceScore:H.number().optional(),threshold:H.number().min(0).max(1).optional()}),z50=H.object({title:H.string(),content:H.string()}),rj$=H.object({existingTopics:H.array(z50),incomingTopic:z50,threshold:H.number().optional()}),oj$=H.object({existingTopics:H.array(z50).default([]),incomingTopic:z50.extend({relevanceScore:H.number().min(0).max(1).optional()}),threshold:H.number().optional()}),sj$=H.object({entities:H.array(Dn).min(1),minRelevanceScore:H.number().optional()}),aj$=H.object({existingTopics:H.array(z50).optional(),entities:H.array(Dn)}),tj$=H.object({entities:H.array(Dn)});function Gn(A,Q=""){return{id:`eval${Q}-${Date.now()}`,entityType:A.entityType,content:A.content,contentHash:e6(A.content),visibility:"public",metadata:A.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}}function Gg2(A){return{title:A.title,relevanceScore:A.relevanceScore}}function ej$(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function AM$(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:ej$(Q)}]}}async function ZT(A){let Q=await A.entityService.listEntities({entityType:Uw});await Promise.all(Q.map(($)=>A.entityService.deleteEntity({entityType:Uw,id:$.id})))}async function QM$(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise(($)=>setTimeout($,100))}}function Dg2(A){let{context:Q,logger:$,config:w}=A,B=new OqA(Q,$),X=async(Y,Z,W="")=>{let K=Gn(Y,W);return B.extractFromEntity(K,Z)};Q.eval.registerHandler("extractFromEntity",async(Y)=>{await ZT(Q);let Z=ij$.parse(Y),W=Z.minRelevanceScore??w.minRelevanceScore,K=Gn(Z);return(await B.extractFromEntity(K,W)).map((G)=>AM$(G,K))}),Q.eval.registerHandler("checkMergeSimilarity",async(Y)=>{await ZT(Q);let Z=nj$.parse(Y),W=Z.minRelevanceScore??w.minRelevanceScore,K=Z.threshold??w.mergeSimilarityThreshold,[U,G]=await Promise.all([X(Z.contentA,W,"-a"),X(Z.contentB,W,"-b")]),D=new $V(Q.entityService,$),q=[];for(let I of U){let P=await D.createTopic(I);if(P)q.push(P)}let J=(await Promise.all(G.map(async(I)=>{let P=await D.findMergeCandidate({incoming:I,threshold:K,additionalCandidates:q});if(!P)return null;return{incomingTitle:I.title,candidateTitle:P.title,candidateScore:P.score}}))).filter((I)=>I!==null),F=J.map((I)=>I.candidateTitle);return{topicsA:U.map(Gg2),topicsB:G.map(Gg2),matchingTitles:F,mergeCandidates:J,wouldMerge:J.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(Y)=>{await ZT(Q);let Z=rj$.parse(Y),W=Z.threshold??w.mergeSimilarityThreshold,K=new $V(Q.entityService,$),U=[];for(let D of Z.existingTopics){let q=await K.createTopic(D);if(q)U.push(q)}let G=await K.findMergeCandidate({incoming:{title:Z.incomingTopic.title},threshold:W,additionalCandidates:U});return{found:G!==null,candidateTitle:G?.title,candidateScore:G?.score}}),Q.eval.registerHandler("processTopicWithAutoMerge",async(Y)=>{await ZT(Q);let Z=oj$.parse(Y),W=new $V(Q.entityService,$);for(let D of Z.existingTopics)await W.createTopic({title:D.title,content:D.content});await QM$(Q);let K=Gn({entityType:"post",content:Z.incomingTopic.content,metadata:{title:Z.incomingTopic.title}},"-source"),U=await YT([K],Q,$,{minRelevanceScore:0,autoMerge:!0,mergeSimilarityThreshold:Z.threshold??w.mergeSimilarityThreshold}),G=await Q.entityService.listEntities({entityType:Uw});return{...U,topicCount:G.length,topics:G.map(MqA)}}),Q.eval.registerHandler("rebuildTopics",async(Y)=>{await ZT(Q);let Z=aj$.parse(Y),W=new $V(Q.entityService,$);for(let D of Z.existingTopics??[])await W.createTopic(D);let K=Z.entities.map((D,q)=>Gn(D,`-rebuild-${q}`)),U=await RqA(K,Q,$,w),G=await Q.entityService.listEntities({entityType:Uw});return{...U,topicCount:G.length,topics:G.map(MqA)}}),Q.eval.registerHandler("extractSequentially",async(Y)=>{await ZT(Q);let Z=sj$.parse(Y),W=Z.minRelevanceScore??w.minRelevanceScore,K=new $V(Q.entityService,$),U=[];for(let[D,q]of Z.entities.entries()){let J=Gn(q,`-sequential-${D}`),F=await B.extractFromEntity(J,W);for(let I of F)await K.createTopic({title:I.title,content:I.content});U.push({extractedTitles:F.map((I)=>I.title)})}let G=await Q.entityService.listEntities({entityType:Uw});return{totalTopics:G.length,perEntity:U,topics:G.map(Un)}}),Q.eval.registerHandler("batchExtract",async(Y)=>{await ZT(Q);let W=tj$.parse(Y).entities.map((G,D)=>Gn(G,`-batch-${D}`)),K=await YT(W,Q,$,{minRelevanceScore:w.minRelevanceScore}),U=await Q.entityService.listEntities({entityType:Uw});return{...K,topics:U.map(Un)}})}var $M$=new QV;async function qg2({entity:A,config:Q}){let $=Kn.parse(A),w=$M$.parseTopicBody($.content);return{$type:"ai.rizom.brain.topic",title:w.title,body:w.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"topic",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function vqA(){return{entityType:"topic",collection:"ai.rizom.brain.topic",lexicon:E8["ai.rizom.brain.topic"],validate:!1,buildRecord:qg2}}var zg2={name:"@brains/topics",version:"0.2.0-alpha.183",description:"Extract and manage topics from conversations",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":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},main:"./src/index.ts",private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var BM$=new QV,XM$=H.looseObject({status:H.unknown().optional()});class Vg2 extends S6{entityType=Uw;schema=Kn;adapter=BM$;unregisterAtprotoProjection;sourceBatch=new xqA;constructor(A={}){super(XT,zg2,A,gy2)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:ly2,"merge-synthesis":dy2,"topic-list":iy2,"topic-detail":ny2}}getDataSources(){return[new bqA(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:PqA,targetType:Uw,job:{type:my2,handler:Zg2({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 Uv(A,Uw,{visibility:this.config.extractionVisibility}),jobData:{mode:"derive",reason:"initial-sync"},jobOptions:Hg2()},sourceChange:{sourceTypes:this.config.includeEntityTypes,requireInitialSync:!0,jobData:(Q)=>{let $=Q.entity;if(!$)return null;if(!this.shouldProcessEntityType($.entityType,A.entityService))return null;if(!this.isEntityPublished($))return null;if(!sj($.visibility,this.config.extractionVisibility))return null;return this.sourceBatch.add({entityId:$.id,entityType:$.entityType,contentHash:$.contentHash}),{mode:"source-batch"}},jobOptions:()=>({priority:5,source:Bj0,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:cy2,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:XT}})}}]}async onRegister(A){A.insights.register("topic-distribution",sy2()),ay2({context:A,pluginId:this.id}),Dg2({context:A,logger:this.logger,config:this.config}),this.unregisterAtprotoProjection=aB.getInstance().register(vqA())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(PqA)?.hasQueuedInitialSync()??!1}shouldProcessEntityType(A,Q){if(A===Uw)return!1;if(!this.config.includeEntityTypes.includes(A))return!1;return Q.getEntityTypeConfig(A).projectionSource!==!1}isEntityPublished(A){let Q=XM$.safeParse(A.metadata),$=Q.success?Q.data.status:void 0;if($===void 0||$===null)return!0;if(typeof $!=="string")return!1;return this.config.extractableStatuses.includes($)}async extractAllTopics(A){await Wg2({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await Kg2({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function Uj0(A={}){return new Vg2(A)}KA();C0();KA();var CqA=H.enum(["linkedin"]),Jg2=H.enum(["linkedin"]),hqA=H.enum(["generating","draft","queued","published","failed"]),Fg2=H.enum(["generating","draft","queued","published","failed"]),Ig2=H.enum(["post","deck"]),YM$=H.enum(["post","deck"]),Lg2=H.object({id:H.string().min(1).describe("Document entity ID")}),ZM$=H.object({id:H.string().min(1)}),wV=H.object({title:H.string().describe("Short descriptive title (3-6 words) for file naming"),platform:CqA.describe("Target platform"),status:hqA,coverImageId:H.string().optional().describe("Image entity ID for post image"),documents:H.array(Lg2).optional().describe("Document attachments for publishing"),publishedAt:H.string().datetime().optional(),platformPostId:H.string().optional().describe("ID from platform after publishing"),sourceEntityId:H.string().optional().describe("Source entity ID if auto-generated"),sourceEntityType:Ig2.optional().describe("Source entity type (post, deck)")}),Ng2=wV.extend({platform:CqA.optional(),status:hqA.optional()}),HM$=wV.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:H.string().describe("URL-friendly identifier: {platform}-{title}"),error:H.string().optional()}),WM$=H.object({title:H.string(),platform:Jg2,status:Fg2,publishedAt:H.string().datetime().optional(),platformPostId:H.string().optional(),slug:H.string(),error:H.string().optional()}),KM$=H.object({title:H.string(),platform:Jg2,status:Fg2,coverImageId:H.string().optional(),documents:H.array(ZM$).optional(),publishedAt:H.string().datetime().optional(),platformPostId:H.string().optional(),sourceEntityId:H.string().optional(),sourceEntityType:YM$.optional()}),eO=H6.extend({entityType:H.literal("social-post"),metadata:WM$}),Gj0=eO.extend({frontmatter:KM$,body:H.string()}),UM$=Gj0.extend({url:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),typeLabel:H.string().optional(),coverImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});KA();S2();class EqA extends UQ{constructor(){super({entityType:"social-post",purpose:"A short post drafted for social media such as LinkedIn or X.",schema:eO,frontmatterSchema:wV,supportsCoverImage:!0})}toMarkdown(A){let Q,$={};try{$=this.parseFrontMatter(A.content,wV),Q=this.extractBody(A.content)}catch{Q=A.content}let 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,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Ng2),$=Q.platform??"linkedin",w=Q.status??"draft",B=`${$}-${k1(Q.title)}`;return{content:A,entityType:"social-post",metadata:{title:Q.title,slug:B,platform:$,status:w,publishedAt:Q.publishedAt,platformPostId:Q.platformPostId}}}parsePostFrontmatter(A){return this.parseFrontMatter(A.content,wV)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}buildStub(A){let $={title:A.title,platform:"linkedin",status:"generating"};return{content:this.buildMarkdown("",$),metadata:{title:A.title,slug:`linkedin-${k1(A.title)}`,platform:"linkedin",status:"generating"}}}}var OY=new EqA;KA();KA();C0();var GM$=H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional(),baseUrl:H.string().optional(),platform:H.enum(["linkedin"]).optional(),status:H.enum(["generating","draft","queued","published","failed"]).optional(),sortByQueue:H.boolean().optional(),nextInQueue:H.boolean().optional()}),DM$=H.looseObject({entityType:H.string().optional(),query:GM$.optional()});function _g2(A){let Q=_Q(A.content,wV);return Gj0.parse({...A,frontmatter:Q.metadata,body:Q.content})}class Dj0 extends x7{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=DM$.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return _g2(A)}buildDetailResult(A,Q){return{post:A}}buildListResult(A,Q,$){return{posts:A,totalCount:Q?.totalItems??A.length,pagination:Q,baseUrl:$.baseUrl}}async fetch(A,Q,$){let{query:w}=this.parseQuery(A),B=$.entityService;if(w.nextInQueue)return this.fetchNextInQueue(Q,B);if(w.id){let{item:U}=await this.fetchDetail(w.id,B);return Q.parse(this.buildDetailResult(U,null))}let X={};if(w.platform)X.platform=w.platform;if(w.status)X.status=w.status;let Y=Object.keys(X).length>0,Z=w.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:W,pagination:K}=await this.fetchList(w,B,{...Y&&{filter:{metadata:X}},sortFields:Z});return Q.parse(this.buildListResult(W,K,w))}async fetchNextInQueue(A,Q){let w=(await Q.listEntities({entityType:this.config.entityType,options:{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}}))[0],B=w?_g2(w):null;return A.parse({post:B})}}C0();var Pg2=H.object({accessToken:H.string().optional(),refreshToken:H.string().optional(),organizationId:H.string().optional(),apiVersion:H.string().regex(/^\d{6}$/).optional()}),TqA=H.object({linkedin:Pg2.optional(),publishInterval:H.number().default(3600000),enabled:H.boolean().default(!0),defaultPrompt:H.string().default("Create an engaging social media post that drives engagement"),maxRetries:H.number().default(3),autoGenerateOnBlogPublish:H.boolean().default(!1)});KA();S2();C0();e8();gqA();import{jsxDEV as $7,Fragment as VM$}from"preact/jsx-dev-runtime";function qM$(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function zM$(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var zj0=({posts:A,pageTitle:Q,pagination:$,baseUrl:w="/social-posts"})=>{let B=Q??"Social Posts",X=$?.totalItems??A.length,Y=`Browse all ${X} social ${X===1?"post":"posts"}`;return $7(VM$,{children:[$7(C6,{title:B,description:Y},void 0,!1,void 0,this),$7("div",{className:"social-post-list bg-theme",children:$7("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[$7("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:B},void 0,!1,void 0,this),A.length===0?$7("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):$7("ul",{className:"space-y-6",children:A.map((Z)=>$7("li",{children:$7(j8,{href:Z.url,variant:"horizontal",children:$7("div",{className:"flex flex-col sm:flex-row gap-4",children:[Z.coverImageUrl&&$7("img",{src:Z.coverImageUrl,alt:Z.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),$7("div",{className:"flex-1 min-w-0",children:[$7("div",{className:"flex items-start justify-between gap-4 mb-2",children:[$7("h2",{className:"text-lg font-semibold text-heading",children:Z.frontmatter.title},void 0,!1,void 0,this),$7("time",{className:"text-sm text-theme-muted shrink-0",children:zM$(Z.frontmatter.publishedAt??Z.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$7("div",{className:"flex items-center gap-2 mb-3",children:[$7(GK,{status:Z.frontmatter.status},void 0,!1,void 0,this),$7("span",{className:"text-xs text-theme-muted uppercase",children:Z.frontmatter.platform},void 0,!1,void 0,this),$7("span",{className:"text-xs text-theme-muted font-mono",children:Z.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$7("p",{className:"text-theme leading-relaxed",children:qM$(Z.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)},Z.id,!1,void 0,this))},void 0,!1,void 0,this),$&&$.totalPages>1&&$7(WP,{currentPage:$.currentPage,totalPages:$.totalPages,baseUrl:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as w7,Fragment as JM$}from"preact/jsx-dev-runtime";function kg2(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var Vj0=({post:A})=>{let Q=`Social Post - ${A.frontmatter.platform}`,$=A.body.slice(0,160),w=[{label:"Home",href:"/"},{label:A.listLabel??"Social Posts",href:A.listUrl??"/social-posts"},{label:A.frontmatter.platform}];return w7(JM$,{children:[w7(C6,{title:Q,description:$},void 0,!1,void 0,this),w7("section",{className:"social-post-detail",children:w7("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:w7("div",{className:"max-w-3xl mx-auto",children:[w7(mF,{items:w},void 0,!1,void 0,this),w7("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),w7("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[w7(GK,{status:A.frontmatter.status},void 0,!1,void 0,this),w7("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),w7("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&&w7(ZP,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),w7(j8,{className:"p-8 mb-8",children:w7("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),w7("div",{className:"space-y-4 text-sm text-theme-muted",children:[w7("div",{children:[w7("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",kg2(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&w7("div",{children:[w7("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",kg2(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&w7("div",{children:w7("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 V50(A){return`social-media:${A}`}var FM$=H.union([H.boolean(),H.object({generate:H.boolean().optional(),prompt:H.string().optional()})]),SqA=H.object({prompt:H.string().optional(),platform:H.enum(["linkedin"]).optional(),sourceEntityType:H.enum(["post","deck"]).optional(),sourceEntityId:H.string().optional(),title:H.string().optional().describe("Required when content is provided directly"),content:H.string().optional(),addToQueue:H.boolean().optional(),generateImage:H.boolean().optional().describe("Auto-generate cover image for post"),coverImage:FM$.optional().describe("Generic cover image generation request")}),IM$=iK.extend({slug:H.string().optional()});class HT extends GZ{constructor(A,Q){super(A,Q,{schema:SqA,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let $=A.platform??"linkedin",w=A.addToQueue??!1,{prompt:B,sourceEntityType:X,sourceEntityId:Y}=A,{content:Z,title:W}=A;if(Z&&W)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(Z&&!W){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let I=await this.context.ai.generate({prompt:Z,templateName:V50($)});W=I.title,Z=I.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(Y&&X){await this.reportProgress(Q,{progress:10,message:`Fetching source ${X}`});let I=await this.context.entityService.getEntity({entityType:X,id:Y});if(!I)this.failEarly(`Source entity not found: ${X}/${Y}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let j=H.looseObject({slug:H.string()}).safeParse(I.metadata),k=j.success?j.data.slug:Y,f=await this.context.ai.generate({prompt:`Create an engaging ${$} post to promote this ${X}:
7997
+ `)}async function YT(A,Q,$,w={}){if(A.length===0)return{created:0,merged:0,skipped:0,batches:0};let B=w.minRelevanceScore??0,X=w.autoMerge??!1,Y=w.mergeSimilarityThreshold??0.85,Z=w.targetVisibility??"public",W=Qg2(A),K=new $V(Q.entityService,$),U=w.topicMergeSynthesizer??new fqA(Q,$),G=await Wj0(Q.entityService,void 0,Z),D=new Map,q=0,J=0,F=0;for(let P of W){$.info(`Processing batch of ${P.length} entities`);let j=cj$(P),k=Kj0({entityTitle:`Batch of ${P.length} entities`,entityType:"batch",content:j,existingTopicTitles:G});try{let R=(await Q.ai.generate({prompt:k,templateName:"topics:extraction"})).topics.filter((x)=>x.relevanceScore>=B);for(let x of R)try{if(X){let u=await K.findMergeCandidate({incoming:x,threshold:Y,additionalCandidates:Array.from(D.values()),targetVisibility:Z});if(u){let n=await U.synthesize({existingTopic:u.topic,incomingTopic:x}),t=await K.applySynthesizedMerge({existingId:u.topic.id,synthesized:{...n,title:u.title},visibility:Z});if(!t)throw Error(`Failed to merge topic: ${x.title}`);D.set(t.id,t),J++;continue}}let O=K.getTopicIdForTitle(x.title,Z);if(D.has(O)){F++;continue}let g=await K.createTopicOptimistic({title:x.title,content:x.content,visibility:Z});if(g.topic)D.set(g.topic.id,g.topic);if(g.created)q++;else F++}catch(O){$.error("Topic batch item failed",{title:x.title,error:aA(O)})}}catch(f){$.error("Batch topic extraction failed",{batchSize:P.length,promptChars:k.length,error:aA(f)})}}let I={created:q,merged:J,skipped:F,batches:W.length};if(q>0||J>0)await Q.messaging.send({type:uy2,payload:I,broadcast:!0});return I}KA();C0();var pj$=H.discriminatedUnion("mode",[H.object({mode:H.literal("derive"),reason:H.string().optional()}),H.object({mode:H.literal("rebuild"),reason:H.string().optional()}),H.object({mode:H.literal("source-batch"),minRelevanceScore:H.number().min(0).max(1).optional()})]);class xqA{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 Zg2(A){let{context:Q,logger:$,config:w}=A;return{process:async(B)=>{if(B.mode==="derive")return await A.extractAllTopics(),{success:!0};if(B.mode==="rebuild")return await A.rebuildAllTopics(),{success:!0};return lj$({context:Q,logger:$,config:w,sourceBatch:A.sourceBatch,isEntityPublished:A.isEntityPublished,minRelevanceScore:B.minRelevanceScore??w.minRelevanceScore})},validateAndParse:(B)=>{let X=pj$.safeParse(B??{});return X.success?X.data:null}}}async function lj$(A){let Q=A.sourceBatch.drain(),$=await Promise.all(Q.map(async(K)=>({ref:K,entity:await A.context.entityService.getEntity({entityType:K.entityType,id:K.entityId})}))),w=0,B=0,X=0,Y=0,Z=[];for(let{ref:K,entity:U}of $){if(!U){B++;continue}if(U.contentHash!==K.contentHash){w++;continue}if(!A.isEntityPublished(U)){X++;continue}if(!sj(U.visibility,A.config.extractionVisibility)){Y++;continue}Z.push(U)}if(Z.length===0)return{success:!0,sources:Q.length,created:0,merged:0,skipped:0,batches:0,stale:w,missing:B,unpublished:X,hidden:Y};let W=await YT(Z,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,...W,stale:w,missing:B,unpublished:X,hidden:Y}}function Hg2(){return{priority:5,source:Bj0,deduplication:"coalesce",deduplicationKey:"topics-initial-derivation",metadata:{operationType:"data_processing",operationTarget:"topics-initial-derivation",pluginId:XT}}}async function Wg2(A){let Q=await Ug2(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 $=await YT(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",$)}async function Kg2(A){let Q=await Ug2(A),$=await RqA(Q,A.context,A.logger,A.config);A.logger.info("Topic rebuild complete",$)}async function RqA(A,Q,$,w){let B=new $V(Q.entityService,$),X=await B.listTopics({visibility:w.extractionVisibility});for(let Z of X)await B.deleteTopic(Z.id);if(A.length===0)return{deleted:X.length,created:0,merged:0,skipped:0,batches:0};let Y=await YT(A,Q,$,{minRelevanceScore:w.minRelevanceScore,autoMerge:w.autoMerge,mergeSimilarityThreshold:w.mergeSimilarityThreshold,targetVisibility:w.extractionVisibility});return{deleted:X.length,...Y}}async function Ug2(A){let Q=dj$(A),$=[];for(let w of Q){let B=await A.context.entityService.listEntities({entityType:w,options:{filter:{visibilityScope:A.config.extractionVisibility}}});for(let X of B){if(!A.isEntityPublished(X))continue;$.push(X)}}return $}function dj$(A){return A.context.entityService.getEntityTypes().filter(($)=>A.shouldProcessEntityType($))}var Dn=H.object({entityType:H.string(),content:H.string(),metadata:H.record(H.string(),H.unknown()).optional()}),ij$=Dn.extend({minRelevanceScore:H.number().optional()}),nj$=H.object({contentA:Dn,contentB:Dn,minRelevanceScore:H.number().optional(),threshold:H.number().min(0).max(1).optional()}),z50=H.object({title:H.string(),content:H.string()}),rj$=H.object({existingTopics:H.array(z50),incomingTopic:z50,threshold:H.number().optional()}),oj$=H.object({existingTopics:H.array(z50).default([]),incomingTopic:z50.extend({relevanceScore:H.number().min(0).max(1).optional()}),threshold:H.number().optional()}),sj$=H.object({entities:H.array(Dn).min(1),minRelevanceScore:H.number().optional()}),aj$=H.object({existingTopics:H.array(z50).optional(),entities:H.array(Dn)}),tj$=H.object({entities:H.array(Dn)});function Gn(A,Q=""){return{id:`eval${Q}-${Date.now()}`,entityType:A.entityType,content:A.content,contentHash:e6(A.content),visibility:"public",metadata:A.metadata??{},created:new Date().toISOString(),updated:new Date().toISOString()}}function Gg2(A){return{title:A.title,relevanceScore:A.relevanceScore}}function ej$(A){let Q=A.metadata.title;return typeof Q==="string"?Q:A.id}function AM$(A,Q){return{...A,sources:[{id:Q.id,type:Q.entityType,title:ej$(Q)}]}}async function ZT(A){let Q=await A.entityService.listEntities({entityType:Uw});await Promise.all(Q.map(($)=>A.entityService.deleteEntity({entityType:Uw,id:$.id})))}async function QM$(A){for(;;){if((await A.jobs.getActiveJobs(["shell:embedding"])).length===0)return;await new Promise(($)=>setTimeout($,100))}}function Dg2(A){let{context:Q,logger:$,config:w}=A,B=new OqA(Q,$),X=async(Y,Z,W="")=>{let K=Gn(Y,W);return B.extractFromEntity(K,Z)};Q.eval.registerHandler("extractFromEntity",async(Y)=>{await ZT(Q);let Z=ij$.parse(Y),W=Z.minRelevanceScore??w.minRelevanceScore,K=Gn(Z);return(await B.extractFromEntity(K,W)).map((G)=>AM$(G,K))}),Q.eval.registerHandler("checkMergeSimilarity",async(Y)=>{await ZT(Q);let Z=nj$.parse(Y),W=Z.minRelevanceScore??w.minRelevanceScore,K=Z.threshold??w.mergeSimilarityThreshold,[U,G]=await Promise.all([X(Z.contentA,W,"-a"),X(Z.contentB,W,"-b")]),D=new $V(Q.entityService,$),q=[];for(let I of U){let P=await D.createTopic(I);if(P)q.push(P)}let J=(await Promise.all(G.map(async(I)=>{let P=await D.findMergeCandidate({incoming:I,threshold:K,additionalCandidates:q});if(!P)return null;return{incomingTitle:I.title,candidateTitle:P.title,candidateScore:P.score}}))).filter((I)=>I!==null),F=J.map((I)=>I.candidateTitle);return{topicsA:U.map(Gg2),topicsB:G.map(Gg2),matchingTitles:F,mergeCandidates:J,wouldMerge:J.length>0}}),Q.eval.registerHandler("detectMergeCandidate",async(Y)=>{await ZT(Q);let Z=rj$.parse(Y),W=Z.threshold??w.mergeSimilarityThreshold,K=new $V(Q.entityService,$),U=[];for(let D of Z.existingTopics){let q=await K.createTopic(D);if(q)U.push(q)}let G=await K.findMergeCandidate({incoming:{title:Z.incomingTopic.title},threshold:W,additionalCandidates:U});return{found:G!==null,candidateTitle:G?.title,candidateScore:G?.score}}),Q.eval.registerHandler("processTopicWithAutoMerge",async(Y)=>{await ZT(Q);let Z=oj$.parse(Y),W=new $V(Q.entityService,$);for(let D of Z.existingTopics)await W.createTopic({title:D.title,content:D.content});await QM$(Q);let K=Gn({entityType:"post",content:Z.incomingTopic.content,metadata:{title:Z.incomingTopic.title}},"-source"),U=await YT([K],Q,$,{minRelevanceScore:0,autoMerge:!0,mergeSimilarityThreshold:Z.threshold??w.mergeSimilarityThreshold}),G=await Q.entityService.listEntities({entityType:Uw});return{...U,topicCount:G.length,topics:G.map(MqA)}}),Q.eval.registerHandler("rebuildTopics",async(Y)=>{await ZT(Q);let Z=aj$.parse(Y),W=new $V(Q.entityService,$);for(let D of Z.existingTopics??[])await W.createTopic(D);let K=Z.entities.map((D,q)=>Gn(D,`-rebuild-${q}`)),U=await RqA(K,Q,$,w),G=await Q.entityService.listEntities({entityType:Uw});return{...U,topicCount:G.length,topics:G.map(MqA)}}),Q.eval.registerHandler("extractSequentially",async(Y)=>{await ZT(Q);let Z=sj$.parse(Y),W=Z.minRelevanceScore??w.minRelevanceScore,K=new $V(Q.entityService,$),U=[];for(let[D,q]of Z.entities.entries()){let J=Gn(q,`-sequential-${D}`),F=await B.extractFromEntity(J,W);for(let I of F)await K.createTopic({title:I.title,content:I.content});U.push({extractedTitles:F.map((I)=>I.title)})}let G=await Q.entityService.listEntities({entityType:Uw});return{totalTopics:G.length,perEntity:U,topics:G.map(Un)}}),Q.eval.registerHandler("batchExtract",async(Y)=>{await ZT(Q);let W=tj$.parse(Y).entities.map((G,D)=>Gn(G,`-batch-${D}`)),K=await YT(W,Q,$,{minRelevanceScore:w.minRelevanceScore}),U=await Q.entityService.listEntities({entityType:Uw});return{...K,topics:U.map(Un)}})}var $M$=new QV;async function qg2({entity:A,config:Q}){let $=Kn.parse(A),w=$M$.parseTopicBody($.content);return{$type:"ai.rizom.brain.topic",title:w.title,body:w.content,format:"text/markdown",...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"topic",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function vqA(){return{entityType:"topic",collection:"ai.rizom.brain.topic",lexicon:E8["ai.rizom.brain.topic"],validate:!1,buildRecord:qg2}}var zg2={name:"@brains/topics",version:"0.2.0-alpha.184",description:"Extract and manage topics from conversations",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":"^1.3.14","@types/node":"^20.19.43",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},main:"./src/index.ts",private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var BM$=new QV,XM$=H.looseObject({status:H.unknown().optional()});class Vg2 extends S6{entityType=Uw;schema=Kn;adapter=BM$;unregisterAtprotoProjection;sourceBatch=new xqA;constructor(A={}){super(XT,zg2,A,gy2)}getEntityTypeConfig(){return{weight:0.5,projectionSource:!1}}getTemplates(){return{extraction:ly2,"merge-synthesis":dy2,"topic-list":iy2,"topic-detail":ny2}}getDataSources(){return[new bqA(this.logger.child("TopicsDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableAutoExtraction)return[];return[{id:PqA,targetType:Uw,job:{type:my2,handler:Zg2({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 Uv(A,Uw,{visibility:this.config.extractionVisibility}),jobData:{mode:"derive",reason:"initial-sync"},jobOptions:Hg2()},sourceChange:{sourceTypes:this.config.includeEntityTypes,requireInitialSync:!0,jobData:(Q)=>{let $=Q.entity;if(!$)return null;if(!this.shouldProcessEntityType($.entityType,A.entityService))return null;if(!this.isEntityPublished($))return null;if(!sj($.visibility,this.config.extractionVisibility))return null;return this.sourceBatch.add({entityId:$.id,entityType:$.entityType,contentHash:$.contentHash}),{mode:"source-batch"}},jobOptions:()=>({priority:5,source:Bj0,delayMs:this.config.sourceChangeBatchDelayMs,deduplication:"skip",deduplicationKey:cy2,metadata:{operationType:"data_processing",operationTarget:"topic-source-batch",pluginId:XT}})}}]}async onRegister(A){A.insights.register("topic-distribution",sy2()),ay2({context:A,pluginId:this.id}),Dg2({context:A,logger:this.logger,config:this.config}),this.unregisterAtprotoProjection=aB.getInstance().register(vqA())}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}hasRunInitialDerivation(){return this.getDerivedEntityProjectionController(PqA)?.hasQueuedInitialSync()??!1}shouldProcessEntityType(A,Q){if(A===Uw)return!1;if(!this.config.includeEntityTypes.includes(A))return!1;return Q.getEntityTypeConfig(A).projectionSource!==!1}isEntityPublished(A){let Q=XM$.safeParse(A.metadata),$=Q.success?Q.data.status:void 0;if($===void 0||$===null)return!0;if(typeof $!=="string")return!1;return this.config.extractableStatuses.includes($)}async extractAllTopics(A){await Wg2({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}async rebuildAllTopics(A){await Kg2({context:A,logger:this.logger,config:this.config,shouldProcessEntityType:(Q)=>this.shouldProcessEntityType(Q,A.entityService),isEntityPublished:(Q)=>this.isEntityPublished(Q)})}}function Uj0(A={}){return new Vg2(A)}KA();C0();KA();var CqA=H.enum(["linkedin"]),Jg2=H.enum(["linkedin"]),hqA=H.enum(["generating","draft","queued","published","failed"]),Fg2=H.enum(["generating","draft","queued","published","failed"]),Ig2=H.enum(["post","deck"]),YM$=H.enum(["post","deck"]),Lg2=H.object({id:H.string().min(1).describe("Document entity ID")}),ZM$=H.object({id:H.string().min(1)}),wV=H.object({title:H.string().describe("Short descriptive title (3-6 words) for file naming"),platform:CqA.describe("Target platform"),status:hqA,coverImageId:H.string().optional().describe("Image entity ID for post image"),documents:H.array(Lg2).optional().describe("Document attachments for publishing"),publishedAt:H.string().datetime().optional(),platformPostId:H.string().optional().describe("ID from platform after publishing"),sourceEntityId:H.string().optional().describe("Source entity ID if auto-generated"),sourceEntityType:Ig2.optional().describe("Source entity type (post, deck)")}),Ng2=wV.extend({platform:CqA.optional(),status:hqA.optional()}),HM$=wV.pick({title:!0,platform:!0,status:!0,publishedAt:!0,platformPostId:!0}).extend({slug:H.string().describe("URL-friendly identifier: {platform}-{title}"),error:H.string().optional()}),WM$=H.object({title:H.string(),platform:Jg2,status:Fg2,publishedAt:H.string().datetime().optional(),platformPostId:H.string().optional(),slug:H.string(),error:H.string().optional()}),KM$=H.object({title:H.string(),platform:Jg2,status:Fg2,coverImageId:H.string().optional(),documents:H.array(ZM$).optional(),publishedAt:H.string().datetime().optional(),platformPostId:H.string().optional(),sourceEntityId:H.string().optional(),sourceEntityType:YM$.optional()}),eO=H6.extend({entityType:H.literal("social-post"),metadata:WM$}),Gj0=eO.extend({frontmatter:KM$,body:H.string()}),UM$=Gj0.extend({url:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),typeLabel:H.string().optional(),coverImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});KA();S2();class EqA extends UQ{constructor(){super({entityType:"social-post",purpose:"A short post drafted for social media such as LinkedIn or X.",schema:eO,frontmatterSchema:wV,supportsCoverImage:!0})}toMarkdown(A){let Q,$={};try{$=this.parseFrontMatter(A.content,wV),Q=this.extractBody(A.content)}catch{Q=A.content}let 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,w)}fromMarkdown(A){let Q=this.parseFrontMatter(A,Ng2),$=Q.platform??"linkedin",w=Q.status??"draft",B=`${$}-${k1(Q.title)}`;return{content:A,entityType:"social-post",metadata:{title:Q.title,slug:B,platform:$,status:w,publishedAt:Q.publishedAt,platformPostId:Q.platformPostId}}}parsePostFrontmatter(A){return this.parseFrontMatter(A.content,wV)}getPostContent(A){return this.extractBody(A.content)}createPostContent(A,Q){return this.buildMarkdown(Q,A)}buildStub(A){let $={title:A.title,platform:"linkedin",status:"generating"};return{content:this.buildMarkdown("",$),metadata:{title:A.title,slug:`linkedin-${k1(A.title)}`,platform:"linkedin",status:"generating"}}}}var OY=new EqA;KA();KA();C0();var GM$=H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional(),baseUrl:H.string().optional(),platform:H.enum(["linkedin"]).optional(),status:H.enum(["generating","draft","queued","published","failed"]).optional(),sortByQueue:H.boolean().optional(),nextInQueue:H.boolean().optional()}),DM$=H.looseObject({entityType:H.string().optional(),query:GM$.optional()});function _g2(A){let Q=_Q(A.content,wV);return Gj0.parse({...A,frontmatter:Q.metadata,body:Q.content})}class Dj0 extends x7{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=DM$.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){return _g2(A)}buildDetailResult(A,Q){return{post:A}}buildListResult(A,Q,$){return{posts:A,totalCount:Q?.totalItems??A.length,pagination:Q,baseUrl:$.baseUrl}}async fetch(A,Q,$){let{query:w}=this.parseQuery(A),B=$.entityService;if(w.nextInQueue)return this.fetchNextInQueue(Q,B);if(w.id){let{item:U}=await this.fetchDetail(w.id,B);return Q.parse(this.buildDetailResult(U,null))}let X={};if(w.platform)X.platform=w.platform;if(w.status)X.status=w.status;let Y=Object.keys(X).length>0,Z=w.sortByQueue?[{field:"queueOrder",direction:"asc"}]:this.config.defaultSort,{items:W,pagination:K}=await this.fetchList(w,B,{...Y&&{filter:{metadata:X}},sortFields:Z});return Q.parse(this.buildListResult(W,K,w))}async fetchNextInQueue(A,Q){let w=(await Q.listEntities({entityType:this.config.entityType,options:{filter:{metadata:{status:"queued"}},sortFields:[{field:"queueOrder",direction:"asc"}],limit:1}}))[0],B=w?_g2(w):null;return A.parse({post:B})}}C0();var Pg2=H.object({accessToken:H.string().optional(),refreshToken:H.string().optional(),organizationId:H.string().optional(),apiVersion:H.string().regex(/^\d{6}$/).optional()}),TqA=H.object({linkedin:Pg2.optional(),publishInterval:H.number().default(3600000),enabled:H.boolean().default(!0),defaultPrompt:H.string().default("Create an engaging social media post that drives engagement"),maxRetries:H.number().default(3),autoGenerateOnBlogPublish:H.boolean().default(!1)});KA();S2();C0();e8();gqA();import{jsxDEV as $7,Fragment as VM$}from"preact/jsx-dev-runtime";function qM$(A,Q){if(A.length<=Q)return A;return A.slice(0,Q).trim()+"..."}function zM$(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"})}var zj0=({posts:A,pageTitle:Q,pagination:$,baseUrl:w="/social-posts"})=>{let B=Q??"Social Posts",X=$?.totalItems??A.length,Y=`Browse all ${X} social ${X===1?"post":"posts"}`;return $7(VM$,{children:[$7(C6,{title:B,description:Y},void 0,!1,void 0,this),$7("div",{className:"social-post-list bg-theme",children:$7("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[$7("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:B},void 0,!1,void 0,this),A.length===0?$7("p",{className:"text-theme-muted italic",children:"No social posts yet."},void 0,!1,void 0,this):$7("ul",{className:"space-y-6",children:A.map((Z)=>$7("li",{children:$7(j8,{href:Z.url,variant:"horizontal",children:$7("div",{className:"flex flex-col sm:flex-row gap-4",children:[Z.coverImageUrl&&$7("img",{src:Z.coverImageUrl,alt:Z.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),$7("div",{className:"flex-1 min-w-0",children:[$7("div",{className:"flex items-start justify-between gap-4 mb-2",children:[$7("h2",{className:"text-lg font-semibold text-heading",children:Z.frontmatter.title},void 0,!1,void 0,this),$7("time",{className:"text-sm text-theme-muted shrink-0",children:zM$(Z.frontmatter.publishedAt??Z.created)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$7("div",{className:"flex items-center gap-2 mb-3",children:[$7(GK,{status:Z.frontmatter.status},void 0,!1,void 0,this),$7("span",{className:"text-xs text-theme-muted uppercase",children:Z.frontmatter.platform},void 0,!1,void 0,this),$7("span",{className:"text-xs text-theme-muted font-mono",children:Z.id},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$7("p",{className:"text-theme leading-relaxed",children:qM$(Z.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)},Z.id,!1,void 0,this))},void 0,!1,void 0,this),$&&$.totalPages>1&&$7(WP,{currentPage:$.currentPage,totalPages:$.totalPages,baseUrl:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as w7,Fragment as JM$}from"preact/jsx-dev-runtime";function kg2(A){return new Date(A).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}var Vj0=({post:A})=>{let Q=`Social Post - ${A.frontmatter.platform}`,$=A.body.slice(0,160),w=[{label:"Home",href:"/"},{label:A.listLabel??"Social Posts",href:A.listUrl??"/social-posts"},{label:A.frontmatter.platform}];return w7(JM$,{children:[w7(C6,{title:Q,description:$},void 0,!1,void 0,this),w7("section",{className:"social-post-detail",children:w7("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:w7("div",{className:"max-w-3xl mx-auto",children:[w7(mF,{items:w},void 0,!1,void 0,this),w7("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-4",children:A.frontmatter.title},void 0,!1,void 0,this),w7("div",{className:"flex flex-wrap items-center gap-3 mb-6",children:[w7(GK,{status:A.frontmatter.status},void 0,!1,void 0,this),w7("span",{className:"text-sm text-theme-muted uppercase",children:A.frontmatter.platform},void 0,!1,void 0,this),w7("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&&w7(ZP,{src:A.coverImageUrl,alt:A.frontmatter.title,width:A.coverImageWidth,height:A.coverImageHeight,className:"mb-8"},void 0,!1,void 0,this),w7(j8,{className:"p-8 mb-8",children:w7("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),w7("div",{className:"space-y-4 text-sm text-theme-muted",children:[w7("div",{children:[w7("span",{className:"font-medium",children:"Created:"},void 0,!1,void 0,this)," ",kg2(A.created)]},void 0,!0,void 0,this),A.frontmatter.publishedAt&&w7("div",{children:[w7("span",{className:"font-medium",children:"Published:"},void 0,!1,void 0,this)," ",kg2(A.frontmatter.publishedAt)]},void 0,!0,void 0,this),A.frontmatter.platformPostId&&w7("div",{children:w7("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 V50(A){return`social-media:${A}`}var FM$=H.union([H.boolean(),H.object({generate:H.boolean().optional(),prompt:H.string().optional()})]),SqA=H.object({prompt:H.string().optional(),platform:H.enum(["linkedin"]).optional(),sourceEntityType:H.enum(["post","deck"]).optional(),sourceEntityId:H.string().optional(),title:H.string().optional().describe("Required when content is provided directly"),content:H.string().optional(),addToQueue:H.boolean().optional(),generateImage:H.boolean().optional().describe("Auto-generate cover image for post"),coverImage:FM$.optional().describe("Generic cover image generation request")}),IM$=iK.extend({slug:H.string().optional()});class HT extends GZ{constructor(A,Q){super(A,Q,{schema:SqA,jobTypeName:"social-post-generation",entityType:"social-post"})}async generate(A,Q){let $=A.platform??"linkedin",w=A.addToQueue??!1,{prompt:B,sourceEntityType:X,sourceEntityId:Y}=A,{content:Z,title:W}=A;if(Z&&W)await this.reportProgress(Q,{progress:50,message:"Using provided content"});else if(Z&&!W){await this.reportProgress(Q,{progress:10,message:"Shaping content with AI"});let I=await this.context.ai.generate({prompt:Z,templateName:V50($)});W=I.title,Z=I.content,await this.reportProgress(Q,{progress:50,message:"Social post shaped from content"})}else if(Y&&X){await this.reportProgress(Q,{progress:10,message:`Fetching source ${X}`});let I=await this.context.entityService.getEntity({entityType:X,id:Y});if(!I)this.failEarly(`Source entity not found: ${X}/${Y}`);await this.reportProgress(Q,{progress:30,message:"Generating social post from source content"});let j=H.looseObject({slug:H.string()}).safeParse(I.metadata),k=j.success?j.data.slug:Y,f=await this.context.ai.generate({prompt:`Create an engaging ${$} post to promote this ${X}:
7998
7998
 
7999
7999
  Source: ${X}/${k}
8000
8000
 
8001
8001
  ${I.content}`,templateName:V50($)});W=f.title,Z=f.content,await this.reportProgress(Q,{progress:50,message:"Social post generated from source"})}else if(B){await this.reportProgress(Q,{progress:10,message:"Generating social post with AI"});let I=await this.context.ai.generate({prompt:B,templateName:V50($)});W=I.title,Z=I.content,await this.reportProgress(Q,{progress:50,message:"Social post generated"})}else this.failEarly("No content source provided (prompt, sourceEntityId, or content)");if(!Z||!W)this.failEarly("Content or title was not generated");let U={title:W,platform:$,status:w?"queued":"draft",...Y&&{sourceEntityId:Y},...X&&{sourceEntityType:X}},G=OY.createPostContent(U,Z),q=OY.fromMarkdown(G).metadata;if(!q)this.failEarly("Failed to parse social post metadata");let J=await uz({entityType:"social-post",title:W,deriveId:(I)=>`${$}-${k1(I)}`,regeneratePrompt:"Generate a different social media post title on the same topic.",context:this.context}),F=G;if(J!==W){q.title=J,q.slug=`${$}-${k1(J)}`;let I={...U,title:J};F=OY.createPostContent(I,Z)}return{id:q.slug,content:F,metadata:q,title:J,resultExtras:{slug:q.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){if(A.generateImage){await this.reportProgress($,{progress:90,message:"Queueing image generation"});let B=w.title??"Social Post";await this.context.jobs.enqueue({type:"image:image-generate",data:{prompt:`Social media graphic for: ${B}`,title:`${B} 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}}}C0();var jg2=200,Mg2="com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest";function J50(A){if(A.length<=jg2)return A;return`${A.slice(0,jg2)}\u2026 (truncated, ${A.length} bytes)`}var LM$=H.looseObject({sub:H.string()}),NM$=H.looseObject({id:H.string()}),_M$=H.looseObject({value:H.looseObject({asset:H.string(),uploadMechanism:H.looseObject({[Mg2]:H.looseObject({uploadUrl:H.url()})})})}).transform((A)=>({uploadUrl:A.value.uploadMechanism[Mg2].uploadUrl,assetUrn:A.value.asset})),PM$=H.looseObject({value:H.looseObject({uploadUrl:H.url(),document:H.string()})}).transform((A)=>({uploadUrl:A.value.uploadUrl,documentUrn:A.value.document}));function kM$(A){let Q={status:"READY",media:A.urn};if(A.title)Q.title={text:A.title};return Q}function jM$(A){let Q=_M$.safeParse(A);return Q.success?Q.data:null}function MM$(A){let Q=PM$.safeParse(A);return Q.success?Q.data:null}var bM$="202604";class mqA{config;logger;name="linkedin";apiBaseUrl="https://api.linkedin.com/v2";restApiBaseUrl="https://api.linkedin.com/rest";fetch;cachedUserId=null;constructor(A,Q,$={}){this.config=A,this.logger=Q,this.fetch=$.fetch??globalThis.fetch.bind(globalThis)}async publish(A,Q,$,w){if(!this.config.accessToken)throw Error("LinkedIn access token not configured");let B=await this.getAuthor(),X=w?.[0];if(w&&w.length>1)this.logger.warn("LinkedIn document publishing supports one PDF",{count:w.length});let Y=null;if(X){let G=await this.uploadDocument(B,X);return this.publishDocumentPost(B,A,G,X.filename)}else if($){let G=await this.uploadImage(B,$);if(G)Y={category:"IMAGE",urn:G}}let Z={shareCommentary:{text:A},shareMediaCategory:Y?.category??"NONE",...Y&&{media:[kM$(Y)]}},W=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:B,lifecycleState:"PUBLISHED",specificContent:{"com.linkedin.ugc.ShareContent":Z},visibility:{"com.linkedin.ugc.MemberNetworkVisibility":"PUBLIC"}})});if(!W.ok){let G=J50(await W.text());throw this.logger.error("LinkedIn API error",{status:W.status,error:G}),Error(`LinkedIn API error: ${W.status} - ${G}`)}let K=W.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn post created",{postId:K,mediaCategory:Y?.category??"NONE"});let U={id:K};if(K)U.url=`https://www.linkedin.com/feed/update/${K}`;return U}getRestHeaders(){return{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":"application/json","Linkedin-Version":this.config.apiVersion??bM$,"X-Restli-Protocol-Version":"2.0.0"}}async uploadImage(A,Q){try{let $=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(!$.ok){let Z=J50(await $.text());return this.logger.warn("LinkedIn image upload registration failed",{status:$.status,error:Z}),null}let w=jM$(await $.json());if(!w)return this.logger.warn("LinkedIn image upload registration was malformed"),null;let{uploadUrl:B,assetUrn:X}=w,Y=await this.fetch(B,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!Y.ok)return this.logger.warn("LinkedIn image binary upload failed",{status:Y.status}),null;return this.logger.info("LinkedIn image uploaded",{assetUrn:X}),X}catch($){return this.logger.warn("LinkedIn image upload error",{error:$}),null}}async uploadDocument(A,Q){let $=await this.fetch(`${this.restApiBaseUrl}/documents?action=initializeUpload`,{method:"POST",headers:this.getRestHeaders(),body:JSON.stringify({initializeUploadRequest:{owner:A}})});if(!$.ok){let X=J50(await $.text());throw Error(`LinkedIn document upload initialization failed: ${$.status} - ${X}`)}let w=MM$(await $.json());if(!w)throw Error("LinkedIn document upload initialization was malformed");let B=await this.fetch(w.uploadUrl,{method:"PUT",headers:{Authorization:`Bearer ${this.config.accessToken}`,"Content-Type":Q.mimeType},body:new Uint8Array(Q.data)});if(!B.ok)throw Error(`LinkedIn document binary upload failed: ${B.status}`);return this.logger.info("LinkedIn document uploaded",{documentUrn:w.documentUrn,filename:Q.filename}),w.documentUrn}async publishDocumentPost(A,Q,$,w){let B=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:$,title:w}},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1})});if(!B.ok){let Z=J50(await B.text());throw this.logger.error("LinkedIn document post API error",{status:B.status,error:Z}),Error(`LinkedIn document post API error: ${B.status} - ${Z}`)}let X=B.headers.get("X-RestLi-Id")??"";this.logger.info("LinkedIn document post created",{postId:X,documentUrn:$});let Y={id:X};if(X)Y.url=`https://www.linkedin.com/feed/update/${X}`;return Y}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 $=await this.fetch("https://api.linkedin.com/v2/userinfo",{headers:{Authorization:`Bearer ${this.config.accessToken}`}});if($.ok){let w=LM$.safeParse(await $.json());if(w.success)return this.cachedUserId=`urn:li:person:${w.data.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 $=J50(await A.text());throw Error(`Failed to get LinkedIn user ID: ${A.status} - ${$}`)}let Q=NM$.parse(await A.json());return this.cachedUserId=`urn:li:person:${Q.id}`,this.cachedUserId}}function uqA(A,Q,$={}){return new mqA(A,Q,$)}C0();Q5();gqA();var OM$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),fM$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),bg2=H.enum(["linkedin"]),Og2=H.enum(["generating","draft","queued","published","failed"]),xM$=H.enum(["post","deck"]),RM$=H.object({id:H.string().min(1)}),vM$=H.object({title:H.string(),platform:bg2,status:Og2,coverImageId:H.string().optional(),documents:H.array(RM$).optional(),publishedAt:H.string().optional(),platformPostId:H.string().optional(),sourceEntityId:H.string().optional(),sourceEntityType:xM$.optional()}),CM$=H.object({title:H.string(),platform:bg2,status:Og2,publishedAt:H.string().optional(),platformPostId:H.string().optional(),slug:H.string(),error:H.string().optional()}),fg2=H.object({id:H.string(),entityType:H.literal("social-post"),content:H.string(),created:H.string(),updated:H.string(),visibility:fM$,metadata:CM$,contentHash:H.string(),frontmatter:vM$,body:H.string(),url:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),typeLabel:H.string().optional(),coverImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()}),hM$=H.object({posts:H.array(fg2),totalCount:H.number().optional(),pagination:OM$.nullable(),baseUrl:H.string().optional()}),EM$=H.object({post:fg2});function xg2(){return{linkedin:qj0,"social-post-list":K2({name:"social-post-list",description:"Social post list page template",schema:hM$,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:zj0}}),"social-post-detail":K2({name:"social-post-detail",description:"Individual social post template",schema:EM$,dataSourceId:"social-media:posts",requiredPermission:"public",layout:{component:Vj0}})}}C0();var TM$=H.object({prompt:H.string().optional(),content:H.string().optional(),platform:H.enum(["linkedin"]).default("linkedin")}),yM$=H.object({prompt:H.string().optional(),content:H.string().optional(),title:H.string().optional(),platform:H.enum(["linkedin"]).optional()});function Rg2(A){A.eval.registerHandler("generation",async(Q)=>{let $=TM$.parse(Q),w=$.content?`Create an engaging LinkedIn post to share this content:
8002
8002
 
8003
- ${$.content}`:$.prompt??"Write an engaging LinkedIn post";return A.ai.generate({prompt:w,templateName:`social-media:${$.platform}`})}),A.eval.registerHandler("create",async(Q)=>{let $=yM$.parse(Q),w=[],B=XH.from(async(K)=>{let U={progress:K.progress};if(K.message!==void 0)U.message=K.message;w.push(U)});if(!B)throw Error("Failed to create progress reporter");let Y=await new HT(A.logger,A).process($,`eval-${Date.now()}`,B),Z=!1,W;if(Y.success&&Y.entityId){let K=await A.entityService.getEntity({entityType:"social-post",id:Y.entityId});Z=!!K,W=K?.content.slice(0,300)}return{...Y,entityExists:Z,entityPreview:W,progressSteps:w}})}KA();class F50{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:$}=A;if(Q!=="social-post")return;this.permissions.assertEntityActionAllowed(Q,"publish",A.authContext??{userPermissionLevel:"anchor"}),this.logger.debug("Handling publish:execute",{entityId:$});try{let w=await this.entityService.getEntity({entityType:"social-post",id:$});if(!w){await this.reportFailure(Q,$,`Post not found: ${$}`);return}let B=w;if(B.metadata.status==="published"){this.logger.debug("Post already published, skipping",{entityId:$});return}let X=B.metadata.platform,Y=this.providers.get(X);if(!Y){await this.reportFailure(Q,$,`No provider configured for platform: ${X}`);return}let Z=_Q(B.content,wV),W;if(Z.metadata.coverImageId)W=await this.fetchImageData(Z.metadata.coverImageId);let K=Z.metadata.documents??[],U=await this.fetchDocumentData(K);try{if(K.length>0&&U.length===0)throw Error(`Refusing to publish: ${K.length} document(s) referenced but none could be fetched`);let G=K.length===0?await this.resolveSourceAttachment(Z.metadata):[],D=U.length>0?U:G,q=D.length?await Y.publish(Z.content,B.metadata,W,D):await Y.publish(Z.content,B.metadata,W),J=new Date().toISOString(),F=q.id||void 0,I={...Z.metadata,status:"published",publishedAt:J,...F&&{platformPostId:F}},P=OY.createPostContent(I,Z.content);await this.entityService.updateEntity({entity:{...B,content:P,metadata:{...B.metadata,status:"published",publishedAt:J,platformPostId:F}}}),await this.reportSuccess(Q,$,q.id),this.logger.info(`Post published successfully: ${$}`,{platform:X,platformPostId:F})}catch(G){let D=G instanceof Error?G.message:String(G),q={...Z.metadata,status:"failed"},J=OY.createPostContent(q,Z.content);await this.entityService.updateEntity({entity:{...B,content:J,metadata:{...B.metadata,status:"failed"}}}),await this.reportFailure(Q,$,D),this.logger.error(`Post publish failed: ${$}`,{platform:X,error:D})}}catch(w){let B=aA(w);this.logger.error("Unexpected error in publish handler",{entityId:$,error:B}),await this.reportFailure(Q,$,B)}}async reportSuccess(A,Q,$){await this.sendMessage({type:"publish:report:success",payload:{entityType:A,entityId:Q,result:{id:$}}})}async reportFailure(A,Q,$){await this.sendMessage({type:"publish:report:failure",payload:{entityType:A,entityId:Q,error:$}})}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 $ of A){let w=await this.fetchSingleDocumentData($.id);if(w)Q.push(w)}return Q}async fetchSingleDocumentData(A){try{let Q=await this.entityService.getEntity({entityType:"document",id:A});if(!Q){this.logger.warn("Document not found",{documentId:A});return}let $=Q.content.match(/^data:application\/pdf;base64,(.+)$/);if(!$?.[1]){this.logger.warn("Invalid document data URL format",{documentId:A});return}let w=typeof Q.metadata.filename==="string"?Q.metadata.filename:`${A}.pdf`;return{type:"document",data:Buffer.from($[1],"base64"),mimeType:"application/pdf",filename:w}}catch(Q){this.logger.warn("Failed to fetch document",{documentId:A,error:Q});return}}async fetchImageData(A){try{let Q=await this.entityService.getEntity({entityType:"image",id:A});if(!Q){this.logger.warn("Cover image not found",{imageId:A});return}let w=Q.content.match(/^data:([^;]+);base64,(.+)$/);if(!w?.[1]||!w[2]){this.logger.warn("Invalid image data URL format",{imageId:A});return}let B=w[1],X=w[2];return{data:Buffer.from(X,"base64"),mimeType:B}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function vg2(A,Q,$){if(Q.size===0){$.debug("No providers configured, skipping publish-pipeline registration");return}A.messaging.subscribe("system:plugins:ready",async()=>{let w=Q.values().next().value;return await A.messaging.send({type:"publish:register",payload:{entityType:"social-post",provider:w,config:{publishResultIdField:"platformPostId"}}}),$.info("Registered social-post with publish-pipeline"),{success:!0}})}function Cg2(A,Q,$){let w=new F50({sendMessage:A.messaging.send,logger:$.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q,permissions:A.permissions,resolveAttachment:A.attachments.resolve});A.messaging.subscribe("publish:execute",async(B)=>{return await w.handle(B.payload),{success:!0}}),$.debug("Subscribed to publish:execute messages")}function hg2(A,Q){A.messaging.subscribe("entity:updated",async($)=>{let{entityType:w,entityId:B,entity:X}=$.payload;if(w!=="post")return{success:!0};if(X.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:B}},limit:1}})).length>0)return Q.debug(`Social post already exists for ${B}, skipping auto-generate`),{success:!0};return await A.messaging.send({type:"social:auto-generate",payload:{sourceEntityType:w,sourceEntityId:B,platform:"linkedin"}}),Q.info(`Auto-generate social post triggered for queued post ${B}`),{success:!0}}catch(Z){let W=aA(Z);return Q.error(`Failed to trigger auto-generate for ${B}:`,{error:W}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function Eg2(A,Q){A.messaging.subscribe("social:auto-generate",async($)=>{let{sourceEntityType:w,sourceEntityId:B,platform:X}=$.payload;try{let Y=await A.jobs.enqueue({type:`${OY.entityType}:generation`,data:{sourceEntityType:w,sourceEntityId:B,platform:X,addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info(`Social post generation job enqueued for ${w}/${B}`,{jobId:Y}),{success:!0,jobId:Y}}catch(Y){let Z=aA(Y);return Q.error(`Failed to enqueue social post generation for ${B}:`,{error:Z}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function Tg2(A,Q){A.messaging.subscribe("generate:execute",async($)=>{let{entityType:w}=$.payload;if(w!=="social-post")return{success:!0};Q.info("Received generate:execute for social-post");try{let B=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:5}});if(B.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 X=null;for(let Z of B)if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:Z.id}},limit:1}})).length===0){X=Z;break}if(!X)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 Y=await A.jobs.enqueue({type:`${OY.entityType}:generation`,data:{sourceEntityType:"post",sourceEntityId:X.id,platform:"linkedin",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info("Social post generation job queued",{jobId:Y,sourcePostId:X.id}),{success:!0}}catch(B){let X=aA(B);return Q.error("Failed to handle generate:execute:",{error:X}),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:X}}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}async function yg2({entity:A,config:Q}){let $=eO.parse(A),w=OY.parsePostFrontmatter($),B=OY.getPostContent($);return{$type:"ai.rizom.brain.socialPost",title:w.title,platform:w.platform,body:B,format:"text/markdown",status:w.status,...w.publishedAt&&{publishedAt:w.publishedAt},...w.platformPostId&&{platformPostId:w.platformPostId},...w.sourceEntityType&&{sourceLocalEntityType:w.sourceEntityType},...w.sourceEntityId&&{sourceLocalEntityId:w.sourceEntityId},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"social-post",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function cqA(){return{entityType:"social-post",collection:"ai.rizom.brain.socialPost",lexicon:E8["ai.rizom.brain.socialPost"],validate:!1,buildRecord:yg2}}var gg2={name:"@brains/social-media",version:"0.2.0-alpha.183",description:"Multi-provider social media posting with queue-based publishing",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class pqA extends S6{entityType=OY.entityType;schema=eO;adapter=OY;providers=new Map;unregisterAtprotoProjection;constructor(A={}){super("social-media",gg2,A,TqA)}createGenerationHandler(A){return new HT(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return xg2()}getDataSources(){return[new Dj0(this.logger.child("SocialPostDataSource"))]}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}async onRegister(A){if(this.initializeProviders(),vg2(A,this.providers,this.logger),Cg2(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)hg2(A,this.logger),Eg2(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");Tg2(A,this.logger),Rg2(A),this.unregisterAtprotoProjection=aB.getInstance().register(cqA()),this.logger.info("Social media plugin registered successfully")}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}initializeProviders(){if(this.config.linkedin?.accessToken){let A=uqA(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function I50(A={}){return new pqA(A)}C0();var SM$=H.enum(["draft","queued","published","failed"]),Sg2=H.object({status:SM$.default("draft"),queueOrder:H.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:H.string().datetime().optional()});class lqA{name="internal";async publish(A,Q){return{id:"internal"}}}var OP={interfaceType:"system",userId:"system",userPermissionLevel:"anchor",authorization:"system"},fY={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"},Af={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"},mg2={REGISTER:"publish-assets:register"};C0();var mM$=H.enum(["provider"]),ug2=H.object({executionMode:mM$.optional(),publishResultIdField:H.string().min(1).optional(),publishTimestampField:H.string().min(1).optional(),enabled:H.boolean().optional()}).strict();var uM$=H.object({skipIfDraftExists:H.boolean().optional(),minSourceEntities:H.number().optional(),maxUnpublishedDrafts:H.number().optional(),sourceEntityType:H.string().optional()}),cg2=H.object({entitySchedules:H.record(H.string(),H.string()).optional(),generationSchedules:H.record(H.string(),H.string()).optional(),generationConditions:H.record(H.string(),uM$).optional()});class WI{static instance=null;queues=new Map;static getInstance(){return WI.instance??=new WI,WI.instance}static resetInstance(){WI.instance=null}static createFresh(){return new WI}constructor(){}async add(A,Q,$=OP){let w=this.getOrCreateQueue(A),B=w.find((Z)=>Z.entityId===Q);if(B)return{position:B.position};let X=w.length+1,Y={entityId:Q,entityType:A,position:X,queuedAt:new Date().toISOString(),authContext:{...$}};return w.push(Y),{position:X}}async remove(A,Q){let $=this.queues.get(A);if(!$)return;let w=$.findIndex((B)=>B.entityId===Q);if(w===-1)return;$.splice(w,1),this.recalculatePositions($)}async reorder(A,Q,$){let w=this.queues.get(A);if(!w)return;let B=w.findIndex((Z)=>Z.entityId===Q);if(B===-1)return;let[X]=w.splice(B,1);if(!X)return;let Y=Math.max(0,Math.min($-1,w.length));w.splice(Y,0,X),this.recalculatePositions(w)}async list(A){let Q=this.queues.get(A);if(!Q)return[];return[...Q]}async getNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;return Q[0]??null}async getNextAcrossTypes(){let A=null;for(let Q of this.queues.values()){let $=Q[0];if(!$)continue;if(!A||$.queuedAt<A.queuedAt)A=$}return A}async popNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let $=Q.shift()??null;if($)this.recalculatePositions(Q);return $}replace(A){this.queues.clear();let Q=[...A].sort(($,w)=>$.entityType.localeCompare(w.entityType)||$.position-w.position);for(let $ of Q)this.getOrCreateQueue($.entityType).push({...$,authContext:{...$.authContext}});for(let $ of this.queues.values())this.recalculatePositions($)}getRegisteredTypes(){return Array.from(this.queues.keys())}async getQueuedEntityTypes(){let A=[];for(let[Q,$]of this.queues.entries())if($.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,$)=>{Q.position=$+1})}}class KI{static instance=null;providers=new Map;executionModes=new Map;publishResultIdFields=new Map;publishTimestampFields=new Map;defaultProvider=new lqA;static getInstance(){return KI.instance??=new KI,KI.instance}static resetInstance(){KI.instance=null}static createFresh(){return new KI}constructor(){}register(A,Q,$){let w=this.providers.get(A);if(w&&w.name!=="internal"&&Q.name==="internal")return;if(this.providers.set(A,Q),this.executionModes.set(A,$?.executionMode??"provider"),$?.publishResultIdField)this.publishResultIdFields.set(A,$.publishResultIdField);else this.publishResultIdFields.delete(A);if($?.publishTimestampField)this.publishTimestampFields.set(A,$.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())}}async function pg2(A,Q){if(!Q.publishExecutor){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"Publish executor not configured",retryCount:0,willRetry:!1});return}await cM$(A,Q)}async function cM$(A,Q){if(!Q.publishExecutor)return;try{let $=await Q.publishExecutor.publish({entityType:A.entityType,id:A.entityId});if("error"in $){let w={entityType:A.entityType,entityId:A.entityId,error:$.error,retryCount:0,willRetry:!1};if(Q.messageBus)await Q.messageBus.send({type:fY.FAILED,payload:w,sender:"publish-service",broadcast:!0});Q.onFailed?.(w);return}dqA(A.entityType,A.entityId,$.result,Q)}catch($){let w=aA($);Q.retryTracker.recordFailure(A.entityId,w);let B=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:w,retryCount:B?.retryCount??1,willRetry:!1})}}function dqA(A,Q,$,w){if(w.retryTracker.clearRetries(Q),w.messageBus)w.messageBus.send({type:fY.COMPLETED,payload:{entityType:A,entityId:Q,result:$},sender:"publish-service",broadcast:!0});w.onPublish?.({entityType:A,entityId:Q,result:$})}function lg2(A,Q,$,w){w.retryTracker.recordFailure(Q,$);let B=w.retryTracker.getRetryInfo(Q),X={entityType:A,entityId:Q,error:$,retryCount:B?.retryCount??1,willRetry:!1};if(w.messageBus)w.messageBus.send({type:fY.FAILED,payload:X,sender:"publish-service",broadcast:!0});w.onFailed?.(X)}async function dg2(A,Q){let $=Q.generationConditions[A];if($&&Q.onCheckGenerationConditions){let B=await Q.onCheckGenerationConditions(A,$);if(!B.shouldGenerate){if(Q.messageBus)Q.messageBus.send({type:Af.SKIPPED,payload:{entityType:A,reason:B.reason??"Conditions not met"},sender:"content-pipeline"});return}}let w={entityType:A};if(Q.messageBus)await Q.messageBus.send({type:Af.EXECUTE,payload:w,sender:"content-pipeline"});Q.onGenerate?.(w)}function ig2(A,Q,$){if($)$.send({type:Af.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function ng2(A,Q,$){if($)$.send({type:Af.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var pM$=1000;class iqA{deps;publishJobs=new Map;immediateIntervalJob=null;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.entitySchedules)){let $=this.deps.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,$)}this.immediateIntervalJob=this.deps.config.backend.scheduleInterval(pM$,()=>this.processUnscheduledTypes())}async stop(){let A=Array.from(this.publishJobs.values());if(this.publishJobs.clear(),this.immediateIntervalJob)A.push(this.immediateIntervalJob),this.immediateIntervalJob=null;await Promise.all(A.map((Q)=>Q.stop()))}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 $=await this.deps.config.queueManager.getNext(Q);if($){await this.processEntry($);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 pg2(A,Q)}get entitySchedules(){return this.deps.config.entitySchedules}}class nqA{deps;generationJobs=new Map;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.generationSchedules)){let $=this.deps.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,$)}}async stop(){let A=Array.from(this.generationJobs.values());this.generationJobs.clear(),await Promise.all(A.map((Q)=>Q.stop()))}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await dg2(A,this.deps.getGenerationDeps())}catch(Q){this.deps.config.logger.error(`Generation trigger error for ${A}:`,Q)}}get generationSchedules(){return this.deps.config.generationSchedules}}class UI{static instance=null;config;publishRunner;generationRunner;running=!1;stopPromise=null;static getInstance(A){return UI.instance??=new UI(A),UI.instance}static async resetInstance(){let A=UI.instance;if(UI.instance=null,A)await A.stop()}static createFresh(A){return new UI(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new iqA({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new nqA({config:this.config,getGenerationDeps:()=>this.generationDeps,isRunning:()=>this.running})}async start(){if(this.running)return;if(this.stopPromise)await this.stopPromise,this.stopPromise=null;this.running=!0,this.publishRunner.start(),this.generationRunner.start()}stop(){if(this.stopPromise)return this.stopPromise;return this.running=!1,this.stopPromise=Promise.all([this.publishRunner.stop(),this.generationRunner.stop()]).then(()=>{return}),this.stopPromise}isRunning(){return this.running}completePublish(A,Q,$){dqA(A,Q,$,this.publishDeps)}failPublish(A,Q,$){lg2(A,Q,$,this.publishDeps)}completeGeneration(A,Q){ig2(A,Q,this.config.messageBus)}failGeneration(A,Q){ng2(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,$){try{this.config.backend.validateCron(Q)}catch(w){throw Error(`Invalid ${$} cron expression for ${A}: "${Q}" - ${aA(w)}`,{cause:w})}}}class GI{static instance=null;retries=new Map;static getInstance(){return GI.instance??=new GI,GI.instance}static resetInstance(){GI.instance=null}static createFresh(){return new GI}constructor(){}recordFailure(A,Q){let w=(this.retries.get(A)?.retryCount??0)+1;this.retries.set(A,{entityId:A,retryCount:w,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}}}oa0();C0();var rg2=H.union([H.string().min(1),H.object({location:H.enum(["metadata","frontmatter"]),field:H.string().min(1)})]),Jj0=H.object({entityType:H.string().min(1),attachmentType:H.string().min(1),mediaEntityType:H.enum(["image","document"]),targetEntityField:rg2.optional(),requiredWhen:H.object({status:H.string().min(1).optional(),visibility:H.string().min(1).optional()}).optional(),autoGenerate:H.boolean().optional(),requiredForPublish:H.boolean().optional(),jobType:H.string().min(1).optional()});function rqA(A){return`${A.entityType}:${A.attachmentType}`}class DI{static instance=null;definitions=new Map;static getInstance(){return DI.instance??=new DI,DI.instance}static resetInstance(){DI.instance=null}static createFresh(){return new DI}constructor(){}register(A){let Q=Jj0.parse(A),$=rqA(Q);return this.definitions.set($,Q),()=>this.unregister(Q.entityType,Q.attachmentType)}get(A,Q){return this.definitions.get(rqA({entityType:A,attachmentType:Q}))}list(A){let Q=Array.from(this.definitions.values());return A?Q.filter(($)=>$.entityType===A):Q}has(A,Q){return this.get(A,Q)!==void 0}unregister(A,Q){this.definitions.delete(rqA({entityType:A,attachmentType:Q}))}clear(){this.definitions.clear()}}_4();S2();class Fj0{deps;constructor(A){this.deps=A}async ensureForEntity(A,Q={}){let $=this.deps.registry.list(A.entityType).filter((B)=>B.autoGenerate===!0).filter((B)=>!Q.attachmentType||B.attachmentType===Q.attachmentType),w={checked:$.length,enqueued:0,skipped:0};for(let B of $)if(await this.ensureDefinition(A,B))w.enqueued+=1;else w.skipped+=1;return w}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 $=this.resolveJobType(Q);if(!$)return!1;let w=this.getPredictedMediaId(A,Q),B=this.getDeduplicationKey(A,Q);return await this.deps.context.jobs.enqueue({type:$,data:{sourceEntityType:A.entityType,sourceEntityId:A.id,attachmentType:Q.attachmentType,imageId:w,dedupKey:B,targetEntityType:A.entityType,targetEntityId:A.id,...this.getTargetImageFieldData(Q.targetEntityField)},options:{source:"content-pipeline",metadata:{operationType:"content_operations"},deduplication:"skip",deduplicationKey:B}}),this.deps.context.logger.debug("Queued publish asset generation",{entityType:A.entityType,entityId:A.id,attachmentType:Q.attachmentType,jobType:$}),!0}matchesPolicy(A,Q){let{requiredWhen:$}=Q;if(!$)return!0;if($.status&&A.metadata.status!==$.status)return!1;if($.visibility&&A.visibility!==$.visibility)return!1;return!0}hasTargetField(A,Q){if(!Q)return!1;if(typeof Q==="string")return oqA(A.metadata[Q]);if(Q.location==="metadata")return oqA(A.metadata[Q.field]);let{frontmatter:$}=c8(A.content);return oqA($[Q.field])}resolveJobType(A){if(A.jobType)return A.jobType;if(A.mediaEntityType==="image")return"image:image-render-source";return}getPredictedMediaId(A,Q){let $=Q.attachmentType==="og-image"?"og":Q.attachmentType;return k1(`${$}-${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 oqA(A){return typeof A==="string"?A.length>0:A!==void 0}KA();C0();var dM$=H.object({id:H.string().min(1)});async function sg2(A,Q){let{bodyContent:$,coverImageId:w,documents:B,sourceEntityType:X,sourceEntityId:Y}=iM$(Q.content),Z=w?await oM$(A,w):void 0,W;if(B&&B.length>0){let U=await sM$(A,B);if(U.length>0)W=U}W??=await rM$(A,X,Y);let K={bodyContent:$};if(Z)K.imageData=Z;if(W&&W.length>0)K.documentData=W;return K}function iM$(A){try{let Q=_Q(A,H.record(H.string(),H.unknown())),$=Q.metadata.coverImageId,w=typeof $==="string"?$:void 0,B=nM$(Q.metadata.documents),X=og2(Q.metadata.sourceEntityType),Y=og2(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...w&&{coverImageId:w},...B.length>0&&{documents:B},...X&&{sourceEntityType:X},...Y&&{sourceEntityId:Y}}}catch{return{bodyContent:A}}}function nM$(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let $=dM$.safeParse(Q);return $.success?[$.data]:[]})}function og2(A){return typeof A==="string"&&A.length>0?A:void 0}async function rM$(A,Q,$){if(!Q||!$)return;let w=await A.attachments.resolve({sourceEntityType:Q,sourceEntityId:$,attachmentType:"carousel"});return w?[w]:void 0}async function oM$(A,Q){let $=await A.entityService.getEntity({entityType:"image",id:Q});if(!$?.content)return;let w=ag2($.content);if(!w?.mimeType.startsWith("image/"))return;return{data:w.data,mimeType:w.mimeType}}async function sM$(A,Q){return(await Promise.all(Q.map((w)=>aM$(A,w)))).filter((w)=>w!==void 0)}async function aM$(A,Q){let $=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!$?.content)return;let w=ag2($.content);if(w?.mimeType!=="application/pdf")return;return{type:"document",data:w.data,mimeType:"application/pdf",filename:tM$($,Q.id)}}function ag2(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function tM$(A,Q){let $=A.metadata.filename;return typeof $==="string"&&$.length>0?$:`${Q}.pdf`}_4();var eM$=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;async function sqA(A,Q,$,w={}){let B=w.publishTimestampField??"publishedAt",X=Q.metadata[B],Y=w.publishedAt??(typeof X==="string"?X:void 0)??new Date().toISOString(),Z={...Q.metadata,status:"published",[B]:Y,platformId:$.id,...Ab$($.id,w.publishResultIdField)},W={...Q,content:tg2(Q.content,Y,$.id,w.publishResultIdField,B),metadata:Z};return await A.entityService.updateEntity({entity:W}),W}function tg2(A,Q,$,w,B="publishedAt"){if(!eM$.test(A))return A;let X=zX(zX(A,"status","published"),B,Q);if(!$||!w)return X;return zX(X,w,$)}function Ab$(A,Q){if(!Q||Q==="platformId")return{};return{[Q]:A}}class qn{deps;constructor(A){this.deps=A}async resolveCandidate(A){let{entityType:Q,id:$,slug:w}=A;if(!$&&!w)return{error:"Either 'id' or 'slug' must be provided"};let B=await this.findPublishableEntity(Q,$,w);if(!B)return{error:`Entity not found: ${Q}:${$??w}`};if(B.visibility!=="public")return{error:`Cannot publish ${Q}:${B.id} to a public provider because visibility is ${B.visibility}`};if(B.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:B}}async publish(A){let Q=await this.resolveCandidate(A);if("error"in Q)return Q;let{entity:$}=Q,{entityType:w}=A,B=this.deps.providerRegistry.get(w),{bodyContent:X,imageData:Y,documentData:Z}=await sg2(this.deps.context,$),W=await B.publish(X,$.metadata,Y,Z),K=this.deps.providerRegistry.getPublishResultIdField(w),U=this.deps.providerRegistry.getPublishTimestampField(w),G=await sqA(this.deps.context,$,W,{...K?{publishResultIdField:K}:{},...U?{publishTimestampField:U}:{}});return await this.runPublishAssetPreflight(G),{entity:G,result:W}}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,$){if(Q)return this.deps.context.entityService.getEntity({entityType:A,id:Q});if(!$)return null;return(await this.deps.context.entityService.listEntities({entityType:A,options:{filter:{metadata:{slug:$}},limit:1}}))[0]??null}}KA();C0();var aqA=H.object({action:H.enum(["list","add","remove","reorder"]).describe("Queue action to perform"),entityType:H.string().optional().describe("Entity type (required for add/remove/reorder, optional for list)"),entityId:H.string().optional().describe("Entity ID (required for add/remove/reorder)"),position:H.number().optional().describe("New position for reorder action (1-based)")}),tqA=H.object({position:H.number(),entityType:H.string(),entityId:H.string(),queuedAt:H.string()}),Qb$=H.object({success:H.literal(!0),message:H.string().optional(),data:H.object({queue:H.array(tqA).optional(),entityType:H.string().optional(),entityId:H.string().optional(),position:H.number().optional()}).optional()}),$b$=H.object({success:H.literal(!1),error:H.string(),code:H.string().optional()}),eqA=H.union([Qb$,$b$]);function Ij0(A,Q,$,w){let B=w??$;return{...p8(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",aqA,async(Y,Z)=>{let{action:W,entityType:K,entityId:U,position:G}=Y;switch(W){case"list":return wb$($,K);case"add":return Bb$(A,B,K,U,Z);case"remove":return Xb$(A,B,K,U,Z);case"reorder":return Yb$(A,B,K,U,G,Z);default:return{success:!1,error:`Unknown action: ${W}`}}},{sideEffects:"writes"}),outputSchema:eqA}}async function wb$(A,Q){let $=[];if(Q)$=await A.list(Q);else{let B=A.getRegisteredTypes();for(let X of B){let Y=await A.list(X);$.push(...Y)}$.sort((X,Y)=>new Date(X.queuedAt).getTime()-new Date(Y.queuedAt).getTime())}if($.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:$.map((B,X)=>({position:X+1,entityType:B.entityType,entityId:B.entityId,queuedAt:B.queuedAt}))},message:`${$.length} items in queue`}}async function Bb$(A,Q,$,w,B){let X=AzA("add",$,w);if(!X.success)return X.error;A.permissions.assertEntityActionAllowed(X.entityType,"publish",B??{});let Y=await Q.add(X.entityType,X.entityId,{...B,authorization:"user"});return{success:!0,data:{entityType:X.entityType,entityId:X.entityId,position:Y.position},message:`Added to queue at position ${Y.position}`}}async function Xb$(A,Q,$,w,B){let X=AzA("remove",$,w);if(!X.success)return X.error;return A.permissions.assertEntityActionAllowed(X.entityType,"update",B??{}),await Q.remove(X.entityType,X.entityId),{success:!0,data:{entityType:X.entityType,entityId:X.entityId},message:"Removed from queue"}}async function Yb$(A,Q,$,w,B,X){let Y=AzA("reorder",$,w);if(!Y.success)return Y.error;let Z=Zb$(B);if(!Z.success)return Z.error;return A.permissions.assertEntityActionAllowed(Y.entityType,"update",X??{}),await Q.reorder(Y.entityType,Y.entityId,Z.position),{success:!0,data:{entityType:Y.entityType,entityId:Y.entityId,position:Z.position},message:`Moved to position ${Z.position}`}}function AzA(A,Q,$){if(!Q)return{success:!1,error:{success:!1,error:`entityType is required for ${A} action`}};if(!$)return{success:!1,error:{success:!1,error:`entityId is required for ${A} action`}};return{success:!0,entityType:Q,entityId:$}}function Zb$(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}}C0();import{createHash as Hb$}from"crypto";var QzA=H.object({entityType:H.string().describe("Entity type to publish (e.g., social-post, post, deck)"),id:H.string().optional().describe("Entity ID to publish"),slug:H.string().optional().describe("Entity slug to publish"),confirmed:H.boolean().optional(),confirmationToken:H.string().optional(),contentHash:H.string().optional(),expiresAt:H.string().datetime().optional()}),Wb$=H.object({entityType:H.string(),id:H.string().optional(),slug:H.string().optional(),confirmed:H.boolean().optional(),confirmationToken:H.string().optional(),contentHash:H.string().optional(),expiresAt:H.string().datetime().optional()}),Kb$=H.object({success:H.literal(!0),message:H.string().optional(),data:H.object({entityType:H.string().optional(),entityId:H.string().optional(),platformId:H.string().optional(),url:H.string().optional()}).optional()}),Ub$=H.object({success:H.literal(!1),error:H.string(),code:H.string().optional()}),Gb$=H.object({success:H.literal(!1).optional(),error:H.string().optional(),needsConfirmation:H.literal(!0),toolName:H.string(),summary:H.string(),preview:H.string().optional(),args:H.unknown()}),$zA=H.union([Kb$,Ub$,Gb$]),Db$=900000;function zn(A,Q,$,w){let B=w??new qn({context:A,providerRegistry:$}),X=`${Q}_publish`;return{name:X,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:QzA.shape,outputSchema:$zA,visibility:"anchor",sideEffects:"external",handler:async(Y,Z)=>{let W=Wb$.safeParse(Y);if(!W.success)return{success:!1,error:`Invalid input: ${W.error.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ")}`};let K=W.data,{entityType:U,id:G,slug:D}=K;try{A.permissions.assertEntityActionAllowed(U,"publish",Z)}catch(F){return{success:!1,error:F instanceof Error?F.message:String(F)}}let q=await B.resolveCandidate({entityType:U,id:G,slug:D});if("error"in q)return{success:!1,error:q.error};let{entity:J}=q;if(K.confirmed){let F=zb$(X,K,J);if(F!==null)return F;let I;try{I=await B.publish({entityType:U,id:J.id})}catch(k){return{success:!1,error:k instanceof Error?k.message:String(k)}}if("error"in I)return{success:!1,error:I.error};let{entity:P,result:j}=I;return{success:!0,data:{entityType:U,entityId:P.id,platformId:j.id,url:j.url},message:`Published ${U}:${P.id}`}}return qb$(X,K,J)}}}function qb$(A,Q,$){let w=new Date(Date.now()+Db$).toISOString(),B=eg2(A,$,w),X=Vb$($);return{needsConfirmation:!0,toolName:A,summary:`Publish "${X}"?`,preview:`This will publish ${$.entityType}:${$.id} to its registered public publish provider.`,args:{...Q,id:$.id,slug:void 0,confirmed:!0,confirmationToken:B,contentHash:$.contentHash,expiresAt:w}}}function zb$(A,Q,$){let{confirmationToken:w,contentHash:B,expiresAt:X}=Q;if(!w||!X)return{success:!1,error:"Invalid publish confirmation token. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};let Y=Date.parse(X);if(Number.isNaN(Y))return{success:!1,error:"Invalid publish confirmation expiry. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};if(Y<=Date.now())return{success:!1,error:"Publish confirmation expired. Request confirmation again before publishing.",code:"EXPIRED_CONFIRMATION_TOKEN"};if(B&&B!==$.contentHash)return{success:!1,error:`Cannot publish ${$.entityType}:${$.id} because it changed after confirmation. Review it and try again.`};if(w!==eg2(A,$,X))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 eg2(A,Q,$){return Hb$("sha256").update(A).update("\x00").update(Q.entityType).update("\x00").update(Q.id).update("\x00").update(Q.contentHash).update("\x00").update($).digest("hex")}function Vb$(A){let Q=A.metadata.title;if(typeof Q==="string"&&Q.length>0)return Q;let $=A.metadata.subject;if(typeof $==="string"&&$.length>0)return $;let w=A.metadata.slug;if(typeof w==="string"&&w.length>0)return w;return A.id}KA();C0();var wzA=H.object({entityType:H.string().min(1).describe("Entity type to reconcile"),status:H.string().min(1).optional().describe("Optional metadata status filter, e.g. published"),assetType:H.string().min(1).optional().describe("Optional attachment type filter, e.g. og-image")}),BzA=H.object({success:H.literal(!0),data:H.object({entityType:H.string(),assetType:H.string().optional(),checkedEntities:H.number(),checkedAssets:H.number(),enqueued:H.number(),skipped:H.number()}),message:H.string().optional()});function Lj0(A,Q,$,w){return{...p8(Q,"ensure-assets","Reconcile configured publish assets for existing entities, queueing missing generated assets such as OG images.",wzA,async(X,Y)=>{if(A.permissions.assertEntityActionAllowed(X.entityType,"publish",Y),$.list(X.entityType).filter((D)=>D.autoGenerate===!0).filter((D)=>!X.assetType||D.attachmentType===X.assetType).length===0)return{success:!0,data:{entityType:X.entityType,...X.assetType&&{assetType:X.assetType},checkedEntities:0,checkedAssets:0,enqueued:0,skipped:0},message:`No publish assets configured for ${X.entityType}`};let W=await A.entityService.listEntities({entityType:X.entityType,options:{...X.status&&{filter:{metadata:{status:X.status}}}}}),K=0,U=0,G=0;for(let D of W){let q=await w.ensureForEntity(D,{...X.assetType&&{attachmentType:X.assetType}});K+=q.checked,U+=q.enqueued,G+=q.skipped}return{success:!0,data:{entityType:X.entityType,...X.assetType&&{assetType:X.assetType},checkedEntities:W.length,checkedAssets:K,enqueued:U,skipped:G},message:`Queued ${U} publish asset job(s)`}},{sideEffects:"writes"}),outputSchema:BzA}}KA();_4();C0();var Jb$="content-pipeline.queue.v1",XzA=1024,Fb$=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/,Ib$=H.object({interfaceType:H.string().optional(),userId:H.string().optional(),userPermissionLevel:H.enum(["public","trusted","anchor"]).optional(),authorization:H.enum(["user","system"]).optional()}),Lb$=H.object({entityType:H.string(),entityId:H.string(),rank:H.number().int().positive(),queuedAt:H.string().datetime(),contentHashAtEnqueue:H.string(),authContext:Ib$,revision:H.number().int().positive()});class YzA{context;queueManager;store;mutationTail=Promise.resolve();constructor(A,Q){this.context=A,this.queueManager=Q,this.store=A.runtimeState.scoped({namespace:Jb$,schema:Lb$})}async add(A,Q,$=OP){return this.enqueue(A,Q,$)}async enqueue(A,Q,$=OP){return this.runExclusive(async()=>{let w=await this.requireEntity(A,Q);await this.persistStatus(w,"queued");let B=await this.queueManager.add(A,Q,$);if(!await this.store.get(Tq(A,Q))){let Y=(await this.queueManager.list(A)).find((W)=>W.entityId===Q),Z=await this.requireEntity(A,Q);await this.store.set(Tq(A,Q),{entityType:A,entityId:Q,rank:B.position*XzA,queuedAt:Y?.queuedAt??new Date().toISOString(),contentHashAtEnqueue:Z.contentHash,authContext:{...$},revision:1})}return B})}async remove(A,Q){await this.runExclusive(async()=>{let $=await this.requireEntity(A,Q);if($.metadata.status==="queued")await this.persistStatus($,"draft");await this.queueManager.remove(A,Q),await this.store.delete(Tq(A,Q)),await this.persistCurrentOrder(A)})}async reorder(A,Q,$){await this.runExclusive(async()=>{await this.requireEntity(A,Q),await this.queueManager.reorder(A,Q,$),await this.persistCurrentOrder(A)})}async complete(A,Q){await this.runExclusive(async()=>{await this.queueManager.remove(A,Q),await this.store.delete(Tq(A,Q)),await this.persistCurrentOrder(A)})}async fail(A,Q,$){await this.runExclusive(async()=>{let w=await this.context.entityService.getEntity({entityType:A,id:Q});if(w)await this.persistStatus(w,"failed",$);await this.queueManager.remove(A,Q),await this.store.delete(Tq(A,Q)),await this.persistCurrentOrder(A)})}async reconcile(A){await this.runExclusive(async()=>{let Q=new Map;for(let W of A){let K=await this.context.entityService.listEntities({entityType:W,options:{filter:{metadata:{status:"queued"}}}});for(let U of K)Q.set(Tq(W,U.id),U)}let $=await this.listStored();for(let W of $)if(!Q.has(Tq(W.entityType,W.entityId)))await this.store.delete(Tq(W.entityType,W.entityId));let w=(await this.listStored()).filter((W)=>Q.has(Tq(W.entityType,W.entityId))),B=new Map;for(let W of w)B.set(W.entityType,Math.max(B.get(W.entityType)??0,W.rank));for(let[W,K]of Q){if(w.some((G)=>Tq(G.entityType,G.entityId)===W))continue;let U=(B.get(K.entityType)??0)+XzA;B.set(K.entityType,U),await this.store.set(W,{entityType:K.entityType,entityId:K.id,rank:U,queuedAt:typeof K.updated==="string"?K.updated:new Date().toISOString(),contentHashAtEnqueue:K.contentHash,authContext:{...OP},revision:1})}let X=await this.listStored(),Y=new Map,Z=X.map((W)=>{let K=(Y.get(W.entityType)??0)+1;return Y.set(W.entityType,K),{entityType:W.entityType,entityId:W.entityId,position:K,queuedAt:W.queuedAt,authContext:{...W.authContext}}});this.queueManager.replace(Z)})}async listStored(A){return(await this.store.list()).map((Q)=>Q.value).filter((Q)=>!A||Q.entityType===A).sort((Q,$)=>Q.entityType.localeCompare($.entityType)||Q.rank-$.rank||Q.queuedAt.localeCompare($.queuedAt)||Q.entityId.localeCompare($.entityId))}async deleteStored(A,Q){return this.store.delete(Tq(A,Q))}async persistCurrentOrder(A){let Q=new Map((await this.listStored(A)).map(($)=>[$.entityId,$]));for(let $ of await this.queueManager.list(A)){let w=Q.get($.entityId);if(!w)continue;let B=$.position*XzA;if(w.rank===B)continue;await this.store.set(Tq(A,$.entityId),{...w,rank:B,revision:w.revision+1})}}async persistStatus(A,Q,$){let w={...A.metadata,status:Q};if($)w.error=$;else delete w.error;let B=Fb$.test(A.content)?zX(A.content,"status",Q):A.content;await this.context.entityService.updateEntity({entity:{...A,metadata:w,content:B}})}async requireEntity(A,Q){let $=await this.context.entityService.getEntity({entityType:A,id:Q});if(!$)throw Error(`Entity not found: ${A}:${Q}`);return $}runExclusive(A){let Q=this.mutationTail.then(A);return this.mutationTail=Q.then(()=>{return},()=>{return}),Q}}function Tq(A,Q){return`${encodeURIComponent(A)}/${encodeURIComponent(Q)}`}function AS2(A,Q){Nb$(A,Q),_b$(A,Q),Pb$(A,Q),kb$(A,Q)}function Nb$(A,Q){A.messaging.subscribe(fY.REGISTER,async($)=>jb$(Q,$.payload)),A.messaging.subscribe(fY.QUEUE,async($)=>fb$(A,Q,$.payload)),A.messaging.subscribe(fY.DIRECT,async($)=>xb$(A,Q,$.payload)),A.messaging.subscribe(fY.REMOVE,async($)=>Rb$(Q,$.payload)),A.messaging.subscribe(fY.REORDER,async($)=>vb$(Q,$.payload)),A.messaging.subscribe(fY.LIST,async($)=>Cb$(A,Q,$.payload)),A.messaging.subscribe(fY.REPORT_SUCCESS,async($)=>hb$(Q,$.payload)),A.messaging.subscribe(fY.REPORT_FAILURE,async($)=>Eb$(Q,$.payload)),A.messaging.subscribe(fY.COMPLETED,async($)=>{return await Q.publicationQueueService.complete($.payload.entityType,$.payload.entityId),{success:!0}}),A.messaging.subscribe(fY.FAILED,async($)=>{return await Q.publicationQueueService.fail($.payload.entityType,$.payload.entityId,$.payload.error),{success:!0}}),Q.logger.debug("Subscribed to publish messages")}function _b$(A,Q){A.messaging.subscribe(Af.REPORT_SUCCESS,async($)=>Tb$(Q,$.payload)),A.messaging.subscribe(Af.REPORT_FAILURE,async($)=>yb$(Q,$.payload)),Q.logger.debug("Subscribed to generation messages")}function Pb$(A,Q){A.messaging.subscribe(mg2.REGISTER,async($)=>Mb$(Q,$.payload)),Q.logger.debug("Subscribed to publish asset messages")}function kb$(A,Q){let $=async(w)=>bb$(A,Q,w.payload);A.messaging.subscribe("entity:created",$),A.messaging.subscribe("entity:updated",$),Q.logger.debug("Subscribed to entity change messages for publish assets")}async function jb$(A,Q){let{entityType:$,provider:w,config:B}=Q;try{let X=B?ug2.safeParse(B):void 0;if(X&&!X.success)return A.logger.warn("Invalid publish provider config",{entityType:$,error:X.error.message}),{success:!1};if(w)A.providerRegistry.register($,w,X?.data),A.logger.info(`Registered provider for entity type: ${$}`,{providerName:w.name,executionMode:A.providerRegistry.getExecutionMode($)});return{success:!0}}catch(X){let Y=aA(X);return A.logger.error(`Failed to register provider: ${Y}`),{success:!1}}}async function Mb$(A,Q){let $=Jj0.safeParse(Q);if(!$.success)return A.logger.warn("Invalid publish asset registration",{error:$.error.message}),{success:!1};return A.publishAssetRegistry.register($.data),A.logger.info("Registered publish asset",{entityType:$.data.entityType,attachmentType:$.data.attachmentType,mediaEntityType:$.data.mediaEntityType}),{success:!0}}async function bb$(A,Q,$){try{if(Q.publishAssetRegistry.list($.entityType).length===0)return{success:!0};let w=$.entity??await A.entityService.getEntity({entityType:$.entityType,id:$.entityId});if(!Ob$(w))return{success:!0};return await Q.publishAssetPreflight.ensureForEntity(w),{success:!0}}catch(w){return Q.logger.warn("Failed to run publish asset preflight for entity event",{entityType:$.entityType,entityId:$.entityId,error:aA(w)}),{success:!1}}}function Ob$(A){if(!A)return!1;let Q=Sg2.safeParse(A.metadata);return Q.success&&Q.data.status==="published"}async function fb$(A,Q,$){let{entityType:w,entityId:B}=$;try{let X=$.authContext??OP;A.permissions.assertEntityActionAllowed(w,"publish",X);let Y=await Q.publicationQueueService.enqueue(w,B,X);return await A.messaging.send({type:fY.QUEUED,payload:{entityType:w,entityId:B,position:Y.position}}),Q.logger.debug(`Entity queued: ${B}`,{entityType:w,position:Y.position}),{success:!0}}catch(X){let Y=aA(X);return Q.logger.error(`Failed to queue entity: ${Y}`),{success:!1}}}async function xb$(A,Q,$){let{entityType:w,entityId:B}=$,X=$.authContext??OP;try{if(A.permissions.assertEntityActionAllowed(w,"publish",X),!Q.providerRegistry.has(w))return Q.scheduler.failPublish(w,B,`No publish provider registered for ${w}`),{success:!1};let Y=await Q.publishExecutor.publish({entityType:w,id:B});if("error"in Y)return Q.scheduler.failPublish(w,B,Y.error),{success:!1};return Q.scheduler.completePublish(w,B,Y.result),Q.logger.debug(`Direct publish completed: ${B}`,{entityType:w}),{success:!0}}catch(Y){let Z=aA(Y);return Q.logger.error(`Failed direct publish request: ${Z}`),{success:!1}}}async function Rb$(A,Q){let{entityType:$,entityId:w}=Q;try{return await A.publicationQueueService.remove($,w),A.logger.debug(`Entity removed from queue: ${w}`,{entityType:$}),{success:!0}}catch(B){let X=aA(B);return A.logger.error(`Failed to remove entity: ${X}`),{success:!1}}}async function vb$(A,Q){let{entityType:$,entityId:w,position:B}=Q;try{return await A.publicationQueueService.reorder($,w,B),A.logger.debug(`Entity reordered: ${w}`,{entityType:$,newPosition:B}),{success:!0}}catch(X){let Y=aA(X);return A.logger.error(`Failed to reorder entity: ${Y}`),{success:!1}}}async function Cb$(A,Q,$){let{entityType:w}=$;try{let B=await Q.queueManager.list(w);return await A.messaging.send({type:fY.LIST_RESPONSE,payload:{entityType:w,queue:B.map((X)=>({entityId:X.entityId,position:X.position,queuedAt:X.queuedAt}))}}),{success:!0}}catch(B){let X=aA(B);return Q.logger.error(`Failed to list queue: ${X}`),{success:!1}}}async function hb$(A,Q){let{entityType:$,entityId:w,result:B}=Q;return A.scheduler.completePublish($,w,B),A.logger.info(`Publish reported success: ${w}`,{entityType:$}),{success:!0}}async function Eb$(A,Q){let{entityType:$,entityId:w,error:B}=Q;A.scheduler.failPublish($,w,B);let X=A.retryTracker.getRetryInfo(w);return A.logger.info(`Publish reported failure: ${w}`,{entityType:$,error:B,retryCount:X?.retryCount}),{success:!0}}async function Tb$(A,Q){let{entityType:$,entityId:w}=Q;return A.scheduler.completeGeneration($,w),A.logger.info("Generation completed",{entityType:$,entityId:w}),{success:!0}}async function yb$(A,Q){let{entityType:$,error:w}=Q;return A.scheduler.failGeneration($,w),A.logger.warn("Generation failed",{entityType:$,error:w}),{success:!0}}async function QS2(A,Q,$,w){try{if(w.skipIfDraftExists!==!1){if((await A.listEntities({entityType:$,options:{filter:{metadata:{status:"draft"}},limit:1}})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(w.maxUnpublishedDrafts!==void 0){let B=await A.listEntities({entityType:$,options:{filter:{metadata:{status:"draft"}},limit:w.maxUnpublishedDrafts+1}});if(B.length>=w.maxUnpublishedDrafts)return{shouldGenerate:!1,reason:`Max unpublished drafts reached (${B.length}/${w.maxUnpublishedDrafts})`}}if(w.minSourceEntities!==void 0&&w.sourceEntityType){let B=await A.listEntities({entityType:w.sourceEntityType,options:{publishedOnly:!0,limit:w.minSourceEntities}});if(B.length<w.minSourceEntities)return{shouldGenerate:!1,reason:`Not enough source entities (${B.length}/${w.minSourceEntities} ${w.sourceEntityType})`}}return{shouldGenerate:!0}}catch(B){return Q.error("Failed to check generation conditions",{entityType:$,error:aA(B)}),{shouldGenerate:!1,reason:`Condition check failed: ${aA(B)}`}}}function $S2(A){let{context:Q,config:$,queueManager:w,providerRegistry:B,retryTracker:X,publishExecutor:Y,logger:Z}=A,W=gb$(Q);return UI.createFresh({queueManager:w,providerRegistry:B,retryTracker:X,logger:Z,backend:new Sv({onOverlapSkipped:(K)=>{Z.debug("Skipping overlapping content scheduler cycle",{jobKey:K})},onCallbackError:(K,U)=>{Z.error("Unhandled content scheduler callback error",{jobKey:K,error:U})}}),...$.entitySchedules&&{entitySchedules:$.entitySchedules},...$.generationSchedules&&{generationSchedules:$.generationSchedules},...$.generationConditions&&{generationConditions:$.generationConditions},messageBus:W,publishExecutor:Y,onCheckGenerationConditions:(K,U)=>QS2(Q.entityService,Z,K,U)})}function gb$(A){return{send:async(B)=>{return A.messaging.send({type:B.type,payload:B.payload,...B.target!==void 0?{target:B.target}:{},...B.metadata!==void 0?{metadata:B.metadata}:{},...B.broadcast!==void 0?{broadcast:B.broadcast}:{}})},subscribe:()=>()=>{},unsubscribe:()=>{}}}C0();C0();var Sb$=H.enum(["draft","queued","published","failed"]),mb$=H.object({entityId:H.string(),entityType:H.string(),title:H.string(),position:H.number().int().positive(),queuedAt:H.string(),destination:H.string(),scheduledFor:H.string().optional()}),ub$=H.object({id:H.string(),label:H.string(),target:H.string(),status:H.enum(["pending","processing"])}),cb$=H.object({entityId:H.string(),entityType:H.string(),title:H.string(),error:H.string(),retryCount:H.number().int().nonnegative()}),pb$=H.object({summary:H.object({draft:H.number().int().nonnegative(),queued:H.number().int().nonnegative(),generating:H.number().int().nonnegative(),failed:H.number().int().nonnegative(),published:H.number().int().nonnegative(),needsOperator:H.number().int().nonnegative()}),queue:H.array(mb$),generating:H.array(ub$),failures:H.array(cb$),publishableEntityTypes:H.array(H.string())}),lb$=H.object({sourceEntityType:H.string(),sourceEntityId:H.string(),attachmentType:H.string().optional()});async function Nj0(A,Q,$,w){let B=Q.getRegisteredTypes().sort(),X=new Map,Y={draft:0,queued:0,generating:0,failed:0,published:0,needsOperator:0};for(let U of B){let G=await A.entityService.listEntities({entityType:U});for(let D of G){let q=Sb$.safeParse(D.metadata.status);if(!q.success)continue;Y[q.data]+=1;let J=D.metadata.scheduledFor,F=D.metadata.error;X.set(wS2(U,D.id),{entityId:D.id,entityType:U,title:ib$(D.id,D.metadata),status:q.data,...typeof J==="string"?{scheduledFor:J}:{},...typeof F==="string"?{error:F}:{}})}}let Z=[];for(let U of B){let G=Q.get(U).name;for(let D of await $.list(U)){let q=X.get(wS2(U,D.entityId));if(!q)continue;Z.push({entityId:D.entityId,entityType:U,title:q.title,position:D.position,queuedAt:D.queuedAt,destination:G,...q.scheduledFor?{scheduledFor:q.scheduledFor}:{}})}}let W=await db$(A);Y.generating=W.length;let K=Array.from(X.values()).filter((U)=>U.status==="failed").map((U)=>{let G=w.getRetryInfo(U.entityId);return{entityId:U.entityId,entityType:U.entityType,title:U.title,error:U.error??G?.lastError??"Publication failed",retryCount:G?.retryCount??0}}).sort((U,G)=>U.title.localeCompare(G.title));return Y.needsOperator=Y.draft+Y.failed,pb$.parse({summary:Y,queue:Z,generating:W,failures:K,publishableEntityTypes:B})}async function db$(A){let Q=[];for(let $ of await A.jobs.getActiveJobs()){if($.source!=="content-pipeline")continue;if($.status!=="pending"&&$.status!=="processing")continue;let w;try{w=JSON.parse($.data)}catch{continue}let B=lb$.safeParse(w);if(!B.success)continue;Q.push({id:$.id,label:B.data.attachmentType??$.type,target:`${B.data.sourceEntityType}/${B.data.sourceEntityId}`,status:$.status})}return Q}function wS2(A,Q){return`${A}\x00${Q}`}function ib$(A,Q){for(let $ of["title","subject","slug"]){let w=Q[$];if(typeof w==="string"&&w.length>0)return w}return A}async function BS2(A,Q,$){await A.messaging.send({type:"dashboard:register-widget",payload:{id:"publication-pipeline",pluginId:Q,title:"Publication Pipeline",group:"publishing",section:"secondary",priority:100,rendererName:"PipelineWidget",visibility:"anchor",dataProvider:async()=>({...await Nj0(A,$.providerRegistry,$.queueManager,$.retryTracker),...$.managementUrl?{managementUrl:$.managementUrl}:{}}),digestProvider:rb$}})}var nb$=H.object({summary:H.object({draft:H.number(),queued:H.number(),generating:H.number(),published:H.number(),failed:H.number(),needsOperator:H.number()})});function rb$(A){let{summary:Q}=nb$.parse(A),$=Q.queued+Q.generating,w=$===0?"idle":`${Q.queued} queued \xB7 ${Q.generating} generating`,B=Q.failed>0?`${Q.draft} drafts \xB7 ${Q.failed} failed`:`${Q.draft} drafts`;return{digest:[{label:"Pipeline",value:w,...$>0?{tone:"warn"}:{}},{label:"Awaiting review",value:B,...Q.needsOperator>0?{tone:"warn"}:{}},{label:"Published",value:String(Q.published),tone:"good"}],needsOperator:Q.needsOperator}}KA();C0();var ob$=H.object({workspaceUrl:H.string()}),sb$=H.object({confirmed:H.literal(!0),confirmationToken:H.string().min(1),contentHash:H.string().min(1),expiresAt:H.string().datetime()}),ab$=H.discriminatedUnion("type",[H.object({type:H.literal("queue"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1)}),H.object({type:H.literal("remove"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1)}),H.object({type:H.literal("retry"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1)}),H.object({type:H.literal("reorder"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1),position:H.number().int().positive()}),H.object({type:H.literal("publish"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1),confirmation:sb$.optional()})]);async function XS2(A,Q,$){let w=zn(A,Q,$.providerRegistry,$.publishExecutor),B={id:"publishing",pluginId:Q,label:"Publishing",rendererName:"PublishingWorkspace",entityTypes:$.providerRegistry.getRegisteredTypes(),dataProvider:()=>Nj0(A,$.providerRegistry,$.queueManager,$.retryTracker),actionHandler:async(Z,W)=>{let K=ab$.safeParse(Z);if(!K.success)throw Error("Invalid publishing workspace action");return tb$(A,$,w,K.data,W)}},X=await A.messaging.send({type:w00,payload:B});if(!("success"in X)||!X.success)return;let Y=ob$.safeParse(X.data);return Y.success?Y.data.workspaceUrl:void 0}async function tb$(A,Q,$,w,B){if(!Q.providerRegistry.has(w.entityType))throw Error(`No publish provider registered for ${w.entityType}`);let X=await A.entityService.getEntity({entityType:w.entityType,id:w.entityId});if(!X)throw Error(`Entity not found: ${w.entityType}:${w.entityId}`);if(w.type==="publish"){let W=await $.handler({entityType:w.entityType,id:w.entityId,...w.confirmation??{}},B);if("success"in W&&W.success===!0)await Q.publicationQueueService.complete(w.entityType,w.entityId),Q.retryTracker.clearRetries(w.entityId);return W}let Y=w.type==="queue"||w.type==="retry"?"publish":"update";A.permissions.assertEntityActionAllowed(w.entityType,Y,B);let Z=X.metadata.status;switch(w.type){case"queue":if(Z!=="draft")throw Error("Only draft entities can be queued");return Q.publicationQueueService.enqueue(w.entityType,w.entityId,{...B,authorization:"user"});case"remove":if(Z!=="queued")throw Error("Only queued entities can be removed from the queue");return await Q.publicationQueueService.remove(w.entityType,w.entityId),{success:!0};case"retry":if(Z!=="failed")throw Error("Only failed publications can be retried");return await Q.publicationQueueService.enqueue(w.entityType,w.entityId,{...B,authorization:"user"}),{success:!0};case"reorder":if(Z!=="queued")throw Error("Only queued entities can be reordered");return await Q.publicationQueueService.reorder(w.entityType,w.entityId,w.position),{success:!0}}}var YS2={name:"@brains/content-pipeline",version:"0.2.0-alpha.183",description:"Content pipeline plugin for managing entity publishing queues, scheduling, and generation",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/scheduler":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14",typescript:"^7.0.2"},exports:{".":{types:"./src/index.ts",default:"./src/index.ts"}},files:["src"],main:"src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"src/index.ts"};class ZzA extends p6{pluginContext;queueManager;publicationQueueService;providerRegistry;retryTracker;publishExecutor;publishAssetRegistry;publishAssetPreflight;scheduler;constructor(A={}){super("content-pipeline",YS2,A,cg2)}async onRegister(A){this.pluginContext=A,this.queueManager=WI.createFresh(),this.publicationQueueService=new YzA(A,this.queueManager),this.providerRegistry=KI.createFresh(),this.retryTracker=GI.createFresh(),this.publishAssetRegistry=DI.createFresh(),this.publishAssetPreflight=new Fj0({context:A,registry:this.publishAssetRegistry}),this.publishExecutor=new qn({context:A,providerRegistry:this.providerRegistry,publishAssetPreflight:this.publishAssetPreflight}),this.scheduler=$S2({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,logger:this.logger}),AS2(A,{queueManager:this.queueManager,publicationQueueService:this.publicationQueueService,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 this.publicationQueueService.reconcile(this.providerRegistry.getRegisteredTypes());let Q=await XS2(A,this.id,{providerRegistry:this.providerRegistry,queueManager:this.queueManager,publicationQueueService:this.publicationQueueService,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor});await BS2(A,this.id,{providerRegistry:this.providerRegistry,queueManager:this.queueManager,retryTracker:this.retryTracker,...Q?{managementUrl:Q}:{}}),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[Ij0(this.pluginContext,this.id,this.queueManager,this.publicationQueueService),zn(this.pluginContext,this.id,this.providerRegistry,this.publishExecutor),Lj0(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}getPublicationQueueService(){return this.publicationQueueService}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getPublishAssetRegistry(){return this.publishAssetRegistry}getScheduler(){return this.scheduler}async onShutdown(){await this.scheduler.stop(),WI.resetInstance(),KI.resetInstance(),GI.resetInstance(),DI.resetInstance()}}function HzA(A={}){return new ZzA(A)}KA();C0();var ZS2=H.object({accountId:H.string().describe("Cloudflare account ID"),apiToken:H.string().describe("Cloudflare API token with Analytics:Read permission"),siteTag:H.string().describe("Cloudflare Web Analytics site tag")}),WzA=H.object({cloudflare:ZS2.optional()});KA();C0();var AO$=H.object({date:H.string().describe("Single date in YYYY-MM-DD format").optional(),days:H.number().min(1).max(365).describe("Number of days back from yesterday (e.g., 7 for last week)").optional(),startDate:H.string().describe("Start date in YYYY-MM-DD format (use with endDate)").optional(),endDate:H.string().describe("End date in YYYY-MM-DD format (use with startDate)").optional(),limit:H.number().min(1).max(100).default(20).describe("Maximum items for breakdowns (pages, referrers, countries)")});function QO$(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 HS2(A,Q,$){let w=[];if(!$)return w;return w.push(p8(A,"query",`Query website analytics from Cloudflare.
8003
+ ${$.content}`:$.prompt??"Write an engaging LinkedIn post";return A.ai.generate({prompt:w,templateName:`social-media:${$.platform}`})}),A.eval.registerHandler("create",async(Q)=>{let $=yM$.parse(Q),w=[],B=XH.from(async(K)=>{let U={progress:K.progress};if(K.message!==void 0)U.message=K.message;w.push(U)});if(!B)throw Error("Failed to create progress reporter");let Y=await new HT(A.logger,A).process($,`eval-${Date.now()}`,B),Z=!1,W;if(Y.success&&Y.entityId){let K=await A.entityService.getEntity({entityType:"social-post",id:Y.entityId});Z=!!K,W=K?.content.slice(0,300)}return{...Y,entityExists:Z,entityPreview:W,progressSteps:w}})}KA();class F50{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:$}=A;if(Q!=="social-post")return;this.permissions.assertEntityActionAllowed(Q,"publish",A.authContext??{userPermissionLevel:"anchor"}),this.logger.debug("Handling publish:execute",{entityId:$});try{let w=await this.entityService.getEntity({entityType:"social-post",id:$});if(!w){await this.reportFailure(Q,$,`Post not found: ${$}`);return}let B=w;if(B.metadata.status==="published"){this.logger.debug("Post already published, skipping",{entityId:$});return}let X=B.metadata.platform,Y=this.providers.get(X);if(!Y){await this.reportFailure(Q,$,`No provider configured for platform: ${X}`);return}let Z=_Q(B.content,wV),W;if(Z.metadata.coverImageId)W=await this.fetchImageData(Z.metadata.coverImageId);let K=Z.metadata.documents??[],U=await this.fetchDocumentData(K);try{if(K.length>0&&U.length===0)throw Error(`Refusing to publish: ${K.length} document(s) referenced but none could be fetched`);let G=K.length===0?await this.resolveSourceAttachment(Z.metadata):[],D=U.length>0?U:G,q=D.length?await Y.publish(Z.content,B.metadata,W,D):await Y.publish(Z.content,B.metadata,W),J=new Date().toISOString(),F=q.id||void 0,I={...Z.metadata,status:"published",publishedAt:J,...F&&{platformPostId:F}},P=OY.createPostContent(I,Z.content);await this.entityService.updateEntity({entity:{...B,content:P,metadata:{...B.metadata,status:"published",publishedAt:J,platformPostId:F}}}),await this.reportSuccess(Q,$,q.id),this.logger.info(`Post published successfully: ${$}`,{platform:X,platformPostId:F})}catch(G){let D=G instanceof Error?G.message:String(G),q={...Z.metadata,status:"failed"},J=OY.createPostContent(q,Z.content);await this.entityService.updateEntity({entity:{...B,content:J,metadata:{...B.metadata,status:"failed"}}}),await this.reportFailure(Q,$,D),this.logger.error(`Post publish failed: ${$}`,{platform:X,error:D})}}catch(w){let B=aA(w);this.logger.error("Unexpected error in publish handler",{entityId:$,error:B}),await this.reportFailure(Q,$,B)}}async reportSuccess(A,Q,$){await this.sendMessage({type:"publish:report:success",payload:{entityType:A,entityId:Q,result:{id:$}}})}async reportFailure(A,Q,$){await this.sendMessage({type:"publish:report:failure",payload:{entityType:A,entityId:Q,error:$}})}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 $ of A){let w=await this.fetchSingleDocumentData($.id);if(w)Q.push(w)}return Q}async fetchSingleDocumentData(A){try{let Q=await this.entityService.getEntity({entityType:"document",id:A});if(!Q){this.logger.warn("Document not found",{documentId:A});return}let $=Q.content.match(/^data:application\/pdf;base64,(.+)$/);if(!$?.[1]){this.logger.warn("Invalid document data URL format",{documentId:A});return}let w=typeof Q.metadata.filename==="string"?Q.metadata.filename:`${A}.pdf`;return{type:"document",data:Buffer.from($[1],"base64"),mimeType:"application/pdf",filename:w}}catch(Q){this.logger.warn("Failed to fetch document",{documentId:A,error:Q});return}}async fetchImageData(A){try{let Q=await this.entityService.getEntity({entityType:"image",id:A});if(!Q){this.logger.warn("Cover image not found",{imageId:A});return}let w=Q.content.match(/^data:([^;]+);base64,(.+)$/);if(!w?.[1]||!w[2]){this.logger.warn("Invalid image data URL format",{imageId:A});return}let B=w[1],X=w[2];return{data:Buffer.from(X,"base64"),mimeType:B}}catch(Q){this.logger.warn("Failed to fetch cover image",{imageId:A,error:Q});return}}}function vg2(A,Q,$){if(Q.size===0){$.debug("No providers configured, skipping publish-pipeline registration");return}A.messaging.subscribe("system:plugins:ready",async()=>{let w=Q.values().next().value;return await A.messaging.send({type:"publish:register",payload:{entityType:"social-post",provider:w,config:{publishResultIdField:"platformPostId"}}}),$.info("Registered social-post with publish-pipeline"),{success:!0}})}function Cg2(A,Q,$){let w=new F50({sendMessage:A.messaging.send,logger:$.child("PublishExecuteHandler"),entityService:A.entityService,providers:Q,permissions:A.permissions,resolveAttachment:A.attachments.resolve});A.messaging.subscribe("publish:execute",async(B)=>{return await w.handle(B.payload),{success:!0}}),$.debug("Subscribed to publish:execute messages")}function hg2(A,Q){A.messaging.subscribe("entity:updated",async($)=>{let{entityType:w,entityId:B,entity:X}=$.payload;if(w!=="post")return{success:!0};if(X.metadata?.status!=="queued")return{success:!0};try{if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:B}},limit:1}})).length>0)return Q.debug(`Social post already exists for ${B}, skipping auto-generate`),{success:!0};return await A.messaging.send({type:"social:auto-generate",payload:{sourceEntityType:w,sourceEntityId:B,platform:"linkedin"}}),Q.info(`Auto-generate social post triggered for queued post ${B}`),{success:!0}}catch(Z){let W=aA(Z);return Q.error(`Failed to trigger auto-generate for ${B}:`,{error:W}),{success:!0}}}),Q.debug("Subscribed to entity:updated for auto-generation")}function Eg2(A,Q){A.messaging.subscribe("social:auto-generate",async($)=>{let{sourceEntityType:w,sourceEntityId:B,platform:X}=$.payload;try{let Y=await A.jobs.enqueue({type:`${OY.entityType}:generation`,data:{sourceEntityType:w,sourceEntityId:B,platform:X,addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info(`Social post generation job enqueued for ${w}/${B}`,{jobId:Y}),{success:!0,jobId:Y}}catch(Y){let Z=aA(Y);return Q.error(`Failed to enqueue social post generation for ${B}:`,{error:Z}),{success:!1}}}),Q.debug("Subscribed to social:auto-generate messages")}function Tg2(A,Q){A.messaging.subscribe("generate:execute",async($)=>{let{entityType:w}=$.payload;if(w!=="social-post")return{success:!0};Q.info("Received generate:execute for social-post");try{let B=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:5}});if(B.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 X=null;for(let Z of B)if((await A.entityService.listEntities({entityType:"social-post",options:{filter:{metadata:{sourceEntityType:"post",sourceEntityId:Z.id}},limit:1}})).length===0){X=Z;break}if(!X)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 Y=await A.jobs.enqueue({type:`${OY.entityType}:generation`,data:{sourceEntityType:"post",sourceEntityId:X.id,platform:"linkedin",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}});return Q.info("Social post generation job queued",{jobId:Y,sourcePostId:X.id}),{success:!0}}catch(B){let X=aA(B);return Q.error("Failed to handle generate:execute:",{error:X}),await A.messaging.send({type:"generate:report:failure",payload:{entityType:"social-post",error:X}}),{success:!0}}}),Q.debug("Subscribed to generate:execute messages")}async function yg2({entity:A,config:Q}){let $=eO.parse(A),w=OY.parsePostFrontmatter($),B=OY.getPostContent($);return{$type:"ai.rizom.brain.socialPost",title:w.title,platform:w.platform,body:B,format:"text/markdown",status:w.status,...w.publishedAt&&{publishedAt:w.publishedAt},...w.platformPostId&&{platformPostId:w.platformPostId},...w.sourceEntityType&&{sourceLocalEntityType:w.sourceEntityType},...w.sourceEntityId&&{sourceLocalEntityId:w.sourceEntityId},...Q.brainDid&&{brainDid:Q.brainDid},...Q.anchorDid&&{anchorDid:Q.anchorDid},sourceEntityType:"social-post",sourceEntityId:$.id,createdAt:$.created,...$.updated&&{updatedAt:$.updated}}}function cqA(){return{entityType:"social-post",collection:"ai.rizom.brain.socialPost",lexicon:E8["ai.rizom.brain.socialPost"],validate:!1,buildRecord:yg2}}var gg2={name:"@brains/social-media",version:"0.2.0-alpha.184",description:"Multi-provider social media posting with queue-based publishing",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class pqA extends S6{entityType=OY.entityType;schema=eO;adapter=OY;providers=new Map;unregisterAtprotoProjection;constructor(A={}){super("social-media",gg2,A,TqA)}createGenerationHandler(A){return new HT(this.logger.child("GenerationJobHandler"),A)}getTemplates(){return xg2()}getDataSources(){return[new Dj0(this.logger.child("SocialPostDataSource"))]}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}async onRegister(A){if(this.initializeProviders(),vg2(A,this.providers,this.logger),Cg2(A,this.providers,this.logger),this.config.autoGenerateOnBlogPublish)hg2(A,this.logger),Eg2(A,this.logger),this.logger.info("Auto-generate on blog publish enabled");Tg2(A,this.logger),Rg2(A),this.unregisterAtprotoProjection=aB.getInstance().register(cqA()),this.logger.info("Social media plugin registered successfully")}async onShutdown(){this.unregisterAtprotoProjection?.(),this.unregisterAtprotoProjection=void 0}initializeProviders(){if(this.config.linkedin?.accessToken){let A=uqA(this.config.linkedin,this.logger.child("LinkedInClient"));this.providers.set("linkedin",A),this.logger.info("LinkedIn provider initialized")}}}function I50(A={}){return new pqA(A)}C0();var SM$=H.enum(["draft","queued","published","failed"]),Sg2=H.object({status:SM$.default("draft"),queueOrder:H.number().optional().describe("Position in publish queue (lower = sooner)"),publishedAt:H.string().datetime().optional()});class lqA{name="internal";async publish(A,Q){return{id:"internal"}}}var OP={interfaceType:"system",userId:"system",userPermissionLevel:"anchor",authorization:"system"},fY={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"},Af={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"},mg2={REGISTER:"publish-assets:register"};C0();var mM$=H.enum(["provider"]),ug2=H.object({executionMode:mM$.optional(),publishResultIdField:H.string().min(1).optional(),publishTimestampField:H.string().min(1).optional(),enabled:H.boolean().optional()}).strict();var uM$=H.object({skipIfDraftExists:H.boolean().optional(),minSourceEntities:H.number().optional(),maxUnpublishedDrafts:H.number().optional(),sourceEntityType:H.string().optional()}),cg2=H.object({entitySchedules:H.record(H.string(),H.string()).optional(),generationSchedules:H.record(H.string(),H.string()).optional(),generationConditions:H.record(H.string(),uM$).optional()});class WI{static instance=null;queues=new Map;static getInstance(){return WI.instance??=new WI,WI.instance}static resetInstance(){WI.instance=null}static createFresh(){return new WI}constructor(){}async add(A,Q,$=OP){let w=this.getOrCreateQueue(A),B=w.find((Z)=>Z.entityId===Q);if(B)return{position:B.position};let X=w.length+1,Y={entityId:Q,entityType:A,position:X,queuedAt:new Date().toISOString(),authContext:{...$}};return w.push(Y),{position:X}}async remove(A,Q){let $=this.queues.get(A);if(!$)return;let w=$.findIndex((B)=>B.entityId===Q);if(w===-1)return;$.splice(w,1),this.recalculatePositions($)}async reorder(A,Q,$){let w=this.queues.get(A);if(!w)return;let B=w.findIndex((Z)=>Z.entityId===Q);if(B===-1)return;let[X]=w.splice(B,1);if(!X)return;let Y=Math.max(0,Math.min($-1,w.length));w.splice(Y,0,X),this.recalculatePositions(w)}async list(A){let Q=this.queues.get(A);if(!Q)return[];return[...Q]}async getNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;return Q[0]??null}async getNextAcrossTypes(){let A=null;for(let Q of this.queues.values()){let $=Q[0];if(!$)continue;if(!A||$.queuedAt<A.queuedAt)A=$}return A}async popNext(A){let Q=this.queues.get(A);if(!Q||Q.length===0)return null;let $=Q.shift()??null;if($)this.recalculatePositions(Q);return $}replace(A){this.queues.clear();let Q=[...A].sort(($,w)=>$.entityType.localeCompare(w.entityType)||$.position-w.position);for(let $ of Q)this.getOrCreateQueue($.entityType).push({...$,authContext:{...$.authContext}});for(let $ of this.queues.values())this.recalculatePositions($)}getRegisteredTypes(){return Array.from(this.queues.keys())}async getQueuedEntityTypes(){let A=[];for(let[Q,$]of this.queues.entries())if($.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,$)=>{Q.position=$+1})}}class KI{static instance=null;providers=new Map;executionModes=new Map;publishResultIdFields=new Map;publishTimestampFields=new Map;defaultProvider=new lqA;static getInstance(){return KI.instance??=new KI,KI.instance}static resetInstance(){KI.instance=null}static createFresh(){return new KI}constructor(){}register(A,Q,$){let w=this.providers.get(A);if(w&&w.name!=="internal"&&Q.name==="internal")return;if(this.providers.set(A,Q),this.executionModes.set(A,$?.executionMode??"provider"),$?.publishResultIdField)this.publishResultIdFields.set(A,$.publishResultIdField);else this.publishResultIdFields.delete(A);if($?.publishTimestampField)this.publishTimestampFields.set(A,$.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())}}async function pg2(A,Q){if(!Q.publishExecutor){Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:"Publish executor not configured",retryCount:0,willRetry:!1});return}await cM$(A,Q)}async function cM$(A,Q){if(!Q.publishExecutor)return;try{let $=await Q.publishExecutor.publish({entityType:A.entityType,id:A.entityId});if("error"in $){let w={entityType:A.entityType,entityId:A.entityId,error:$.error,retryCount:0,willRetry:!1};if(Q.messageBus)await Q.messageBus.send({type:fY.FAILED,payload:w,sender:"publish-service",broadcast:!0});Q.onFailed?.(w);return}dqA(A.entityType,A.entityId,$.result,Q)}catch($){let w=aA($);Q.retryTracker.recordFailure(A.entityId,w);let B=Q.retryTracker.getRetryInfo(A.entityId);Q.onFailed?.({entityType:A.entityType,entityId:A.entityId,error:w,retryCount:B?.retryCount??1,willRetry:!1})}}function dqA(A,Q,$,w){if(w.retryTracker.clearRetries(Q),w.messageBus)w.messageBus.send({type:fY.COMPLETED,payload:{entityType:A,entityId:Q,result:$},sender:"publish-service",broadcast:!0});w.onPublish?.({entityType:A,entityId:Q,result:$})}function lg2(A,Q,$,w){w.retryTracker.recordFailure(Q,$);let B=w.retryTracker.getRetryInfo(Q),X={entityType:A,entityId:Q,error:$,retryCount:B?.retryCount??1,willRetry:!1};if(w.messageBus)w.messageBus.send({type:fY.FAILED,payload:X,sender:"publish-service",broadcast:!0});w.onFailed?.(X)}async function dg2(A,Q){let $=Q.generationConditions[A];if($&&Q.onCheckGenerationConditions){let B=await Q.onCheckGenerationConditions(A,$);if(!B.shouldGenerate){if(Q.messageBus)Q.messageBus.send({type:Af.SKIPPED,payload:{entityType:A,reason:B.reason??"Conditions not met"},sender:"content-pipeline"});return}}let w={entityType:A};if(Q.messageBus)await Q.messageBus.send({type:Af.EXECUTE,payload:w,sender:"content-pipeline"});Q.onGenerate?.(w)}function ig2(A,Q,$){if($)$.send({type:Af.COMPLETED,payload:{entityType:A,entityId:Q},sender:"content-pipeline"})}function ng2(A,Q,$){if($)$.send({type:Af.FAILED,payload:{entityType:A,error:Q},sender:"content-pipeline"})}var pM$=1000;class iqA{deps;publishJobs=new Map;immediateIntervalJob=null;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.entitySchedules)){let $=this.deps.config.backend.scheduleCron(Q,()=>this.processEntityType(A));this.publishJobs.set(A,$)}this.immediateIntervalJob=this.deps.config.backend.scheduleInterval(pM$,()=>this.processUnscheduledTypes())}async stop(){let A=Array.from(this.publishJobs.values());if(this.publishJobs.clear(),this.immediateIntervalJob)A.push(this.immediateIntervalJob),this.immediateIntervalJob=null;await Promise.all(A.map((Q)=>Q.stop()))}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 $=await this.deps.config.queueManager.getNext(Q);if($){await this.processEntry($);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 pg2(A,Q)}get entitySchedules(){return this.deps.config.entitySchedules}}class nqA{deps;generationJobs=new Map;constructor(A){this.deps=A}start(){for(let[A,Q]of Object.entries(this.generationSchedules)){let $=this.deps.config.backend.scheduleCron(Q,()=>this.handleTriggerGeneration(A));this.generationJobs.set(A,$)}}async stop(){let A=Array.from(this.generationJobs.values());this.generationJobs.clear(),await Promise.all(A.map((Q)=>Q.stop()))}async handleTriggerGeneration(A){if(!this.deps.isRunning())return;try{await dg2(A,this.deps.getGenerationDeps())}catch(Q){this.deps.config.logger.error(`Generation trigger error for ${A}:`,Q)}}get generationSchedules(){return this.deps.config.generationSchedules}}class UI{static instance=null;config;publishRunner;generationRunner;running=!1;stopPromise=null;static getInstance(A){return UI.instance??=new UI(A),UI.instance}static async resetInstance(){let A=UI.instance;if(UI.instance=null,A)await A.stop()}static createFresh(A){return new UI(A)}constructor(A){this.config={...A,entitySchedules:A.entitySchedules??{},generationSchedules:A.generationSchedules??{},generationConditions:A.generationConditions??{}},this.validateCronExpressions(),this.publishRunner=new iqA({config:this.config,getPublishDeps:()=>this.publishDeps,isRunning:()=>this.running}),this.generationRunner=new nqA({config:this.config,getGenerationDeps:()=>this.generationDeps,isRunning:()=>this.running})}async start(){if(this.running)return;if(this.stopPromise)await this.stopPromise,this.stopPromise=null;this.running=!0,this.publishRunner.start(),this.generationRunner.start()}stop(){if(this.stopPromise)return this.stopPromise;return this.running=!1,this.stopPromise=Promise.all([this.publishRunner.stop(),this.generationRunner.stop()]).then(()=>{return}),this.stopPromise}isRunning(){return this.running}completePublish(A,Q,$){dqA(A,Q,$,this.publishDeps)}failPublish(A,Q,$){lg2(A,Q,$,this.publishDeps)}completeGeneration(A,Q){ig2(A,Q,this.config.messageBus)}failGeneration(A,Q){ng2(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,$){try{this.config.backend.validateCron(Q)}catch(w){throw Error(`Invalid ${$} cron expression for ${A}: "${Q}" - ${aA(w)}`,{cause:w})}}}class GI{static instance=null;retries=new Map;static getInstance(){return GI.instance??=new GI,GI.instance}static resetInstance(){GI.instance=null}static createFresh(){return new GI}constructor(){}recordFailure(A,Q){let w=(this.retries.get(A)?.retryCount??0)+1;this.retries.set(A,{entityId:A,retryCount:w,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}}}oa0();C0();var rg2=H.union([H.string().min(1),H.object({location:H.enum(["metadata","frontmatter"]),field:H.string().min(1)})]),Jj0=H.object({entityType:H.string().min(1),attachmentType:H.string().min(1),mediaEntityType:H.enum(["image","document"]),targetEntityField:rg2.optional(),requiredWhen:H.object({status:H.string().min(1).optional(),visibility:H.string().min(1).optional()}).optional(),autoGenerate:H.boolean().optional(),requiredForPublish:H.boolean().optional(),jobType:H.string().min(1).optional()});function rqA(A){return`${A.entityType}:${A.attachmentType}`}class DI{static instance=null;definitions=new Map;static getInstance(){return DI.instance??=new DI,DI.instance}static resetInstance(){DI.instance=null}static createFresh(){return new DI}constructor(){}register(A){let Q=Jj0.parse(A),$=rqA(Q);return this.definitions.set($,Q),()=>this.unregister(Q.entityType,Q.attachmentType)}get(A,Q){return this.definitions.get(rqA({entityType:A,attachmentType:Q}))}list(A){let Q=Array.from(this.definitions.values());return A?Q.filter(($)=>$.entityType===A):Q}has(A,Q){return this.get(A,Q)!==void 0}unregister(A,Q){this.definitions.delete(rqA({entityType:A,attachmentType:Q}))}clear(){this.definitions.clear()}}_4();S2();class Fj0{deps;constructor(A){this.deps=A}async ensureForEntity(A,Q={}){let $=this.deps.registry.list(A.entityType).filter((B)=>B.autoGenerate===!0).filter((B)=>!Q.attachmentType||B.attachmentType===Q.attachmentType),w={checked:$.length,enqueued:0,skipped:0};for(let B of $)if(await this.ensureDefinition(A,B))w.enqueued+=1;else w.skipped+=1;return w}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 $=this.resolveJobType(Q);if(!$)return!1;let w=this.getPredictedMediaId(A,Q),B=this.getDeduplicationKey(A,Q);return await this.deps.context.jobs.enqueue({type:$,data:{sourceEntityType:A.entityType,sourceEntityId:A.id,attachmentType:Q.attachmentType,imageId:w,dedupKey:B,targetEntityType:A.entityType,targetEntityId:A.id,...this.getTargetImageFieldData(Q.targetEntityField)},options:{source:"content-pipeline",metadata:{operationType:"content_operations"},deduplication:"skip",deduplicationKey:B}}),this.deps.context.logger.debug("Queued publish asset generation",{entityType:A.entityType,entityId:A.id,attachmentType:Q.attachmentType,jobType:$}),!0}matchesPolicy(A,Q){let{requiredWhen:$}=Q;if(!$)return!0;if($.status&&A.metadata.status!==$.status)return!1;if($.visibility&&A.visibility!==$.visibility)return!1;return!0}hasTargetField(A,Q){if(!Q)return!1;if(typeof Q==="string")return oqA(A.metadata[Q]);if(Q.location==="metadata")return oqA(A.metadata[Q.field]);let{frontmatter:$}=c8(A.content);return oqA($[Q.field])}resolveJobType(A){if(A.jobType)return A.jobType;if(A.mediaEntityType==="image")return"image:image-render-source";return}getPredictedMediaId(A,Q){let $=Q.attachmentType==="og-image"?"og":Q.attachmentType;return k1(`${$}-${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 oqA(A){return typeof A==="string"?A.length>0:A!==void 0}KA();C0();var dM$=H.object({id:H.string().min(1)});async function sg2(A,Q){let{bodyContent:$,coverImageId:w,documents:B,sourceEntityType:X,sourceEntityId:Y}=iM$(Q.content),Z=w?await oM$(A,w):void 0,W;if(B&&B.length>0){let U=await sM$(A,B);if(U.length>0)W=U}W??=await rM$(A,X,Y);let K={bodyContent:$};if(Z)K.imageData=Z;if(W&&W.length>0)K.documentData=W;return K}function iM$(A){try{let Q=_Q(A,H.record(H.string(),H.unknown())),$=Q.metadata.coverImageId,w=typeof $==="string"?$:void 0,B=nM$(Q.metadata.documents),X=og2(Q.metadata.sourceEntityType),Y=og2(Q.metadata.sourceEntityId);return{bodyContent:Q.content,...w&&{coverImageId:w},...B.length>0&&{documents:B},...X&&{sourceEntityType:X},...Y&&{sourceEntityId:Y}}}catch{return{bodyContent:A}}}function nM$(A){if(!Array.isArray(A))return[];return A.flatMap((Q)=>{let $=dM$.safeParse(Q);return $.success?[$.data]:[]})}function og2(A){return typeof A==="string"&&A.length>0?A:void 0}async function rM$(A,Q,$){if(!Q||!$)return;let w=await A.attachments.resolve({sourceEntityType:Q,sourceEntityId:$,attachmentType:"carousel"});return w?[w]:void 0}async function oM$(A,Q){let $=await A.entityService.getEntity({entityType:"image",id:Q});if(!$?.content)return;let w=ag2($.content);if(!w?.mimeType.startsWith("image/"))return;return{data:w.data,mimeType:w.mimeType}}async function sM$(A,Q){return(await Promise.all(Q.map((w)=>aM$(A,w)))).filter((w)=>w!==void 0)}async function aM$(A,Q){let $=await A.entityService.getEntity({entityType:"document",id:Q.id});if(!$?.content)return;let w=ag2($.content);if(w?.mimeType!=="application/pdf")return;return{type:"document",data:w.data,mimeType:"application/pdf",filename:tM$($,Q.id)}}function ag2(A){let Q=A.match(/^data:([^;]+);base64,(.+)$/);if(!Q?.[1]||!Q[2])return;return{mimeType:Q[1],data:Buffer.from(Q[2],"base64")}}function tM$(A,Q){let $=A.metadata.filename;return typeof $==="string"&&$.length>0?$:`${Q}.pdf`}_4();var eM$=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;async function sqA(A,Q,$,w={}){let B=w.publishTimestampField??"publishedAt",X=Q.metadata[B],Y=w.publishedAt??(typeof X==="string"?X:void 0)??new Date().toISOString(),Z={...Q.metadata,status:"published",[B]:Y,platformId:$.id,...Ab$($.id,w.publishResultIdField)},W={...Q,content:tg2(Q.content,Y,$.id,w.publishResultIdField,B),metadata:Z};return await A.entityService.updateEntity({entity:W}),W}function tg2(A,Q,$,w,B="publishedAt"){if(!eM$.test(A))return A;let X=zX(zX(A,"status","published"),B,Q);if(!$||!w)return X;return zX(X,w,$)}function Ab$(A,Q){if(!Q||Q==="platformId")return{};return{[Q]:A}}class qn{deps;constructor(A){this.deps=A}async resolveCandidate(A){let{entityType:Q,id:$,slug:w}=A;if(!$&&!w)return{error:"Either 'id' or 'slug' must be provided"};let B=await this.findPublishableEntity(Q,$,w);if(!B)return{error:`Entity not found: ${Q}:${$??w}`};if(B.visibility!=="public")return{error:`Cannot publish ${Q}:${B.id} to a public provider because visibility is ${B.visibility}`};if(B.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:B}}async publish(A){let Q=await this.resolveCandidate(A);if("error"in Q)return Q;let{entity:$}=Q,{entityType:w}=A,B=this.deps.providerRegistry.get(w),{bodyContent:X,imageData:Y,documentData:Z}=await sg2(this.deps.context,$),W=await B.publish(X,$.metadata,Y,Z),K=this.deps.providerRegistry.getPublishResultIdField(w),U=this.deps.providerRegistry.getPublishTimestampField(w),G=await sqA(this.deps.context,$,W,{...K?{publishResultIdField:K}:{},...U?{publishTimestampField:U}:{}});return await this.runPublishAssetPreflight(G),{entity:G,result:W}}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,$){if(Q)return this.deps.context.entityService.getEntity({entityType:A,id:Q});if(!$)return null;return(await this.deps.context.entityService.listEntities({entityType:A,options:{filter:{metadata:{slug:$}},limit:1}}))[0]??null}}KA();C0();var aqA=H.object({action:H.enum(["list","add","remove","reorder"]).describe("Queue action to perform"),entityType:H.string().optional().describe("Entity type (required for add/remove/reorder, optional for list)"),entityId:H.string().optional().describe("Entity ID (required for add/remove/reorder)"),position:H.number().optional().describe("New position for reorder action (1-based)")}),tqA=H.object({position:H.number(),entityType:H.string(),entityId:H.string(),queuedAt:H.string()}),Qb$=H.object({success:H.literal(!0),message:H.string().optional(),data:H.object({queue:H.array(tqA).optional(),entityType:H.string().optional(),entityId:H.string().optional(),position:H.number().optional()}).optional()}),$b$=H.object({success:H.literal(!1),error:H.string(),code:H.string().optional()}),eqA=H.union([Qb$,$b$]);function Ij0(A,Q,$,w){let B=w??$;return{...p8(Q,"queue","Manage the publish queue for all entity types (list, add, remove, reorder)",aqA,async(Y,Z)=>{let{action:W,entityType:K,entityId:U,position:G}=Y;switch(W){case"list":return wb$($,K);case"add":return Bb$(A,B,K,U,Z);case"remove":return Xb$(A,B,K,U,Z);case"reorder":return Yb$(A,B,K,U,G,Z);default:return{success:!1,error:`Unknown action: ${W}`}}},{sideEffects:"writes"}),outputSchema:eqA}}async function wb$(A,Q){let $=[];if(Q)$=await A.list(Q);else{let B=A.getRegisteredTypes();for(let X of B){let Y=await A.list(X);$.push(...Y)}$.sort((X,Y)=>new Date(X.queuedAt).getTime()-new Date(Y.queuedAt).getTime())}if($.length===0)return{success:!0,data:{queue:[]},message:"No items in queue"};return{success:!0,data:{queue:$.map((B,X)=>({position:X+1,entityType:B.entityType,entityId:B.entityId,queuedAt:B.queuedAt}))},message:`${$.length} items in queue`}}async function Bb$(A,Q,$,w,B){let X=AzA("add",$,w);if(!X.success)return X.error;A.permissions.assertEntityActionAllowed(X.entityType,"publish",B??{});let Y=await Q.add(X.entityType,X.entityId,{...B,authorization:"user"});return{success:!0,data:{entityType:X.entityType,entityId:X.entityId,position:Y.position},message:`Added to queue at position ${Y.position}`}}async function Xb$(A,Q,$,w,B){let X=AzA("remove",$,w);if(!X.success)return X.error;return A.permissions.assertEntityActionAllowed(X.entityType,"update",B??{}),await Q.remove(X.entityType,X.entityId),{success:!0,data:{entityType:X.entityType,entityId:X.entityId},message:"Removed from queue"}}async function Yb$(A,Q,$,w,B,X){let Y=AzA("reorder",$,w);if(!Y.success)return Y.error;let Z=Zb$(B);if(!Z.success)return Z.error;return A.permissions.assertEntityActionAllowed(Y.entityType,"update",X??{}),await Q.reorder(Y.entityType,Y.entityId,Z.position),{success:!0,data:{entityType:Y.entityType,entityId:Y.entityId,position:Z.position},message:`Moved to position ${Z.position}`}}function AzA(A,Q,$){if(!Q)return{success:!1,error:{success:!1,error:`entityType is required for ${A} action`}};if(!$)return{success:!1,error:{success:!1,error:`entityId is required for ${A} action`}};return{success:!0,entityType:Q,entityId:$}}function Zb$(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}}C0();import{createHash as Hb$}from"crypto";var QzA=H.object({entityType:H.string().describe("Entity type to publish (e.g., social-post, post, deck)"),id:H.string().optional().describe("Entity ID to publish"),slug:H.string().optional().describe("Entity slug to publish"),confirmed:H.boolean().optional(),confirmationToken:H.string().optional(),contentHash:H.string().optional(),expiresAt:H.string().datetime().optional()}),Wb$=H.object({entityType:H.string(),id:H.string().optional(),slug:H.string().optional(),confirmed:H.boolean().optional(),confirmationToken:H.string().optional(),contentHash:H.string().optional(),expiresAt:H.string().datetime().optional()}),Kb$=H.object({success:H.literal(!0),message:H.string().optional(),data:H.object({entityType:H.string().optional(),entityId:H.string().optional(),platformId:H.string().optional(),url:H.string().optional()}).optional()}),Ub$=H.object({success:H.literal(!1),error:H.string(),code:H.string().optional()}),Gb$=H.object({success:H.literal(!1).optional(),error:H.string().optional(),needsConfirmation:H.literal(!0),toolName:H.string(),summary:H.string(),preview:H.string().optional(),args:H.unknown()}),$zA=H.union([Kb$,Ub$,Gb$]),Db$=900000;function zn(A,Q,$,w){let B=w??new qn({context:A,providerRegistry:$}),X=`${Q}_publish`;return{name:X,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:QzA.shape,outputSchema:$zA,visibility:"anchor",sideEffects:"external",handler:async(Y,Z)=>{let W=Wb$.safeParse(Y);if(!W.success)return{success:!1,error:`Invalid input: ${W.error.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ")}`};let K=W.data,{entityType:U,id:G,slug:D}=K;try{A.permissions.assertEntityActionAllowed(U,"publish",Z)}catch(F){return{success:!1,error:F instanceof Error?F.message:String(F)}}let q=await B.resolveCandidate({entityType:U,id:G,slug:D});if("error"in q)return{success:!1,error:q.error};let{entity:J}=q;if(K.confirmed){let F=zb$(X,K,J);if(F!==null)return F;let I;try{I=await B.publish({entityType:U,id:J.id})}catch(k){return{success:!1,error:k instanceof Error?k.message:String(k)}}if("error"in I)return{success:!1,error:I.error};let{entity:P,result:j}=I;return{success:!0,data:{entityType:U,entityId:P.id,platformId:j.id,url:j.url},message:`Published ${U}:${P.id}`}}return qb$(X,K,J)}}}function qb$(A,Q,$){let w=new Date(Date.now()+Db$).toISOString(),B=eg2(A,$,w),X=Vb$($);return{needsConfirmation:!0,toolName:A,summary:`Publish "${X}"?`,preview:`This will publish ${$.entityType}:${$.id} to its registered public publish provider.`,args:{...Q,id:$.id,slug:void 0,confirmed:!0,confirmationToken:B,contentHash:$.contentHash,expiresAt:w}}}function zb$(A,Q,$){let{confirmationToken:w,contentHash:B,expiresAt:X}=Q;if(!w||!X)return{success:!1,error:"Invalid publish confirmation token. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};let Y=Date.parse(X);if(Number.isNaN(Y))return{success:!1,error:"Invalid publish confirmation expiry. Request confirmation again and retry with the returned confirmation args.",code:"INVALID_CONFIRMATION_TOKEN"};if(Y<=Date.now())return{success:!1,error:"Publish confirmation expired. Request confirmation again before publishing.",code:"EXPIRED_CONFIRMATION_TOKEN"};if(B&&B!==$.contentHash)return{success:!1,error:`Cannot publish ${$.entityType}:${$.id} because it changed after confirmation. Review it and try again.`};if(w!==eg2(A,$,X))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 eg2(A,Q,$){return Hb$("sha256").update(A).update("\x00").update(Q.entityType).update("\x00").update(Q.id).update("\x00").update(Q.contentHash).update("\x00").update($).digest("hex")}function Vb$(A){let Q=A.metadata.title;if(typeof Q==="string"&&Q.length>0)return Q;let $=A.metadata.subject;if(typeof $==="string"&&$.length>0)return $;let w=A.metadata.slug;if(typeof w==="string"&&w.length>0)return w;return A.id}KA();C0();var wzA=H.object({entityType:H.string().min(1).describe("Entity type to reconcile"),status:H.string().min(1).optional().describe("Optional metadata status filter, e.g. published"),assetType:H.string().min(1).optional().describe("Optional attachment type filter, e.g. og-image")}),BzA=H.object({success:H.literal(!0),data:H.object({entityType:H.string(),assetType:H.string().optional(),checkedEntities:H.number(),checkedAssets:H.number(),enqueued:H.number(),skipped:H.number()}),message:H.string().optional()});function Lj0(A,Q,$,w){return{...p8(Q,"ensure-assets","Reconcile configured publish assets for existing entities, queueing missing generated assets such as OG images.",wzA,async(X,Y)=>{if(A.permissions.assertEntityActionAllowed(X.entityType,"publish",Y),$.list(X.entityType).filter((D)=>D.autoGenerate===!0).filter((D)=>!X.assetType||D.attachmentType===X.assetType).length===0)return{success:!0,data:{entityType:X.entityType,...X.assetType&&{assetType:X.assetType},checkedEntities:0,checkedAssets:0,enqueued:0,skipped:0},message:`No publish assets configured for ${X.entityType}`};let W=await A.entityService.listEntities({entityType:X.entityType,options:{...X.status&&{filter:{metadata:{status:X.status}}}}}),K=0,U=0,G=0;for(let D of W){let q=await w.ensureForEntity(D,{...X.assetType&&{attachmentType:X.assetType}});K+=q.checked,U+=q.enqueued,G+=q.skipped}return{success:!0,data:{entityType:X.entityType,...X.assetType&&{assetType:X.assetType},checkedEntities:W.length,checkedAssets:K,enqueued:U,skipped:G},message:`Queued ${U} publish asset job(s)`}},{sideEffects:"writes"}),outputSchema:BzA}}KA();_4();C0();var Jb$="content-pipeline.queue.v1",XzA=1024,Fb$=/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/,Ib$=H.object({interfaceType:H.string().optional(),userId:H.string().optional(),userPermissionLevel:H.enum(["public","trusted","anchor"]).optional(),authorization:H.enum(["user","system"]).optional()}),Lb$=H.object({entityType:H.string(),entityId:H.string(),rank:H.number().int().positive(),queuedAt:H.string().datetime(),contentHashAtEnqueue:H.string(),authContext:Ib$,revision:H.number().int().positive()});class YzA{context;queueManager;store;mutationTail=Promise.resolve();constructor(A,Q){this.context=A,this.queueManager=Q,this.store=A.runtimeState.scoped({namespace:Jb$,schema:Lb$})}async add(A,Q,$=OP){return this.enqueue(A,Q,$)}async enqueue(A,Q,$=OP){return this.runExclusive(async()=>{let w=await this.requireEntity(A,Q);await this.persistStatus(w,"queued");let B=await this.queueManager.add(A,Q,$);if(!await this.store.get(Tq(A,Q))){let Y=(await this.queueManager.list(A)).find((W)=>W.entityId===Q),Z=await this.requireEntity(A,Q);await this.store.set(Tq(A,Q),{entityType:A,entityId:Q,rank:B.position*XzA,queuedAt:Y?.queuedAt??new Date().toISOString(),contentHashAtEnqueue:Z.contentHash,authContext:{...$},revision:1})}return B})}async remove(A,Q){await this.runExclusive(async()=>{let $=await this.requireEntity(A,Q);if($.metadata.status==="queued")await this.persistStatus($,"draft");await this.queueManager.remove(A,Q),await this.store.delete(Tq(A,Q)),await this.persistCurrentOrder(A)})}async reorder(A,Q,$){await this.runExclusive(async()=>{await this.requireEntity(A,Q),await this.queueManager.reorder(A,Q,$),await this.persistCurrentOrder(A)})}async complete(A,Q){await this.runExclusive(async()=>{await this.queueManager.remove(A,Q),await this.store.delete(Tq(A,Q)),await this.persistCurrentOrder(A)})}async fail(A,Q,$){await this.runExclusive(async()=>{let w=await this.context.entityService.getEntity({entityType:A,id:Q});if(w)await this.persistStatus(w,"failed",$);await this.queueManager.remove(A,Q),await this.store.delete(Tq(A,Q)),await this.persistCurrentOrder(A)})}async reconcile(A){await this.runExclusive(async()=>{let Q=new Map;for(let W of A){let K=await this.context.entityService.listEntities({entityType:W,options:{filter:{metadata:{status:"queued"}}}});for(let U of K)Q.set(Tq(W,U.id),U)}let $=await this.listStored();for(let W of $)if(!Q.has(Tq(W.entityType,W.entityId)))await this.store.delete(Tq(W.entityType,W.entityId));let w=(await this.listStored()).filter((W)=>Q.has(Tq(W.entityType,W.entityId))),B=new Map;for(let W of w)B.set(W.entityType,Math.max(B.get(W.entityType)??0,W.rank));for(let[W,K]of Q){if(w.some((G)=>Tq(G.entityType,G.entityId)===W))continue;let U=(B.get(K.entityType)??0)+XzA;B.set(K.entityType,U),await this.store.set(W,{entityType:K.entityType,entityId:K.id,rank:U,queuedAt:typeof K.updated==="string"?K.updated:new Date().toISOString(),contentHashAtEnqueue:K.contentHash,authContext:{...OP},revision:1})}let X=await this.listStored(),Y=new Map,Z=X.map((W)=>{let K=(Y.get(W.entityType)??0)+1;return Y.set(W.entityType,K),{entityType:W.entityType,entityId:W.entityId,position:K,queuedAt:W.queuedAt,authContext:{...W.authContext}}});this.queueManager.replace(Z)})}async listStored(A){return(await this.store.list()).map((Q)=>Q.value).filter((Q)=>!A||Q.entityType===A).sort((Q,$)=>Q.entityType.localeCompare($.entityType)||Q.rank-$.rank||Q.queuedAt.localeCompare($.queuedAt)||Q.entityId.localeCompare($.entityId))}async deleteStored(A,Q){return this.store.delete(Tq(A,Q))}async persistCurrentOrder(A){let Q=new Map((await this.listStored(A)).map(($)=>[$.entityId,$]));for(let $ of await this.queueManager.list(A)){let w=Q.get($.entityId);if(!w)continue;let B=$.position*XzA;if(w.rank===B)continue;await this.store.set(Tq(A,$.entityId),{...w,rank:B,revision:w.revision+1})}}async persistStatus(A,Q,$){let w={...A.metadata,status:Q};if($)w.error=$;else delete w.error;let B=Fb$.test(A.content)?zX(A.content,"status",Q):A.content;await this.context.entityService.updateEntity({entity:{...A,metadata:w,content:B}})}async requireEntity(A,Q){let $=await this.context.entityService.getEntity({entityType:A,id:Q});if(!$)throw Error(`Entity not found: ${A}:${Q}`);return $}runExclusive(A){let Q=this.mutationTail.then(A);return this.mutationTail=Q.then(()=>{return},()=>{return}),Q}}function Tq(A,Q){return`${encodeURIComponent(A)}/${encodeURIComponent(Q)}`}function AS2(A,Q){Nb$(A,Q),_b$(A,Q),Pb$(A,Q),kb$(A,Q)}function Nb$(A,Q){A.messaging.subscribe(fY.REGISTER,async($)=>jb$(Q,$.payload)),A.messaging.subscribe(fY.QUEUE,async($)=>fb$(A,Q,$.payload)),A.messaging.subscribe(fY.DIRECT,async($)=>xb$(A,Q,$.payload)),A.messaging.subscribe(fY.REMOVE,async($)=>Rb$(Q,$.payload)),A.messaging.subscribe(fY.REORDER,async($)=>vb$(Q,$.payload)),A.messaging.subscribe(fY.LIST,async($)=>Cb$(A,Q,$.payload)),A.messaging.subscribe(fY.REPORT_SUCCESS,async($)=>hb$(Q,$.payload)),A.messaging.subscribe(fY.REPORT_FAILURE,async($)=>Eb$(Q,$.payload)),A.messaging.subscribe(fY.COMPLETED,async($)=>{return await Q.publicationQueueService.complete($.payload.entityType,$.payload.entityId),{success:!0}}),A.messaging.subscribe(fY.FAILED,async($)=>{return await Q.publicationQueueService.fail($.payload.entityType,$.payload.entityId,$.payload.error),{success:!0}}),Q.logger.debug("Subscribed to publish messages")}function _b$(A,Q){A.messaging.subscribe(Af.REPORT_SUCCESS,async($)=>Tb$(Q,$.payload)),A.messaging.subscribe(Af.REPORT_FAILURE,async($)=>yb$(Q,$.payload)),Q.logger.debug("Subscribed to generation messages")}function Pb$(A,Q){A.messaging.subscribe(mg2.REGISTER,async($)=>Mb$(Q,$.payload)),Q.logger.debug("Subscribed to publish asset messages")}function kb$(A,Q){let $=async(w)=>bb$(A,Q,w.payload);A.messaging.subscribe("entity:created",$),A.messaging.subscribe("entity:updated",$),Q.logger.debug("Subscribed to entity change messages for publish assets")}async function jb$(A,Q){let{entityType:$,provider:w,config:B}=Q;try{let X=B?ug2.safeParse(B):void 0;if(X&&!X.success)return A.logger.warn("Invalid publish provider config",{entityType:$,error:X.error.message}),{success:!1};if(w)A.providerRegistry.register($,w,X?.data),A.logger.info(`Registered provider for entity type: ${$}`,{providerName:w.name,executionMode:A.providerRegistry.getExecutionMode($)});return{success:!0}}catch(X){let Y=aA(X);return A.logger.error(`Failed to register provider: ${Y}`),{success:!1}}}async function Mb$(A,Q){let $=Jj0.safeParse(Q);if(!$.success)return A.logger.warn("Invalid publish asset registration",{error:$.error.message}),{success:!1};return A.publishAssetRegistry.register($.data),A.logger.info("Registered publish asset",{entityType:$.data.entityType,attachmentType:$.data.attachmentType,mediaEntityType:$.data.mediaEntityType}),{success:!0}}async function bb$(A,Q,$){try{if(Q.publishAssetRegistry.list($.entityType).length===0)return{success:!0};let w=$.entity??await A.entityService.getEntity({entityType:$.entityType,id:$.entityId});if(!Ob$(w))return{success:!0};return await Q.publishAssetPreflight.ensureForEntity(w),{success:!0}}catch(w){return Q.logger.warn("Failed to run publish asset preflight for entity event",{entityType:$.entityType,entityId:$.entityId,error:aA(w)}),{success:!1}}}function Ob$(A){if(!A)return!1;let Q=Sg2.safeParse(A.metadata);return Q.success&&Q.data.status==="published"}async function fb$(A,Q,$){let{entityType:w,entityId:B}=$;try{let X=$.authContext??OP;A.permissions.assertEntityActionAllowed(w,"publish",X);let Y=await Q.publicationQueueService.enqueue(w,B,X);return await A.messaging.send({type:fY.QUEUED,payload:{entityType:w,entityId:B,position:Y.position}}),Q.logger.debug(`Entity queued: ${B}`,{entityType:w,position:Y.position}),{success:!0}}catch(X){let Y=aA(X);return Q.logger.error(`Failed to queue entity: ${Y}`),{success:!1}}}async function xb$(A,Q,$){let{entityType:w,entityId:B}=$,X=$.authContext??OP;try{if(A.permissions.assertEntityActionAllowed(w,"publish",X),!Q.providerRegistry.has(w))return Q.scheduler.failPublish(w,B,`No publish provider registered for ${w}`),{success:!1};let Y=await Q.publishExecutor.publish({entityType:w,id:B});if("error"in Y)return Q.scheduler.failPublish(w,B,Y.error),{success:!1};return Q.scheduler.completePublish(w,B,Y.result),Q.logger.debug(`Direct publish completed: ${B}`,{entityType:w}),{success:!0}}catch(Y){let Z=aA(Y);return Q.logger.error(`Failed direct publish request: ${Z}`),{success:!1}}}async function Rb$(A,Q){let{entityType:$,entityId:w}=Q;try{return await A.publicationQueueService.remove($,w),A.logger.debug(`Entity removed from queue: ${w}`,{entityType:$}),{success:!0}}catch(B){let X=aA(B);return A.logger.error(`Failed to remove entity: ${X}`),{success:!1}}}async function vb$(A,Q){let{entityType:$,entityId:w,position:B}=Q;try{return await A.publicationQueueService.reorder($,w,B),A.logger.debug(`Entity reordered: ${w}`,{entityType:$,newPosition:B}),{success:!0}}catch(X){let Y=aA(X);return A.logger.error(`Failed to reorder entity: ${Y}`),{success:!1}}}async function Cb$(A,Q,$){let{entityType:w}=$;try{let B=await Q.queueManager.list(w);return await A.messaging.send({type:fY.LIST_RESPONSE,payload:{entityType:w,queue:B.map((X)=>({entityId:X.entityId,position:X.position,queuedAt:X.queuedAt}))}}),{success:!0}}catch(B){let X=aA(B);return Q.logger.error(`Failed to list queue: ${X}`),{success:!1}}}async function hb$(A,Q){let{entityType:$,entityId:w,result:B}=Q;return A.scheduler.completePublish($,w,B),A.logger.info(`Publish reported success: ${w}`,{entityType:$}),{success:!0}}async function Eb$(A,Q){let{entityType:$,entityId:w,error:B}=Q;A.scheduler.failPublish($,w,B);let X=A.retryTracker.getRetryInfo(w);return A.logger.info(`Publish reported failure: ${w}`,{entityType:$,error:B,retryCount:X?.retryCount}),{success:!0}}async function Tb$(A,Q){let{entityType:$,entityId:w}=Q;return A.scheduler.completeGeneration($,w),A.logger.info("Generation completed",{entityType:$,entityId:w}),{success:!0}}async function yb$(A,Q){let{entityType:$,error:w}=Q;return A.scheduler.failGeneration($,w),A.logger.warn("Generation failed",{entityType:$,error:w}),{success:!0}}async function QS2(A,Q,$,w){try{if(w.skipIfDraftExists!==!1){if((await A.listEntities({entityType:$,options:{filter:{metadata:{status:"draft"}},limit:1}})).length>0)return{shouldGenerate:!1,reason:"Draft already exists"}}if(w.maxUnpublishedDrafts!==void 0){let B=await A.listEntities({entityType:$,options:{filter:{metadata:{status:"draft"}},limit:w.maxUnpublishedDrafts+1}});if(B.length>=w.maxUnpublishedDrafts)return{shouldGenerate:!1,reason:`Max unpublished drafts reached (${B.length}/${w.maxUnpublishedDrafts})`}}if(w.minSourceEntities!==void 0&&w.sourceEntityType){let B=await A.listEntities({entityType:w.sourceEntityType,options:{publishedOnly:!0,limit:w.minSourceEntities}});if(B.length<w.minSourceEntities)return{shouldGenerate:!1,reason:`Not enough source entities (${B.length}/${w.minSourceEntities} ${w.sourceEntityType})`}}return{shouldGenerate:!0}}catch(B){return Q.error("Failed to check generation conditions",{entityType:$,error:aA(B)}),{shouldGenerate:!1,reason:`Condition check failed: ${aA(B)}`}}}function $S2(A){let{context:Q,config:$,queueManager:w,providerRegistry:B,retryTracker:X,publishExecutor:Y,logger:Z}=A,W=gb$(Q);return UI.createFresh({queueManager:w,providerRegistry:B,retryTracker:X,logger:Z,backend:new Sv({onOverlapSkipped:(K)=>{Z.debug("Skipping overlapping content scheduler cycle",{jobKey:K})},onCallbackError:(K,U)=>{Z.error("Unhandled content scheduler callback error",{jobKey:K,error:U})}}),...$.entitySchedules&&{entitySchedules:$.entitySchedules},...$.generationSchedules&&{generationSchedules:$.generationSchedules},...$.generationConditions&&{generationConditions:$.generationConditions},messageBus:W,publishExecutor:Y,onCheckGenerationConditions:(K,U)=>QS2(Q.entityService,Z,K,U)})}function gb$(A){return{send:async(B)=>{return A.messaging.send({type:B.type,payload:B.payload,...B.target!==void 0?{target:B.target}:{},...B.metadata!==void 0?{metadata:B.metadata}:{},...B.broadcast!==void 0?{broadcast:B.broadcast}:{}})},subscribe:()=>()=>{},unsubscribe:()=>{}}}C0();C0();var Sb$=H.enum(["draft","queued","published","failed"]),mb$=H.object({entityId:H.string(),entityType:H.string(),title:H.string(),position:H.number().int().positive(),queuedAt:H.string(),destination:H.string(),scheduledFor:H.string().optional()}),ub$=H.object({id:H.string(),label:H.string(),target:H.string(),status:H.enum(["pending","processing"])}),cb$=H.object({entityId:H.string(),entityType:H.string(),title:H.string(),error:H.string(),retryCount:H.number().int().nonnegative()}),pb$=H.object({summary:H.object({draft:H.number().int().nonnegative(),queued:H.number().int().nonnegative(),generating:H.number().int().nonnegative(),failed:H.number().int().nonnegative(),published:H.number().int().nonnegative(),needsOperator:H.number().int().nonnegative()}),queue:H.array(mb$),generating:H.array(ub$),failures:H.array(cb$),publishableEntityTypes:H.array(H.string())}),lb$=H.object({sourceEntityType:H.string(),sourceEntityId:H.string(),attachmentType:H.string().optional()});async function Nj0(A,Q,$,w){let B=Q.getRegisteredTypes().sort(),X=new Map,Y={draft:0,queued:0,generating:0,failed:0,published:0,needsOperator:0};for(let U of B){let G=await A.entityService.listEntities({entityType:U});for(let D of G){let q=Sb$.safeParse(D.metadata.status);if(!q.success)continue;Y[q.data]+=1;let J=D.metadata.scheduledFor,F=D.metadata.error;X.set(wS2(U,D.id),{entityId:D.id,entityType:U,title:ib$(D.id,D.metadata),status:q.data,...typeof J==="string"?{scheduledFor:J}:{},...typeof F==="string"?{error:F}:{}})}}let Z=[];for(let U of B){let G=Q.get(U).name;for(let D of await $.list(U)){let q=X.get(wS2(U,D.entityId));if(!q)continue;Z.push({entityId:D.entityId,entityType:U,title:q.title,position:D.position,queuedAt:D.queuedAt,destination:G,...q.scheduledFor?{scheduledFor:q.scheduledFor}:{}})}}let W=await db$(A);Y.generating=W.length;let K=Array.from(X.values()).filter((U)=>U.status==="failed").map((U)=>{let G=w.getRetryInfo(U.entityId);return{entityId:U.entityId,entityType:U.entityType,title:U.title,error:U.error??G?.lastError??"Publication failed",retryCount:G?.retryCount??0}}).sort((U,G)=>U.title.localeCompare(G.title));return Y.needsOperator=Y.draft+Y.failed,pb$.parse({summary:Y,queue:Z,generating:W,failures:K,publishableEntityTypes:B})}async function db$(A){let Q=[];for(let $ of await A.jobs.getActiveJobs()){if($.source!=="content-pipeline")continue;if($.status!=="pending"&&$.status!=="processing")continue;let w;try{w=JSON.parse($.data)}catch{continue}let B=lb$.safeParse(w);if(!B.success)continue;Q.push({id:$.id,label:B.data.attachmentType??$.type,target:`${B.data.sourceEntityType}/${B.data.sourceEntityId}`,status:$.status})}return Q}function wS2(A,Q){return`${A}\x00${Q}`}function ib$(A,Q){for(let $ of["title","subject","slug"]){let w=Q[$];if(typeof w==="string"&&w.length>0)return w}return A}async function BS2(A,Q,$){await A.messaging.send({type:"dashboard:register-widget",payload:{id:"publication-pipeline",pluginId:Q,title:"Publication Pipeline",group:"publishing",section:"secondary",priority:100,rendererName:"PipelineWidget",visibility:"anchor",dataProvider:async()=>({...await Nj0(A,$.providerRegistry,$.queueManager,$.retryTracker),...$.managementUrl?{managementUrl:$.managementUrl}:{}}),digestProvider:rb$}})}var nb$=H.object({summary:H.object({draft:H.number(),queued:H.number(),generating:H.number(),published:H.number(),failed:H.number(),needsOperator:H.number()})});function rb$(A){let{summary:Q}=nb$.parse(A),$=Q.queued+Q.generating,w=$===0?"idle":`${Q.queued} queued \xB7 ${Q.generating} generating`,B=Q.failed>0?`${Q.draft} drafts \xB7 ${Q.failed} failed`:`${Q.draft} drafts`;return{digest:[{label:"Pipeline",value:w,...$>0?{tone:"warn"}:{}},{label:"Awaiting review",value:B,...Q.needsOperator>0?{tone:"warn"}:{}},{label:"Published",value:String(Q.published),tone:"good"}],needsOperator:Q.needsOperator}}KA();C0();var ob$=H.object({workspaceUrl:H.string()}),sb$=H.object({confirmed:H.literal(!0),confirmationToken:H.string().min(1),contentHash:H.string().min(1),expiresAt:H.string().datetime()}),ab$=H.discriminatedUnion("type",[H.object({type:H.literal("queue"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1)}),H.object({type:H.literal("remove"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1)}),H.object({type:H.literal("retry"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1)}),H.object({type:H.literal("reorder"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1),position:H.number().int().positive()}),H.object({type:H.literal("publish"),entityType:H.string().trim().min(1),entityId:H.string().trim().min(1),confirmation:sb$.optional()})]);async function XS2(A,Q,$){let w=zn(A,Q,$.providerRegistry,$.publishExecutor),B={id:"publishing",pluginId:Q,label:"Publishing",rendererName:"PublishingWorkspace",entityTypes:$.providerRegistry.getRegisteredTypes(),dataProvider:()=>Nj0(A,$.providerRegistry,$.queueManager,$.retryTracker),actionHandler:async(Z,W)=>{let K=ab$.safeParse(Z);if(!K.success)throw Error("Invalid publishing workspace action");return tb$(A,$,w,K.data,W)}},X=await A.messaging.send({type:w00,payload:B});if(!("success"in X)||!X.success)return;let Y=ob$.safeParse(X.data);return Y.success?Y.data.workspaceUrl:void 0}async function tb$(A,Q,$,w,B){if(!Q.providerRegistry.has(w.entityType))throw Error(`No publish provider registered for ${w.entityType}`);let X=await A.entityService.getEntity({entityType:w.entityType,id:w.entityId});if(!X)throw Error(`Entity not found: ${w.entityType}:${w.entityId}`);if(w.type==="publish"){let W=await $.handler({entityType:w.entityType,id:w.entityId,...w.confirmation??{}},B);if("success"in W&&W.success===!0)await Q.publicationQueueService.complete(w.entityType,w.entityId),Q.retryTracker.clearRetries(w.entityId);return W}let Y=w.type==="queue"||w.type==="retry"?"publish":"update";A.permissions.assertEntityActionAllowed(w.entityType,Y,B);let Z=X.metadata.status;switch(w.type){case"queue":if(Z!=="draft")throw Error("Only draft entities can be queued");return Q.publicationQueueService.enqueue(w.entityType,w.entityId,{...B,authorization:"user"});case"remove":if(Z!=="queued")throw Error("Only queued entities can be removed from the queue");return await Q.publicationQueueService.remove(w.entityType,w.entityId),{success:!0};case"retry":if(Z!=="failed")throw Error("Only failed publications can be retried");return await Q.publicationQueueService.enqueue(w.entityType,w.entityId,{...B,authorization:"user"}),{success:!0};case"reorder":if(Z!=="queued")throw Error("Only queued entities can be reordered");return await Q.publicationQueueService.reorder(w.entityType,w.entityId,w.position),{success:!0}}}var YS2={name:"@brains/content-pipeline",version:"0.2.0-alpha.184",description:"Content pipeline plugin for managing entity publishing queues, scheduling, and generation",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/scheduler":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14",typescript:"^7.0.2"},exports:{".":{types:"./src/index.ts",default:"./src/index.ts"}},files:["src"],main:"src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"src/index.ts"};class ZzA extends p6{pluginContext;queueManager;publicationQueueService;providerRegistry;retryTracker;publishExecutor;publishAssetRegistry;publishAssetPreflight;scheduler;constructor(A={}){super("content-pipeline",YS2,A,cg2)}async onRegister(A){this.pluginContext=A,this.queueManager=WI.createFresh(),this.publicationQueueService=new YzA(A,this.queueManager),this.providerRegistry=KI.createFresh(),this.retryTracker=GI.createFresh(),this.publishAssetRegistry=DI.createFresh(),this.publishAssetPreflight=new Fj0({context:A,registry:this.publishAssetRegistry}),this.publishExecutor=new qn({context:A,providerRegistry:this.providerRegistry,publishAssetPreflight:this.publishAssetPreflight}),this.scheduler=$S2({context:A,config:this.config,queueManager:this.queueManager,providerRegistry:this.providerRegistry,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor,logger:this.logger}),AS2(A,{queueManager:this.queueManager,publicationQueueService:this.publicationQueueService,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 this.publicationQueueService.reconcile(this.providerRegistry.getRegisteredTypes());let Q=await XS2(A,this.id,{providerRegistry:this.providerRegistry,queueManager:this.queueManager,publicationQueueService:this.publicationQueueService,retryTracker:this.retryTracker,publishExecutor:this.publishExecutor});await BS2(A,this.id,{providerRegistry:this.providerRegistry,queueManager:this.queueManager,retryTracker:this.retryTracker,...Q?{managementUrl:Q}:{}}),await this.scheduler.start(),this.logger.info("Content pipeline plugin started")}async getTools(){if(!this.pluginContext)throw Error("Plugin context not initialized");return[Ij0(this.pluginContext,this.id,this.queueManager,this.publicationQueueService),zn(this.pluginContext,this.id,this.providerRegistry,this.publishExecutor),Lj0(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}getPublicationQueueService(){return this.publicationQueueService}getProviderRegistry(){return this.providerRegistry}getRetryTracker(){return this.retryTracker}getPublishAssetRegistry(){return this.publishAssetRegistry}getScheduler(){return this.scheduler}async onShutdown(){await this.scheduler.stop(),WI.resetInstance(),KI.resetInstance(),GI.resetInstance(),DI.resetInstance()}}function HzA(A={}){return new ZzA(A)}KA();C0();var ZS2=H.object({accountId:H.string().describe("Cloudflare account ID"),apiToken:H.string().describe("Cloudflare API token with Analytics:Read permission"),siteTag:H.string().describe("Cloudflare Web Analytics site tag")}),WzA=H.object({cloudflare:ZS2.optional()});KA();C0();var AO$=H.object({date:H.string().describe("Single date in YYYY-MM-DD format").optional(),days:H.number().min(1).max(365).describe("Number of days back from yesterday (e.g., 7 for last week)").optional(),startDate:H.string().describe("Start date in YYYY-MM-DD format (use with endDate)").optional(),endDate:H.string().describe("End date in YYYY-MM-DD format (use with startDate)").optional(),limit:H.number().min(1).max(100).default(20).describe("Maximum items for breakdowns (pages, referrers, countries)")});function QO$(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 HS2(A,Q,$){let w=[];if(!$)return w;return w.push(p8(A,"query",`Query website analytics from Cloudflare.
8004
8004
 
8005
8005
  Date range options (use only one):
8006
8006
  - No params: yesterday only
@@ -8138,7 +8138,7 @@ Returns pageviews, visitors, top pages, referrers, devices, and countries.`,AO$,
8138
8138
  }
8139
8139
  }
8140
8140
  }
8141
- `,{...this.baseVariables(A),limit:A.limit??20})).map((w)=>({country:w.dimensions.countryName,visits:w.sum.visits}))}}var UzA=7,$O$=10;function KS2(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=Yz0(),$=gD1(UzA),w=Oc($),B=Oc(Q);try{let[X,Y]=await Promise.all([A.getWebsiteStats({startDate:w,endDate:B}),A.getTopPages({startDate:w,endDate:B,limit:$O$})]);return{days:UzA,startDate:w,endDate:B,pageviews:X.pageviews,visitors:X.visitors,topPages:Y}}catch(X){return{error:X instanceof Error?X.message:"Failed to fetch analytics",days:UzA}}}}var US2={name:"@brains/analytics",version:"0.2.0-alpha.183",description:"Analytics plugin for collecting website and social media metrics",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class GS2 extends p6{cloudflareClient;constructor(A={}){super("analytics",US2,A,WzA)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new KzA(this.config.cloudflare):void 0,A.insights.register("traffic-overview",KS2(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:WS2(Q)}})}async getTools(){return HS2(this.id,this.getContext(),this.cloudflareClient)}}function BO$(A={}){return new GS2(A)}var _j0=BO$;KA();C0();KA();C0();import{join as DO$}from"path";S2();var DS2="note",XO$=new Set(["description","excerpt","summary","tagline","story"]);function YO$(A){if(A.endsWith("s"))return A;return Dz(A)}function _50(A){return A===DS2}function qS2(A,Q){let $=A===DS2?"Note":dk(A),w=Q?.label??$;return{label:w,pluralLabel:Q?.pluralName??YO$(w)}}function L50(A){return typeof A==="object"&&A!==null}function WT(A){if(!L50(A))return;let Q=A.def;return L50(Q)?Q:void 0}function zS2(A){let Q=WT(A)?.type;return typeof Q==="string"?Q:void 0}function ZO$(A){return typeof A==="function"?A():A}function GzA(A,Q=!1,$){let w=zS2(A),B=WT(A);if(w==="optional"||w==="nullable")return GzA(B?.innerType,!0,$);if(w==="default")return GzA(B?.innerType,!0,ZO$(B?.defaultValue));let X={inner:A,isOptional:Q};if($!==void 0)X.defaultValue=$;return X}function HO$(A){let Q=WT(A)?.entries;if(!L50(Q))return;let $=Object.values(Q);return $.every((w)=>typeof w==="string")?$:void 0}function WO$(A){let Q=WT(A)?.values;return Array.isArray(Q)?Q[0]:void 0}function KO$(A){let Q=WT(A)?.checks;if(!Array.isArray(Q))return!1;return Q.some(($)=>{return WT($)?.format==="datetime"})}function UO$(A){return A==="imageId"||A.endsWith("ImageId")}function GO$(A){if(!L50(A))return;let Q=A.shape;return L50(Q)?Q:void 0}function N50(A,Q){let{inner:$,isOptional:w,defaultValue:B}=GzA(Q),X=zS2($),Y=B??WO$($),Z={name:A,label:dk(A),widget:"string",...w&&{required:!1},...Y!==void 0&&{default:Y}};switch(X){case"string":{if(UO$(A))return{...Z,widget:"image"};if(KO$($))return{...Z,widget:"datetime"};if(XO$.has(A))return{...Z,widget:"text"};return{...Z,widget:"string"}}case"number":return{...Z,widget:"number"};case"boolean":return{...Z,widget:"boolean"};case"enum":{let W=HO$($);return{...Z,widget:"select",...W?{options:W}:{}}}case"array":{let W=WT($)?.element,K=N50("item",W);if(K.widget==="object"&&K.fields)return{...Z,widget:"list",fields:K.fields};return{...Z,widget:"list",field:{name:A,label:dk(A),widget:K.widget}}}case"object":{let W=Object.entries(GO$($)??{}).map(([K,U])=>N50(K,U));return{...Z,widget:"object",fields:W}}case"literal":return{...Z,widget:"string"};default:return{...Z,widget:"string"}}}function VS2(A){return`<!doctype html>
8141
+ `,{...this.baseVariables(A),limit:A.limit??20})).map((w)=>({country:w.dimensions.countryName,visits:w.sum.visits}))}}var UzA=7,$O$=10;function KS2(A){return async()=>{if(!A)return{unavailable:!0,reason:"Cloudflare analytics not configured"};let Q=Yz0(),$=gD1(UzA),w=Oc($),B=Oc(Q);try{let[X,Y]=await Promise.all([A.getWebsiteStats({startDate:w,endDate:B}),A.getTopPages({startDate:w,endDate:B,limit:$O$})]);return{days:UzA,startDate:w,endDate:B,pageviews:X.pageviews,visitors:X.visitors,topPages:Y}}catch(X){return{error:X instanceof Error?X.message:"Failed to fetch analytics",days:UzA}}}}var US2={name:"@brains/analytics",version:"0.2.0-alpha.184",description:"Analytics plugin for collecting website and social media metrics",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};class GS2 extends p6{cloudflareClient;constructor(A={}){super("analytics",US2,A,WzA)}async onRegister(A){this.cloudflareClient=this.config.cloudflare?new KzA(this.config.cloudflare):void 0,A.insights.register("traffic-overview",KS2(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:WS2(Q)}})}async getTools(){return HS2(this.id,this.getContext(),this.cloudflareClient)}}function BO$(A={}){return new GS2(A)}var _j0=BO$;KA();C0();KA();C0();import{join as DO$}from"path";S2();var DS2="note",XO$=new Set(["description","excerpt","summary","tagline","story"]);function YO$(A){if(A.endsWith("s"))return A;return Dz(A)}function _50(A){return A===DS2}function qS2(A,Q){let $=A===DS2?"Note":dk(A),w=Q?.label??$;return{label:w,pluralLabel:Q?.pluralName??YO$(w)}}function L50(A){return typeof A==="object"&&A!==null}function WT(A){if(!L50(A))return;let Q=A.def;return L50(Q)?Q:void 0}function zS2(A){let Q=WT(A)?.type;return typeof Q==="string"?Q:void 0}function ZO$(A){return typeof A==="function"?A():A}function GzA(A,Q=!1,$){let w=zS2(A),B=WT(A);if(w==="optional"||w==="nullable")return GzA(B?.innerType,!0,$);if(w==="default")return GzA(B?.innerType,!0,ZO$(B?.defaultValue));let X={inner:A,isOptional:Q};if($!==void 0)X.defaultValue=$;return X}function HO$(A){let Q=WT(A)?.entries;if(!L50(Q))return;let $=Object.values(Q);return $.every((w)=>typeof w==="string")?$:void 0}function WO$(A){let Q=WT(A)?.values;return Array.isArray(Q)?Q[0]:void 0}function KO$(A){let Q=WT(A)?.checks;if(!Array.isArray(Q))return!1;return Q.some(($)=>{return WT($)?.format==="datetime"})}function UO$(A){return A==="imageId"||A.endsWith("ImageId")}function GO$(A){if(!L50(A))return;let Q=A.shape;return L50(Q)?Q:void 0}function N50(A,Q){let{inner:$,isOptional:w,defaultValue:B}=GzA(Q),X=zS2($),Y=B??WO$($),Z={name:A,label:dk(A),widget:"string",...w&&{required:!1},...Y!==void 0&&{default:Y}};switch(X){case"string":{if(UO$(A))return{...Z,widget:"image"};if(KO$($))return{...Z,widget:"datetime"};if(XO$.has(A))return{...Z,widget:"text"};return{...Z,widget:"string"}}case"number":return{...Z,widget:"number"};case"boolean":return{...Z,widget:"boolean"};case"enum":{let W=HO$($);return{...Z,widget:"select",...W?{options:W}:{}}}case"array":{let W=WT($)?.element,K=N50("item",W);if(K.widget==="object"&&K.fields)return{...Z,widget:"list",fields:K.fields};return{...Z,widget:"list",field:{name:A,label:dk(A),widget:K.widget}}}case"object":{let W=Object.entries(GO$($)??{}).map(([K,U])=>N50(K,U));return{...Z,widget:"object",fields:W}}case"literal":return{...Z,widget:"string"};default:return{...Z,widget:"string"}}}function VS2(A){return`<!doctype html>
8142
8142
  <html lang="en" data-climate="paper">
8143
8143
  <head>
8144
8144
  <meta charset="utf-8" />
@@ -8196,7 +8196,7 @@ ${Vd}
8196
8196
  </html>`}var qO$=DO$(import.meta.dir,"..","dist","ui","cms-app.js"),zO$=H.object({entityType:H.string(),id:H.string(),frontmatter:H.record(H.string(),H.unknown()),body:H.string().optional(),baseContentHash:H.string().optional()}),VO$=H.object({entityType:H.string(),frontmatter:H.record(H.string(),H.unknown()),body:H.string().optional()}),JO$=H.object({id:H.string().trim().min(1),action:H.unknown()}),DzA={entityType:H.string(),body:H.string(),frontmatter:H.record(H.string(),H.unknown())},FO$=H.union([H.object({...DzA,variant:H.literal("rewrite").optional(),instruction:H.string().trim().min(1),selection:H.string().min(1).max(8000)}),H.object({...DzA,variant:H.literal("summarise"),targetField:H.string().trim().min(1),body:H.string().min(1)}),H.object({...DzA,variant:H.literal("tag-suggest"),targetField:H.string().trim().min(1),body:H.string().min(1)})]),JS2=H.object({suggestion:H.string()}),IO$=H.object({suggestions:H.array(H.string().trim().min(1)).max(12)}),LO$=H.object({selection:H.string().min(1).max(8000),instruction:H.string().trim().min(1).max(2000),agent:H.string().trim().min(1).max(253)}),NO$=H.looseObject({response:H.string()}),_O$=H.object({agents:H.array(H.object({id:H.string(),label:H.string()}))}),PO$="file",FS2=10485760,kO$=H.object({watchEnabled:H.boolean(),lastSync:H.string().nullable(),git:H.object({branch:H.string(),hasChanges:H.boolean(),ahead:H.number(),behind:H.number(),lastCommit:H.string().nullable(),remote:H.string().nullable()}).nullable()});function IS2(A){let{routePath:Q,getContext:$,resolveOperatorSession:w,getEntityDisplay:B,workspaceRegistry:X}=A,Y=`${Q}/assets/app.js`,Z=(K)=>`${Q}/api/${K}`,W=async(K)=>await w(K)?null:FQ({error:"Operator session required"},401);return[{path:Q,method:"GET",public:!0,handler:async(K)=>{if(!await w(K))return new Response(null,{status:302,headers:{Location:`/login?return_to=${encodeURIComponent(Q)}`,"Cache-Control":"no-store"}});return new Response(VS2({assetPath:Y,surfaces:WO($().webRoutes.getRoutes(),{activeId:"cms",self:{id:"cms",href:Q}}),sessionHref:`/logout?return_to=${encodeURIComponent(Q)}`}),{headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}})}},{path:Y,method:"GET",public:!0,handler:async()=>{let K=Bun.file(qO$);if(!await K.exists())return new Response("CMS editor UI asset not built",{status:404});return new Response(K,{headers:{"Content-Type":"text/javascript; charset=utf-8","Cache-Control":"no-cache"}})}},{path:Z("types"),method:"GET",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return MO$($(),B(),X)}},{path:Z("workspace"),method:"GET",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return bO$(X,K)}},{path:Z("workspace"),method:"POST",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return OO$(X,K)}},{path:Z("schema"),method:"GET",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return fO$($(),K)}},{path:Z("entities"),method:"GET",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return xO$($(),K)}},{path:Z("entities"),method:"PUT",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return RO$($(),K)}},{path:Z("entities"),method:"POST",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return vO$($(),K)}},{path:Z("entities"),method:"DELETE",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return CO$($(),K)}},{path:Z("upload"),method:"POST",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return yO$($(),K,Z("upload"))}},{path:Z("assist"),method:"POST",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return hO$($(),K)}},{path:Z("agents"),method:"GET",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return EO$($())}},{path:Z("ask-agent"),method:"POST",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return TO$($(),K)}},{path:Z("sync-status"),method:"GET",public:!0,handler:async(K)=>{let U=await W(K);if(U)return U;return jO$($())}}]}async function jO$(A){let Q={directorySync:null,git:null},$=await A.messaging.send({type:"sync:status:request",payload:{}});if(!("success"in $)||!$.success)return FQ(Q);let w=kO$.safeParse($.data);if(!w.success)return FQ(Q);return FQ({directorySync:{lastSync:w.data.lastSync,watching:w.data.watchEnabled},git:w.data.git})}async function MO$(A,Q,$){let w=new Map((await A.entityService.getEntityCounts()).map((X)=>[X.entityType,X.count])),B=A.entityService.getEntityTypes().flatMap((X)=>{if(!A.entities.getEffectiveFrontmatterSchema(X))return[];let Z=A.entities.getAdapter(X);return[{entityType:X,label:qS2(X,Q?.[X]).pluralLabel,isSingleton:Z?.isSingleton===!0,hasBody:Z?.hasBody!==!1,count:w.get(X)??0}]});return FQ({types:B,workspaces:$.listDescriptors()})}async function bO$(A,Q){let $=new URL(Q.url).searchParams.get("id");if(!$)return FQ({error:"id query parameter is required"},400);let w=A.get($);if(!w)return FQ({error:`Unknown CMS workspace: ${$}`},404);try{return FQ({workspace:{id:w.id,rendererName:w.rendererName,data:await w.dataProvider()}})}catch(B){return FQ({error:B instanceof Error?B.message:"CMS workspace data provider failed"},502)}}async function OO$(A,Q){let $;try{$=JO$.parse(await Q.json())}catch{return FQ({error:"Invalid workspace action payload"},400)}let w=A.get($.id);if(!w)return FQ({error:`Unknown CMS workspace: ${$.id}`},404);if(!w.actionHandler)return FQ({error:`CMS workspace ${$.id} does not provide actions`},405);let B={interfaceType:"cms",userId:"operator",userPermissionLevel:"anchor"};try{return FQ({result:await w.actionHandler($.action,B)})}catch(X){return FQ({error:X instanceof Error?X.message:"CMS workspace action failed"},400)}}function fO$(A,Q){let $=new URL(Q.url).searchParams.get("type");if(!$)return FQ({error:"type query parameter is required"},400);let w=A.entities.getEffectiveFrontmatterSchema($);if(!w)return FQ({error:`Unknown entity type: ${$}`},404);let B=A.entities.getAdapter($),X=_50($),Y=X?[]:Object.entries(w.shape).map(([Z,W])=>N50(Z,W));return FQ({entityType:$,format:X?"raw":"frontmatter",isSingleton:B?.isSingleton===!0,hasBody:X||B?.hasBody!==!1,fields:Y})}async function xO$(A,Q){let $=new URL(Q.url).searchParams,w=$.get("type");if(!w)return FQ({error:"type query parameter is required"},400);if(!A.entities.getEffectiveFrontmatterSchema(w))return FQ({error:`Unknown entity type: ${w}`},404);let B=$.get("id");if(B){let Y=await A.entityService.getEntity({entityType:w,id:B});if(!Y)return FQ({error:`Entity not found: ${B}`},404);let{frontmatter:Z,body:W}=qzA(w,Y.content);return FQ({entity:{id:Y.id,entityType:Y.entityType,frontmatter:Z,body:W,contentHash:Y.contentHash,created:Y.created,updated:Y.updated}})}let X=await A.entityService.listEntities({entityType:w});return FQ({entities:X.map((Y)=>({id:Y.id,entityType:Y.entityType,frontmatter:qzA(w,Y.content).frontmatter,updated:Y.updated}))})}async function RO$(A,Q){let $;try{$=zO$.parse(await Q.json())}catch{return FQ({error:"Invalid update payload"},400)}let{entityType:w,id:B}=$,X=A.entities.getEffectiveFrontmatterSchema(w);if(!X)return FQ({error:`Unknown entity type: ${w}`},404);let Y=LS2(A,w,$.body);if(Y)return Y;let Z=_50(w);if(Z&&Object.keys($.frontmatter).length>0)return FQ({error:`Entity type ${w} is raw markdown without frontmatter`},400);let W=Z?{success:!0,data:{}}:X.safeParse($.frontmatter);if(!W.success)return FQ({error:"Invalid frontmatter",issues:W.error.issues},400);let K=await A.entityService.getEntity({entityType:w,id:B});if(!K)return FQ({error:`Entity not found: ${B}`},404);if($.baseContentHash!==void 0&&$.baseContentHash!==K.contentHash)return FQ({error:"This entry changed since it was opened \u2014 likely updated by "+"another writer (an agent, or a git import via directory-sync). Reload to review before saving again.",currentContentHash:K.contentHash},409);let U=$.body??qzA(w,K.content).body,G=Z?U:O7(U,W.data),D=A.entities.getAdapter(w)?.fromMarkdown(G),q={...K,...D,id:K.id,entityType:K.entityType,content:G},J=await A.entityService.updateEntity({entity:q});return FQ({entityId:J.entityId,jobId:J.jobId,skipped:J.skipped})}async function vO$(A,Q){let $;try{$=VO$.parse(await Q.json())}catch{return FQ({error:"Invalid create payload"},400)}let{entityType:w}=$,B=A.entities.getEffectiveFrontmatterSchema(w);if(!B)return FQ({error:`Unknown entity type: ${w}`},404);let X=LS2(A,w,$.body);if(X)return X;let Y=_50(w);if(Y&&Object.keys($.frontmatter).length>0)return FQ({error:`Entity type ${w} is raw markdown without frontmatter`},400);let Z=Y?{success:!0,data:{}}:B.safeParse($.frontmatter);if(!Z.success)return FQ({error:"Invalid frontmatter",issues:Z.error.issues},400);let W=Y?$.body??"":O7($.body??"",Z.data),K=A.entities.getAdapter(w)?.fromMarkdown(W),U=await A.entityService.createEntity({entity:{...K,entityType:w,content:W,metadata:K?.metadata??{}}});return FQ({entityId:U.entityId,jobId:U.jobId},201)}async function CO$(A,Q){let $=new URL(Q.url).searchParams,w=$.get("type"),B=$.get("id");if(!w||!B)return FQ({error:"type and id query parameters are required"},400);if(!await A.entityService.getEntity({entityType:w,id:B}))return FQ({error:`Entity not found: ${B}`},404);let Y=await A.entityService.deleteEntity({entityType:w,id:B});return FQ({deleted:Y})}async function hO$(A,Q){let $;try{$=FO$.parse(await Q.json())}catch{return FQ({error:"Invalid assist payload or selection length"},400)}let w=A.entities.getEffectiveFrontmatterSchema($.entityType);if(!w)return FQ({error:`Unknown entity type: ${$.entityType}`},404);if($.variant==="summarise"||$.variant==="tag-suggest"){let Y=w.shape[$.targetField];if(!Y)return FQ({error:`Unknown frontmatter field: ${$.targetField}`},400);let Z=N50($.targetField,Y);if(!($.variant==="summarise"?Z.widget==="string"||Z.widget==="text":Z.widget==="list"&&Z.field?.widget==="string"))return FQ({error:`Field ${$.targetField} is incompatible with ${$.variant}`},400);let K=["You are editing CMS frontmatter from an existing markdown body.",`Entity type: ${$.entityType}`,`Target field: ${$.targetField}`,`Existing frontmatter JSON: ${JSON.stringify($.frontmatter)}`,"","Full markdown body:",$.body];if($.variant==="summarise"){let{object:G}=await A.ai.generateObject(["Summarise the body for the target frontmatter field.","Return only the field value in the suggestion field.",...K].join(`
8197
8197
  `),JS2);return FQ({variant:$.variant,targetField:$.targetField,suggestion:G.suggestion})}let{object:U}=await A.ai.generateObject(["Suggest tags for the target frontmatter field.","Return concise tag strings in the suggestions field without duplicates.",...K].join(`
8198
8198
  `),IO$);return FQ({variant:$.variant,targetField:$.targetField,suggestions:[...new Set(U.suggestions)]})}let B=["You are editing markdown for the CMS.","Rewrite only the selected text according to the instruction.","Return only replacement markdown in the suggestion field.","Do not include commentary, code fences, or unchanged surrounding body text.","",`Entity type: ${$.entityType}`,`Frontmatter JSON: ${JSON.stringify($.frontmatter)}`,`Instruction: ${$.instruction}`,"","Selected markdown:",$.selection,"","Full body for context:",$.body].join(`
8199
- `),{object:X}=await A.ai.generateObject(B,JS2);return FQ({suggestion:X.suggestion})}async function EO$(A){let Q=await A.messaging.send({type:"a2a:call:agents",payload:{}});if(!("success"in Q)||!Q.success)return FQ({agents:[]});let $=_O$.safeParse(Q.data);return FQ($.success?$.data:{agents:[]})}async function TO$(A,Q){let $;try{$=LO$.parse(await Q.json())}catch{return FQ({error:"Invalid agent ask payload or selection length"},400)}let w=await A.messaging.send({type:"a2a:call:request",payload:$});if(!("success"in w)||!w.success){let X="error"in w&&typeof w.error==="string"?w.error:"Agent call failed",Y=X.startsWith("No handler found");return FQ({error:Y?"Agent asking is unavailable":X},Y?503:400)}if(w.data===void 0)return FQ({error:"Agent asking is unavailable"},503);let B=NO$.safeParse(w.data);if(!B.success)return FQ({error:"Invalid response from agent"},502);return FQ({agentId:$.agent,response:B.data.response})}async function yO$(A,Q,$){let w=Number(Q.headers.get("content-length"));if(Number.isFinite(w)&&w>FS2)return FQ({error:"Upload too large"},400);let B;try{B=await Q.formData()}catch{return FQ({error:"Invalid multipart upload"},400)}let X=B.get(PO$);if(!(X instanceof File))return FQ({error:"Missing upload file"},400);if(X.size>FS2)return FQ({error:"Upload too large"},400);let Y=A.entities.getUploadSaveHandler(X.type);if(!Y)return FQ({error:`No handler accepts uploads of type ${X.type}`},415);let W=await A.uploads.scoped({namespace:"upload",refKind:"upload",routePath:$}).save({filename:X.name,mediaType:X.type,content:Buffer.from(await X.arrayBuffer())}),K=await Y.handler({upload:{kind:"upload",id:W.id}},{interfaceType:"cms",userId:"operator"});if(!K.success)return FQ({error:K.error},502);return FQ({entityId:K.data.entityId,jobId:K.data.jobId},201)}function LS2(A,Q,$){if($===void 0)return null;if(A.entities.getAdapter(Q)?.hasBody===!1)return FQ({error:`Entity type ${Q} does not have a body`},400);return null}function qzA(A,Q){if(_50(A))return{frontmatter:{},body:Q};try{let $=_Q(Q,H.record(H.string(),H.unknown()));return{frontmatter:$.metadata,body:$.content}}catch{return{frontmatter:{},body:Q}}}function FQ(A,Q=200){return new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}})}C0();var gO$=H.object({id:H.string().trim().min(1),pluginId:H.string().trim().min(1),label:H.string().trim().min(1),rendererName:H.literal("PublishingWorkspace"),entityTypes:H.array(H.string().trim().min(1)).default([]),dataProvider:H.custom((A)=>typeof A==="function",{message:"Expected CMS workspace data provider function"}),actionHandler:H.custom((A)=>typeof A==="function",{message:"Expected CMS workspace action handler function"}).optional()});class zzA{workspaces=new Map;register(A){let Q=gO$.parse(A),$={id:Q.id,pluginId:Q.pluginId,label:Q.label,rendererName:Q.rendererName,entityTypes:Q.entityTypes,dataProvider:Q.dataProvider,...Q.actionHandler?{actionHandler:Q.actionHandler}:{}};return this.workspaces.set($.id,$),$}get(A){return this.workspaces.get(A)}listDescriptors(){return Array.from(this.workspaces.values()).map(({id:A,pluginId:Q,label:$,rendererName:w,entityTypes:B})=>({id:A,pluginId:Q,label:$,rendererName:w,entityTypes:B}))}}var NS2={name:"@brains/cms",version:"0.2.0-alpha.183",description:"CMS plugin for config and browser authoring routes",dependencies:{"@brains/auth-service":"workspace:*","@brains/console-theme":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@codemirror/lang-markdown":"^6.5.0","@codemirror/language":"^6.12.4","@codemirror/state":"^6.7.1","@codemirror/view":"^6.43.6","@lezer/highlight":"^1.2.3","@tanstack/react-query":"^5.0.0",react:"^19.2.7","react-dom":"^19.2.7",streamdown:"^2.5.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/react":"^19.2.17","@types/react-dom":"^19.0.3","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json"},type:"module"};var mO$=H.looseObject({label:H.string().optional(),pluralName:H.string().optional()}),uO$=H.object({entityDisplay:H.record(H.string(),mO$).optional(),routePath:H.string().default("/cms")});class VzA extends p6{workspaceRegistry=new zzA;constructor(A={}){super("cms",NS2,A,uO$)}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"}),A.messaging.subscribe(w00,async(Q)=>{try{let $=this.workspaceRegistry.register(Q.payload);return{success:!0,data:{workspaceUrl:`${this.config.routePath}#/workspace/${encodeURIComponent($.id)}`}}}catch($){return{success:!1,error:$ instanceof Error?$.message:String($)}}})}getWebRoutes(){return IS2({routePath:this.config.routePath,getContext:()=>this.getContext(),resolveOperatorSession:cO$,getEntityDisplay:()=>this.config.entityDisplay??this.getContext().entityDisplay,workspaceRegistry:this.workspaceRegistry})}}function KT(A={}){return new VzA(A)}async function cO$(A){return Boolean(await UY()?.getOperatorSession(A))}KA();C0();KA();C0();var Pj0=["StatsWidget","ListWidget","CustomWidget","PipelineWidget","IdentityWidget","ProfileWidget","SystemWidget"],pO$=new Set(Pj0),lO$=H.enum(["public","trusted","anchor"]);function JzA(A){return pO$.has(A)}var _S2=H.object({label:H.string(),value:H.string(),tone:H.enum(["plain","good","warn"]).optional()}),PS2=H.object({id:H.string(),pluginId:H.string(),title:H.string(),description:H.string().optional(),group:H.string().min(1),priority:H.number().default(50),section:H.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:H.string(),visibility:lO$.default("public"),needsOperator:H.number().int().nonnegative().optional(),digest:H.array(_S2).max(4).optional()});class kj0{widgets=new Map;logger;constructor(A){this.logger=A.child("DashboardWidgetRegistry")}register(A){let $={...PS2.parse(A),dataProvider:A.dataProvider,...A.digestProvider?{digestProvider:A.digestProvider}:{},...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{}},w=`${$.pluginId}:${$.id}`;this.widgets.set(w,$),this.logger.debug("Dashboard widget registered",{key:w,title:$.title,rendererName:$.rendererName,group:$.group})}unregister(A,Q){if(Q){this.widgets.delete(`${A}:${Q}`);return}for(let $ of this.widgets.keys())if($.startsWith(`${A}:`))this.widgets.delete($)}get(A,Q){return this.widgets.get(`${A}:${Q}`)}list(A={}){let Q=typeof A==="string"?{section:A}:A,$=Q.permissionLevel??"public";return Array.from(this.widgets.values()).filter((w)=>!Q.section||w.section===Q.section).filter((w)=>P4.hasPermission($,w.visibility)).sort((w,B)=>w.priority-B.priority)}get size(){return this.widgets.size}}class jj0{id="dashboard:dashboard";name="Dashboard DataSource";description="Aggregates dashboard widgets from all plugins";registry;logger;constructor(A,Q){this.registry=A,this.logger=Q.child("DashboardDataSource")}async getDashboardData(A={}){let Q={},$=A.widgets??this.registry.list({...A.permissionLevel!==void 0&&{permissionLevel:A.permissionLevel}}),w=await Promise.allSettled($.map(async(B)=>{let X=await B.dataProvider(),{dataProvider:Y,digestProvider:Z,component:W,clientScript:K,visibility:U="public",...G}=B;return{key:`${B.pluginId}:${B.id}`,widget:{...G,visibility:U,...this.deriveLiveDigest(B,X)},data:X}}));for(let B=0;B<w.length;B++){let X=w[B],Y=$[B];if(!X||!Y)continue;if(X.status==="fulfilled")Q[X.value.key]={widget:X.value.widget,data:X.value.data};else this.logger.error("Widget data provider failed",{widgetId:Y.id,pluginId:Y.pluginId,error:aA(X.reason)})}return{widgets:Q}}deriveLiveDigest(A,Q){if(!A.digestProvider)return{};try{let $=A.digestProvider(Q);return{...$.digest!==void 0&&{digest:$.digest},...$.needsOperator!==void 0&&{needsOperator:$.needsOperator}}}catch($){return this.logger.error("Widget digest provider failed",{widgetId:A.id,pluginId:A.pluginId,error:aA($)}),{}}}async fetch(A,Q,$){return await this.getDashboardData()}}import{render as Ff$}from"preact-render-to-string";var kS2=`* { margin: 0; padding: 0; box-sizing: border-box; }
8199
+ `),{object:X}=await A.ai.generateObject(B,JS2);return FQ({suggestion:X.suggestion})}async function EO$(A){let Q=await A.messaging.send({type:"a2a:call:agents",payload:{}});if(!("success"in Q)||!Q.success)return FQ({agents:[]});let $=_O$.safeParse(Q.data);return FQ($.success?$.data:{agents:[]})}async function TO$(A,Q){let $;try{$=LO$.parse(await Q.json())}catch{return FQ({error:"Invalid agent ask payload or selection length"},400)}let w=await A.messaging.send({type:"a2a:call:request",payload:$});if(!("success"in w)||!w.success){let X="error"in w&&typeof w.error==="string"?w.error:"Agent call failed",Y=X.startsWith("No handler found");return FQ({error:Y?"Agent asking is unavailable":X},Y?503:400)}if(w.data===void 0)return FQ({error:"Agent asking is unavailable"},503);let B=NO$.safeParse(w.data);if(!B.success)return FQ({error:"Invalid response from agent"},502);return FQ({agentId:$.agent,response:B.data.response})}async function yO$(A,Q,$){let w=Number(Q.headers.get("content-length"));if(Number.isFinite(w)&&w>FS2)return FQ({error:"Upload too large"},400);let B;try{B=await Q.formData()}catch{return FQ({error:"Invalid multipart upload"},400)}let X=B.get(PO$);if(!(X instanceof File))return FQ({error:"Missing upload file"},400);if(X.size>FS2)return FQ({error:"Upload too large"},400);let Y=A.entities.getUploadSaveHandler(X.type);if(!Y)return FQ({error:`No handler accepts uploads of type ${X.type}`},415);let W=await A.uploads.scoped({namespace:"upload",refKind:"upload",routePath:$}).save({filename:X.name,mediaType:X.type,content:Buffer.from(await X.arrayBuffer())}),K=await Y.handler({upload:{kind:"upload",id:W.id}},{interfaceType:"cms",userId:"operator"});if(!K.success)return FQ({error:K.error},502);return FQ({entityId:K.data.entityId,jobId:K.data.jobId},201)}function LS2(A,Q,$){if($===void 0)return null;if(A.entities.getAdapter(Q)?.hasBody===!1)return FQ({error:`Entity type ${Q} does not have a body`},400);return null}function qzA(A,Q){if(_50(A))return{frontmatter:{},body:Q};try{let $=_Q(Q,H.record(H.string(),H.unknown()));return{frontmatter:$.metadata,body:$.content}}catch{return{frontmatter:{},body:Q}}}function FQ(A,Q=200){return new Response(JSON.stringify(A),{status:Q,headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}})}C0();var gO$=H.object({id:H.string().trim().min(1),pluginId:H.string().trim().min(1),label:H.string().trim().min(1),rendererName:H.literal("PublishingWorkspace"),entityTypes:H.array(H.string().trim().min(1)).default([]),dataProvider:H.custom((A)=>typeof A==="function",{message:"Expected CMS workspace data provider function"}),actionHandler:H.custom((A)=>typeof A==="function",{message:"Expected CMS workspace action handler function"}).optional()});class zzA{workspaces=new Map;register(A){let Q=gO$.parse(A),$={id:Q.id,pluginId:Q.pluginId,label:Q.label,rendererName:Q.rendererName,entityTypes:Q.entityTypes,dataProvider:Q.dataProvider,...Q.actionHandler?{actionHandler:Q.actionHandler}:{}};return this.workspaces.set($.id,$),$}get(A){return this.workspaces.get(A)}listDescriptors(){return Array.from(this.workspaces.values()).map(({id:A,pluginId:Q,label:$,rendererName:w,entityTypes:B})=>({id:A,pluginId:Q,label:$,rendererName:w,entityTypes:B}))}}var NS2={name:"@brains/cms",version:"0.2.0-alpha.184",description:"CMS plugin for config and browser authoring routes",dependencies:{"@brains/auth-service":"workspace:*","@brains/console-theme":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*","@codemirror/lang-markdown":"^6.5.0","@codemirror/language":"^6.12.4","@codemirror/state":"^6.7.1","@codemirror/view":"^6.43.6","@lezer/highlight":"^1.2.3","@tanstack/react-query":"^5.0.0",react:"^19.2.7","react-dom":"^19.2.7",streamdown:"^2.5.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","@types/react":"^19.2.17","@types/react-dom":"^19.0.3","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{build:"bun scripts/build-ui.ts","build:ui":"bun scripts/build-ui.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit && tsc --noEmit -p ui-react/tsconfig.json"},type:"module"};var mO$=H.looseObject({label:H.string().optional(),pluralName:H.string().optional()}),uO$=H.object({entityDisplay:H.record(H.string(),mO$).optional(),routePath:H.string().default("/cms")});class VzA extends p6{workspaceRegistry=new zzA;constructor(A={}){super("cms",NS2,A,uO$)}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"}),A.messaging.subscribe(w00,async(Q)=>{try{let $=this.workspaceRegistry.register(Q.payload);return{success:!0,data:{workspaceUrl:`${this.config.routePath}#/workspace/${encodeURIComponent($.id)}`}}}catch($){return{success:!1,error:$ instanceof Error?$.message:String($)}}})}getWebRoutes(){return IS2({routePath:this.config.routePath,getContext:()=>this.getContext(),resolveOperatorSession:cO$,getEntityDisplay:()=>this.config.entityDisplay??this.getContext().entityDisplay,workspaceRegistry:this.workspaceRegistry})}}function KT(A={}){return new VzA(A)}async function cO$(A){return Boolean(await UY()?.getOperatorSession(A))}KA();C0();KA();C0();var Pj0=["StatsWidget","ListWidget","CustomWidget","PipelineWidget","IdentityWidget","ProfileWidget","SystemWidget"],pO$=new Set(Pj0),lO$=H.enum(["public","trusted","anchor"]);function JzA(A){return pO$.has(A)}var _S2=H.object({label:H.string(),value:H.string(),tone:H.enum(["plain","good","warn"]).optional()}),PS2=H.object({id:H.string(),pluginId:H.string(),title:H.string(),description:H.string().optional(),group:H.string().min(1),priority:H.number().default(50),section:H.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:H.string(),visibility:lO$.default("public"),needsOperator:H.number().int().nonnegative().optional(),digest:H.array(_S2).max(4).optional()});class kj0{widgets=new Map;logger;constructor(A){this.logger=A.child("DashboardWidgetRegistry")}register(A){let $={...PS2.parse(A),dataProvider:A.dataProvider,...A.digestProvider?{digestProvider:A.digestProvider}:{},...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{}},w=`${$.pluginId}:${$.id}`;this.widgets.set(w,$),this.logger.debug("Dashboard widget registered",{key:w,title:$.title,rendererName:$.rendererName,group:$.group})}unregister(A,Q){if(Q){this.widgets.delete(`${A}:${Q}`);return}for(let $ of this.widgets.keys())if($.startsWith(`${A}:`))this.widgets.delete($)}get(A,Q){return this.widgets.get(`${A}:${Q}`)}list(A={}){let Q=typeof A==="string"?{section:A}:A,$=Q.permissionLevel??"public";return Array.from(this.widgets.values()).filter((w)=>!Q.section||w.section===Q.section).filter((w)=>P4.hasPermission($,w.visibility)).sort((w,B)=>w.priority-B.priority)}get size(){return this.widgets.size}}class jj0{id="dashboard:dashboard";name="Dashboard DataSource";description="Aggregates dashboard widgets from all plugins";registry;logger;constructor(A,Q){this.registry=A,this.logger=Q.child("DashboardDataSource")}async getDashboardData(A={}){let Q={},$=A.widgets??this.registry.list({...A.permissionLevel!==void 0&&{permissionLevel:A.permissionLevel}}),w=await Promise.allSettled($.map(async(B)=>{let X=await B.dataProvider(),{dataProvider:Y,digestProvider:Z,component:W,clientScript:K,visibility:U="public",...G}=B;return{key:`${B.pluginId}:${B.id}`,widget:{...G,visibility:U,...this.deriveLiveDigest(B,X)},data:X}}));for(let B=0;B<w.length;B++){let X=w[B],Y=$[B];if(!X||!Y)continue;if(X.status==="fulfilled")Q[X.value.key]={widget:X.value.widget,data:X.value.data};else this.logger.error("Widget data provider failed",{widgetId:Y.id,pluginId:Y.pluginId,error:aA(X.reason)})}return{widgets:Q}}deriveLiveDigest(A,Q){if(!A.digestProvider)return{};try{let $=A.digestProvider(Q);return{...$.digest!==void 0&&{digest:$.digest},...$.needsOperator!==void 0&&{needsOperator:$.needsOperator}}}catch($){return this.logger.error("Widget digest provider failed",{widgetId:A.id,pluginId:A.pluginId,error:aA($)}),{}}}async fetch(A,Q,$){return await this.getDashboardData()}}import{render as Ff$}from"preact-render-to-string";var kS2=`* { margin: 0; padding: 0; box-sizing: border-box; }
8200
8200
  html, body { min-height: 100%; max-width: 100%; }
8201
8201
  body {
8202
8202
  font-family: var(--console-ui);
@@ -10077,7 +10077,7 @@ ${jS2}`;import{jsxDEV as UT,Fragment as bS2}from"preact/jsx-dev-runtime";functio
10077
10077
  activate(resolveId(window.location.hash), false);
10078
10078
  });
10079
10079
  })();`;function jf$({hiddenWidgetCount:A,loginUrl:Q}){return jA("section",{class:"card operator-gate",children:[jA("div",{children:[jA("div",{class:"card-title",children:"Operator access"},void 0,!1,void 0,this),jA("p",{children:[A===1?"1 private console widget is hidden.":`${A} private console widgets are hidden.`," ","","Sign in with your passkey to unlock the restricted layer."]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),jA("a",{class:"operator-gate-link",href:Q,children:"Sign in"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Mf$({dashboardPath:A,surfaces:Q,operatorAccess:$}){let w=$?.isOperator?$.logoutUrl:$?.loginUrl??"/login",B=$?.isOperator?"Operator":"Visitor",X=$?.isOperator?"Sign out":"Sign in";return jA("header",{class:"console-strip","aria-label":"Operator surfaces",children:[jA("a",{class:"console-mark",href:A,"aria-label":"Dashboard home",children:[jA("span",{class:"pulse"},void 0,!1,void 0,this),jA("span",{children:["Brain"," ",jA("span",{class:"console-mark-long",children:["\xB7 ",jA("b",{children:"Console"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),jA("nav",{class:"surface-nav","aria-label":"Console surfaces",children:Q.map((Y)=>jA("a",{class:Y.isActive?"surface-nav-link is-active":"surface-nav-link",href:Y.href,children:Y.label},Y.id,!1,void 0,this))},void 0,!1,void 0,this),jA("button",{class:"command-chip",type:"button","aria-label":"Search or jump",children:[jA("span",{class:"command-chip-hint",children:"Search or jump\u2026"},void 0,!1,void 0,this),jA("kbd",{children:"\u2318K"},void 0,!1,void 0,this),jA("span",{class:"command-chip-icon","aria-hidden":"true",children:"\u2315"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("button",{id:"climateToggle",class:"climate-chip",type:"button","aria-label":"Toggle climate",children:"\u25D0"},void 0,!1,void 0,this),jA("a",{class:$?.isOperator?"session-chip":"session-chip is-visitor",href:w,"aria-label":`${B} \xB7 ${X}`,children:[jA("span",{children:B},void 0,!1,void 0,this),jA("strong",{children:X},void 0,!1,void 0,this),jA("span",{class:"session-chip-avatar","aria-hidden":"true",children:$?.isOperator?"OP":"VI"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function bf$({tabs:A}){return jA("nav",{class:"dashboard-tabs","aria-label":"Dashboard sections",role:"tablist",children:[jA("a",{class:"dashboard-tab is-active",href:"#overview",role:"tab","aria-selected":"true","data-dashboard-tab-link":"overview",children:"Overview"},void 0,!1,void 0,this),A.map((Q)=>jA("a",{class:"dashboard-tab",href:`#${Q.id}`,role:"tab","aria-selected":"false","data-dashboard-tab-link":Q.id,children:[jA("span",{children:Q.label},void 0,!1,void 0,this),Q.needsOperator>0?jA("span",{class:"tab-badge tab-badge--needs",children:Q.needsOperator},void 0,!1,void 0,this):Q.widgetCount>0?jA("span",{class:"tab-badge tab-badge--muted",children:Q.widgetCount},void 0,!1,void 0,this):null]},Q.id,!0,void 0,this))]},void 0,!0,void 0,this)}function NzA(A){return A.indexStatus?.ready??A.indexReady??A.appInfo.embeddings>0}function Of$({input:A}){let Q=NzA(A),$=A.activityLog?.[0],w=A.appInfo.entityCounts.length,B=A.appInfo.interactions.map((G)=>G.id).slice(0,3).join(" / "),X=A.indexStatus?.embeddedEntities??A.appInfo.embeddings,Y=A.indexStatus?.embeddableEntities,Z=A.indexStatus?(A.indexStatus.activeEmbeddingJobs??0)+(A.indexStatus.missingEmbeddings??0)+(A.indexStatus.staleEmbeddings??0):0,W=Y===void 0?`${X}`:`${X}/${Y}`,K=Z>0?`${W} embedded \xB7 ${Z} queued`:`${W} embedded`,U=(A.jobProgress??[]).some((G)=>G.status==="processing"||G.status==="pending");return jA("section",{class:"overview-vitals","aria-label":"Runtime vitals",children:[jA("article",{class:"vital-card",children:[jA("span",{class:"vital-label",children:"Entities"},void 0,!1,void 0,this),jA("strong",{class:"vital-num",children:A.appInfo.entities},void 0,!1,void 0,this),jA("span",{class:"vital-sub",children:w===1?"1 type":`${w} types`},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("article",{class:"vital-card",children:[jA("span",{class:"vital-label",children:"Interactions"},void 0,!1,void 0,this),jA("strong",{class:"vital-num",children:A.appInfo.interactions.length},void 0,!1,void 0,this),jA("span",{class:"vital-sub",children:B||"no channels"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("article",{class:`vital-card ${Q?"vital-card--ok":"vital-card--warm"}`,children:[jA("span",{class:"vital-label",children:"Semantic index"},void 0,!1,void 0,this),jA("strong",{class:"vital-num vital-num--text",children:Q?"Ready":"Pending"},void 0,!1,void 0,this),jA("span",{class:"vital-sub",children:K},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("article",{class:`vital-card${U?" vital-card--warm":""}`,children:[jA("span",{class:"vital-label",children:"Last write"},void 0,!1,void 0,this),jA("strong",{class:"vital-num vital-num--text",children:$?_zA($.timestamp):"\u2014"},void 0,!1,void 0,this),jA("span",{class:"vital-sub",children:$?`${$.entityType}/${$.entityId}`:"no writes observed"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function ff$({input:A}){let{role:Q,purpose:$,values:w}=A.character;if(!Q&&!$&&w.length===0)return null;return jA("aside",{class:"card identity-capsule",children:[jA("div",{class:"card-head",children:[jA("span",{class:"card-title",children:"Identity"},void 0,!1,void 0,this),jA("span",{class:"card-from",children:"identity"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("div",{class:"identity-capsule-body",children:[Q&&jA("span",{class:"identity-role",children:["\u201C",Q,"\u201D"]},void 0,!0,void 0,this),w.length>0&&jA("span",{class:"values",children:w.map((B)=>jA("span",{class:"value",children:B},B,!1,void 0,this))},void 0,!1,void 0,this),$&&jA("span",{class:"identity-purpose",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function xf$({cards:A}){if(A.length===0)return jA("section",{class:"card overview-empty-digest",children:[jA("div",{class:"card-head",children:jA("span",{class:"card-title",children:"Group digests"},void 0,!1,void 0,this)},void 0,!1,void 0,this),jA("p",{class:"muted",children:"No plugin groups are visible yet."},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return jA("section",{class:"digests","aria-label":"Group digests",children:A.map((Q)=>jA("a",{class:"card digest-card",href:Q.href,children:[jA("div",{class:"digest-head",children:[jA("h4",{children:Q.label},void 0,!1,void 0,this),jA("span",{class:"digest-go",children:"open \u2192"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("dl",{class:"digest-lines",children:Q.lines.map(($)=>jA("div",{class:`digest-line digest-line--${$.tone??"plain"}`,children:[jA("dt",{children:$.label},void 0,!1,void 0,this),jA("dd",{children:$.value},void 0,!1,void 0,this)]},`${$.label}:${$.value}`,!0,void 0,this))},void 0,!1,void 0,this)]},Q.id,!0,void 0,this))},void 0,!1,void 0,this)}function Rf$(A){let Q=new Date(A);if(Number.isNaN(Q.getTime()))return"\u2014";return Q.toLocaleString("en",{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"})}function _zA(A){let Q=new Date(A);if(Number.isNaN(Q.getTime()))return"\u2014";return Q.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}var ES2={created:{glyph:"\uFF0B",tone:""},updated:{glyph:"\u2713",tone:" ledger-glyph--ok"},deleted:{glyph:"\u2212",tone:" ledger-glyph--warn"}};function vf$({events:A}){return jA("section",{class:"card activity-ledger",children:[jA("div",{class:"card-head",children:[jA("span",{class:"card-title",children:"Activity"},void 0,!1,void 0,this),jA("span",{class:"card-from",children:"entity events"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.length===0?jA("p",{class:"muted",children:"No entity activity has been observed this session."},void 0,!1,void 0,this):jA("ol",{class:"ledger",children:A.map((Q)=>jA("li",{class:"ledger-entry",children:[jA("time",{class:"ledger-time",dateTime:Q.timestamp,children:_zA(Q.timestamp)},void 0,!1,void 0,this),jA("span",{class:`ledger-glyph${ES2[Q.action].tone}`,"aria-hidden":"true",children:ES2[Q.action].glyph},void 0,!1,void 0,this),jA("span",{class:"ledger-what",children:[jA("b",{children:Q.entityType},void 0,!1,void 0,this)," ",Q.action," \u2014"," ",jA("code",{children:[Q.entityType,"/",Q.entityId]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},`${Q.timestamp}:${Q.action}:${Q.entityType}:${Q.entityId}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Cf$(A){let Q=(A.activeEmbeddingJobs??0)+(A.missingEmbeddings??0)+(A.staleEmbeddings??0);if(A.ready&&!A.degraded)return 100;if(A.ready)return 92;if(Q===0)return 50;return Math.max(8,Math.min(88,100-Q*12))}function hf$(A){return["Semantic index",A.ready?A.degraded?"ready, degraded":"ready":"pending",A.activeEmbeddingJobs!==void 0?`${A.activeEmbeddingJobs} active`:void 0,A.missingEmbeddings!==void 0?`${A.missingEmbeddings} missing`:void 0,A.staleEmbeddings!==void 0?`${A.staleEmbeddings} stale`:void 0,A.failedEmbeddings!==void 0?`${A.failedEmbeddings} failed`:void 0].filter(Boolean).join(" \xB7 ")}function Ef$({status:A}){let Q=Cf$(A),$=A.ready?A.degraded?"Degraded":"Ready":"Indexing";return jA("div",{class:"index-gauge",style:`--index-percent: ${Q}%`,children:[jA("div",{class:"index-gauge-ring","aria-hidden":"true",children:jA("span",{children:[Q,"%"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),jA("div",{class:"index-gauge-copy",children:[jA("strong",{children:$},void 0,!1,void 0,this),jA("span",{children:hf$(A)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function Tf$({input:A}){let Q=NzA(A);return jA("section",{class:"card semantic-index-card",children:[jA("div",{class:"card-head",children:[jA("span",{class:"card-title",children:"Semantic index"},void 0,!1,void 0,this),jA("span",{class:"card-from",children:"entity-service"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.indexStatus?jA(Ef$,{status:A.indexStatus},void 0,!1,void 0,this):jA("dl",{class:"kv",children:jA("div",{class:"kv-row",children:[jA("dt",{children:"Semantic index"},void 0,!1,void 0,this),jA("dd",{children:Q?"Ready":"Pending"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yf$({status:A}){let Q=A.totalFiles===void 0?"\u2014":A.totalFiles===1?"1 file":`${A.totalFiles} files`,$=A.byEntityType?Object.entries(A.byEntityType).sort(([,w],[,B])=>B-w).slice(0,2).map(([w,B])=>`${w} ${B}`).join(", "):void 0;return jA("section",{class:"card content-sync-card",children:[jA("div",{class:"card-head",children:[jA("span",{class:"card-title",children:"Content sync"},void 0,!1,void 0,this),jA("span",{class:"card-from",children:"directory-sync"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("dl",{class:"kv",children:[jA("div",{class:"kv-row",children:[jA("dt",{children:"Path"},void 0,!1,void 0,this),jA("dd",{children:A.syncPath},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("div",{class:"kv-row",children:[jA("dt",{children:"Files"},void 0,!1,void 0,this),jA("dd",{children:$?`${Q} \xB7 ${$}`:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("div",{class:"kv-row",children:[jA("dt",{children:"Watch"},void 0,!1,void 0,this),jA("dd",{children:A.watchEnabled?"Watching":A.isInitialized?"Manual":"Not initialized"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("div",{class:"kv-row",children:[jA("dt",{children:"Last sync"},void 0,!1,void 0,this),jA("dd",{children:A.lastSync?`last sync ${Rf$(A.lastSync)}`:"\u2014"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),jA("div",{class:"pipeline-mini","aria-label":"Write pipeline",children:[jA("span",{class:`pipeline-step${A.isInitialized?" is-done":""}`,children:"entity db"},void 0,!1,void 0,this),jA("span",{class:"pipeline-track"},void 0,!1,void 0,this),jA("span",{class:`pipeline-step${(A.totalFiles??0)>0?" is-done":""}`,children:"exported"},void 0,!1,void 0,this),jA("span",{class:"pipeline-track"},void 0,!1,void 0,this),jA("span",{class:`pipeline-step${A.lastSync?" is-done":""}`,children:"committed"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var gf$={pending:"run",processing:"run",completed:"done",failed:"fail"},Sf$={pending:"pending",processing:"running",completed:"done",failed:"failed"};function mf$({jobs:A}){return jA("section",{class:"card widget-card--wide job-queue-card",children:[jA("div",{class:"card-head",children:[jA("span",{class:"card-title",children:"Job queue"},void 0,!1,void 0,this),jA("span",{class:"card-from",children:"job-queue"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.length===0?jA("p",{class:"muted",children:"No recent job progress observed."},void 0,!1,void 0,this):jA("table",{class:"jobs",children:[jA("thead",{children:jA("tr",{children:[jA("th",{children:"Job"},void 0,!1,void 0,this),jA("th",{children:"Type"},void 0,!1,void 0,this),jA("th",{children:"Updated"},void 0,!1,void 0,this),jA("th",{children:"Status"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),jA("tbody",{children:A.map((Q)=>jA("tr",{children:[jA("td",{class:"mono",children:Q.id.slice(0,8)},void 0,!1,void 0,this),jA("td",{children:Q.jobType??Q.kind},void 0,!1,void 0,this),jA("td",{class:"mono",children:_zA(Q.updatedAt)},void 0,!1,void 0,this),jA("td",{children:jA("span",{class:`status-pill status-pill--${gf$[Q.status]}`,children:[Sf$[Q.status],Q.progressLabel?` \xB7 ${Q.progressLabel}`:""]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},`${Q.kind}:${Q.id}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function uf$({input:A,tabs:Q,showOperatorGate:$}){let w=Nf$(Q,A),B=A.activityLog??[];return jA("section",{id:"overview",class:"dashboard-tab-panel is-active","data-dashboard-tab-panel":!0,"aria-labelledby":"dashboard-tab-overview",children:[jA(Of$,{input:A},void 0,!1,void 0,this),jA(ff$,{input:A},void 0,!1,void 0,this),$&&A.operatorAccess&&jA(jf$,{hiddenWidgetCount:A.operatorAccess.hiddenWidgetCount,loginUrl:A.operatorAccess.loginUrl},void 0,!1,void 0,this),jA("div",{class:"overview-grid",children:[jA(xf$,{cards:w},void 0,!1,void 0,this),jA(vf$,{events:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function cf$({tab:A,input:Q,now:$}){let w=[...A.widgets.primary,...A.widgets.secondary],B=A.group==="system",X=A.group==="knowledge",Y=A.widgets.sidebar.length>0||B;return jA("section",{id:A.id,class:"dashboard-tab-panel","data-dashboard-tab-panel":!0,"data-dashboard-group":A.group,children:[jA("header",{class:"tab-section-head",children:jA("h2",{children:A.label},void 0,!1,void 0,this)},void 0,!1,void 0,this),jA("div",{class:`layout tab-layout${Y?"":" tab-layout--main-only"}`,children:[jA("div",{class:"main-column",children:[X&&jA(fS2,{total:Q.appInfo.entities,entityCounts:Q.appInfo.entityCounts},void 0,!1,void 0,this),B&&jA(TS2,{children:[jA(Tf$,{input:Q},void 0,!1,void 0,this),Q.directorySyncStatus&&jA(yf$,{status:Q.directorySyncStatus},void 0,!1,void 0,this),jA(mf$,{jobs:Q.jobProgress??[]},void 0,!1,void 0,this)]},void 0,!0,void 0,this),w.map((Z)=>jA(FzA,{widget:Z},`${Z.widget.pluginId}:${Z.widget.id}`,!1,void 0,this))]},void 0,!0,void 0,this),Y&&jA("div",{class:"sidebar-column",children:[B&&jA(TS2,{children:[jA(xS2,{endpoints:Q.appInfo.endpoints,baseUrl:Q.baseUrl},void 0,!1,void 0,this),jA(CS2,{appInfo:Q.appInfo,now:$},void 0,!1,void 0,this),jA(RS2,{interactions:Q.appInfo.interactions,baseUrl:Q.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.widgets.sidebar.map((Z)=>jA(FzA,{widget:Z},`${Z.widget.pluginId}:${Z.widget.id}`,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function pf$({input:A}){let Q=Pf$(A.widgets),$=A.operatorAccess&&!A.operatorAccess.isOperator&&A.operatorAccess.hiddenWidgetCount>0,w=A.dashboardPath??"/dashboard",B=new Date;return jA("html",{lang:"en","data-climate":"instrument",children:[jA("head",{children:[jA("meta",{charSet:"utf-8"},void 0,!1,void 0,this),jA("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0, viewport-fit=cover"},void 0,!1,void 0,this),jA("title",{children:A.title},void 0,!1,void 0,this),jA("link",{rel:"preconnect",href:"https://fonts.googleapis.com"},void 0,!1,void 0,this),jA("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"},void 0,!1,void 0,this),jA("link",{href:k$0,rel:"stylesheet"},void 0,!1,void 0,this),A.themeCSS!==void 0&&jA("style",{"data-dashboard-theme":!0,dangerouslySetInnerHTML:{__html:A.themeCSS}},void 0,!1,void 0,this),jA("style",{"data-dashboard-styles":!0,dangerouslySetInnerHTML:{__html:MS2}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("body",{children:[jA(Mf$,{dashboardPath:w,surfaces:A.surfaces??[{id:"dashboard",label:"Dashboard",href:w,isActive:!0}],operatorAccess:A.operatorAccess},void 0,!1,void 0,this),jA("main",{class:"console","data-component":"dashboard:dashboard",children:[jA("div",{class:"frame",children:[jA(OS2,{title:A.title,tagline:A.profile.description},void 0,!1,void 0,this),jA(bf$,{tabs:Q},void 0,!1,void 0,this),jA("div",{class:"canvas",children:jA("div",{class:"dashboard-tab-panels",children:[jA(uf$,{input:A,tabs:Q,showOperatorGate:Boolean($)},void 0,!1,void 0,this),Q.map((X)=>jA(cf$,{tab:X,input:A,now:B},X.id,!1,void 0,this))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA(hS2,{title:A.title,appInfo:A.appInfo,baseUrl:A.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),jA("script",{dangerouslySetInnerHTML:{__html:oh}},void 0,!1,void 0,this),jA("script",{dangerouslySetInnerHTML:{__html:sh}},void 0,!1,void 0,this),jA("script",{dangerouslySetInnerHTML:{__html:kf$}},void 0,!1,void 0,this),A.widgetScripts.map((X,Y)=>jA("script",{dangerouslySetInnerHTML:{__html:X}},`widget-script:${Y}`,!1,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}function gS2(A){return`<!doctype html>
10080
- ${Ff$(jA(pf$,{input:A},void 0,!1,void 0,this))}`}function lf$(A){return A.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"group"}function SS2(A){let Q=A.query.trim().toLowerCase(),$=[];if(A.cmsPath!==void 0&&A.entities.length>0){let B=A.cmsPath;$.push({id:"entities",label:"Entities",items:A.entities.map((X)=>({id:`${X.entityType}/${X.id}`,title:X.title,sub:X.entityType,href:`${B}#/${encodeURIComponent(X.entityType)}/${encodeURIComponent(X.id)}`,tag:"edit in cms"}))})}let w=Oj0([...new Set(A.groups)]).map((B)=>({group:B,label:Vn(B)})).filter(({group:B,label:X})=>Q===""||X.toLowerCase().includes(Q)||B.toLowerCase().includes(Q)).map(({group:B,label:X})=>({id:`tab/${B}`,title:X,sub:"tab",href:`${A.dashboardPath}#${lf$(B)}`,tag:"dashboard"}));if(w.length>0)$.push({id:"tabs",label:"Dashboard",items:w});return $}function mS2(A,Q){let $={},w=new Set;for(let[B,X]of Object.entries(A)){let Y=Q?.get(X.widget.pluginId,X.widget.id);if($[B]={...X,...Y?.component?{component:Y.component}:{}},Y?.clientScript)w.add(Y.clientScript)}return{widgets:$,widgetScripts:Array.from(w)}}var uS2={name:"@brains/dashboard",version:"0.2.0-alpha.183",description:"Dashboard plugin with extensible widget system",dependencies:{"@brains/auth-service":"workspace:*","@brains/console-theme":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2","preact-render-to-string":"^6.7.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var if$=H.object({version:H.string().default("1.0.0"),routePath:H.string().default("/dashboard"),themeCSS:H.string().optional()}),nf$=H.object({id:H.string(),pluginId:H.string(),title:H.string(),description:H.string().optional(),group:H.string().min(1),priority:H.number().default(50),section:H.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:H.string(),visibility:H.enum(["public","trusted","anchor"]).default("public"),needsOperator:H.number().int().nonnegative().optional(),digest:H.array(H.object({label:H.string(),value:H.string(),tone:H.enum(["plain","good","warn"]).optional()})).max(4).optional(),component:H.custom().optional(),clientScript:H.string().optional(),dataProvider:H.custom((A)=>typeof A==="function",{message:"Expected dashboard widget data provider function"}),digestProvider:H.custom((A)=>typeof A==="function",{message:"Expected dashboard widget digest provider function"}).optional()}).superRefine((A,Q)=>{if(!JzA(A.rendererName)&&!A.component)Q.addIssue({code:"custom",message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),rf$=H.object({pluginId:H.string(),widgetId:H.string().optional()}),of$=H.object({entityType:H.string(),entityId:H.string(),conversationId:H.string().optional()}),sf$=H.object({id:H.string(),type:H.enum(["job","batch"]),status:H.enum(["pending","processing","completed","failed"]),message:H.string().optional(),progress:H.object({current:H.number(),total:H.number(),percentage:H.number()}).optional(),jobDetails:H.object({jobType:H.string(),priority:H.number(),retryCount:H.number()}).optional()}),af$=H.object({success:H.literal(!0),data:H.object({syncPath:H.string(),isInitialized:H.boolean(),watchEnabled:H.boolean(),lastSync:H.string().datetime().optional(),totalFiles:H.number().int().nonnegative().optional(),byEntityType:H.record(H.string(),H.number().int().nonnegative()).optional()})});function tf$(A){return{id:A.id,pluginId:A.pluginId,title:A.title,...A.description?{description:A.description}:{},group:A.group,priority:A.priority,section:A.section,rendererName:A.rendererName,visibility:A.visibility,...A.needsOperator!==void 0&&{needsOperator:A.needsOperator},...A.digest?{digest:A.digest}:{},...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider,...A.digestProvider?{digestProvider:A.digestProvider}:{}}}class PzA extends p6{widgetRegistry=null;datasource=null;siteUrl;ctx;activityLog=[];jobProgress=[];constructor(A={}){super("dashboard",uS2,A,if$)}recordActivity(A,Q){let $=of$.safeParse(Q);if(!$.success)return;this.activityLog=[{action:A,entityType:$.data.entityType,entityId:$.data.entityId,timestamp:new Date().toISOString(),...$.data.conversationId?{conversationId:$.data.conversationId}:{}},...this.activityLog].slice(0,12)}recordJobProgress(A){let Q=sf$.safeParse(A);if(!Q.success)return;let $=Q.data.progress?`${Q.data.progress.current}/${Q.data.progress.total}`:void 0,w={id:Q.data.id,kind:Q.data.type,status:Q.data.status,updatedAt:new Date().toISOString(),...Q.data.message?{message:Q.data.message}:{},...Q.data.jobDetails?.jobType?{jobType:Q.data.jobDetails.jobType}:{},...$?{progressLabel:$}:{}};this.jobProgress=[w,...this.jobProgress.filter((B)=>B.id!==w.id||B.kind!==w.kind)].slice(0,8)}async getIndexStatus(){if(!this.ctx)return;let A=this.ctx.entityService;try{if(typeof A.awaitIndexReady==="function")return await A.awaitIndexReady({timeoutMs:0,intervalMs:0});if(typeof A.isIndexReady==="function")return{ready:A.isIndexReady()}}catch(Q){this.logger.debug("Semantic index status unavailable",{error:aA(Q)})}return}async getDirectorySyncStatus(){if(!this.ctx)return;try{let A=await this.ctx.messaging.send({type:"sync:status:request",payload:{}}),Q=af$.safeParse(A);return Q.success?Q.data.data:void 0}catch(A){this.logger.debug("Directory sync status unavailable",{error:aA(A)});return}}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new kj0(this.logger),this.datasource=new jj0(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("entity:created",async(Q)=>{return this.recordActivity("created",Q.payload),{success:!0}}),A.messaging.subscribe("entity:updated",async(Q)=>{return this.recordActivity("updated",Q.payload),{success:!0}}),A.messaging.subscribe("entity:deleted",async(Q)=>{return this.recordActivity("deleted",Q.payload),{success:!0}}),A.messaging.subscribe("job-progress",async(Q)=>{return this.recordJobProgress(Q.payload),{success:!0}}),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let $=nf$.parse(Q.payload),w=tf$($);return this.widgetRegistry?.register(w),this.logger.debug("Widget registered via messaging",{widgetId:$.id,pluginId:$.pluginId,rendererName:$.rendererName,builtIn:Pj0.includes($.rendererName)}),{success:!0}}catch($){return this.logger.error("Failed to register widget",{error:aA($),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{try{let $=rf$.parse(Q.payload);return this.widgetRegistry?.unregister($.pluginId,$.widgetId),this.logger.debug("Widget unregistered via messaging",{pluginId:$.pluginId,widgetId:$.widgetId}),{success:!0}}catch($){return this.logger.error("Failed to unregister widget",{error:aA($),payload:Q.payload}),{success:!1,error:"Widget unregistration failed"}}}),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,$=await UY()?.getOperatorSession(A),w=Boolean($),B=w?"anchor":"public",X=this.widgetRegistry?.list({permissionLevel:"anchor"})??[],Y=X.filter((x)=>P4.hasPermission(B,x.visibility)),Z=X.length-Y.length,[W,K,U,G]=await Promise.all([this.datasource.getDashboardData({permissionLevel:B,widgets:Y}),Q.appInfo(),this.getDirectorySyncStatus(),this.getIndexStatus()]),D=Q.identity.get(),q=Q.identity.getProfile(),J=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),F={...K,endpoints:K.endpoints.filter((x)=>P4.hasPermission(B,x.visibility)),interactions:K.interactions.filter((x)=>P4.hasPermission(B,x.visibility))},I=q.name||K.model||"Brain Dashboard",P=new URL(A.url),j=`${P.pathname}${P.search}`,k=encodeURIComponent(j),f=mS2(W.widgets,this.widgetRegistry),R={title:I,baseUrl:J,widgets:f.widgets,widgetScripts:f.widgetScripts,dashboardPath:this.config.routePath,surfaces:WO(Q.webRoutes.getRoutes(),{activeId:"dashboard",self:{id:"dashboard",href:this.config.routePath}}),character:D,profile:q,appInfo:F,activityLog:this.activityLog,jobProgress:this.jobProgress,...G!==void 0&&{indexStatus:G},...U!==void 0&&{directorySyncStatus:U},...this.config.themeCSS!==void 0&&{themeCSS:this.config.themeCSS},operatorAccess:{isOperator:w,hiddenWidgetCount:Z,loginUrl:`/login?return_to=${k}`,logoutUrl:`/logout?return_to=${k}`}};return new Response(gS2(R),{headers:{"Content-Type":"text/html; charset=utf-8"}})}},{path:"/api/console/jump",method:"GET",public:!0,handler:async(A)=>{if(!await UY()?.getOperatorSession(A))return Response.json({error:"Operator session required"},{status:401});let $=this.ctx;if(!$)return Response.json({groups:[]});let w=new URL(A.url).searchParams.get("q")?.trim()??"",B=[];if(w.length>=2)try{B=(await $.entityService.search({query:w,options:{limit:6}})).map((W)=>({entityType:W.entity.entityType,id:W.entity.id,title:W.entity.title??W.entity.id}))}catch{}let X=(this.widgetRegistry?.list({permissionLevel:"anchor"})??[]).map((Z)=>Z.group),Y=WO($.webRoutes.getRoutes(),{activeId:"dashboard"}).find((Z)=>Z.id==="cms")?.href;return Response.json({groups:SS2({query:w,groups:[...X,"knowledge","system"],dashboardPath:this.config.routePath,cmsPath:Y,entities:B})})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function $f(A={}){return new PzA(A)}C0();var ef$=H.enum(["public","trusted","anchor"]),Ax$=H.object({label:H.string(),value:H.string(),tone:H.enum(["plain","good","warn"]).optional()}),Qx$=H.object({id:H.string(),pluginId:H.string(),title:H.string(),description:H.string().optional(),group:H.string().min(1),priority:H.number(),section:H.enum(["primary","secondary","sidebar"]),rendererName:H.string(),visibility:ef$,needsOperator:H.number().int().nonnegative().optional(),digest:H.array(Ax$).max(4).optional(),component:H.custom().optional()}),$x$=H.object({widget:Qx$,data:H.unknown()}),wx$=H.object({widgets:H.record(H.string(),$x$)});KA();C0();KA();C0();import{h as Nx$}from"preact";KA();bH();S2();C0();var fj0=H.enum(["generating","draft","queued","published","failed"]),Bx$=H.enum(["generating","draft","queued","published","failed"]),xj0=H.object({subject:H.string(),status:fj0,entityIds:H.array(H.string()).optional(),scheduledFor:H.string().datetime().optional(),sentAt:H.string().datetime().optional(),buttondownId:H.string().optional(),sourceEntityType:H.string().optional()}),cS2=H.object({subject:H.string(),status:fj0,entityIds:H.array(H.string()).optional(),scheduledFor:H.string().datetime().optional(),sentAt:H.string().datetime().optional(),buttondownId:H.string().optional(),sourceEntityType:H.string().optional(),error:H.string().optional()}),Xx$=H.object({subject:H.string(),status:Bx$,entityIds:H.array(H.string()).optional(),scheduledFor:H.string().datetime().optional(),sentAt:H.string().datetime().optional(),buttondownId:H.string().optional(),sourceEntityType:H.string().optional(),error:H.string().optional()}),Jn=H6.extend({entityType:H.literal("newsletter"),metadata:Xx$});KA();class pS2 extends UQ{constructor(){super({entityType:"newsletter",purpose:"An email newsletter issue composed for subscribers.",schema:Jn,frontmatterSchema:xj0})}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 lS2=new pS2;KA();KA();S2();C0();var Yx$=H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional(),baseUrl:H.string().optional(),status:H.enum(["generating","draft","queued","published","failed"]).optional()}),Zx$=H.looseObject({entityType:H.string().optional(),query:Yx$.optional()});function dS2(A){try{let{content:Q}=_Q(A.content,xj0);return Q}catch{return A.content}}class kzA extends x7{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=Zx$.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=dS2(A),$={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:GH(Q,150),created:A.created,url:`/newsletters/${A.id}`};if(A.metadata.sentAt)$.sentAt=A.metadata.sentAt;return $}buildListResult(A,Q,$){return{newsletters:A,totalCount:Q?.totalItems??A.length,pagination:Q}}async fetch(A,Q,$){let{query:w}=this.parseQuery(A),B=$.entityService;if(w.id)return this.fetchSingleNewsletter(w.id,Q,B);let X=w.status,Y=X?{filter:{metadata:{status:X}}}:void 0,{items:Z,pagination:W}=await this.fetchList(w,B,Y);return Q.parse(this.buildListResult(Z,W,w))}async fetchSingleNewsletter(A,Q,$){let w=await $.getEntity({entityType:this.config.entityType,id:A});if(!w)throw Error(`Newsletter not found: ${A}`);let B=await this.resolveNavigation(w,$),X=[];if(w.metadata.entityIds?.length){let W=w.metadata.sourceEntityType??"post";X=(await Promise.all(w.metadata.entityIds.map(async(U)=>{let G=await $.getEntity({entityType:W,id:U});if(G){let D=G.metadata;return{id:U,title:D.title??U,url:`/${W}s/${D.slug??U}`}}return null}))).filter((U)=>U!==null)}let Y=dS2(w),Z={id:w.id,subject:w.metadata.subject,status:w.metadata.status,content:Y,created:w.created,updated:w.updated,sentAt:w.metadata.sentAt,scheduledFor:w.metadata.scheduledFor,newsletter:w,prevNewsletter:B.prev?{id:B.prev.id,subject:B.prev.subject,url:B.prev.url}:null,nextNewsletter:B.next?{id:B.next.id,subject:B.next.subject,url:B.next.url}:null,sourceEntities:X.length>0?X:void 0};return Q.parse(Z)}}KA();S2();C0();var Hx$=H.object({prompt:H.string().optional().describe("AI generation prompt"),sourceEntityIds:H.array(H.string()).optional().describe("Entity IDs to include in newsletter (e.g., blog posts)"),sourceEntityType:H.enum(["post"]).optional().describe("Type of source entities"),content:H.string().optional().describe("Direct content (skip AI)"),subject:H.string().optional().describe("Newsletter subject (AI-generated if not provided)"),addToQueue:H.boolean().optional().describe("Create as queued (true) or draft (false)")});class jzA extends GZ{constructor(A,Q){super(A,Q,{schema:Hx$,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let $=A.addToQueue??!1,{prompt:w,sourceEntityIds:B,sourceEntityType:X}=A,{content:Y,subject:Z}=A;if(Y){if(!Z)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if(B&&B.length>0){let D=X??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${B.length} source entities`});let J=(await Promise.all(B.map((k)=>this.context.entityService.getEntity({entityType:D,id:k})))).filter((k)=>k!=null);if(J.length===0)this.failEarly(`No source entities found for IDs: ${B.join(", ")}`);await this.reportProgress(Q,{progress:30,message:`Generating newsletter from ${J.length} posts`});let I=`Create an engaging newsletter that highlights these blog posts:
10080
+ ${Ff$(jA(pf$,{input:A},void 0,!1,void 0,this))}`}function lf$(A){return A.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"group"}function SS2(A){let Q=A.query.trim().toLowerCase(),$=[];if(A.cmsPath!==void 0&&A.entities.length>0){let B=A.cmsPath;$.push({id:"entities",label:"Entities",items:A.entities.map((X)=>({id:`${X.entityType}/${X.id}`,title:X.title,sub:X.entityType,href:`${B}#/${encodeURIComponent(X.entityType)}/${encodeURIComponent(X.id)}`,tag:"edit in cms"}))})}let w=Oj0([...new Set(A.groups)]).map((B)=>({group:B,label:Vn(B)})).filter(({group:B,label:X})=>Q===""||X.toLowerCase().includes(Q)||B.toLowerCase().includes(Q)).map(({group:B,label:X})=>({id:`tab/${B}`,title:X,sub:"tab",href:`${A.dashboardPath}#${lf$(B)}`,tag:"dashboard"}));if(w.length>0)$.push({id:"tabs",label:"Dashboard",items:w});return $}function mS2(A,Q){let $={},w=new Set;for(let[B,X]of Object.entries(A)){let Y=Q?.get(X.widget.pluginId,X.widget.id);if($[B]={...X,...Y?.component?{component:Y.component}:{}},Y?.clientScript)w.add(Y.clientScript)}return{widgets:$,widgetScripts:Array.from(w)}}var uS2={name:"@brains/dashboard",version:"0.2.0-alpha.184",description:"Dashboard plugin with extensible widget system",dependencies:{"@brains/auth-service":"workspace:*","@brains/console-theme":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2","preact-render-to-string":"^6.7.0"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var if$=H.object({version:H.string().default("1.0.0"),routePath:H.string().default("/dashboard"),themeCSS:H.string().optional()}),nf$=H.object({id:H.string(),pluginId:H.string(),title:H.string(),description:H.string().optional(),group:H.string().min(1),priority:H.number().default(50),section:H.enum(["primary","secondary","sidebar"]).default("primary"),rendererName:H.string(),visibility:H.enum(["public","trusted","anchor"]).default("public"),needsOperator:H.number().int().nonnegative().optional(),digest:H.array(H.object({label:H.string(),value:H.string(),tone:H.enum(["plain","good","warn"]).optional()})).max(4).optional(),component:H.custom().optional(),clientScript:H.string().optional(),dataProvider:H.custom((A)=>typeof A==="function",{message:"Expected dashboard widget data provider function"}),digestProvider:H.custom((A)=>typeof A==="function",{message:"Expected dashboard widget digest provider function"}).optional()}).superRefine((A,Q)=>{if(!JzA(A.rendererName)&&!A.component)Q.addIssue({code:"custom",message:"Custom dashboard widgets must register a Preact component.",path:["component"]})}),rf$=H.object({pluginId:H.string(),widgetId:H.string().optional()}),of$=H.object({entityType:H.string(),entityId:H.string(),conversationId:H.string().optional()}),sf$=H.object({id:H.string(),type:H.enum(["job","batch"]),status:H.enum(["pending","processing","completed","failed"]),message:H.string().optional(),progress:H.object({current:H.number(),total:H.number(),percentage:H.number()}).optional(),jobDetails:H.object({jobType:H.string(),priority:H.number(),retryCount:H.number()}).optional()}),af$=H.object({success:H.literal(!0),data:H.object({syncPath:H.string(),isInitialized:H.boolean(),watchEnabled:H.boolean(),lastSync:H.string().datetime().optional(),totalFiles:H.number().int().nonnegative().optional(),byEntityType:H.record(H.string(),H.number().int().nonnegative()).optional()})});function tf$(A){return{id:A.id,pluginId:A.pluginId,title:A.title,...A.description?{description:A.description}:{},group:A.group,priority:A.priority,section:A.section,rendererName:A.rendererName,visibility:A.visibility,...A.needsOperator!==void 0&&{needsOperator:A.needsOperator},...A.digest?{digest:A.digest}:{},...A.component?{component:A.component}:{},...A.clientScript?{clientScript:A.clientScript}:{},dataProvider:A.dataProvider,...A.digestProvider?{digestProvider:A.digestProvider}:{}}}class PzA extends p6{widgetRegistry=null;datasource=null;siteUrl;ctx;activityLog=[];jobProgress=[];constructor(A={}){super("dashboard",uS2,A,if$)}recordActivity(A,Q){let $=of$.safeParse(Q);if(!$.success)return;this.activityLog=[{action:A,entityType:$.data.entityType,entityId:$.data.entityId,timestamp:new Date().toISOString(),...$.data.conversationId?{conversationId:$.data.conversationId}:{}},...this.activityLog].slice(0,12)}recordJobProgress(A){let Q=sf$.safeParse(A);if(!Q.success)return;let $=Q.data.progress?`${Q.data.progress.current}/${Q.data.progress.total}`:void 0,w={id:Q.data.id,kind:Q.data.type,status:Q.data.status,updatedAt:new Date().toISOString(),...Q.data.message?{message:Q.data.message}:{},...Q.data.jobDetails?.jobType?{jobType:Q.data.jobDetails.jobType}:{},...$?{progressLabel:$}:{}};this.jobProgress=[w,...this.jobProgress.filter((B)=>B.id!==w.id||B.kind!==w.kind)].slice(0,8)}async getIndexStatus(){if(!this.ctx)return;let A=this.ctx.entityService;try{if(typeof A.awaitIndexReady==="function")return await A.awaitIndexReady({timeoutMs:0,intervalMs:0});if(typeof A.isIndexReady==="function")return{ready:A.isIndexReady()}}catch(Q){this.logger.debug("Semantic index status unavailable",{error:aA(Q)})}return}async getDirectorySyncStatus(){if(!this.ctx)return;try{let A=await this.ctx.messaging.send({type:"sync:status:request",payload:{}}),Q=af$.safeParse(A);return Q.success?Q.data.data:void 0}catch(A){this.logger.debug("Directory sync status unavailable",{error:aA(A)});return}}async onRegister(A){this.siteUrl=A.siteUrl,this.ctx=A,this.widgetRegistry=new kj0(this.logger),this.datasource=new jj0(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("entity:created",async(Q)=>{return this.recordActivity("created",Q.payload),{success:!0}}),A.messaging.subscribe("entity:updated",async(Q)=>{return this.recordActivity("updated",Q.payload),{success:!0}}),A.messaging.subscribe("entity:deleted",async(Q)=>{return this.recordActivity("deleted",Q.payload),{success:!0}}),A.messaging.subscribe("job-progress",async(Q)=>{return this.recordJobProgress(Q.payload),{success:!0}}),A.messaging.subscribe("dashboard:register-widget",async(Q)=>{try{let $=nf$.parse(Q.payload),w=tf$($);return this.widgetRegistry?.register(w),this.logger.debug("Widget registered via messaging",{widgetId:$.id,pluginId:$.pluginId,rendererName:$.rendererName,builtIn:Pj0.includes($.rendererName)}),{success:!0}}catch($){return this.logger.error("Failed to register widget",{error:aA($),payload:Q.payload}),{success:!1,error:"Widget registration failed"}}}),A.messaging.subscribe("dashboard:unregister-widget",async(Q)=>{try{let $=rf$.parse(Q.payload);return this.widgetRegistry?.unregister($.pluginId,$.widgetId),this.logger.debug("Widget unregistered via messaging",{pluginId:$.pluginId,widgetId:$.widgetId}),{success:!0}}catch($){return this.logger.error("Failed to unregister widget",{error:aA($),payload:Q.payload}),{success:!1,error:"Widget unregistration failed"}}}),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,$=await UY()?.getOperatorSession(A),w=Boolean($),B=w?"anchor":"public",X=this.widgetRegistry?.list({permissionLevel:"anchor"})??[],Y=X.filter((x)=>P4.hasPermission(B,x.visibility)),Z=X.length-Y.length,[W,K,U,G]=await Promise.all([this.datasource.getDashboardData({permissionLevel:B,widgets:Y}),Q.appInfo(),this.getDirectorySyncStatus(),this.getIndexStatus()]),D=Q.identity.get(),q=Q.identity.getProfile(),J=this.siteUrl??(()=>{try{return new URL(A.url).origin}catch{return}})(),F={...K,endpoints:K.endpoints.filter((x)=>P4.hasPermission(B,x.visibility)),interactions:K.interactions.filter((x)=>P4.hasPermission(B,x.visibility))},I=q.name||K.model||"Brain Dashboard",P=new URL(A.url),j=`${P.pathname}${P.search}`,k=encodeURIComponent(j),f=mS2(W.widgets,this.widgetRegistry),R={title:I,baseUrl:J,widgets:f.widgets,widgetScripts:f.widgetScripts,dashboardPath:this.config.routePath,surfaces:WO(Q.webRoutes.getRoutes(),{activeId:"dashboard",self:{id:"dashboard",href:this.config.routePath}}),character:D,profile:q,appInfo:F,activityLog:this.activityLog,jobProgress:this.jobProgress,...G!==void 0&&{indexStatus:G},...U!==void 0&&{directorySyncStatus:U},...this.config.themeCSS!==void 0&&{themeCSS:this.config.themeCSS},operatorAccess:{isOperator:w,hiddenWidgetCount:Z,loginUrl:`/login?return_to=${k}`,logoutUrl:`/logout?return_to=${k}`}};return new Response(gS2(R),{headers:{"Content-Type":"text/html; charset=utf-8"}})}},{path:"/api/console/jump",method:"GET",public:!0,handler:async(A)=>{if(!await UY()?.getOperatorSession(A))return Response.json({error:"Operator session required"},{status:401});let $=this.ctx;if(!$)return Response.json({groups:[]});let w=new URL(A.url).searchParams.get("q")?.trim()??"",B=[];if(w.length>=2)try{B=(await $.entityService.search({query:w,options:{limit:6}})).map((W)=>({entityType:W.entity.entityType,id:W.entity.id,title:W.entity.title??W.entity.id}))}catch{}let X=(this.widgetRegistry?.list({permissionLevel:"anchor"})??[]).map((Z)=>Z.group),Y=WO($.webRoutes.getRoutes(),{activeId:"dashboard"}).find((Z)=>Z.id==="cms")?.href;return Response.json({groups:SS2({query:w,groups:[...X,"knowledge","system"],dashboardPath:this.config.routePath,cmsPath:Y,entities:B})})}}]}async getTools(){return[]}getWidgetRegistry(){return this.widgetRegistry}}function $f(A={}){return new PzA(A)}C0();var ef$=H.enum(["public","trusted","anchor"]),Ax$=H.object({label:H.string(),value:H.string(),tone:H.enum(["plain","good","warn"]).optional()}),Qx$=H.object({id:H.string(),pluginId:H.string(),title:H.string(),description:H.string().optional(),group:H.string().min(1),priority:H.number(),section:H.enum(["primary","secondary","sidebar"]),rendererName:H.string(),visibility:ef$,needsOperator:H.number().int().nonnegative().optional(),digest:H.array(Ax$).max(4).optional(),component:H.custom().optional()}),$x$=H.object({widget:Qx$,data:H.unknown()}),wx$=H.object({widgets:H.record(H.string(),$x$)});KA();C0();KA();C0();import{h as Nx$}from"preact";KA();bH();S2();C0();var fj0=H.enum(["generating","draft","queued","published","failed"]),Bx$=H.enum(["generating","draft","queued","published","failed"]),xj0=H.object({subject:H.string(),status:fj0,entityIds:H.array(H.string()).optional(),scheduledFor:H.string().datetime().optional(),sentAt:H.string().datetime().optional(),buttondownId:H.string().optional(),sourceEntityType:H.string().optional()}),cS2=H.object({subject:H.string(),status:fj0,entityIds:H.array(H.string()).optional(),scheduledFor:H.string().datetime().optional(),sentAt:H.string().datetime().optional(),buttondownId:H.string().optional(),sourceEntityType:H.string().optional(),error:H.string().optional()}),Xx$=H.object({subject:H.string(),status:Bx$,entityIds:H.array(H.string()).optional(),scheduledFor:H.string().datetime().optional(),sentAt:H.string().datetime().optional(),buttondownId:H.string().optional(),sourceEntityType:H.string().optional(),error:H.string().optional()}),Jn=H6.extend({entityType:H.literal("newsletter"),metadata:Xx$});KA();class pS2 extends UQ{constructor(){super({entityType:"newsletter",purpose:"An email newsletter issue composed for subscribers.",schema:Jn,frontmatterSchema:xj0})}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 lS2=new pS2;KA();KA();S2();C0();var Yx$=H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional(),baseUrl:H.string().optional(),status:H.enum(["generating","draft","queued","published","failed"]).optional()}),Zx$=H.looseObject({entityType:H.string().optional(),query:Yx$.optional()});function dS2(A){try{let{content:Q}=_Q(A.content,xj0);return Q}catch{return A.content}}class kzA extends x7{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=Zx$.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}transformEntity(A){let Q=dS2(A),$={id:A.id,subject:A.metadata.subject,status:A.metadata.status,excerpt:GH(Q,150),created:A.created,url:`/newsletters/${A.id}`};if(A.metadata.sentAt)$.sentAt=A.metadata.sentAt;return $}buildListResult(A,Q,$){return{newsletters:A,totalCount:Q?.totalItems??A.length,pagination:Q}}async fetch(A,Q,$){let{query:w}=this.parseQuery(A),B=$.entityService;if(w.id)return this.fetchSingleNewsletter(w.id,Q,B);let X=w.status,Y=X?{filter:{metadata:{status:X}}}:void 0,{items:Z,pagination:W}=await this.fetchList(w,B,Y);return Q.parse(this.buildListResult(Z,W,w))}async fetchSingleNewsletter(A,Q,$){let w=await $.getEntity({entityType:this.config.entityType,id:A});if(!w)throw Error(`Newsletter not found: ${A}`);let B=await this.resolveNavigation(w,$),X=[];if(w.metadata.entityIds?.length){let W=w.metadata.sourceEntityType??"post";X=(await Promise.all(w.metadata.entityIds.map(async(U)=>{let G=await $.getEntity({entityType:W,id:U});if(G){let D=G.metadata;return{id:U,title:D.title??U,url:`/${W}s/${D.slug??U}`}}return null}))).filter((U)=>U!==null)}let Y=dS2(w),Z={id:w.id,subject:w.metadata.subject,status:w.metadata.status,content:Y,created:w.created,updated:w.updated,sentAt:w.metadata.sentAt,scheduledFor:w.metadata.scheduledFor,newsletter:w,prevNewsletter:B.prev?{id:B.prev.id,subject:B.prev.subject,url:B.prev.url}:null,nextNewsletter:B.next?{id:B.next.id,subject:B.next.subject,url:B.next.url}:null,sourceEntities:X.length>0?X:void 0};return Q.parse(Z)}}KA();S2();C0();var Hx$=H.object({prompt:H.string().optional().describe("AI generation prompt"),sourceEntityIds:H.array(H.string()).optional().describe("Entity IDs to include in newsletter (e.g., blog posts)"),sourceEntityType:H.enum(["post"]).optional().describe("Type of source entities"),content:H.string().optional().describe("Direct content (skip AI)"),subject:H.string().optional().describe("Newsletter subject (AI-generated if not provided)"),addToQueue:H.boolean().optional().describe("Create as queued (true) or draft (false)")});class jzA extends GZ{constructor(A,Q){super(A,Q,{schema:Hx$,jobTypeName:"newsletter:generation",entityType:"newsletter"})}async generate(A,Q){let $=A.addToQueue??!1,{prompt:w,sourceEntityIds:B,sourceEntityType:X}=A,{content:Y,subject:Z}=A;if(Y){if(!Z)this.failEarly("Subject is required when providing content directly");await this.reportProgress(Q,{progress:50,message:"Using provided content"})}else if(B&&B.length>0){let D=X??"post";await this.reportProgress(Q,{progress:10,message:`Fetching ${B.length} source entities`});let J=(await Promise.all(B.map((k)=>this.context.entityService.getEntity({entityType:D,id:k})))).filter((k)=>k!=null);if(J.length===0)this.failEarly(`No source entities found for IDs: ${B.join(", ")}`);await this.reportProgress(Q,{progress:30,message:`Generating newsletter from ${J.length} posts`});let I=`Create an engaging newsletter that highlights these blog posts:
10081
10081
 
10082
10082
  ${J.map((k)=>`## ${k.metadata.title}
10083
10083
 
@@ -10146,17 +10146,17 @@ Newsletter-specific guidelines:
10146
10146
  - "Reply and let me know..."
10147
10147
  - "Until next time..."
10148
10148
 
10149
- The goal is to build a relationship with readers through valuable, authentic content.`});C0();KA();import{jsxDEV as wW,Fragment as qx$}from"preact/jsx-dev-runtime";var Kx$=H.enum(["generating","draft","queued","published","failed"]),Ux$=H.object({id:H.string(),subject:H.string(),status:Kx$,excerpt:H.string(),created:H.string(),sentAt:H.string().optional(),url:H.string()}),Gx$=H.object({newsletters:H.array(Ux$),totalCount:H.number(),pagination:GU0.nullable()}),Dx$=({newsletters:A,totalCount:Q,pageTitle:$,pagination:w,baseUrl:B="/newsletters"})=>{let X=$??"Newsletters",Y=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return wW(qx$,{children:[wW(C6,{title:X,description:Y},void 0,!1,void 0,this),wW("div",{className:"newsletter-list bg-theme",children:wW("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[wW("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:X},void 0,!1,void 0,this),A.length===0?wW("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):wW("div",{className:"space-y-4",children:A.map((Z)=>wW(j8,{href:Z.url,children:[wW(hX,{className:"text-lg",children:Z.subject},void 0,!1,void 0,this),wW(FY,{children:wW("div",{className:"flex items-center gap-3",children:[wW(GK,{status:Z.status},void 0,!1,void 0,this),wW("span",{className:"text-sm text-theme-muted",children:_9(Z.sentAt??Z.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z.excerpt&&wW("p",{className:"text-theme-muted line-clamp-2",children:Z.excerpt},void 0,!1,void 0,this)]},Z.id,!0,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&wW(WP,{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)},nS2=K2({name:"newsletter-list",description:"Newsletter list page template",schema:Gx$,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:Dx$}});C0();KA();import{jsxDEV as x5,Fragment as Ix$}from"preact/jsx-dev-runtime";var zx$=H.enum(["generating","draft","queued","published","failed"]),Vx$=H.object({id:H.string(),title:H.string(),url:H.string()}),rS2=H.object({id:H.string(),subject:H.string(),url:H.string()}),Jx$=H.object({id:H.string(),subject:H.string(),status:zx$,content:H.string(),created:H.string(),updated:H.string(),sentAt:H.string().optional(),scheduledFor:H.string().optional(),sourceEntities:H.array(Vx$).optional(),prevNewsletter:rS2.nullable().optional(),nextNewsletter:rS2.nullable().optional()}),Fx$=({subject:A,status:Q,content:$,created:w,sentAt:B,scheduledFor:X,sourceEntities:Y,prevNewsletter:Z,nextNewsletter:W})=>{let K=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],U=B??w,G=B?"Sent":"Created";return x5(Ix$,{children:[x5(C6,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),x5("section",{className:"newsletter-detail-section",children:x5("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:x5("div",{className:"max-w-3xl mx-auto",children:[x5(mF,{items:K},void 0,!1,void 0,this),x5("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),x5("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[x5(GK,{status:Q},void 0,!1,void 0,this),x5("span",{children:[G,": ",_9(U,{style:"long"})]},void 0,!0,void 0,this),X&&Q==="queued"&&x5("span",{children:["Scheduled for: ",_9(X,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Y&&Y.length>0&&x5(j8,{variant:"compact",className:"mb-8",children:[x5("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),x5("ul",{className:"space-y-1",children:Y.map((D)=>x5("li",{children:x5("a",{href:D.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:D.title},void 0,!1,void 0,this)},D.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x5(u4,{markdown:$},void 0,!1,void 0,this),(Z??W)&&x5("nav",{className:"mt-12 pt-8 border-t border-theme",children:x5("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Z?x5(j8,{href:Z.url,variant:"compact",children:[x5("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),x5("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:Z.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this):x5("div",{},void 0,!1,void 0,this),W&&x5(j8,{href:W.url,variant:"compact",className:"md:text-right",children:[x5("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),x5("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:W.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)},oS2=K2({name:"newsletter-detail",description:"Individual newsletter detail template",schema:Jx$,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:Fx$}});var Rj0={name:"@brains/newsletter",version:"0.2.0-alpha.183",description:"Newsletter composite \u2014 bundles the newsletter entity with the buttondown service plugin",dependencies:{"@brains/contracts":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var _x$=H.looseObject({}),Px$=H.object({prompt:H.string().optional(),content:H.string().optional()});class vj0 extends S6{entityType="newsletter";schema=Jn;adapter=lS2;constructor(A={}){super("newsletter",Rj0,A,_x$)}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}createGenerationHandler(A){return new jzA(this.logger,A)}getTemplates(){return{generation:iS2,"newsletter-list":nS2,"newsletter-detail":oS2}}getDataSources(){return[new kzA(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:()=>Nx$(qWA,{variant:"inline"})}});return{success:!0}}),this.logger.debug("Newsletter plugin registered")}deferPublishRegistration(A){let Q={name:"internal",publish:async($,w)=>{let B=typeof w.subject==="string"?w.subject:"",X=await A.messaging.send({type:"buttondown:send",payload:{entityId:"",subject:B,content:$}});return{id:!("noop"in X)&&X.data?.emailId?X.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 $=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:10}});if($.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:$.map((w)=>w.id),sourceEntityType:"post",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}}),{success:!0}}catch($){return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:aA($)}}),{success:!0}}})}registerEvalHandlers(A){A.eval.registerHandler("generation",async(Q)=>{let $=Px$.parse(Q),w=$.content?`Create an engaging newsletter based on this content:
10149
+ The goal is to build a relationship with readers through valuable, authentic content.`});C0();KA();import{jsxDEV as wW,Fragment as qx$}from"preact/jsx-dev-runtime";var Kx$=H.enum(["generating","draft","queued","published","failed"]),Ux$=H.object({id:H.string(),subject:H.string(),status:Kx$,excerpt:H.string(),created:H.string(),sentAt:H.string().optional(),url:H.string()}),Gx$=H.object({newsletters:H.array(Ux$),totalCount:H.number(),pagination:GU0.nullable()}),Dx$=({newsletters:A,totalCount:Q,pageTitle:$,pagination:w,baseUrl:B="/newsletters"})=>{let X=$??"Newsletters",Y=`Browse all ${Q} ${Q===1?"newsletter":"newsletters"}`;return wW(qx$,{children:[wW(C6,{title:X,description:Y},void 0,!1,void 0,this),wW("div",{className:"newsletter-list bg-theme",children:wW("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-16 md:py-24",children:[wW("h1",{className:"text-3xl md:text-4xl font-bold text-heading mb-8",children:X},void 0,!1,void 0,this),A.length===0?wW("p",{className:"text-theme-muted italic",children:"No newsletters yet."},void 0,!1,void 0,this):wW("div",{className:"space-y-4",children:A.map((Z)=>wW(j8,{href:Z.url,children:[wW(hX,{className:"text-lg",children:Z.subject},void 0,!1,void 0,this),wW(FY,{children:wW("div",{className:"flex items-center gap-3",children:[wW(GK,{status:Z.status},void 0,!1,void 0,this),wW("span",{className:"text-sm text-theme-muted",children:_9(Z.sentAt??Z.created,{style:"long"})},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z.excerpt&&wW("p",{className:"text-theme-muted line-clamp-2",children:Z.excerpt},void 0,!1,void 0,this)]},Z.id,!0,void 0,this))},void 0,!1,void 0,this),w&&w.totalPages>1&&wW(WP,{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)},nS2=K2({name:"newsletter-list",description:"Newsletter list page template",schema:Gx$,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:Dx$}});C0();KA();import{jsxDEV as x5,Fragment as Ix$}from"preact/jsx-dev-runtime";var zx$=H.enum(["generating","draft","queued","published","failed"]),Vx$=H.object({id:H.string(),title:H.string(),url:H.string()}),rS2=H.object({id:H.string(),subject:H.string(),url:H.string()}),Jx$=H.object({id:H.string(),subject:H.string(),status:zx$,content:H.string(),created:H.string(),updated:H.string(),sentAt:H.string().optional(),scheduledFor:H.string().optional(),sourceEntities:H.array(Vx$).optional(),prevNewsletter:rS2.nullable().optional(),nextNewsletter:rS2.nullable().optional()}),Fx$=({subject:A,status:Q,content:$,created:w,sentAt:B,scheduledFor:X,sourceEntities:Y,prevNewsletter:Z,nextNewsletter:W})=>{let K=[{label:"Home",href:"/"},{label:"Newsletters",href:"/newsletters"},{label:A}],U=B??w,G=B?"Sent":"Created";return x5(Ix$,{children:[x5(C6,{title:A,description:`Newsletter: ${A}`},void 0,!1,void 0,this),x5("section",{className:"newsletter-detail-section",children:x5("div",{className:"container mx-auto px-6 md:px-8 py-12 md:py-20",children:x5("div",{className:"max-w-3xl mx-auto",children:[x5(mF,{items:K},void 0,!1,void 0,this),x5("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),x5("div",{className:"flex flex-wrap items-center gap-3 mb-8 text-sm text-theme-muted",children:[x5(GK,{status:Q},void 0,!1,void 0,this),x5("span",{children:[G,": ",_9(U,{style:"long"})]},void 0,!0,void 0,this),X&&Q==="queued"&&x5("span",{children:["Scheduled for: ",_9(X,{style:"long"})]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),Y&&Y.length>0&&x5(j8,{variant:"compact",className:"mb-8",children:[x5("h3",{className:"text-sm font-medium text-heading mb-2",children:"Related Content"},void 0,!1,void 0,this),x5("ul",{className:"space-y-1",children:Y.map((D)=>x5("li",{children:x5("a",{href:D.url,className:"text-sm text-brand hover:text-brand-dark transition-colors",children:D.title},void 0,!1,void 0,this)},D.id,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x5(u4,{markdown:$},void 0,!1,void 0,this),(Z??W)&&x5("nav",{className:"mt-12 pt-8 border-t border-theme",children:x5("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Z?x5(j8,{href:Z.url,variant:"compact",children:[x5("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Newer"},void 0,!1,void 0,this),x5("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:Z.subject},void 0,!1,void 0,this)]},void 0,!0,void 0,this):x5("div",{},void 0,!1,void 0,this),W&&x5(j8,{href:W.url,variant:"compact",className:"md:text-right",children:[x5("span",{className:"text-xs text-theme-muted uppercase tracking-wide",children:"Older"},void 0,!1,void 0,this),x5("span",{className:"block mt-1 font-medium text-heading group-hover:text-brand transition-colors truncate",children:W.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)},oS2=K2({name:"newsletter-detail",description:"Individual newsletter detail template",schema:Jx$,dataSourceId:"newsletter:entities",requiredPermission:"public",layout:{component:Fx$}});var Rj0={name:"@brains/newsletter",version:"0.2.0-alpha.184",description:"Newsletter composite \u2014 bundles the newsletter entity with the buttondown service plugin",dependencies:{"@brains/contracts":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var _x$=H.looseObject({}),Px$=H.object({prompt:H.string().optional(),content:H.string().optional()});class vj0 extends S6{entityType="newsletter";schema=Jn;adapter=lS2;constructor(A={}){super("newsletter",Rj0,A,_x$)}getEntityTypeConfig(){return{publish:{publishStatuses:["queued","published","failed"]}}}createGenerationHandler(A){return new jzA(this.logger,A)}getTemplates(){return{generation:iS2,"newsletter-list":nS2,"newsletter-detail":oS2}}getDataSources(){return[new kzA(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:()=>Nx$(qWA,{variant:"inline"})}});return{success:!0}}),this.logger.debug("Newsletter plugin registered")}deferPublishRegistration(A){let Q={name:"internal",publish:async($,w)=>{let B=typeof w.subject==="string"?w.subject:"",X=await A.messaging.send({type:"buttondown:send",payload:{entityId:"",subject:B,content:$}});return{id:!("noop"in X)&&X.data?.emailId?X.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 $=await A.entityService.listEntities({entityType:"post",options:{filter:{metadata:{status:"published"}},limit:10}});if($.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:$.map((w)=>w.id),sourceEntityType:"post",addToQueue:!1},toolContext:{interfaceType:"job",userId:"system"}}),{success:!0}}catch($){return await A.messaging.send({type:"generate:report:failure",payload:{entityType:"newsletter",error:aA($)}}),{success:!0}}})}registerEvalHandlers(A){A.eval.registerHandler("generation",async(Q)=>{let $=Px$.parse(Q),w=$.content?`Create an engaging newsletter based on this content:
10150
10150
 
10151
10151
  ${$.content}`:$.prompt??"Write an engaging newsletter";return A.ai.generate({prompt:w,templateName:"newsletter:generation"})})}}function Cj0(A={}){return new vj0(A)}KA();C0();C0();var jx$="https://api.buttondown.email/v1",Mx$=H.enum(["unactivated","regular","unsubscribed","already_subscribed"]),bx$=H.enum(["draft","about_to_send","scheduled","sent"]),MzA=H.looseObject({id:H.string(),email:H.string(),subscriber_type:Mx$,metadata:H.record(H.string(),H.string()).optional()}),sS2=H.looseObject({id:H.string(),subject:H.string(),body:H.string().optional(),status:bx$,publish_date:H.string().optional()}),Ox$=H.looseObject({results:H.array(MzA),count:H.number()}),fx$=H.looseObject({detail:H.string().optional(),message:H.string().optional(),code:H.string().optional()});class bzA extends Error{status;code;constructor(A,Q,$){super(A);this.name="ButtondownApiError",this.status=Q,this.code=$}}class GT{config;logger;constructor(A,Q){this.config=A,this.logger=Q}async request(A,Q={}){let $=`${jx$}${A}`;this.logger.debug("Buttondown API request",{endpoint:A,method:Q.method??"GET"});let w=await fetch($,{...Q,headers:{Authorization:`Token ${this.config.apiKey}`,"Content-Type":"application/json",...Q.headers}});if(!w.ok){let B=await w.json().catch(()=>({})),X=fx$.safeParse(B),Y=X.success?X.data.detail??X.data.message??`HTTP ${w.status}`:`HTTP ${w.status}`,Z=X.success?X.data.code:void 0;throw this.logger.error("Buttondown API error",{endpoint:A,status:w.status,code:Z,error:Y}),new bzA(`Buttondown API error: ${Y}`,w.status,Z)}return w.json()}async createSubscriber(A){let Q={email_address:A.email,type:this.config.doubleOptIn?"unactivated":"regular"};if(A.name)Q.metadata={name:A.name};if(A.tags&&A.tags.length>0)Q.tags=A.tags;this.logger.info("Creating subscriber",{email:A.email});try{return MzA.parse(await this.request("/subscribers",{method:"POST",body:JSON.stringify(Q)}))}catch($){if($ instanceof bzA&&$.code==="email_already_exists")return this.logger.info("Subscriber already exists",{email:A.email}),{...await this.getSubscriberByEmail(A.email),subscriber_type:"already_subscribed"};throw $}}async getSubscriberByEmail(A){return MzA.parse(await this.request(`/subscribers/${encodeURIComponent(A)}`))}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 $=Q.toString(),w=$?`/subscribers?${$}`:"/subscribers";return Ox$.parse(await this.request(w))}async createEmail(A){let Q={subject:A.subject,body:A.body,status:A.status??"draft"};if(A.publish_date)Q.publish_date=A.publish_date;return this.logger.info("Creating email",{subject:A.subject,status:A.status??"draft"}),sS2.parse(await this.request("/emails",{method:"POST",body:JSON.stringify(Q)}))}async getEmail(A){return sS2.parse(await this.request(`/emails/${A}`))}async validateCredentials(){try{return await this.request("/subscribers?page_size=1"),!0}catch{return!1}}}KA();C0();var aS2=H.string().email({pattern:H.regexes.html5Email}),xx$=H.object({email:aS2.describe("Email address to subscribe"),name:H.string().optional().describe("Subscriber name (optional)"),tags:H.array(H.string()).optional().describe("Tags to apply to subscriber (optional)")}),Rx$=H.object({email:aS2.describe("Email address to unsubscribe")}),vx$=H.object({type:H.enum(["unactivated","regular","unsubscribed"]).optional().describe("Filter by subscriber status"),limit:H.number().optional().describe("Maximum number of results")});function tS2(A,Q,$){let w=new GT(Q,$);return[p8(A,"subscribe","Subscribe an email address to the newsletter. Uses double opt-in by default.",xx$,async(B)=>{try{let X=await w.createSubscriber({email:B.email,...B.name&&{name:B.name},...B.tags&&{tags:B.tags}}),Y=X.subscriber_type==="already_subscribed";return f7({subscriberId:X.id,email:X.email,status:X.subscriber_type,message:Y?"already_subscribed":"subscribed"},Y?`${B.email} is already subscribed`:`Subscribed ${B.email} successfully`)}catch(X){return YY(aA(X))}}),p8(A,"unsubscribe","Unsubscribe an email address from the newsletter.",Rx$,async(B)=>{try{return await w.unsubscribe(B.email),f7({email:B.email},`Unsubscribed ${B.email} successfully`)}catch(X){return YY(aA(X))}}),p8(A,"list_subscribers","List newsletter subscribers with optional filtering by status.",vx$,async(B)=>{try{let X=await w.listSubscribers({...B.type&&{type:B.type},...B.limit&&{limit:B.limit}});return f7({subscribers:X.results.map((Y)=>({id:Y.id,email:Y.email,status:Y.subscriber_type})),count:X.count},`Found ${X.count} subscribers`)}catch(X){return YY(aA(X))}})]}async function eS2(A,Q,$,w){if(A.entityType!=="post")return{success:!0,skipped:!0,reason:"Only post entity types trigger auto-send"};let B=await $.getEntity({entityType:"post",id:A.entityId});if(!B)return{success:!1,error:`Post ${A.entityId} not found`};w.info("Auto-sending newsletter for published post",{postId:B.id,title:B.metadata.title});try{let X=await Q.createEmail({subject:B.metadata.title,body:B.content,status:"about_to_send"});return w.info("Newsletter sent for post",{postId:B.id,emailId:X.id}),{success:!0,emailId:X.id}}catch(X){let Y=aA(X);return w.error("Failed to send newsletter for post",{postId:B.id,error:Y}),{success:!1,error:Y}}}var Cx$=H.object({apiKey:H.string().optional().describe("Buttondown API key"),doubleOptIn:H.boolean().default(!0).describe("Require email confirmation for new subscribers"),autoSendOnPublish:H.boolean().default(!1).describe("Automatically send newsletter when a blog post is published")});class hj0 extends p6{constructor(A={}){super("buttondown",Rj0,A,Cx$)}async onRegister(A){if(A.messaging.subscribe("buttondown:is-configured",async()=>{return{success:!!this.config.apiKey}}),this.config.apiKey){let Q=new GT({apiKey:this.config.apiKey,doubleOptIn:this.config.doubleOptIn},this.logger);if(A.messaging.subscribe("buttondown:send",async($)=>{try{return{success:!0,data:{emailId:(await Q.createEmail({subject:$.payload.subject,body:$.payload.content,status:"about_to_send"})).id}}}catch(w){return this.logger.error("Buttondown send failed",{error:aA(w)}),{success:!1}}}),this.config.autoSendOnPublish)A.messaging.subscribe("publish:completed",async($)=>{let w=await eS2($.payload,Q,A.entityService,this.logger);if(!w.success)return this.logger.error("Buttondown auto-send failed",{entityId:$.payload.entityId,error:w.error}),{success:!1,error:w.error};return{success:!0}}),this.logger.info("Buttondown auto-send on publish enabled")}}async getTools(){if(!this.config.apiKey)return[];return tS2(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 Ej0(A={}){return new hj0(A)}var hx$=H.object({apiKey:H.string().optional().describe("Buttondown API key"),doubleOptIn:H.boolean().optional().describe("Require email confirmation for new subscribers"),autoSendOnPublish:H.boolean().optional().describe("Automatically send newsletter when a blog post is published")});function Am2(A={}){let Q=hx$.safeParse(A);if(!Q.success)throw new GL("newsletter",Q.error.issues.map((w)=>({path:w.path.map(String).join("."),code:w.code,message:w.message})));let $=Q.data;return[Cj0({}),Ej0({...$.apiKey!==void 0&&{apiKey:$.apiKey},...$.doubleOptIn!==void 0&&{doubleOptIn:$.doubleOptIn},...$.autoSendOnPublish!==void 0&&{autoSendOnPublish:$.autoSendOnPublish}})]}KA();C0();import{existsSync as rx$,mkdirSync as ox$,writeFileSync as sx$}from"fs";import{join as xP}from"path";C0();var OzA=H.object({baseFolder:H.string().default("_obsidian")});function fzA(A){return typeof A==="object"&&A!==null}function P50(A){if(!fzA(A))return;let Q=A.def;return fzA(Q)?Q:void 0}function Qm2(A){let Q=P50(A)?.type;return typeof Q==="string"?Q:void 0}function Ex$(A){return typeof A==="function"?A():A}function Tx$(A){let Q=A,$=!0,w=void 0,B=!1,X=!0;while(X){X=!1;let Z=P50(Q),W=Qm2(Q);if(W==="optional"||W==="nullable"){$=!1,Q=Z?.innerType,X=!0;continue}if(W==="default")$=!1,B=!0,w=Ex$(Z?.defaultValue),Q=Z?.innerType,X=!0}let Y={inner:Q,required:$};if(B)Y.defaultValue=w;return Y}function yx$(A){let $=P50(A)?.entries;if(!fzA($))return;let w=Object.values($);if(!w.every((B)=>typeof B==="string"))return;return w}function gx$(A){let Q=P50(A),$=Q?.values;if(Array.isArray($))return $[0];return Q?.value}function $m2(A){let Q=Qm2(A);if(Q==="enum"){let $=yx$(A);return $?{type:"enum",enumValues:$}:{type:"enum"}}if(Q==="literal")return{type:"string",defaultValue:gx$(A)};if(Q==="string")return{type:"string"};if(Q==="number")return{type:"number"};if(Q==="boolean")return{type:"boolean"};if(Q==="array")return{type:"array"};if(Q==="date")return{type:"date"};if(Q==="pipeline"||Q==="pipe"){let $=P50(A);return $m2($?.out)}return{type:"unknown"}}function wm2(A){let Q=[];for(let[$,w]of Object.entries(A.shape)){let{inner:B,required:X,defaultValue:Y}=Tx$(w),Z=$m2(B),W={name:$,type:Z.type,required:X},K=Y!==void 0?Y:Z.defaultValue;if(K!==void 0)W.defaultValue=K;if(Z.enumValues)W.enumValues=Z.enumValues;Q.push(W)}return Q}function Sx$(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 Bm2(A,Q,$=""){let w=["---"];for(let B of Q){let X=Sx$(B,A);if(X==="")w.push(`${B.name}:`);else w.push(`${B.name}: ${X}`)}if(w.push("---"),w.push(""),$)w.push($);else w.push("<!-- Write your content here -->"),w.push("");return w.join(`
10152
10152
  `)}du();var mx$={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function ux$(A){let Q={name:A.name,id:A.name,type:mx$[A.type]};if(A.type==="enum"&&A.enumValues){let $={};A.enumValues.forEach((w,B)=>{$[String(B)]=w}),Q.options=$}return Q}function Xm2(A,Q){let $={filesPaths:A,fields:Q.map(ux$)};return`---
10153
10153
  ${lu($)}---
10154
- `}S2();du();var cx$=new Set(["entityType"]),px$={base:"Notes"},lx$=new Set(["note"]);function dx$(A){let Q=["file.name"];for(let $ of A)if(!cx$.has($.name))Q.push($.name);return Q}function ix$(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function Ym2(A,Q){let $=px$[A]??LRA(A),w=ix$(Q),B=dx$(Q),X=[{type:"table",name:`All ${$}`,order:B}];if(w)X.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:B});let Z={filters:{and:[lx$.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:X};return{filename:`${$}.base`,content:lu(Z),hasStatus:w}}function Zm2(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w}")`),$={filters:{and:[Q.length===1?Q[0]:{or:Q}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return lu($)}function Hm2(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w.entityType}")`),$={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 lu($)}var Wm2={name:"@brains/obsidian-vault",version:"0.2.0-alpha.183",description:"Obsidian vault integration \u2014 generates templates from entity schemas",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var ax$={mkdir:ox$,writeFile:sx$,existsFile:rx$},tx$=H.object({entityTypes:H.array(H.string()).optional().describe("Entity types to generate templates for (default: all)")});class xzA extends p6{deps;constructor(A={},Q={}){super("obsidian-vault",Wm2,A,OzA);this.deps={...ax$,...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[p8(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",tx$,async(Q)=>{return this.sync(A,Q.entityTypes)},{sideEffects:"external"})]}async sync(A,Q){try{let $=A.entityService.getEntityTypes(),w=Q?$.filter((I)=>Q.includes(I)):$,B=xP(A.dataDir,this.config.baseFolder),X=xP(B,"templates"),Y=xP(B,"fileClasses"),Z=xP(B,"bases");this.deps.mkdir(X,{recursive:!0}),this.deps.mkdir(Y,{recursive:!0}),this.deps.mkdir(Z,{recursive:!0});let W=[],K=[],U=[],G=[],D=[],q=[];for(let I of w){let P=A.entities.getEffectiveFrontmatterSchema(I);if(!P){this.logger.debug(`Skipping ${I}: no frontmatter schema`),K.push(I);continue}let j=wm2(P),k=A.entities.getAdapter(I),f=k?.isSingleton===!0,R=Xm2(I,j);if(this.deps.writeFile(xP(Y,`${I}.md`),R),U.push(I),f){D.push(I),this.logger.debug(`Generated fileClass (singleton): ${I}`);continue}let x=k?.getBodyTemplate()??"",O=Bm2(I,j,x);this.deps.writeFile(xP(X,`${I}.md`),O),W.push(I);let g=Ym2(I,j),u=xP(Z,g.filename);if(!this.deps.existsFile(u))this.deps.writeFile(u,g.content),G.push(I),this.logger.debug(`Generated base: ${g.filename}`);if(g.hasStatus)q.push({entityType:I,fields:j});this.logger.debug(`Generated template + fileClass: ${I}`)}let J=Zm2(D);if(J){let I=xP(Z,"Settings.base");if(!this.deps.existsFile(I))this.deps.writeFile(I,J),G.push("Settings"),this.logger.debug("Generated Settings.base")}let F=Hm2(q);if(F){let I=xP(Z,"Pipeline.base");if(!this.deps.existsFile(I))this.deps.writeFile(I,F),G.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${W.length} templates, ${U.length} fileClasses, ${G.length} bases (${K.length} skipped)`),f7({generated:W,skipped:K,fileClasses:U,bases:G})}catch($){return this.logger.error("Failed to sync",{error:$}),YY($ instanceof Error?$.message:"Unknown error")}}}function RzA(A={},Q){return new xzA(A,Q)}qA0();KA();C0();var Km2={name:"@brains/notifications",version:"0.2.0-alpha.183",description:"Generic notification routing for transactional and administrative messages",dependencies:{"@brains/email-contracts":"workspace:*","@brains/notification-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};qA0();var AR$=H.looseObject({defaultRecipient:WD0.optional()});class Um2 extends p6{constructor(A={}){super("notifications",Km2,A,AR$)}async onRegister(A){A.messaging.subscribe(gv,async(Q)=>{let $=Ea0.parse(Q.payload),w=$.recipient??this.config.defaultRecipient;if(!w)return A.logger.warn("Notification has no recipient"),{success:!1,error:"Notification recipient missing"};let B={to:w.address,subject:$.title,text:$.body,...$.html?{html:$.html}:{},sensitivity:$.sensitivity},X=await A.messaging.send({type:nL0,payload:B});if(!("success"in X)||!X.success||!X.data)return{success:!1,error:"Notification delivery failed"};let Y=X.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 Tj0(A={}){return new Um2(A)}e8();KA();KA();S2();y9();KA();C0();var yj0=H.enum(["draft","active","archived"]),gj0=H.enum(["anchor","trusted","public"]),Sj0=H.enum(["agent-confirmed","manual"]),QR$=H.enum(["draft","active","archived"]),$R$=H.enum(["anchor","trusted","public"]),wR$=H.enum(["agent-confirmed","manual"]),qI=H.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,H.string().min(1).optional()),RP=H.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,H.string().min(1).optional()),vzA=H.object({event:H.string().min(1),target:H.string().min(1),operatorAction:H.boolean().optional(),label:RP,description:RP,operatorDescription:RP}),CzA=H.object({id:H.string().min(1),title:H.string().min(1),prompt:RP,requiredDetails:H.array(H.string().min(1)).default([]),instructions:H.array(H.string().min(1)).default([]),doneWhen:H.array(H.string().min(1)).default([]),transitions:H.array(vzA).default([])}),mj0=H.object({purpose:H.string().min(1),operatingRules:H.array(H.string().min(1)).default([]),initialState:H.string().min(1),states:H.array(CzA).min(1),finalStates:H.array(H.string().min(1)).min(1),nextPrompts:H.array(H.string().min(1)).default([])}),Fn=H.object({title:H.string(),status:yj0.default("active"),audience:gj0.default("anchor"),trigger:qI.optional(),lifecycle:qI.optional(),once:H.boolean().optional(),starterText:qI.optional(),description:qI.optional(),starterPrompt:qI.optional(),completionMode:Sj0.default("agent-confirmed")}),Gm2=H.object({title:H.string(),status:yj0,audience:gj0,trigger:qI.optional(),lifecycle:qI.optional(),once:H.boolean().optional(),starterText:qI.optional(),description:qI.optional(),starterPrompt:qI.optional(),completionMode:Sj0}),BR$=H.object({title:H.string(),status:QR$,audience:$R$,trigger:RP.optional(),lifecycle:RP.optional(),once:H.boolean().optional(),starterText:RP.optional(),description:RP.optional(),starterPrompt:RP.optional(),completionMode:wR$}),In=H6.extend({entityType:H.literal("playbook"),metadata:BR$});class uj0 extends d${constructor(){super(mj0,{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:hzA,parser:EzA},{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:XR$,parser:YR$},{key:"label",label:"Label",type:"custom",formatter:hzA,parser:EzA},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:hzA,parser:EzA}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var k50=new uj0;function hzA(A){return typeof A==="string"?A:""}function EzA(A){let Q=A.trim();return Q.length>0?Q:void 0}function XR$(A){return typeof A==="boolean"?String(A):""}function YR$(A){let Q=A.trim().toLowerCase();if(Q==="true")return!0;if(Q==="false")return!1;return}function TzA(A){let Q=[],$=new Set,w=new Set;for(let B of A.states){if($.has(B.id))w.add(B.id);$.add(B.id)}if(!$.has(A.initialState))Q.push(`Playbook initial state '${A.initialState}' is not defined.`);for(let B of w)Q.push(`Duplicate playbook state id '${B}'.`);for(let B of A.finalStates)if(!$.has(B))Q.push(`Playbook final state '${B}' is not defined.`);for(let B of A.states)for(let X of B.transitions)if(!$.has(X.target))Q.push(`Playbook transition '${B.id}' -> '${X.target}' targets an undefined state.`);for(let B of ZR$(A,$))Q.push(`Playbook state '${B}' is unreachable.`);return{valid:Q.length===0,errors:Q}}function Ln(A){let Q=TzA(A);if(!Q.valid)throw Error(Q.errors.join(`
10154
+ `}S2();du();var cx$=new Set(["entityType"]),px$={base:"Notes"},lx$=new Set(["note"]);function dx$(A){let Q=["file.name"];for(let $ of A)if(!cx$.has($.name))Q.push($.name);return Q}function ix$(A){return A.some((Q)=>Q.name==="status"&&Q.type==="enum")}function Ym2(A,Q){let $=px$[A]??LRA(A),w=ix$(Q),B=dx$(Q),X=[{type:"table",name:`All ${$}`,order:B}];if(w)X.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:B});let Z={filters:{and:[lx$.has(A)?'file.folder == "/"':`file.inFolder("${A}")`]},views:X};return{filename:`${$}.base`,content:lu(Z),hasStatus:w}}function Zm2(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w}")`),$={filters:{and:[Q.length===1?Q[0]:{or:Q}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return lu($)}function Hm2(A){if(A.length===0)return null;let Q=A.map((w)=>`file.inFolder("${w.entityType}")`),$={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 lu($)}var Wm2={name:"@brains/obsidian-vault",version:"0.2.0-alpha.184",description:"Obsidian vault integration \u2014 generates templates from entity schemas",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var ax$={mkdir:ox$,writeFile:sx$,existsFile:rx$},tx$=H.object({entityTypes:H.array(H.string()).optional().describe("Entity types to generate templates for (default: all)")});class xzA extends p6{deps;constructor(A={},Q={}){super("obsidian-vault",Wm2,A,OzA);this.deps={...ax$,...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[p8(this.id,"sync-templates","Generate Obsidian templates, Metadata Menu fileClass definitions, and Bases views for all registered entity types.",tx$,async(Q)=>{return this.sync(A,Q.entityTypes)},{sideEffects:"external"})]}async sync(A,Q){try{let $=A.entityService.getEntityTypes(),w=Q?$.filter((I)=>Q.includes(I)):$,B=xP(A.dataDir,this.config.baseFolder),X=xP(B,"templates"),Y=xP(B,"fileClasses"),Z=xP(B,"bases");this.deps.mkdir(X,{recursive:!0}),this.deps.mkdir(Y,{recursive:!0}),this.deps.mkdir(Z,{recursive:!0});let W=[],K=[],U=[],G=[],D=[],q=[];for(let I of w){let P=A.entities.getEffectiveFrontmatterSchema(I);if(!P){this.logger.debug(`Skipping ${I}: no frontmatter schema`),K.push(I);continue}let j=wm2(P),k=A.entities.getAdapter(I),f=k?.isSingleton===!0,R=Xm2(I,j);if(this.deps.writeFile(xP(Y,`${I}.md`),R),U.push(I),f){D.push(I),this.logger.debug(`Generated fileClass (singleton): ${I}`);continue}let x=k?.getBodyTemplate()??"",O=Bm2(I,j,x);this.deps.writeFile(xP(X,`${I}.md`),O),W.push(I);let g=Ym2(I,j),u=xP(Z,g.filename);if(!this.deps.existsFile(u))this.deps.writeFile(u,g.content),G.push(I),this.logger.debug(`Generated base: ${g.filename}`);if(g.hasStatus)q.push({entityType:I,fields:j});this.logger.debug(`Generated template + fileClass: ${I}`)}let J=Zm2(D);if(J){let I=xP(Z,"Settings.base");if(!this.deps.existsFile(I))this.deps.writeFile(I,J),G.push("Settings"),this.logger.debug("Generated Settings.base")}let F=Hm2(q);if(F){let I=xP(Z,"Pipeline.base");if(!this.deps.existsFile(I))this.deps.writeFile(I,F),G.push("Pipeline"),this.logger.debug("Generated Pipeline.base")}return this.logger.info(`Synced ${W.length} templates, ${U.length} fileClasses, ${G.length} bases (${K.length} skipped)`),f7({generated:W,skipped:K,fileClasses:U,bases:G})}catch($){return this.logger.error("Failed to sync",{error:$}),YY($ instanceof Error?$.message:"Unknown error")}}}function RzA(A={},Q){return new xzA(A,Q)}qA0();KA();C0();var Km2={name:"@brains/notifications",version:"0.2.0-alpha.184",description:"Generic notification routing for transactional and administrative messages",dependencies:{"@brains/email-contracts":"workspace:*","@brains/notification-contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};qA0();var AR$=H.looseObject({defaultRecipient:WD0.optional()});class Um2 extends p6{constructor(A={}){super("notifications",Km2,A,AR$)}async onRegister(A){A.messaging.subscribe(gv,async(Q)=>{let $=Ea0.parse(Q.payload),w=$.recipient??this.config.defaultRecipient;if(!w)return A.logger.warn("Notification has no recipient"),{success:!1,error:"Notification recipient missing"};let B={to:w.address,subject:$.title,text:$.body,...$.html?{html:$.html}:{},sensitivity:$.sensitivity},X=await A.messaging.send({type:nL0,payload:B});if(!("success"in X)||!X.success||!X.data)return{success:!1,error:"Notification delivery failed"};let Y=X.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 Tj0(A={}){return new Um2(A)}e8();KA();KA();S2();y9();KA();C0();var yj0=H.enum(["draft","active","archived"]),gj0=H.enum(["anchor","trusted","public"]),Sj0=H.enum(["agent-confirmed","manual"]),QR$=H.enum(["draft","active","archived"]),$R$=H.enum(["anchor","trusted","public"]),wR$=H.enum(["agent-confirmed","manual"]),qI=H.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,H.string().min(1).optional()),RP=H.preprocess((A)=>typeof A==="string"&&A.trim().length===0?void 0:A,H.string().min(1).optional()),vzA=H.object({event:H.string().min(1),target:H.string().min(1),operatorAction:H.boolean().optional(),label:RP,description:RP,operatorDescription:RP}),CzA=H.object({id:H.string().min(1),title:H.string().min(1),prompt:RP,requiredDetails:H.array(H.string().min(1)).default([]),instructions:H.array(H.string().min(1)).default([]),doneWhen:H.array(H.string().min(1)).default([]),transitions:H.array(vzA).default([])}),mj0=H.object({purpose:H.string().min(1),operatingRules:H.array(H.string().min(1)).default([]),initialState:H.string().min(1),states:H.array(CzA).min(1),finalStates:H.array(H.string().min(1)).min(1),nextPrompts:H.array(H.string().min(1)).default([])}),Fn=H.object({title:H.string(),status:yj0.default("active"),audience:gj0.default("anchor"),trigger:qI.optional(),lifecycle:qI.optional(),once:H.boolean().optional(),starterText:qI.optional(),description:qI.optional(),starterPrompt:qI.optional(),completionMode:Sj0.default("agent-confirmed")}),Gm2=H.object({title:H.string(),status:yj0,audience:gj0,trigger:qI.optional(),lifecycle:qI.optional(),once:H.boolean().optional(),starterText:qI.optional(),description:qI.optional(),starterPrompt:qI.optional(),completionMode:Sj0}),BR$=H.object({title:H.string(),status:QR$,audience:$R$,trigger:RP.optional(),lifecycle:RP.optional(),once:H.boolean().optional(),starterText:RP.optional(),description:RP.optional(),starterPrompt:RP.optional(),completionMode:wR$}),In=H6.extend({entityType:H.literal("playbook"),metadata:BR$});class uj0 extends d${constructor(){super(mj0,{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:hzA,parser:EzA},{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:XR$,parser:YR$},{key:"label",label:"Label",type:"custom",formatter:hzA,parser:EzA},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:hzA,parser:EzA}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var k50=new uj0;function hzA(A){return typeof A==="string"?A:""}function EzA(A){let Q=A.trim();return Q.length>0?Q:void 0}function XR$(A){return typeof A==="boolean"?String(A):""}function YR$(A){let Q=A.trim().toLowerCase();if(Q==="true")return!0;if(Q==="false")return!1;return}function TzA(A){let Q=[],$=new Set,w=new Set;for(let B of A.states){if($.has(B.id))w.add(B.id);$.add(B.id)}if(!$.has(A.initialState))Q.push(`Playbook initial state '${A.initialState}' is not defined.`);for(let B of w)Q.push(`Duplicate playbook state id '${B}'.`);for(let B of A.finalStates)if(!$.has(B))Q.push(`Playbook final state '${B}' is not defined.`);for(let B of A.states)for(let X of B.transitions)if(!$.has(X.target))Q.push(`Playbook transition '${B.id}' -> '${X.target}' targets an undefined state.`);for(let B of ZR$(A,$))Q.push(`Playbook state '${B}' is unreachable.`);return{valid:Q.length===0,errors:Q}}function Ln(A){let Q=TzA(A);if(!Q.valid)throw Error(Q.errors.join(`
10155
10155
  `))}function ZR$(A,Q){if(!Q.has(A.initialState))return[];let $=new Set,w=[A.initialState];while(w.length>0){let B=w.shift();if(!B||$.has(B))continue;$.add(B);let X=A.states.find((Y)=>Y.id===B);if(!X)continue;for(let Y of X.transitions)if(Q.has(Y.target)&&!$.has(Y.target))w.push(Y.target)}return A.states.map((B)=>B.id).filter((B)=>!$.has(B))}class pj0 extends UQ{constructor(){super({entityType:"playbook",purpose:"A guided multi-step workflow the assistant runs together with the user.",schema:In,frontmatterSchema:Fn})}createPlaybookContent(A,Q){return this.buildMarkdown(k50.format(Q),A)}parsePlaybookContent(A){let Q=this.parseFrontMatter(A,Fn),$=this.extractBody(A).trim(),w=HR$($)?WR$($):k50.parse($);return Ln(w),{frontmatter:Fn.parse(Q),body:w,bodyMarkdown:$}}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 DT=new pj0;function HR$(A){return/^##\s+Steps\s*$/im.test(A)}function WR$(A){let Q=KR$(yzA(A,"Steps"));if(Q.length===0)throw Error("Playbook must declare at least one step.");let $=Q.map((w,B)=>{let X=B===Q.length-1;if(!X&&w.doneWhen.length===0&&w.choices.length===0&&!w.skip)throw Error(`Playbook step '${w.title}' must declare Done when, Choices, or Skip.`);return{id:w.id,title:w.title,...w.prompt?{prompt:w.prompt}:{},requiredDetails:w.requiredDetails,instructions:w.instructions,doneWhen:w.doneWhen,transitions:[...w.doneWhen.length>0&&!X?[{event:"NEXT",target:Q[B+1]?.id??w.id}]:[],...w.choices.map((Y,Z)=>({event:`CHOICE_${Z+1}`,target:k1(Y.target),operatorAction:!0,label:Y.label})),...w.skip?[{event:"SKIP",target:k1(w.skip.target),operatorAction:!0,label:w.skip.label}]:[]]}});return{purpose:UR$(A,"Purpose"),operatingRules:Dm2(A,"Operating Rules"),initialState:Q[0]?.id??"",states:$,finalStates:[Q.at(-1)?.id??""],nextPrompts:Dm2(A,"Next Prompts")}}function KR$(A){let Q=[],$;for(let w of A.split(/\r?\n/)){let B=/^###\s+(.+?)\s*$/.exec(w);if(B){$={title:B[1]??"",content:[]},Q.push($);continue}$?.content.push(w)}return Q.map((w)=>{let B=w.content.join(`
10156
10156
  `);return{title:w.title,id:k1(w.title),...qm2(B,"Say")?{prompt:qm2(B,"Say")}:{},requiredDetails:cj0(B,"Required details"),instructions:cj0(B,"To do"),doneWhen:cj0(B,"Done when"),choices:GR$(B,"Choices"),...zm2(B)?{skip:zm2(B)}:{}}})}function yzA(A,Q){let $=A.split(/\r?\n/),w=$.findIndex((X)=>X.trim().toLowerCase()===`## ${Q.toLowerCase()}`);if(w===-1)return"";let B=[];for(let X of $.slice(w+1)){if(/^##\s+/.test(X))break;B.push(X)}return B.join(`
10157
10157
  `).trim()}function UR$(A,Q){return yzA(A,Q).split(/\r?\n/).map(($)=>$.trim()).filter(($)=>$.length>0&&!$.startsWith("#")).join(`
10158
10158
  `).trim()}function Dm2(A,Q){return Vm2(yzA(A,Q))}function qm2(A,Q){return new RegExp(`^${qR$(Q)}:\\s*(.+?)\\s*$`,"im").exec(A)?.[1]?.trim()}function cj0(A,Q){let $=A.split(/\r?\n/),w=$.findIndex((X)=>X.trim().toLowerCase()===`${Q.toLowerCase()}:`);if(w===-1)return[];let B=[];for(let X of $.slice(w+1)){let Y=X.trim();if(Y.length===0)continue;if(/^[A-Za-z][A-Za-z ]+:/.test(Y)||/^#{1,6}\s+/.test(Y))break;B.push(X)}return Vm2(B.join(`
10159
- `))}function GR$(A,Q){return cj0(A,Q).map(DR$)}function DR$(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 zm2(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 Vm2(A){return A.split(/\r?\n/).map((Q)=>/^-\s+(.+?)\s*$/.exec(Q)?.[1]?.trim()).filter((Q)=>Boolean(Q))}function qR$(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}C0();var lj0=H.object({}).catchall(H.unknown()).transform(()=>({}));var dj0={name:"@brains/playbooks",version:"0.2.0-alpha.183",description:"Runtime orchestration for chat-native playbook runs",dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/runtime-state":"workspace:*","@brains/utils":"workspace:*",xstate:"^5.32.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var VR$="playbook";class gzA extends S6{entityType=VR$;schema=In;adapter=DT;constructor(A={}){super("playbook",dj0,A,lj0)}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 SzA(A={}){return new gzA(A)}e8();KA();C0();bH();WA0();function ij0(A,Q){return A.length===Q.length&&A.every(($,w)=>$===Q[w])}function mzA(A,Q){return Q==="NEXT"&&A.doneWhen.length>0}function nj0(A,Q){return Q.gateVerdicts.some(($)=>$.stateId===A.id&&ij0($.goal,A.doneWhen)&&$.met)}function JR$(A,Q,$){return z2.createMachine({id:A,initial:Q.initialState,states:Object.fromEntries(Q.states.map((w)=>{let B=Q.finalStates.includes(w.id);return[w.id,{...B?{type:"final"}:{},...B?{}:{on:Object.fromEntries(w.transitions.map((X)=>[X.event,{target:X.target,...mzA(w,X.event)?{guard:()=>nj0(w,$)}:{}}]))}}]}))})}function uzA(A,Q){let $=JR$(Q.playbookId,A,Q);return z2.createActor($,{snapshot:$.resolveState({value:Q.currentState})})}function FR$(A,Q,$){let w=uzA(Q,A);w.start();let B=w.getSnapshot().can({type:$});return w.stop(),B}function Nn(A,Q,$){return $.transitions.filter((w)=>FR$(A,Q,w.event))}function j50(A,Q,$){let w=new Set(Nn(A,Q,$).map((B)=>`${B.event}\x00${B.target}`));return $.transitions.filter((B)=>!w.has(`${B.event}\x00${B.target}`))}function Jm2(A,Q){return A.evidence.filter(($)=>!$.stateId||$.stateId===Q)}function qT(A,Q){return A.states.find(($)=>$.id===Q)}function zT(A){let Q=A.operatorDescription??A.description??A.label;return Q?`- ${A.event} -> ${A.target}: ${Q}`:`- ${A.event} -> ${A.target}`}function Fm2(A,Q){if(Q.doneWhen.length===0)return"- no gated Done When conditions";let $=A.gateVerdicts.find((w)=>w.stateId===Q.id&&ij0(w.goal,Q.doneWhen));if(!$)return`- Not yet met: ${Q.doneWhen.join("; ")}`;return $.met?`- Met: ${$.reason}`:`- Not yet met: ${$.reason}`}function Im2(A,Q,$){let w=Nn(A,Q,$),B=w.filter((W)=>W.operatorAction!==!0),X=w.filter((W)=>W.operatorAction===!0),Y=j50(A,Q,$),Z=A.gateVerdicts.find((W)=>W.stateId===$.id&&ij0(W.goal,$.doneWhen));return[`Current state: ${$.id} (${$.title})`,"Instructions:",...$.instructions.map((W)=>`- ${W}`),"Done When:",...$.doneWhen.length>0?$.doneWhen.map((W)=>`- ${W}`):["- none"],"Goal status:",Z?`- ${Z.met?"Met":"Not yet met"}: ${Z.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:",...B.length>0?B.map((W)=>zT(W)):["- none"],"Available operator actions:",...X.length>0?X.map((W)=>zT(W)):["- none"],"Blocked events:",...Y.length>0?Y.map((W)=>zT(W)):["- none"]].join(`
10159
+ `))}function GR$(A,Q){return cj0(A,Q).map(DR$)}function DR$(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 zm2(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 Vm2(A){return A.split(/\r?\n/).map((Q)=>/^-\s+(.+?)\s*$/.exec(Q)?.[1]?.trim()).filter((Q)=>Boolean(Q))}function qR$(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}C0();var lj0=H.object({}).catchall(H.unknown()).transform(()=>({}));var dj0={name:"@brains/playbooks",version:"0.2.0-alpha.184",description:"Runtime orchestration for chat-native playbook runs",dependencies:{"@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/runtime-state":"workspace:*","@brains/utils":"workspace:*",xstate:"^5.32.1"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var VR$="playbook";class gzA extends S6{entityType=VR$;schema=In;adapter=DT;constructor(A={}){super("playbook",dj0,A,lj0)}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 SzA(A={}){return new gzA(A)}e8();KA();C0();bH();WA0();function ij0(A,Q){return A.length===Q.length&&A.every(($,w)=>$===Q[w])}function mzA(A,Q){return Q==="NEXT"&&A.doneWhen.length>0}function nj0(A,Q){return Q.gateVerdicts.some(($)=>$.stateId===A.id&&ij0($.goal,A.doneWhen)&&$.met)}function JR$(A,Q,$){return z2.createMachine({id:A,initial:Q.initialState,states:Object.fromEntries(Q.states.map((w)=>{let B=Q.finalStates.includes(w.id);return[w.id,{...B?{type:"final"}:{},...B?{}:{on:Object.fromEntries(w.transitions.map((X)=>[X.event,{target:X.target,...mzA(w,X.event)?{guard:()=>nj0(w,$)}:{}}]))}}]}))})}function uzA(A,Q){let $=JR$(Q.playbookId,A,Q);return z2.createActor($,{snapshot:$.resolveState({value:Q.currentState})})}function FR$(A,Q,$){let w=uzA(Q,A);w.start();let B=w.getSnapshot().can({type:$});return w.stop(),B}function Nn(A,Q,$){return $.transitions.filter((w)=>FR$(A,Q,w.event))}function j50(A,Q,$){let w=new Set(Nn(A,Q,$).map((B)=>`${B.event}\x00${B.target}`));return $.transitions.filter((B)=>!w.has(`${B.event}\x00${B.target}`))}function Jm2(A,Q){return A.evidence.filter(($)=>!$.stateId||$.stateId===Q)}function qT(A,Q){return A.states.find(($)=>$.id===Q)}function zT(A){let Q=A.operatorDescription??A.description??A.label;return Q?`- ${A.event} -> ${A.target}: ${Q}`:`- ${A.event} -> ${A.target}`}function Fm2(A,Q){if(Q.doneWhen.length===0)return"- no gated Done When conditions";let $=A.gateVerdicts.find((w)=>w.stateId===Q.id&&ij0(w.goal,Q.doneWhen));if(!$)return`- Not yet met: ${Q.doneWhen.join("; ")}`;return $.met?`- Met: ${$.reason}`:`- Not yet met: ${$.reason}`}function Im2(A,Q,$){let w=Nn(A,Q,$),B=w.filter((W)=>W.operatorAction!==!0),X=w.filter((W)=>W.operatorAction===!0),Y=j50(A,Q,$),Z=A.gateVerdicts.find((W)=>W.stateId===$.id&&ij0(W.goal,$.doneWhen));return[`Current state: ${$.id} (${$.title})`,"Instructions:",...$.instructions.map((W)=>`- ${W}`),"Done When:",...$.doneWhen.length>0?$.doneWhen.map((W)=>`- ${W}`):["- none"],"Goal status:",Z?`- ${Z.met?"Met":"Not yet met"}: ${Z.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:",...B.length>0?B.map((W)=>zT(W)):["- none"],"Available operator actions:",...X.length>0?X.map((W)=>zT(W)):["- none"],"Blocked events:",...Y.length>0?Y.map((W)=>zT(W)):["- none"]].join(`
10160
10160
  `)}function Lm2(A){let{run:Q,body:$,state:w,playbookTitle:B}=A,X=Nn(Q,$,w),Y=X.filter((I)=>I.operatorAction!==!0),Z=X.filter((I)=>I.operatorAction===!0),W=j50(Q,$,w),K=Y.map((I)=>zT(I)).join(`
10161
10161
  `),U=Z.map((I)=>zT(I)).join(`
10162
10162
  `),G=W.map((I)=>zT(I)).join(`
@@ -10230,9 +10230,9 @@ ${Object.entries(A).map(([$,w])=>`- ${$}: playbookId=${w.playbookId}, trigger=${
10230
10230
  ${A.guidance}`:B}}function vm2(A){return{...A,evidence:A.evidence.map((Q)=>({...Q,data:CR$(Q.data)}))}}function CR$(A){return Object.fromEntries(["entityType","entityId","operation"].flatMap((Q)=>A[Q]!==void 0?[[Q,A[Q]]]:[]))}function hR$(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 ER$(A){if(!A)return"Continuing.";return A.prompt??`Continuing to ${A.title}.`}function Cm2(){return{promptTokens:0,completionTokens:0,totalTokens:0}}function hm2(A,Q){let $=A.filter(Q),w=$.filter((B)=>B.status==="active"||B.status==="offered");return nzA(w)??nzA($)}function nzA(A){return[...A].sort((Q,$)=>($.completedAt??$.updatedAt).localeCompare(Q.completedAt??Q.updatedAt))[0]}function TR$(A){return{async evaluate(Q){let $=Q.goal.join(`
10231
10231
  `),w=await A.entityService.search({query:$,options:{limit:8,excludeTypes:["playbook"],visibilityScope:c5("anchor")}}),B=yR$(Q,w),{verdict:X}=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:B,schema:OR$});return X}}}function yR$(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(($)=>`- ${$}`),"","## Done When goal",...A.goal.map(($)=>`- ${$}`),"","## Runtime evidence",...A.evidence.length>0?A.evidence.map(($,w)=>gR$(w+1,$)):["No runtime evidence collected for this state."],"","## KB excerpts",...Q.length>0?Q.map(($,w)=>SR$(w+1,$)):["No relevant KB excerpts found."]].join(`
10232
10232
  `)}function gR$(A,Q){return`${A}. ${Q.kind} at ${Q.observedAt}: ${Tm2(Q.data)}`}function SR$(A,Q){return[`${A}. ${Q.entity.entityType}/${Q.entity.id} (score ${Q.score})`,`Excerpt: ${Q.excerpt}`,`Content: ${ym2(Q.entity.content,1200)}`,`Metadata: ${Tm2(Q.entity.metadata)}`].join(`
10233
- `)}function Tm2(A){try{return ym2(JSON.stringify(A),1200)}catch{return"[unserializable]"}}function ym2(A,Q){return A.length>Q?`${A.slice(0,Q)}\u2026`:A}var mR$={async evaluate(){return{met:!1,reason:"No playbook goal check is configured."}}};function ozA(A={},Q={}){return new rzA(A,Q)}e8();KA();C0();import{readFile as cR$}from"fs/promises";import{join as pR$}from"path";var gm2={name:"@brains/rover-onboarding",version:"0.2.0-alpha.183",description:"Rover onboarding playbook bundle and activation plugin",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/playbooks":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var lR$=H.object({enabled:H.boolean().default(!1)}).strict(),Sm2=[{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 mm2 extends p6{dependencies=["playbook","playbooks"];constructor(A={}){super("rover-onboarding",gm2,A,lR$)}async onReady(A){if(!this.config.enabled)return;for(let Q of Sm2)await this.seedPlaybookIfMissing(A,Q);for(let Q of Sm2){if(!Q.starter)continue;await A.messaging.send({type:Hg,payload:Q.starter})}}async seedPlaybookIfMissing(A,Q){if(await A.entityService.getEntity({entityType:"playbook",id:Q.id,visibilityScope:"restricted"}))return;let w=await cR$(pR$(import.meta.dir,"..","content","playbook",Q.fileName),"utf8");await A.entityService.createEntityFromMarkdown({input:{entityType:"playbook",id:Q.id,markdown:w}})}}function um2(A={}){return new mm2(A)}KA();C0();C0();KA();var szA=H.enum(["new","planned","in-progress","done","declined"]),azA=H.enum(["low","medium","high","critical"]),dR$=H.enum(["new","planned","in-progress","done","declined"]),iR$=H.enum(["low","medium","high","critical"]),M50=H.object({title:H.string(),status:szA,priority:azA.default("medium"),requested:H.number().int().default(1),declinedReason:H.string().optional()}),nR$=H.object({title:H.string(),status:szA,priority:azA,requested:H.number().int(),slug:H.string()}),rR$=H.object({title:H.string(),status:dR$,priority:iR$,requested:H.number().int(),slug:H.string()}),b50=H6.extend({entityType:H.literal("wish"),metadata:rR$});C0();var tzA=H.object({}).catchall(H.unknown()).transform(()=>({}));KA();S2();class O50 extends UQ{constructor(){super({entityType:"wish",purpose:"An explicitly recorded capability or outcome the assistant cannot currently fulfill, kept for future planning.",schema:b50,frontmatterSchema:M50})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,M50);return{frontmatter:M50.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),$=k1(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:$}}}}var cm2=new O50;S2();S2();async function pm2(A,Q){let $=`${Q.title}: ${Q.description}`,B=(await A.search({query:$,options:{types:["wish"],limit:1}}))[0];if(B&&B.score>=A.similarityThreshold)return B.entity;let X=k1(Q.title);return A.getEntity({entityType:"wish",id:X})}class aj0{logger;context;adapter=new O50;constructor(A,Q){this.logger=A,this.context=Q}async process(A,Q,$){let w=A.title??A.prompt??"Untitled wish",B=A.content??A.prompt??"",X=await pm2({search:(K)=>this.context.entityService.search(K),getEntity:(K)=>this.context.entityService.getEntity(K),similarityThreshold:0.85},{title:w,description:B});if(X){let{frontmatter:K,description:U}=this.adapter.parseWishContent(X.content),G=K.requested+1,D=this.adapter.createWishContent({...K,requested:G},U);return await this.context.entityService.updateEntity({entity:{...X,content:D,metadata:{...X.metadata,requested:G}}}),this.logger.info("Incremented wish request count",{id:X.id,requested:G}),{success:!0,entityId:X.id,existed:!0,requested:G}}let Y=k1(w),Z=A.options?.priority??"medium",W=this.adapter.createWishContent({title:w,status:"new",priority:Z,requested:1},B);return await this.context.entityService.createEntity({entity:{id:Y,entityType:"wish",content:W,metadata:{title:w,status:"new",priority:Z,requested:1,slug:Y}}}),this.logger.info("Created new wish",{id:Y,title:w}),{success:!0,entityId:Y,existed:!1,requested:1}}}var lm2={critical:0,high:1,medium:2,low:3};function dm2(A){A.sort((Q,$)=>{let w=$.metadata.requested-Q.metadata.requested;if(w!==0)return w;return lm2[Q.metadata.priority]-lm2[$.metadata.priority]})}var im2={name:"@brains/wishlist",version:"0.2.0-alpha.183",description:"Wishlist plugin for tracking unfulfilled user requests",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var sR$=H.object({items:H.array(H.object({name:H.string(),count:H.number()}))}),aR$="wish";class nm2 extends S6{entityType=aR$;schema=b50;adapter=cm2;constructor(A={}){super("wishlist",im2,A,tzA)}async interceptCreate(A,Q,$){let w=await new aj0(this.logger,$).process({...A.title?{title:A.title}:{},...A.prompt?{prompt:A.prompt}:{},...A.content?{content:A.content}:{}},`wish-create-${Date.now()}`,{});if(!w.success)return{kind:"handled",result:{success:!1,error:w.error??"Failed to create wish"}};return{kind:"handled",result:{success:!0,data:{...w.entityId?{entityId:w.entityId}:{},status:w.existed?"updated":"created"}}}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"top-wishes",pluginId:this.id,title:"Top Wishes",group:"knowledge",section:"secondary",priority:30,rendererName:"ListWidget",digestProvider:($)=>{let{items:w}=sR$.parse($),B=w[0];return{digest:B?[{label:"Top wish",value:`${B.name} \xB7 \xD7${B.count}`}]:[{label:"Wishes",value:"none yet"}]}},dataProvider:async()=>{let $=await A.entityService.listEntities({entityType:"wish",options:{limit:10}});return dm2($),{items:$.map((w)=>({id:w.id,name:w.metadata.title,count:w.metadata.requested,priority:w.metadata.priority,status:w.metadata.status}))}}}}),{success:!0}});let Q=new aj0(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:($)=>$})}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 tR$(A={}){return new nm2(A)}var tj0=tR$;KA();KA();C0();var f50=H.object({title:H.string(),target:H.string()}),rm2=H.object({title:H.string(),target:H.string(),slug:H.string().optional()}),x50=H6.extend({entityType:H.literal("prompt"),metadata:rm2});KA();S2();class ezA extends UQ{constructor(){super({entityType:"prompt",purpose:"A reusable prompt or instruction template.",schema:x50,frontmatterSchema:f50})}toMarkdown(A){let Q=this.extractBody(A.content),$=this.parseFrontMatter(A.content,f50);return this.buildMarkdown(Q,$)}fromMarkdown(A){let Q=this.parseFrontMatter(A,f50),$=k1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:$}}}}var A3A=new ezA;var om2={name:"@brains/prompt",version:"0.2.0-alpha.183",description:"Prompt entity type \u2014 AI prompts as editable markdown entities",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Av$="prompt";class Q3A extends S6{entityType=Av$;schema=x50;adapter=A3A;constructor(){super("prompt",om2,{},XY)}getEntityTypeConfig(){return{embeddable:!1}}}function JT(){return new Q3A}KA();C0();C0();class ej0{apiKey;fetchFn;baseUrl="https://api.unsplash.com";constructor(A,Q){this.apiKey=A,this.fetchFn=Q}async searchPhotos(A,Q){let $=new URL(`${this.baseUrl}/search/photos`);$.searchParams.set("query",A),$.searchParams.set("page",String(Q.page)),$.searchParams.set("per_page",String(Q.perPage));let w=await this.fetchFn($.toString(),{headers:{Authorization:`Client-ID ${this.apiKey}`}});if(!w.ok)throw Error(`Unsplash API error: ${w.status} ${w.statusText}`);let B=$v$.parse(await w.json());return{photos:B.results.map(wv$),total:B.total,totalPages:B.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}var Qv$=H.looseObject({id:H.string(),description:H.string().nullable(),alt_description:H.string().nullable(),urls:H.looseObject({raw:H.url(),full:H.url(),regular:H.url(),small:H.url(),thumb:H.url()}),links:H.looseObject({html:H.url(),download_location:H.url()}),user:H.looseObject({name:H.string(),links:H.looseObject({html:H.url()})}),width:H.number().int().nonnegative(),height:H.number().int().nonnegative()}),$v$=H.looseObject({total:H.number().int().nonnegative(),total_pages:H.number().int().nonnegative(),results:H.array(Qv$)});function wv$(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}}C0();async function AM0(A,Q,$,w){let B=await A.getEntity({entityType:Q,id:$});if(!B)return!1;return await A.updateEntity({entity:{...B,metadata:{...B.metadata,coverImageId:w}}}),!0}var Bv$={query:H.string().describe("Search terms for stock photos"),perPage:H.number().min(1).max(30).default(10).describe("Results per page (1-30)"),page:H.number().min(1).default(1).describe("Page number")},Xv$={photoId:H.string().describe("Photo ID from search results"),downloadLocation:H.url().describe("Download tracking URL (required by provider ToS)"),photographerName:H.string().describe("Photographer name for attribution"),photographerUrl:H.url().describe("Photographer profile URL for attribution"),sourceUrl:H.url().describe("Photo page URL on provider"),imageUrl:H.url().describe("Image URL to download"),title:H.string().optional().describe("Image entity title"),alt:H.string().optional().describe("Alt text for the image"),targetEntityType:H.string().optional().describe("Entity type to set cover image on"),targetEntityId:H.string().optional().describe("Entity ID to set cover image on")},Yv$=H.object({query:H.string(),perPage:H.number().min(1).max(30).default(10),page:H.number().min(1).default(1)}),Zv$=H.object({photoId:H.string(),downloadLocation:H.url(),photographerName:H.string(),photographerUrl:H.url(),sourceUrl:H.url(),imageUrl:H.url(),title:H.string().optional(),alt:H.string().optional(),targetEntityType:H.string().optional(),targetEntityId:H.string().optional()});function sm2(A,Q){return[Hv$(A,Q),Wv$(A,Q)]}function Hv$(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:Bv$,visibility:"anchor",sideEffects:"none",handler:async($)=>{let w=Yv$.safeParse($);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};try{return{success:!0,data:await Q.provider.searchPhotos(w.data.query,{page:w.data.page,perPage:w.data.perPage})}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Search failed"}}}}}function Wv$(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:Xv$,visibility:"anchor",sideEffects:"external",handler:async($)=>{let w=Zv$.safeParse($);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{photoId:B,downloadLocation:X,photographerName:Y,photographerUrl:Z,sourceUrl:W,imageUrl:K,title:U,alt:G,targetEntityType:D,targetEntityId:q}=w.data,J={photographerName:Y,photographerUrl:Z,sourceUrl:W},F=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:K}}}});if(F[0]){let j={imageEntityId:F[0].id,alreadyExisted:!0,attribution:J};if(D&&q)j.coverSet=await AM0(Q.entityService,D,q,F[0].id);return{success:!0,data:j}}let I=await Q.jobs.enqueue({type:"select-photo",data:{photoId:B,downloadLocation:X,photographerName:Y,photographerUrl:Z,sourceUrl:W,imageUrl:K,...U!==void 0?{title:U}:{},...G!==void 0?{alt:G}:{},...D!==void 0?{targetEntityType:D}:{},...q!==void 0?{targetEntityId:q}:{}}}),P={imageEntityId:B,alreadyExisted:!1,attribution:J,jobId:I,status:"generating"};if(D&&q)P.coverSet=!1;return{success:!0,data:P}}}}KA();C0();JZ();var Kv$=H.object({photoId:H.string(),downloadLocation:H.url(),photographerName:H.string(),photographerUrl:H.url(),sourceUrl:H.url(),imageUrl:H.url(),title:H.string().optional(),alt:H.string().optional(),targetEntityType:H.string().optional(),targetEntityId:H.string().optional()});class $3A extends X8{deps;constructor(A,Q){super(A,{schema:Kv$,jobTypeName:"select-photo"});this.deps=Q}async process(A,Q,$){await this.reportProgress($,{progress:10,message:"Tracking stock photo download"}),await this.deps.provider.triggerDownload(A.downloadLocation),await this.reportProgress($,{progress:35,message:"Downloading stock photo"});let w=await this.deps.fetchImage(A.imageUrl),B=A.title??`Stock photo ${A.photoId}`,X=PU.createImageEntity({dataUrl:w,title:B,alt:A.alt??B});await this.reportProgress($,{progress:75,message:"Saving stock photo"});let{entityId:Y}=await this.deps.entityService.createEntity({entity:{id:A.photoId,...X,metadata:{...X.metadata,sourceUrl:A.imageUrl}}}),Z={imageEntityId:Y,alreadyExisted:!1};if(A.targetEntityType&&A.targetEntityId){if(Z.coverSet=await AM0(this.deps.entityService,A.targetEntityType,A.targetEntityId,Y),!Z.coverSet)Z.warning=`Target entity ${A.targetEntityType}:${A.targetEntityId} not found; cover image not set`}return await this.reportProgress($,{progress:100,message:"Stock photo selected"}),Z}summarizeDataForLog(A){return{photoId:A.photoId,hasTarget:A.targetEntityType!==void 0}}}JZ();var am2={name:"@brains/stock-photo",version:"0.2.0-alpha.183",description:"Stock photo search and selection \u2014 Unsplash provider",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Gv$=H.object({provider:H.enum(["unsplash"]).default("unsplash"),apiKey:H.string().optional().describe("Stock photo provider API key")});class w3A extends p6{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",am2,A,Gv$);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=sm2(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??rD,jobs:A.jobs}),this.cachedTools}async registerJobHandlers(){if(!this.config.apiKey)return;let A=this.getContext();A.jobs.registerHandler("select-photo",new $3A(this.logger.child("SelectPhotoJobHandler"),{provider:this.createProvider(),entityService:A.entityService,fetchImage:this.deps.fetchImage??rD}))}createProvider(){return new ej0(this.config.apiKey??"",this.deps.fetch??globalThis.fetch)}}function B3A(A={},Q={}){return new w3A(A,Q)}KA();C0();KA();KA();C0();var tm2=H.enum(["ai","foundation","work"]),em2=H.object({suffix:tm2,title:H.string(),body:H.string(),linkLabel:H.string(),linkHref:H.string()}),R50=H.object({eyebrow:H.string(),headline:H.string(),cards:H.array(em2).min(1)}),X3A=H.object({title:H.string(),slug:H.string(),status:H.enum(["draft","published"])}),Dv$=H.object({title:H.string(),slug:H.string(),status:H.enum(["draft","published"])}),v50=H6.extend({entityType:H.literal("ecosystem-section"),metadata:Dv$});class Au2 extends UQ{constructor(){super({entityType:"ecosystem-section",purpose:"A section of the Rizom ecosystem overview.",schema:v50,frontmatterSchema:X3A})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var Y3A=new Au2;C0();function qv$(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function Z3A(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function C50(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function QM0(A){let Q=qv$(A),w=Z3A(Q,"Cards").split(/^### Card \d+\s*$/m).map((B)=>B.trim()).filter(Boolean);return R50.parse({eyebrow:Z3A(Q,"Eyebrow"),headline:Z3A(Q,"Headline"),cards:w.map((B)=>({suffix:C50(B,"Suffix"),title:C50(B,"Title"),body:C50(B,"Body"),linkLabel:C50(B,"Link Label"),linkHref:C50(B,"Link Href")}))})}function Qu2(A){return["# Ecosystem Section","","## Eyebrow",A.eyebrow,"","## Headline",A.headline,"","## Cards","",...A.cards.flatMap((Q,$)=>[`### Card ${$+1}`,"","#### Suffix",Q.suffix,"","#### Title",Q.title,"","#### Body",Q.body,"","#### Link Label",Q.linkLabel,"","#### Link Href",Q.linkHref,""])].join(`
10233
+ `)}function Tm2(A){try{return ym2(JSON.stringify(A),1200)}catch{return"[unserializable]"}}function ym2(A,Q){return A.length>Q?`${A.slice(0,Q)}\u2026`:A}var mR$={async evaluate(){return{met:!1,reason:"No playbook goal check is configured."}}};function ozA(A={},Q={}){return new rzA(A,Q)}e8();KA();C0();import{readFile as cR$}from"fs/promises";import{join as pR$}from"path";var gm2={name:"@brains/rover-onboarding",version:"0.2.0-alpha.184",description:"Rover onboarding playbook bundle and activation plugin",dependencies:{"@brains/contracts":"workspace:*","@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/playbooks":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var lR$=H.object({enabled:H.boolean().default(!1)}).strict(),Sm2=[{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 mm2 extends p6{dependencies=["playbook","playbooks"];constructor(A={}){super("rover-onboarding",gm2,A,lR$)}async onReady(A){if(!this.config.enabled)return;for(let Q of Sm2)await this.seedPlaybookIfMissing(A,Q);for(let Q of Sm2){if(!Q.starter)continue;await A.messaging.send({type:Hg,payload:Q.starter})}}async seedPlaybookIfMissing(A,Q){if(await A.entityService.getEntity({entityType:"playbook",id:Q.id,visibilityScope:"restricted"}))return;let w=await cR$(pR$(import.meta.dir,"..","content","playbook",Q.fileName),"utf8");await A.entityService.createEntityFromMarkdown({input:{entityType:"playbook",id:Q.id,markdown:w}})}}function um2(A={}){return new mm2(A)}KA();C0();C0();KA();var szA=H.enum(["new","planned","in-progress","done","declined"]),azA=H.enum(["low","medium","high","critical"]),dR$=H.enum(["new","planned","in-progress","done","declined"]),iR$=H.enum(["low","medium","high","critical"]),M50=H.object({title:H.string(),status:szA,priority:azA.default("medium"),requested:H.number().int().default(1),declinedReason:H.string().optional()}),nR$=H.object({title:H.string(),status:szA,priority:azA,requested:H.number().int(),slug:H.string()}),rR$=H.object({title:H.string(),status:dR$,priority:iR$,requested:H.number().int(),slug:H.string()}),b50=H6.extend({entityType:H.literal("wish"),metadata:rR$});C0();var tzA=H.object({}).catchall(H.unknown()).transform(()=>({}));KA();S2();class O50 extends UQ{constructor(){super({entityType:"wish",purpose:"An explicitly recorded capability or outcome the assistant cannot currently fulfill, kept for future planning.",schema:b50,frontmatterSchema:M50})}createWishContent(A,Q){return this.buildMarkdown(Q,A)}parseWishContent(A){let Q=this.parseFrontMatter(A,M50);return{frontmatter:M50.parse(Q),description:this.extractBody(A).trim()}}fromMarkdown(A){let{frontmatter:Q}=this.parseWishContent(A),$=k1(Q.title);return{content:A,entityType:"wish",metadata:{title:Q.title,status:Q.status,priority:Q.priority,requested:Q.requested,slug:$}}}}var cm2=new O50;S2();S2();async function pm2(A,Q){let $=`${Q.title}: ${Q.description}`,B=(await A.search({query:$,options:{types:["wish"],limit:1}}))[0];if(B&&B.score>=A.similarityThreshold)return B.entity;let X=k1(Q.title);return A.getEntity({entityType:"wish",id:X})}class aj0{logger;context;adapter=new O50;constructor(A,Q){this.logger=A,this.context=Q}async process(A,Q,$){let w=A.title??A.prompt??"Untitled wish",B=A.content??A.prompt??"",X=await pm2({search:(K)=>this.context.entityService.search(K),getEntity:(K)=>this.context.entityService.getEntity(K),similarityThreshold:0.85},{title:w,description:B});if(X){let{frontmatter:K,description:U}=this.adapter.parseWishContent(X.content),G=K.requested+1,D=this.adapter.createWishContent({...K,requested:G},U);return await this.context.entityService.updateEntity({entity:{...X,content:D,metadata:{...X.metadata,requested:G}}}),this.logger.info("Incremented wish request count",{id:X.id,requested:G}),{success:!0,entityId:X.id,existed:!0,requested:G}}let Y=k1(w),Z=A.options?.priority??"medium",W=this.adapter.createWishContent({title:w,status:"new",priority:Z,requested:1},B);return await this.context.entityService.createEntity({entity:{id:Y,entityType:"wish",content:W,metadata:{title:w,status:"new",priority:Z,requested:1,slug:Y}}}),this.logger.info("Created new wish",{id:Y,title:w}),{success:!0,entityId:Y,existed:!1,requested:1}}}var lm2={critical:0,high:1,medium:2,low:3};function dm2(A){A.sort((Q,$)=>{let w=$.metadata.requested-Q.metadata.requested;if(w!==0)return w;return lm2[Q.metadata.priority]-lm2[$.metadata.priority]})}var im2={name:"@brains/wishlist",version:"0.2.0-alpha.184",description:"Wishlist plugin for tracking unfulfilled user requests",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var sR$=H.object({items:H.array(H.object({name:H.string(),count:H.number()}))}),aR$="wish";class nm2 extends S6{entityType=aR$;schema=b50;adapter=cm2;constructor(A={}){super("wishlist",im2,A,tzA)}async interceptCreate(A,Q,$){let w=await new aj0(this.logger,$).process({...A.title?{title:A.title}:{},...A.prompt?{prompt:A.prompt}:{},...A.content?{content:A.content}:{}},`wish-create-${Date.now()}`,{});if(!w.success)return{kind:"handled",result:{success:!1,error:w.error??"Failed to create wish"}};return{kind:"handled",result:{success:!0,data:{...w.entityId?{entityId:w.entityId}:{},status:w.existed?"updated":"created"}}}}async onRegister(A){A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"top-wishes",pluginId:this.id,title:"Top Wishes",group:"knowledge",section:"secondary",priority:30,rendererName:"ListWidget",digestProvider:($)=>{let{items:w}=sR$.parse($),B=w[0];return{digest:B?[{label:"Top wish",value:`${B.name} \xB7 \xD7${B.count}`}]:[{label:"Wishes",value:"none yet"}]}},dataProvider:async()=>{let $=await A.entityService.listEntities({entityType:"wish",options:{limit:10}});return dm2($),{items:$.map((w)=>({id:w.id,name:w.metadata.title,count:w.metadata.requested,priority:w.metadata.priority,status:w.metadata.status}))}}}}),{success:!0}});let Q=new aj0(this.logger,A);A.jobs.registerHandler("wish:create",{process:Q.process.bind(Q),validateAndParse:($)=>$})}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 tR$(A={}){return new nm2(A)}var tj0=tR$;KA();KA();C0();var f50=H.object({title:H.string(),target:H.string()}),rm2=H.object({title:H.string(),target:H.string(),slug:H.string().optional()}),x50=H6.extend({entityType:H.literal("prompt"),metadata:rm2});KA();S2();class ezA extends UQ{constructor(){super({entityType:"prompt",purpose:"A reusable prompt or instruction template.",schema:x50,frontmatterSchema:f50})}toMarkdown(A){let Q=this.extractBody(A.content),$=this.parseFrontMatter(A.content,f50);return this.buildMarkdown(Q,$)}fromMarkdown(A){let Q=this.parseFrontMatter(A,f50),$=k1(Q.target.replace(/:/g,"-"));return{content:A,entityType:"prompt",metadata:{title:Q.title,target:Q.target,slug:$}}}}var A3A=new ezA;var om2={name:"@brains/prompt",version:"0.2.0-alpha.184",description:"Prompt entity type \u2014 AI prompts as editable markdown entities",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","bun-types":"^1.3.14",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Av$="prompt";class Q3A extends S6{entityType=Av$;schema=x50;adapter=A3A;constructor(){super("prompt",om2,{},XY)}getEntityTypeConfig(){return{embeddable:!1}}}function JT(){return new Q3A}KA();C0();C0();class ej0{apiKey;fetchFn;baseUrl="https://api.unsplash.com";constructor(A,Q){this.apiKey=A,this.fetchFn=Q}async searchPhotos(A,Q){let $=new URL(`${this.baseUrl}/search/photos`);$.searchParams.set("query",A),$.searchParams.set("page",String(Q.page)),$.searchParams.set("per_page",String(Q.perPage));let w=await this.fetchFn($.toString(),{headers:{Authorization:`Client-ID ${this.apiKey}`}});if(!w.ok)throw Error(`Unsplash API error: ${w.status} ${w.statusText}`);let B=$v$.parse(await w.json());return{photos:B.results.map(wv$),total:B.total,totalPages:B.total_pages,page:Q.page}}async triggerDownload(A){try{await this.fetchFn(A,{headers:{Authorization:`Client-ID ${this.apiKey}`}})}catch{}}}var Qv$=H.looseObject({id:H.string(),description:H.string().nullable(),alt_description:H.string().nullable(),urls:H.looseObject({raw:H.url(),full:H.url(),regular:H.url(),small:H.url(),thumb:H.url()}),links:H.looseObject({html:H.url(),download_location:H.url()}),user:H.looseObject({name:H.string(),links:H.looseObject({html:H.url()})}),width:H.number().int().nonnegative(),height:H.number().int().nonnegative()}),$v$=H.looseObject({total:H.number().int().nonnegative(),total_pages:H.number().int().nonnegative(),results:H.array(Qv$)});function wv$(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}}C0();async function AM0(A,Q,$,w){let B=await A.getEntity({entityType:Q,id:$});if(!B)return!1;return await A.updateEntity({entity:{...B,metadata:{...B.metadata,coverImageId:w}}}),!0}var Bv$={query:H.string().describe("Search terms for stock photos"),perPage:H.number().min(1).max(30).default(10).describe("Results per page (1-30)"),page:H.number().min(1).default(1).describe("Page number")},Xv$={photoId:H.string().describe("Photo ID from search results"),downloadLocation:H.url().describe("Download tracking URL (required by provider ToS)"),photographerName:H.string().describe("Photographer name for attribution"),photographerUrl:H.url().describe("Photographer profile URL for attribution"),sourceUrl:H.url().describe("Photo page URL on provider"),imageUrl:H.url().describe("Image URL to download"),title:H.string().optional().describe("Image entity title"),alt:H.string().optional().describe("Alt text for the image"),targetEntityType:H.string().optional().describe("Entity type to set cover image on"),targetEntityId:H.string().optional().describe("Entity ID to set cover image on")},Yv$=H.object({query:H.string(),perPage:H.number().min(1).max(30).default(10),page:H.number().min(1).default(1)}),Zv$=H.object({photoId:H.string(),downloadLocation:H.url(),photographerName:H.string(),photographerUrl:H.url(),sourceUrl:H.url(),imageUrl:H.url(),title:H.string().optional(),alt:H.string().optional(),targetEntityType:H.string().optional(),targetEntityId:H.string().optional()});function sm2(A,Q){return[Hv$(A,Q),Wv$(A,Q)]}function Hv$(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:Bv$,visibility:"anchor",sideEffects:"none",handler:async($)=>{let w=Yv$.safeParse($);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};try{return{success:!0,data:await Q.provider.searchPhotos(w.data.query,{page:w.data.page,perPage:w.data.perPage})}}catch(B){return{success:!1,error:B instanceof Error?B.message:"Search failed"}}}}}function Wv$(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:Xv$,visibility:"anchor",sideEffects:"external",handler:async($)=>{let w=Zv$.safeParse($);if(!w.success)return{success:!1,error:`Invalid input: ${w.error.message}`};let{photoId:B,downloadLocation:X,photographerName:Y,photographerUrl:Z,sourceUrl:W,imageUrl:K,title:U,alt:G,targetEntityType:D,targetEntityId:q}=w.data,J={photographerName:Y,photographerUrl:Z,sourceUrl:W},F=await Q.entityService.listEntities({entityType:"image",options:{limit:1,filter:{metadata:{sourceUrl:K}}}});if(F[0]){let j={imageEntityId:F[0].id,alreadyExisted:!0,attribution:J};if(D&&q)j.coverSet=await AM0(Q.entityService,D,q,F[0].id);return{success:!0,data:j}}let I=await Q.jobs.enqueue({type:"select-photo",data:{photoId:B,downloadLocation:X,photographerName:Y,photographerUrl:Z,sourceUrl:W,imageUrl:K,...U!==void 0?{title:U}:{},...G!==void 0?{alt:G}:{},...D!==void 0?{targetEntityType:D}:{},...q!==void 0?{targetEntityId:q}:{}}}),P={imageEntityId:B,alreadyExisted:!1,attribution:J,jobId:I,status:"generating"};if(D&&q)P.coverSet=!1;return{success:!0,data:P}}}}KA();C0();JZ();var Kv$=H.object({photoId:H.string(),downloadLocation:H.url(),photographerName:H.string(),photographerUrl:H.url(),sourceUrl:H.url(),imageUrl:H.url(),title:H.string().optional(),alt:H.string().optional(),targetEntityType:H.string().optional(),targetEntityId:H.string().optional()});class $3A extends X8{deps;constructor(A,Q){super(A,{schema:Kv$,jobTypeName:"select-photo"});this.deps=Q}async process(A,Q,$){await this.reportProgress($,{progress:10,message:"Tracking stock photo download"}),await this.deps.provider.triggerDownload(A.downloadLocation),await this.reportProgress($,{progress:35,message:"Downloading stock photo"});let w=await this.deps.fetchImage(A.imageUrl),B=A.title??`Stock photo ${A.photoId}`,X=PU.createImageEntity({dataUrl:w,title:B,alt:A.alt??B});await this.reportProgress($,{progress:75,message:"Saving stock photo"});let{entityId:Y}=await this.deps.entityService.createEntity({entity:{id:A.photoId,...X,metadata:{...X.metadata,sourceUrl:A.imageUrl}}}),Z={imageEntityId:Y,alreadyExisted:!1};if(A.targetEntityType&&A.targetEntityId){if(Z.coverSet=await AM0(this.deps.entityService,A.targetEntityType,A.targetEntityId,Y),!Z.coverSet)Z.warning=`Target entity ${A.targetEntityType}:${A.targetEntityId} not found; cover image not set`}return await this.reportProgress($,{progress:100,message:"Stock photo selected"}),Z}summarizeDataForLog(A){return{photoId:A.photoId,hasTarget:A.targetEntityType!==void 0}}}JZ();var am2={name:"@brains/stock-photo",version:"0.2.0-alpha.184",description:"Stock photo search and selection \u2014 Unsplash provider",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Gv$=H.object({provider:H.enum(["unsplash"]).default("unsplash"),apiKey:H.string().optional().describe("Stock photo provider API key")});class w3A extends p6{deps;cachedTools=null;constructor(A={},Q={}){super("stock-photo",am2,A,Gv$);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=sm2(this.id,{provider:Q,entityService:A.entityService,fetchImage:this.deps.fetchImage??rD,jobs:A.jobs}),this.cachedTools}async registerJobHandlers(){if(!this.config.apiKey)return;let A=this.getContext();A.jobs.registerHandler("select-photo",new $3A(this.logger.child("SelectPhotoJobHandler"),{provider:this.createProvider(),entityService:A.entityService,fetchImage:this.deps.fetchImage??rD}))}createProvider(){return new ej0(this.config.apiKey??"",this.deps.fetch??globalThis.fetch)}}function B3A(A={},Q={}){return new w3A(A,Q)}KA();C0();KA();KA();C0();var tm2=H.enum(["ai","foundation","work"]),em2=H.object({suffix:tm2,title:H.string(),body:H.string(),linkLabel:H.string(),linkHref:H.string()}),R50=H.object({eyebrow:H.string(),headline:H.string(),cards:H.array(em2).min(1)}),X3A=H.object({title:H.string(),slug:H.string(),status:H.enum(["draft","published"])}),Dv$=H.object({title:H.string(),slug:H.string(),status:H.enum(["draft","published"])}),v50=H6.extend({entityType:H.literal("ecosystem-section"),metadata:Dv$});class Au2 extends UQ{constructor(){super({entityType:"ecosystem-section",purpose:"A section of the Rizom ecosystem overview.",schema:v50,frontmatterSchema:X3A})}fromMarkdown(A){return{content:A,entityType:"ecosystem-section",metadata:this.parseFrontmatter(A)}}}var Y3A=new Au2;C0();function qv$(A){return A.replace(/^---\n[\s\S]*?\n---\n?/,"")}function Z3A(A,Q){return new RegExp(`(?:^|\\n)## ${Q}\\s*\\n([\\s\\S]*?)(?=\\n## |$)`).exec(A)?.[1]?.trim()??""}function C50(A,Q){return new RegExp(`(?:^|\\n)#### ${Q}\\s*\\n([\\s\\S]*?)(?=\\n#### |\\n### |$)`).exec(A)?.[1]?.trim()??""}function QM0(A){let Q=qv$(A),w=Z3A(Q,"Cards").split(/^### Card \d+\s*$/m).map((B)=>B.trim()).filter(Boolean);return R50.parse({eyebrow:Z3A(Q,"Eyebrow"),headline:Z3A(Q,"Headline"),cards:w.map((B)=>({suffix:C50(B,"Suffix"),title:C50(B,"Title"),body:C50(B,"Body"),linkLabel:C50(B,"Link Label"),linkHref:C50(B,"Link Href")}))})}function Qu2(A){return["# Ecosystem Section","","## Eyebrow",A.eyebrow,"","## Headline",A.headline,"","## Cards","",...A.cards.flatMap((Q,$)=>[`### Card ${$+1}`,"","#### Suffix",Q.suffix,"","#### Title",Q.title,"","#### Body",Q.body,"","#### Link Label",Q.linkLabel,"","#### Link Href",Q.linkHref,""])].join(`
10234
10234
  `)}var zv$=H.looseObject({query:H.object({id:H.string().optional()}).optional()});class $M0{id="rizom-ecosystem:entities";name="Rizom Ecosystem";description="Fetches an ecosystem-section entity for rendering";async fetch(A,Q,$){let B=zv$.parse(A??{}).query?.id??"rizom-ecosystem",X=await $.entityService.getEntity({entityType:"ecosystem-section",id:B});if(!X)throw Error(`Ecosystem section not found: ${B}`);return Q.parse(QM0(X.content))}}import{jsxDEV as Fv$}from"preact/jsx-dev-runtime";var Vv$="px-6 md:px-10 xl:px-20",Jv$=`${Vv$} relative z-[1]`,$u2=({id:A,className:Q,children:$})=>Fv$("section",{id:A,className:e2(Jv$,Q),children:$},void 0,!1,void 0,this);import{jsxDEV as wM0}from"preact/jsx-dev-runtime";var Iv$=new Map([["work","text-accent"],["foundation","text-secondary"],["ai","text-accent-bright"]]),wu2=({name:A="rizom",brandSuffix:Q,className:$,dotClassName:w,suffixClassName:B})=>{let X=Iv$.get(Q);return wM0("span",{className:e2("inline-flex items-baseline gap-0 font-display font-medium tracking-[-0.015em] [font-variation-settings:'opsz'_24]",$),children:[wM0("span",{className:"text-theme",children:A},void 0,!1,void 0,this),wM0("span",{className:e2(X??"text-accent",w),children:"."},void 0,!1,void 0,this),wM0("span",{className:e2("italic font-normal text-theme-muted",B),children:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Fragment as H3A}from"preact";import{jsxDEV as h50}from"preact/jsx-dev-runtime";var Lv$=/(\*[^*]+\*)/;function Bu2(A,Q){let $=A.split(`
10235
- `);return h50(H3A,{children:$.map((w,B)=>h50(H3A,{children:[B>0&&h50("br",{},void 0,!1,void 0,this),w.split(Lv$).map((X,Y)=>{if(X.length>=3&&X.startsWith("*")&&X.endsWith("*"))return h50("span",{className:Q,children:X.slice(1,-1)},Y,!1,void 0,this);return h50(H3A,{children:X},Y,!1,void 0,this)})]},B,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as FK,Fragment as Rv$}from"preact/jsx-dev-runtime";var Nv$="italic text-accent font-normal",_v$="You are here",Pv$={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},kv$={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},jv$={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},Mv$="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",bv$="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",Ov$="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",fv$="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",xv$=({card:A})=>{let Q=A.linkLabel===_v$,$=A.linkHref.trim().length===0,w=FK(Rv$,{children:[FK(wu2,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),FK("span",{className:`${Mv$} ${Pv$[A.suffix]}`,children:A.title},void 0,!1,void 0,this),FK("p",{className:bv$,children:A.body},void 0,!1,void 0,this),Q?FK("span",{className:fv$,children:A.linkLabel},void 0,!1,void 0,this):FK("span",{className:Ov$,children:A.linkLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B=`flex flex-col gap-[14px] border-t pt-7 ${Q?kv$[A.suffix]:"border-white/10"}`;return Q||$?FK("div",{className:B,children:w},void 0,!1,void 0,this):FK("a",{href:A.linkHref,className:`${B} text-inherit no-underline transition-colors ${jv$[A.suffix]}`,children:w},void 0,!1,void 0,this)},Xu2=({eyebrow:A,headline:Q,cards:$})=>FK($u2,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[FK("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[FK("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),FK("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:Bu2(Q,Nv$)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),FK("div",{className:"mx-auto grid max-w-[1180px] grid-cols-3 gap-16 max-[768px]:grid-cols-1 max-[768px]:gap-7",children:$.map((w)=>FK(xv$,{card:w},w.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);KA();var W3A=K2({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:R50,formatter:{parse:QM0,format:Qu2},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:Xu2}});var Yu2={name:"@brains/rizom-ecosystem",version:"0.2.0-alpha.183",description:"Entity-backed Rizom ecosystem section",dependencies:{"@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Cv$=H.object({}).catchall(H.unknown()).transform(()=>({})),hv$="ecosystem-section";class K3A extends S6{entityType=hv$;schema=v50;adapter=Y3A;constructor(A={}){super("rizom-ecosystem",Yu2,A,Cv$)}getTemplates(){return{ecosystem:W3A}}getDataSources(){return[new $M0]}}function FT(A={}){return new K3A(A)}KA();KA();S2();C0();y9();C0();KA();var Gw="agent",Zu2="agent-discovery";var Hu2="agent-network",Wu2="AgentNetworkWidget",Ku2="agent-proximity",Uu2="AgentProximityWidget",E50="agent-discovery:entities",BM0="agent-discovery:proximity-map",U3A="proximity-map",G3A="agent-list",D3A="agent-detail",k9="skill",Gu2="skill",XM0="skill-derivation",Du2="skill:project",qu2="skill-derivation",zu2="skill:skill-derivation",Vu2="skills";var YM0=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),wf=H.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),Ju2=H.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),Ev$=H.enum(["professional","team","collective"]),BV=H.object({name:H.string(),kind:Ev$,organization:H.string().optional(),brainName:H.string().describe("Name of the brain instance"),url:H.string().url().describe("Brain endpoint URL"),did:H.string().optional().describe("Decentralized identifier (public)"),repoDid:H.string().optional().describe("ATProto repo DID"),brainDid:H.string().optional().describe("ATProto brain DID"),anchorDid:H.string().optional().describe("ATProto anchor DID"),cardUri:H.string().optional().describe("ATProto brain card URI"),cardCid:H.string().optional().describe("ATProto brain card CID"),a2aEndpoint:H.string().url().optional().describe("A2A endpoint URL"),status:wf,discoveredAt:H.string().datetime().describe("When this agent was first discovered"),introducedBy:H.array(H.string()).optional().describe("Agent ids of the peers whose directories reported this agent"),hops:H.number().int().min(2).optional().describe("Discovery order: 2 = sighted through a first-order peer")}),Fu2=H.object({name:H.string(),url:H.string().url(),status:wf,discoveredAt:H.string().datetime().optional(),slug:H.string(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.string().url().optional()}),Tv$=H.object({name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),brainName:H.string(),url:H.string().url(),did:H.string().optional(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.string().url().optional(),status:Ju2,discoveredAt:H.string().datetime(),introducedBy:H.array(H.string()).optional(),hops:H.number().int().min(2).optional()}),yv$=H.object({name:H.string(),url:H.string().url(),status:Ju2,discoveredAt:H.string().datetime().optional(),slug:H.string(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.string().url().optional()}),T50=qB.extend({entityType:H.literal(Gw),metadata:Fu2}),gv$=H6.extend({entityType:H.literal(Gw),metadata:yv$}),y50=gv$.extend({frontmatter:Tv$,about:H.string(),skills:H.array(YM0),notes:H.string()}),Sv$=y50.extend({url:H.string().optional(),typeLabel:H.string().optional()}),mv$=y50.extend({url:H.string(),typeLabel:H.string()});C0();var uv$=H.array(YM0);function Iu2(A){let Q=uv$.safeParse(A);if(!Q.success||Q.data.length===0)return"";return Q.data.map(($)=>{let w=$.tags.length>0?` [${$.tags.join(", ")}]`:"";return`- ${$.name}: ${$.description}${w}`}).join(`
10235
+ `);return h50(H3A,{children:$.map((w,B)=>h50(H3A,{children:[B>0&&h50("br",{},void 0,!1,void 0,this),w.split(Lv$).map((X,Y)=>{if(X.length>=3&&X.startsWith("*")&&X.endsWith("*"))return h50("span",{className:Q,children:X.slice(1,-1)},Y,!1,void 0,this);return h50(H3A,{children:X},Y,!1,void 0,this)})]},B,!0,void 0,this))},void 0,!1,void 0,this)}import{jsxDEV as FK,Fragment as Rv$}from"preact/jsx-dev-runtime";var Nv$="italic text-accent font-normal",_v$="You are here",Pv$={work:"text-accent",foundation:"text-secondary",ai:"text-accent-bright"},kv$={work:"border-t-accent/60",foundation:"border-t-secondary/60",ai:"border-t-accent-bright/60"},jv$={work:"hover:border-t-accent",foundation:"hover:border-t-secondary",ai:"hover:border-t-accent-bright"},Mv$="font-label text-[10.5px] uppercase tracking-[0.26em] mt-1",bv$="font-body text-[15px] leading-[1.6] text-theme-muted mt-2",Ov$="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",fv$="font-label text-[10.5px] uppercase tracking-[0.22em] text-accent self-start mt-[18px] pb-1",xv$=({card:A})=>{let Q=A.linkLabel===_v$,$=A.linkHref.trim().length===0,w=FK(Rv$,{children:[FK(wu2,{brandSuffix:A.suffix,className:"text-[clamp(28px,3vw,40px)] [font-variation-settings:'opsz'_96]"},void 0,!1,void 0,this),FK("span",{className:`${Mv$} ${Pv$[A.suffix]}`,children:A.title},void 0,!1,void 0,this),FK("p",{className:bv$,children:A.body},void 0,!1,void 0,this),Q?FK("span",{className:fv$,children:A.linkLabel},void 0,!1,void 0,this):FK("span",{className:Ov$,children:A.linkLabel},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B=`flex flex-col gap-[14px] border-t pt-7 ${Q?kv$[A.suffix]:"border-white/10"}`;return Q||$?FK("div",{className:B,children:w},void 0,!1,void 0,this):FK("a",{href:A.linkHref,className:`${B} text-inherit no-underline transition-colors ${jv$[A.suffix]}`,children:w},void 0,!1,void 0,this)},Xu2=({eyebrow:A,headline:Q,cards:$})=>FK($u2,{id:"ecosystem",className:"pt-[112px] pb-[144px] border-t border-white/5",children:[FK("div",{className:"mx-auto mb-[88px] max-w-[1180px] text-center",children:[FK("span",{className:"font-label text-[11px] font-semibold uppercase tracking-[0.24em] text-accent",children:A},void 0,!1,void 0,this),FK("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:Bu2(Q,Nv$)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),FK("div",{className:"mx-auto grid max-w-[1180px] grid-cols-3 gap-16 max-[768px]:grid-cols-1 max-[768px]:gap-7",children:$.map((w)=>FK(xv$,{card:w},w.suffix,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this);KA();var W3A=K2({name:"ecosystem",description:"Rizom ecosystem sibling-site section",schema:R50,formatter:{parse:QM0,format:Qu2},dataSourceId:"rizom-ecosystem:entities",requiredPermission:"public",layout:{component:Xu2}});var Yu2={name:"@brains/rizom-ecosystem",version:"0.2.0-alpha.184",description:"Entity-backed Rizom ecosystem section",dependencies:{"@brains/plugins":"workspace:*","@brains/ui-library":"workspace:*","@brains/utils":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Cv$=H.object({}).catchall(H.unknown()).transform(()=>({})),hv$="ecosystem-section";class K3A extends S6{entityType=hv$;schema=v50;adapter=Y3A;constructor(A={}){super("rizom-ecosystem",Yu2,A,Cv$)}getTemplates(){return{ecosystem:W3A}}getDataSources(){return[new $M0]}}function FT(A={}){return new K3A(A)}KA();KA();S2();C0();y9();C0();KA();var Gw="agent",Zu2="agent-discovery";var Hu2="agent-network",Wu2="AgentNetworkWidget",Ku2="agent-proximity",Uu2="AgentProximityWidget",E50="agent-discovery:entities",BM0="agent-discovery:proximity-map",U3A="proximity-map",G3A="agent-list",D3A="agent-detail",k9="skill",Gu2="skill",XM0="skill-derivation",Du2="skill:project",qu2="skill-derivation",zu2="skill:skill-derivation",Vu2="skills";var YM0=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),wf=H.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),Ju2=H.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),Ev$=H.enum(["professional","team","collective"]),BV=H.object({name:H.string(),kind:Ev$,organization:H.string().optional(),brainName:H.string().describe("Name of the brain instance"),url:H.string().url().describe("Brain endpoint URL"),did:H.string().optional().describe("Decentralized identifier (public)"),repoDid:H.string().optional().describe("ATProto repo DID"),brainDid:H.string().optional().describe("ATProto brain DID"),anchorDid:H.string().optional().describe("ATProto anchor DID"),cardUri:H.string().optional().describe("ATProto brain card URI"),cardCid:H.string().optional().describe("ATProto brain card CID"),a2aEndpoint:H.string().url().optional().describe("A2A endpoint URL"),status:wf,discoveredAt:H.string().datetime().describe("When this agent was first discovered"),introducedBy:H.array(H.string()).optional().describe("Agent ids of the peers whose directories reported this agent"),hops:H.number().int().min(2).optional().describe("Discovery order: 2 = sighted through a first-order peer")}),Fu2=H.object({name:H.string(),url:H.string().url(),status:wf,discoveredAt:H.string().datetime().optional(),slug:H.string(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.string().url().optional()}),Tv$=H.object({name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),brainName:H.string(),url:H.string().url(),did:H.string().optional(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.string().url().optional(),status:Ju2,discoveredAt:H.string().datetime(),introducedBy:H.array(H.string()).optional(),hops:H.number().int().min(2).optional()}),yv$=H.object({name:H.string(),url:H.string().url(),status:Ju2,discoveredAt:H.string().datetime().optional(),slug:H.string(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.string().url().optional()}),T50=qB.extend({entityType:H.literal(Gw),metadata:Fu2}),gv$=H6.extend({entityType:H.literal(Gw),metadata:yv$}),y50=gv$.extend({frontmatter:Tv$,about:H.string(),skills:H.array(YM0),notes:H.string()}),Sv$=y50.extend({url:H.string().optional(),typeLabel:H.string().optional()}),mv$=y50.extend({url:H.string(),typeLabel:H.string()});C0();var uv$=H.array(YM0);function Iu2(A){let Q=uv$.safeParse(A);if(!Q.success||Q.data.length===0)return"";return Q.data.map(($)=>{let w=$.tags.length>0?` [${$.tags.join(", ")}]`:"";return`- ${$.name}: ${$.description}${w}`}).join(`
10236
10236
  `)}function Lu2(A){if(!A.trim())return[];let Q=[];for(let $ of A.split(`
10237
10237
  `)){let w=$.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/);if(!w)continue;let B=w[1]??"",X=w[2]??"",Y=w[3],Z=Y?Y.split(",").map((W)=>W.trim()).filter(Boolean):[];Q.push({name:B,description:X,tags:Z})}return Q}var cv$=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),pv$=H.object({about:H.string(),skills:H.array(cv$),notes:H.string()}),Nu2=new d$(pv$,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:Iu2,parser:Lu2},{key:"notes",label:"Notes",type:"string"}]});class e7 extends UQ{constructor(){super({entityType:Gw,purpose:"A saved remote peer-brain contact in the local agent directory.",schema:T50,frontmatterSchema:BV,publishedStatuses:["approved"]})}fromMarkdown(A){let Q=this.parseFrontMatter(A,BV),$=_g(Q.url);return{content:A,entityType:Gw,metadata:{name:Q.name,url:Q.url,status:Q.status,discoveredAt:Q.discoveredAt,slug:$,...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,...A.introducedBy?.length&&{introducedBy:A.introducedBy},...A.hops!==void 0&&{hops:A.hops}},$=Nu2.format({about:A.about,skills:A.skills,notes:A.notes});return this.buildMarkdown($,Q)}parseAgentContent(A){let Q=this.extractBody(A);if(!Q.trim())return{about:"",skills:[],notes:""};try{let $=Nu2.parse(Q);return{about:$.about,skills:$.skills,notes:$.notes}}catch{return{about:"",skills:[],notes:""}}}parseEntity(A){return{frontmatter:this.parseFrontMatter(A.content,BV),body:this.parseAgentContent(A.content)}}}KA();C0();var lv$=new e7,_u2=H.enum(["discovered","approved","archived"]),dv$=H.looseObject({id:H.string().optional(),limit:H.number().optional(),page:H.number().optional(),pageSize:H.number().optional(),baseUrl:H.string().optional(),status:_u2.optional()}),iv$=H.looseObject({entityType:H.string().optional(),query:dv$.optional()});function nv$(A){let Q=_Q(A.content,BV),$=lv$.parseAgentContent(A.content);return y50.parse({...A,frontmatter:Q.metadata,about:$.about,skills:$.skills,notes:$.notes})}class ZM0 extends x7{id=E50;name="Agent Directory DataSource";description="Fetches and transforms agent entities for rendering";config={entityType:Gw,defaultSort:[{field:"discoveredAt",direction:"desc"}],defaultLimit:50,lookupField:"slug",enableNavigation:!0};constructor(A){super(A)}transformEntity(A){return nv$(A)}buildDetailResult(A,Q){return{agent:A,prevAgent:Q?.prev??null,nextAgent:Q?.next??null}}parseQuery(A){let Q=iv$.parse(A);return{entityType:Q.entityType??this.config.entityType,query:Q.query??{}}}buildListResult(A,Q,$){let w=_u2.safeParse($.status);return{agents:A,pagination:Q,baseUrl:$.baseUrl,selectedStatus:w.success?w.data:"all"}}async fetch(A,Q,$){let{query:w}=this.parseQuery(A);if(w.id)return super.fetch(A,Q,$);let{items:B,pagination:X}=await this.fetchList(w,$.entityService,w.status?{filter:{metadata:{status:w.status}}}:void 0);return Q.parse(this.buildListResult(B,X,w))}}var rv$=180*(3-Math.sqrt(5));function q3A(A){return Math.max(0,Math.min(1,A))}function z3A(A,Q){let[$,w]=A;if(Math.hypot($,w)<=0.000000000001)return Q*rv$%360;return(Math.atan2(w,$)*180/Math.PI%360+360)%360}function Pu2(A,Q){let $=new Map(A.map((Y)=>[Y.id,Y])),w=new Map(A.map((Y)=>[Y.id,new Set]));for(let Y of Q){if(Y.source.entityType!=="agent"||Y.target.entityType!=="agent"||Y.source.entityId===Y.target.entityId||!$.has(Y.source.entityId)||!$.has(Y.target.entityId))continue;w.get(Y.source.entityId)?.add(Y.target.entityId),w.get(Y.target.entityId)?.add(Y.source.entityId)}let B=new Set,X=[];for(let Y of Array.from($.keys()).sort()){if(B.has(Y))continue;let Z=[],W=[Y];B.add(Y);while(W.length>0){let K=W.pop();if(!K)continue;Z.push(K);for(let U of Array.from(w.get(K)??[]).sort()){if(B.has(U))continue;B.add(U),W.push(U)}}if(Z.length>=2)X.push(Z.sort())}return X.map((Y)=>({label:ov$(Y,$),memberIds:Y,links:Y.flatMap((Z)=>Array.from(w.get(Z)??[]).filter((W)=>Z.localeCompare(W)<0).sort().map((W)=>({sourceId:Z,targetId:W})))})).sort((Y,Z)=>{let W=Y.memberIds.some((G)=>($.get(G)?.tags.length??0)>0),K=Z.memberIds.some((G)=>($.get(G)?.tags.length??0)>0);if(W!==K)return W?-1:1;let U=Y.label.localeCompare(Z.label);return U!==0?U:(Y.memberIds[0]??"").localeCompare(Z.memberIds[0]??"")})}function ov$(A,Q){let $=new Map;for(let B of A){let X=Q.get(B);for(let Y of new Set(X?.tags??[]))$.set(Y,($.get(Y)??0)+1)}let w=Array.from($.entries()).sort((B,X)=>{let Y=X[1]-B[1];return Y!==0?Y:B[0].localeCompare(X[0])})[0]?.[0];return w?`${w} \xB7 ${A.length}`:`unknown \xB7 ${A.length}`}C0();var sv$=BV.shape.kind,av$=H.object({kind:H.enum(["identity","centroid"])}),tv$=H.object({id:H.string(),name:H.string(),kind:sv$,status:wf,tags:H.array(H.string()),distance:H.number().min(0).max(1),bearing:H.number().min(0).lt(360)}),ev$=H.object({sourceId:H.string(),targetId:H.string()}),AC$=H.object({label:H.string(),memberIds:H.array(H.string()).min(2),links:H.array(ev$).min(1)}),QC$=H.object({min:H.number().min(0),max:H.number().min(0)}),ku2=H.object({kicker:H.string().optional(),headingLead:H.string().optional(),headingAccent:H.string().optional(),lede:H.string().optional(),ctaLabel:H.string().optional(),ctaHref:H.string().optional()}),$C$=H.object({id:H.string(),name:H.string(),viaIds:H.array(H.string()).min(1),tags:H.array(H.string()),distance:H.number().min(0).max(1),bearing:H.number().min(0).lt(360)}),vP=H.object({center:av$,nodes:H.array(tv$),clusters:H.array(AC$),sightings:H.array($C$),distanceRange:QC$,pendingCount:H.number().int().min(0),kicker:H.string().optional(),headingLead:H.string().optional(),headingAccent:H.string().optional(),lede:H.string().optional(),ctaLabel:H.string().optional(),ctaHref:H.string().optional()});var wC$=new e7;function ju2(A){return A.trim().toLowerCase().replace(/[_\s]+/g,"-")}function zI(A){let Q=new Set,$=[];for(let w of A){let B=ju2(w);if(!B||Q.has(B))continue;Q.add(B),$.push(B)}return $}function BC$(A,Q){if(Q.count!==A.count)return Q.count-A.count;return A.tag.localeCompare(Q.tag)}async function Mu2(A,Q={}){let $=Q.minCount??1,w=Q.topN??12,B=Q.visibilityScope??"public",X=new Map,[Y,Z]=await Promise.all([A.entityService.listEntities({entityType:k9,options:{filter:{visibilityScope:B}}}),A.entityService.listEntities({entityType:Gw,options:{filter:{visibilityScope:B}}})]),W=(K)=>{for(let U of zI(K))X.set(U,(X.get(U)??0)+1)};for(let K of Y)W(K.metadata.tags);for(let K of Z){let U=wC$.parseAgentContent(K.content);W(U.skills.flatMap((G)=>G.tags))}return Array.from(X.entries()).map(([K,U])=>({tag:K,count:U})).filter((K)=>K.count>=$).sort(BC$).slice(0,w)}function bu2(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:$})=>`- ${Q} (${$})`)].join(`
10238
10238
  `)}var XC$={entityId:"brain-character",entityType:"brain-character"},YC$=0.25,ZC$=0.5,HC$=new e7;function Ou2(A){return A.status==="discovered"&&(A.introducedBy?.length??0)>0}async function HM0(A){let[Q,$]=await Promise.all([A.entityService.listEntities({entityType:Gw}),A.semantic.project({types:[Gw],origin:XC$,maxNeighborDistance:YC$})]),w=new Map($.points.map((D)=>[D.entityId,D])),B=Q.slice().sort((D,q)=>D.id.localeCompare(q.id)).map((D)=>({agent:D,...HC$.parseEntity(D)})),X=B.filter((D)=>!Ou2(D.frontmatter)),Y=B.filter((D)=>Ou2(D.frontmatter)),Z=[];for(let{agent:D,frontmatter:q,body:J}of X){let F=w.get(D.id);if(!F)continue;Z.push({id:D.id,name:q.name,kind:q.kind,status:q.status,tags:fu2(J.skills),distance:q3A(F.distanceToOrigin),bearing:z3A(F.coordinates,Z.length)})}let W=Z.filter((D)=>D.status!=="archived"),K=new Set(W.map((D)=>D.id)),U=Math.max(ZC$,...W.map((D)=>D.distance)),G=[];for(let{agent:D,frontmatter:q,body:J}of Y){let F=w.get(D.id);if(!F)continue;let I=q3A(F.distanceToOrigin);if(I>U)continue;let P=(q.introducedBy??[]).filter((j)=>K.has(j));if(P.length===0)continue;G.push({id:D.id,name:q.name,viaIds:P,tags:fu2(J.skills),distance:I,bearing:z3A(F.coordinates,G.length)})}return vP.parse({center:{kind:$.origin.kind==="entity"?"identity":"centroid"},nodes:Z,clusters:Pu2(W,$.neighbors),sightings:G,distanceRange:$.distanceRange,pendingCount:Math.max(0,X.length-Z.length)})}function fu2(A){return zI(A.flatMap((Q)=>Q.tags))}class WM0{id=BM0;name="Agent Proximity Map DataSource";description="Builds a public semantic proximity map for saved agents";async fetch(A,Q,$){let w=await HM0({entityService:$.entityService,semantic:{project:(B)=>$.entityService.projectSemanticSpace(B)}});return Q.parse(w)}}KA();C0();e8();KA();async function Pn(A,Q,$){let B=`${(A.startsWith("http")?A:`https://${A}`).replace(/\/$/,"")}/.well-known/agent-card.json`;try{let X=await Q(B,$?{signal:$}:void 0);if(!X.ok)return null;let Y=await X.json();return B00(Y)}catch{if($?.aborted)throw $.reason;return null}}function CP(A){let Q=A.trim();if(Q.startsWith("http://")||Q.startsWith("https://"))try{return new URL(Q).hostname}catch{return Q}let $=Q.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if($)try{return new URL($[0]).hostname}catch{return $[0]}if(/^[^\s]+\.[^\s]+$/.test(Q))return Q;return""}S2();var WC$=new e7;function kn(A,Q={}){let $=A.anchor?.name??A.brainName,w=A.anchor?.kind??"professional",B=[];if(A.anchor?.description)B.push(A.anchor.description);if(A.description)B.push(A.description);let X=Q.status??"discovered",Y=new Date().toISOString();return{content:WC$.createAgentContent({name:$,kind:w,...A.anchor?.organization&&{organization:A.anchor.organization},brainName:A.brainName,url:A.url,status:X,discoveredAt:Y,...Q.provenance&&{introducedBy:Q.provenance.introducedBy,hops:Q.provenance.hops},about:B.join(`
@@ -10814,7 +10814,7 @@ ${A.guidance}`:B}}function vm2(A){return{...A,evidence:A.evidence.map((Q)=>({...
10814
10814
  /* the shimmer delay is inlined per node, so the override needs force */
10815
10815
  .agent-proximity-site .proximity-agent { animation: none !important; }
10816
10816
  }
10817
- `,On={kicker:"Agent network",headingLead:"The rhizome grows",headingAccent:"beneath this brain",lede:"Every agent this brain has met, mapped by how close its work runs to ours \u2014 distance measured in meaning, not geography. Threads thicken where practices touch; where several lights gather, a constellation forms.",ctaLabel:"Meet the agents",ctaHref:"/agents"};function _3A(A){let Q=A.nodes.filter((K)=>K.status!=="archived").length,$=A.nodes.length-Q,w=A.kicker??On.kicker,B=A.headingLead??On.headingLead,X=A.headingAccent??On.headingAccent,Y=A.lede??On.lede,Z=A.ctaLabel??On.ctaLabel,W=A.ctaHref??On.ctaHref;return o8("section",{class:"agent-proximity-site","aria-label":"Agent proximity map",children:[o8("style",{children:oC$},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__grid",children:[o8("div",{class:"agent-proximity-site__copy",children:[o8("p",{class:"agent-proximity-site__kicker",children:w},void 0,!1,void 0,this),o8("h2",{class:"agent-proximity-site__heading",children:[B," ",o8("em",{children:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("p",{class:"agent-proximity-site__lede",children:Y},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stats","aria-label":"Network summary",children:[o8("div",{children:[o8("div",{class:"agent-proximity-site__stat-number",children:Q},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stat-label",children:"agents"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{children:[o8("div",{class:"agent-proximity-site__stat-number",children:A.clusters.length},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stat-label",children:"constellations"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{children:[o8("div",{class:"agent-proximity-site__stat-number",children:$},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stat-label",children:"archived traces"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o8("a",{class:"agent-proximity-site__cta",href:W,children:Z},void 0,!1,void 0,this),A.pendingCount>0&&o8("p",{class:"agent-proximity-site__note",children:[A.pendingCount," pending semantic indexing"]},void 0,!0,void 0,this),A.center.kind==="centroid"&&o8("p",{class:"agent-proximity-site__note",children:"Identity not indexed yet \u2014 using network centroid"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{class:"agent-proximity-site__map",children:o8(zM0,{data:A,surface:"site"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{class:"agent-proximity-site__legend","aria-label":"Agent kinds",children:[o8("span",{children:[o8("b",{children:"\u25CF"},void 0,!1,void 0,this)," professional"]},void 0,!0,void 0,this),o8("span",{children:[o8("b",{children:"\u2234"},void 0,!1,void 0,this)," team"]},void 0,!0,void 0,this),o8("span",{children:[o8("b",{children:"\u25CC"},void 0,!1,void 0,this)," collective"]},void 0,!0,void 0,this),o8("span",{children:[o8("b",{children:"\xB7"},void 0,!1,void 0,this)," archived trace"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var sC$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),aC$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),tC$=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),P3A=H.enum(["discovered","approved","archived"]),eC$=H.enum(["professional","team","collective"]),Ah$=H.object({name:H.string(),kind:eC$,organization:H.string().optional(),brainName:H.string(),url:H.url(),did:H.string().optional(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.url().optional(),status:P3A,discoveredAt:H.string()}),Qh$=H.object({name:H.string(),url:H.url(),status:P3A,discoveredAt:H.string().optional(),slug:H.string(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.url().optional()}),JM0=H.object({id:H.string(),entityType:H.literal(Gw),content:H.string(),created:H.string(),updated:H.string(),visibility:sC$,metadata:Qh$,contentHash:H.string(),frontmatter:Ah$,about:H.string(),skills:H.array(tC$),notes:H.string(),url:H.string().optional(),typeLabel:H.string().optional()}),$h$=H.object({agents:H.array(JM0),pageTitle:H.string().optional(),pagination:aC$.nullable(),baseUrl:H.string().optional(),selectedStatus:H.union([H.literal("all"),P3A])}),au2="/scripts/agent-proximity-map.js",wh$=new d$(ku2,{title:"Network",mappings:[{key:"kicker",label:"Kicker",type:"string"},{key:"headingLead",label:"Heading Lead",type:"string"},{key:"headingAccent",label:"Heading Accent",type:"string"},{key:"lede",label:"Lede",type:"string"},{key:"ctaLabel",label:"Cta Label",type:"string"},{key:"ctaHref",label:"Cta Href",type:"string"}]});function tu2(){return{[U3A]:K2({name:U3A,description:"Semantic agent proximity map site section",schema:vP,dataSourceId:BM0,overlayFormatter:wh$,requiredPermission:"public",runtimeScripts:[{src:au2,defer:!0}],staticAssets:{[au2]:jn},layout:{component:_3A}}),[G3A]:K2({name:G3A,description:"Agent directory list page template",schema:$h$,dataSourceId:E50,requiredPermission:"public",layout:{component:ru2}}),[D3A]:K2({name:D3A,description:"Individual agent profile template",schema:H.object({agent:JM0,prevAgent:JM0.nullable(),nextAgent:JM0.nullable()}),dataSourceId:E50,requiredPermission:"public",layout:{component:su2}})}}var fn={name:"@brains/agent-discovery",version:"0.2.0-alpha.183",description:"Agent discovery \u2014 brain+anchor contacts and skills",dependencies:{"@brains/atproto-contracts":"workspace:*","@brains/auth-service":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/dashboard":"workspace:*","@brains/http-signatures":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Xh$=new e7;class k3A extends S6{entityType=Gw;schema=T50;adapter=Xh$;constructor(){super(Zu2,fn,{},XY)}createGenerationHandler(A){return new V3A(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return tu2()}getDataSources(){return[new ZM0(this.logger.child("AgentDataSource")),new WM0]}async onRegister(A){cu2(A),mu2(A,this.id)}async getInstructions(){return pu2()}}function j3A(){return new k3A}KA();bH();C0();k4();C0();var eu2=H.object({source:H.object({kind:H.literal("url"),url:H.string().min(1).describe("Remote agent domain or URL to verify and connect. Preserve bare domains as bare domains.")}),confirmed:H.boolean().optional(),confirmationToken:H.string().optional()}),Yh$=new e7;function Zh$(A){let Q=CP(A);if(!Q)return null;return{domain:Q,fetchTarget:A.trim().startsWith("http")?A.trim():Q}}function Hh$(A,Q){return(CP(Q)||A).toLowerCase()}async function Wh$(A){let{context:Q,entityId:$,card:w}=A,B=new Date().toISOString(),X=await Q.entityService.getEntity({entityType:Gw,id:$}),Y=kn(w,{status:"approved"}),W={...Yh$.fromMarkdown(Y.content).metadata,...Y.metadata,a2aEndpoint:w.url};if(X){let U={...X,content:Y.content,metadata:W,updated:B};return await Q.entityService.updateEntity({entity:U}),{entity:U,created:!1}}let K={id:$,entityType:Gw,content:Y.content,metadata:W,contentHash:"",visibility:"public",created:B,updated:B};return await Q.entityService.createEntity({entity:K}),{entity:K,created:!0}}function Ac2(A,Q=globalThis.fetch){let w=new zU;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 outbound calls. This adds a directory contact; it does not message the remote agent or grant it inbound trusted access. 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:eu2.shape,visibility:"trusted",sideEffects:"external",handler:async(B,X)=>{let Y=eu2.safeParse(B);if(!Y.success)return{success:!1,error:`Invalid input: ${Y.error.issues.map((U)=>`${U.path.join(".")}: ${U.message}`).join(", ")}`};let Z=Y.data,W=Zh$(Z.source.url);if(!W)return{success:!1,error:"Provide a valid remote agent domain or URL to connect.",code:"invalid_agent_url"};try{A.permissions.assertEntityActionAllowed(Gw,"create",X)}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}if(Z.confirmed){let U=Z.confirmationToken,G=w.validate(U,Z);if(G.status==="missing")return{success:!1,error:"No pending agent connection confirmation found. Please request connection again and confirm the new approval."};if(G.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 D=await Pn(W.fetchTarget,Q);if(!D)return{success:!1,error:`Could not verify an A2A Agent Card for ${W.domain}.`,code:"not_an_agent"};let q=Hh$(W.domain,D.url),{entity:J,created:F}=await Wh$({context:A,entityId:q,sourceUrl:Z.source.url,card:D});return{success:!0,data:{status:J.metadata.status,entityId:J.id,connected:!0,created:F,a2aEndpoint:D.url,skills:D.skills.map((I)=>({name:I.name,description:I.description,tags:I.tags}))}}}let K=w.create((U)=>({source:Z.source,confirmed:!0,confirmationToken:U}));return{needsConfirmation:!0,toolName:"agent_connect",summary:`Verify and connect agent ${W.domain}?`,preview:`This will fetch and validate ${W.domain}'s A2A Agent Card, then save the verified contact as approved for future outbound calls. It will not message the remote agent or grant it inbound trusted access.`,args:K}}}}C0();var Qc2=H.object({}),Kh$=H.object({agents:H.array(H.object({name:H.string(),url:H.string()}))}),M3A=new e7;async function Uh$(A,Q,$){let w=`https://${A}/.well-known/agent-directory.json`;try{let B=await Q(w,$?{signal:$}:void 0);if(!B.ok)return null;let X=Kh$.safeParse(await B.json());return X.success?X.data:null}catch{if($?.aborted)throw $.reason;return null}}async function b3A(A,Q=globalThis.fetch,$){let w=await A.entityService.listEntities({entityType:Gw}),B=w.filter((I)=>I.metadata.status==="approved"),X=A.domain?.toLowerCase(),Y=new Map,Z=0;for(let I of B){$?.throwIfAborted();let P=await Uh$(I.id,Q,$);if(!P){Z+=1;continue}for(let j of P.agents){let k=CP(j.url).toLowerCase();if(!k||k===X||k===I.id)continue;let f=Y.get(k)??new Set;f.add(I.id),Y.set(k,f)}}let W=new Map(w.map((I)=>[I.id,I])),K=new Date().toISOString(),U=[],G=new Set,D=0,q=0,J=0,F=0;for(let[I,P]of Y){$?.throwIfAborted();let j=W.get(I);if(j){let{frontmatter:x,body:O}=M3A.parseEntity(j),g=x.introducedBy??[];if(x.status!=="discovered"||g.length===0){J+=1;continue}let u=[...g,...[...P].filter((n)=>!g.includes(n))];if(u.length===g.length)continue;await A.entityService.updateEntity({entity:{...j,content:M3A.createAgentContent({...x,introducedBy:u,about:O.about,skills:O.skills,notes:O.notes}),updated:K}}),q+=1;continue}let k=await Pn(I,Q,$);if(!k){F+=1;continue}let f=kn(k,{status:"discovered",provenance:{introducedBy:[...P],hops:2}}),R=M3A.fromMarkdown(f.content);await A.entityService.createEntity({entity:{id:I,entityType:Gw,content:f.content,metadata:{...R.metadata,...f.metadata},visibility:"public",created:K,updated:K}}),D+=1,U.push(I);for(let x of P)G.add(x)}return{peersScanned:B.length,unreachablePeers:Z,created:D,updated:q,alreadyKnown:J,unverified:F,createdDomains:U,introducingPeers:[...G],observedAt:K}}function $c2(A,Q=globalThis.fetch){return{name:"agent_scan_directories",description:"Walk each approved agent's public directory at /.well-known/agent-directory.json and record second-order sightings: agents your peers list that you are not connected to. A sighting is saved as a discovered agent with provenance (which peers introduced it, hop count) and data from its own verified Agent Card. Re-scanning is idempotent: connected agents are skipped and repeat sightings only merge new introducers. Never approves anything; promotion stays with agent_connect.",inputSchema:Qc2.shape,visibility:"trusted",sideEffects:"external",handler:async($,w)=>{let B=Qc2.safeParse($);if(!B.success)return{success:!1,error:`Invalid input: ${B.error.message}`};try{A.permissions.assertEntityActionAllowed(Gw,"create",w)}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:String(Y)}}let X=await b3A(A,Q,w.signal);return{success:!0,data:{peersScanned:X.peersScanned,unreachablePeers:X.unreachablePeers,created:X.created,updated:X.updated,alreadyKnown:X.alreadyKnown,unverified:X.unverified}}}}}k4();C0();var Gh$=H.enum(["public","trusted"]),wc2=H.object({agent:H.string().min(1).describe("Saved agent id, domain, or URL whose inbound A2A trust to set."),level:Gh$.describe("Inbound A2A trust level. Use trusted to grant trusted inbound access, public to revoke it."),confirmed:H.boolean().optional(),confirmationToken:H.string().optional(),keyFingerprint:H.string().optional()}),Dh$=H.object({keys:H.array(H.unknown())}),qh$=H.object({kty:H.literal("OKP"),crv:H.literal("Ed25519"),x:H.string(),kid:H.string().optional(),alg:H.literal("EdDSA").optional()}).passthrough();function Bc2(A){return(CP(A)||A.trim()).toLowerCase()}async function zh$(A,Q){let $=Bc2(Q),w=await A.entityService.getEntity({entityType:Gw,id:$});if(!w)return null;let B=Bc2(w.metadata.a2aEndpoint??w.metadata.url);if(!B)return null;return{domain:B}}async function Vh$(A,Q){try{let $=await Q(`https://${A}/.well-known/jwks.json`);if(!$.ok)return null;let w=Dh$.safeParse(await $.json());if(!w.success)return null;let B=w.data.keys.map((X)=>qh$.safeParse(X)).find((X)=>X.success);if(!B?.success)return null;return _XA(B.data)}catch{return null}}function Xc2(A,Q=globalThis.fetch){let w=new zU;return{name:"agent_set_trust_level",description:"Grant or revoke inbound A2A trust for a saved contact; this is the only tool for inbound trust changes. To revoke, call directly with level public\u2014no key fingerprint or preliminary lookup is needed. To grant, use level trusted; the tool resolves and pins the peer key. This does not add or remove directory contacts or change outbound calling. Requires confirmation.",inputSchema:wc2.shape,visibility:"anchor",sideEffects:"external",handler:async(B)=>{let X=wc2.safeParse(B);if(!X.success)return{success:!1,error:`Invalid input: ${X.error.issues.map((D)=>`${D.path.join(".")}: ${D.message}`).join(", ")}`};let Y=UY();if(!Y)return{success:!1,error:"Auth service is required to set inbound A2A trust.",code:"auth_service_unavailable"};let Z=await zh$(A,X.data.agent);if(!Z)return{success:!1,error:`No saved agent contact found for ${X.data.agent}. Connect the agent before setting inbound trust.`,code:"agent_not_found"};let W=X.data;if(W.confirmed){let D=w.validate(W.confirmationToken,W);if(D.status==="missing")return{success:!1,error:"No pending agent trust confirmation found. Please request the trust change again and confirm the new approval."};if(D.status==="mismatch")return{success:!1,error:"Confirmed agent trust arguments do not match the pending approval. Please request the trust change again and confirm the new approval."};if(W.level==="trusted"){if(!W.keyFingerprint)return{success:!1,error:"Missing key fingerprint for trusted A2A grant."};let q=await Y.grantA2APeerTrust({domain:Z.domain,keyFingerprint:W.keyFingerprint,grantedLevel:"trusted"});return{success:!0,data:{agent:Z.domain,level:q.grantedLevel,keyFingerprint:q.keyFingerprint}}}return await Y.revokeA2APeerTrust(Z.domain),{success:!0,data:{agent:Z.domain,level:"public"}}}let K=W.level==="trusted"?await Vh$(Z.domain,Q):void 0;if(W.level==="trusted"&&!K)return{success:!1,error:`Could not fetch an A2A signing key from ${Z.domain}.`,code:"jwks_unavailable"};let U=w.create((D)=>({agent:Z.domain,level:W.level,confirmed:!0,confirmationToken:D,...K?{keyFingerprint:K}:{}})),G=W.level==="trusted";return{needsConfirmation:!0,toolName:"agent_set_trust_level",summary:G?`Grant inbound trusted A2A access to ${Z.domain}?`:`Revoke inbound trusted A2A access from ${Z.domain}?`,preview:G?`This will grant inbound trusted A2A access to ${Z.domain} and pin key fingerprint ${K}. It will not add or remove the directory contact.`:`This will revoke inbound trusted A2A access from ${Z.domain}. The directory contact remains saved for outbound calls.`,args:U}}}}var FM0=H.object({notifyOnNewAgents:H.boolean().default(!1).describe("Notify when directory scans discover new agents")}).strict();class O3A extends p6{fetchFn;constructor(A,Q={}){super("agent",fn,Q,FM0);this.fetchFn=A}async onRegister(A){A.recurringChecks.register({id:"directory-scan",cadence:"daily",deliverAlerts:this.config.notifyOnNewAgents,run:async({signal:Q})=>{let $=await b3A(A,this.fetchFn,Q);if($.created===0||!this.config.notifyOnNewAgents)return{};let w=[...$.createdDomains].sort(),B=[...$.introducingPeers].sort(),X=`${$.created} agent${$.created===1?"":"s"}`;return{alerts:[{dedupeKey:`sightings:${e6(`${$.observedAt}\x00${w.join("\x00")}`)}`,title:"New agent sightings",body:`${X} sighted through ${B.join(", ")}`}]}}})}async getTools(){return[Ac2(this.getContext(),this.fetchFn),$c2(this.getContext(),this.fetchFn),Xc2(this.getContext(),this.fetchFn)]}}function f3A(A={}){return new O3A(void 0,A)}KA();KA();C0();var LT=H.object({name:H.string(),description:H.string(),tags:H.array(H.string()),examples:H.array(H.string())}),Yc2=LT,c50=qB.extend({entityType:H.literal(k9),metadata:Yc2});KA();class xn extends UQ{constructor(){super({entityType:k9,purpose:"A capability advertised by a remote agent.",schema:c50,frontmatterSchema:LT})}fromMarkdown(A){let Q=this.parseFrontMatter(A,LT);return{content:A,entityType:k9,metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}KA();C0();var Jh$=H.object({skills:H.array(LT).max(8)}),Zc2=K2({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:Jh$,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
10817
+ `,On={kicker:"Agent network",headingLead:"The rhizome grows",headingAccent:"beneath this brain",lede:"Every agent this brain has met, mapped by how close its work runs to ours \u2014 distance measured in meaning, not geography. Threads thicken where practices touch; where several lights gather, a constellation forms.",ctaLabel:"Meet the agents",ctaHref:"/agents"};function _3A(A){let Q=A.nodes.filter((K)=>K.status!=="archived").length,$=A.nodes.length-Q,w=A.kicker??On.kicker,B=A.headingLead??On.headingLead,X=A.headingAccent??On.headingAccent,Y=A.lede??On.lede,Z=A.ctaLabel??On.ctaLabel,W=A.ctaHref??On.ctaHref;return o8("section",{class:"agent-proximity-site","aria-label":"Agent proximity map",children:[o8("style",{children:oC$},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__grid",children:[o8("div",{class:"agent-proximity-site__copy",children:[o8("p",{class:"agent-proximity-site__kicker",children:w},void 0,!1,void 0,this),o8("h2",{class:"agent-proximity-site__heading",children:[B," ",o8("em",{children:X},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("p",{class:"agent-proximity-site__lede",children:Y},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stats","aria-label":"Network summary",children:[o8("div",{children:[o8("div",{class:"agent-proximity-site__stat-number",children:Q},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stat-label",children:"agents"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{children:[o8("div",{class:"agent-proximity-site__stat-number",children:A.clusters.length},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stat-label",children:"constellations"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{children:[o8("div",{class:"agent-proximity-site__stat-number",children:$},void 0,!1,void 0,this),o8("div",{class:"agent-proximity-site__stat-label",children:"archived traces"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),o8("a",{class:"agent-proximity-site__cta",href:W,children:Z},void 0,!1,void 0,this),A.pendingCount>0&&o8("p",{class:"agent-proximity-site__note",children:[A.pendingCount," pending semantic indexing"]},void 0,!0,void 0,this),A.center.kind==="centroid"&&o8("p",{class:"agent-proximity-site__note",children:"Identity not indexed yet \u2014 using network centroid"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{class:"agent-proximity-site__map",children:o8(zM0,{data:A,surface:"site"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),o8("div",{class:"agent-proximity-site__legend","aria-label":"Agent kinds",children:[o8("span",{children:[o8("b",{children:"\u25CF"},void 0,!1,void 0,this)," professional"]},void 0,!0,void 0,this),o8("span",{children:[o8("b",{children:"\u2234"},void 0,!1,void 0,this)," team"]},void 0,!0,void 0,this),o8("span",{children:[o8("b",{children:"\u25CC"},void 0,!1,void 0,this)," collective"]},void 0,!0,void 0,this),o8("span",{children:[o8("b",{children:"\xB7"},void 0,!1,void 0,this)," archived trace"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var sC$=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),aC$=H.object({currentPage:H.number(),totalPages:H.number(),totalItems:H.number(),pageSize:H.number(),hasNextPage:H.boolean(),hasPrevPage:H.boolean()}),tC$=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),P3A=H.enum(["discovered","approved","archived"]),eC$=H.enum(["professional","team","collective"]),Ah$=H.object({name:H.string(),kind:eC$,organization:H.string().optional(),brainName:H.string(),url:H.url(),did:H.string().optional(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.url().optional(),status:P3A,discoveredAt:H.string()}),Qh$=H.object({name:H.string(),url:H.url(),status:P3A,discoveredAt:H.string().optional(),slug:H.string(),repoDid:H.string().optional(),brainDid:H.string().optional(),anchorDid:H.string().optional(),cardUri:H.string().optional(),cardCid:H.string().optional(),a2aEndpoint:H.url().optional()}),JM0=H.object({id:H.string(),entityType:H.literal(Gw),content:H.string(),created:H.string(),updated:H.string(),visibility:sC$,metadata:Qh$,contentHash:H.string(),frontmatter:Ah$,about:H.string(),skills:H.array(tC$),notes:H.string(),url:H.string().optional(),typeLabel:H.string().optional()}),$h$=H.object({agents:H.array(JM0),pageTitle:H.string().optional(),pagination:aC$.nullable(),baseUrl:H.string().optional(),selectedStatus:H.union([H.literal("all"),P3A])}),au2="/scripts/agent-proximity-map.js",wh$=new d$(ku2,{title:"Network",mappings:[{key:"kicker",label:"Kicker",type:"string"},{key:"headingLead",label:"Heading Lead",type:"string"},{key:"headingAccent",label:"Heading Accent",type:"string"},{key:"lede",label:"Lede",type:"string"},{key:"ctaLabel",label:"Cta Label",type:"string"},{key:"ctaHref",label:"Cta Href",type:"string"}]});function tu2(){return{[U3A]:K2({name:U3A,description:"Semantic agent proximity map site section",schema:vP,dataSourceId:BM0,overlayFormatter:wh$,requiredPermission:"public",runtimeScripts:[{src:au2,defer:!0}],staticAssets:{[au2]:jn},layout:{component:_3A}}),[G3A]:K2({name:G3A,description:"Agent directory list page template",schema:$h$,dataSourceId:E50,requiredPermission:"public",layout:{component:ru2}}),[D3A]:K2({name:D3A,description:"Individual agent profile template",schema:H.object({agent:JM0,prevAgent:JM0.nullable(),nextAgent:JM0.nullable()}),dataSourceId:E50,requiredPermission:"public",layout:{component:su2}})}}var fn={name:"@brains/agent-discovery",version:"0.2.0-alpha.184",description:"Agent discovery \u2014 brain+anchor contacts and skills",dependencies:{"@brains/atproto-contracts":"workspace:*","@brains/auth-service":"workspace:*","@brains/content-formatters":"workspace:*","@brains/contracts":"workspace:*","@brains/dashboard":"workspace:*","@brains/http-signatures":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Xh$=new e7;class k3A extends S6{entityType=Gw;schema=T50;adapter=Xh$;constructor(){super(Zu2,fn,{},XY)}createGenerationHandler(A){return new V3A(this.logger.child("AgentGenerationJobHandler"),A)}getTemplates(){return tu2()}getDataSources(){return[new ZM0(this.logger.child("AgentDataSource")),new WM0]}async onRegister(A){cu2(A),mu2(A,this.id)}async getInstructions(){return pu2()}}function j3A(){return new k3A}KA();bH();C0();k4();C0();var eu2=H.object({source:H.object({kind:H.literal("url"),url:H.string().min(1).describe("Remote agent domain or URL to verify and connect. Preserve bare domains as bare domains.")}),confirmed:H.boolean().optional(),confirmationToken:H.string().optional()}),Yh$=new e7;function Zh$(A){let Q=CP(A);if(!Q)return null;return{domain:Q,fetchTarget:A.trim().startsWith("http")?A.trim():Q}}function Hh$(A,Q){return(CP(Q)||A).toLowerCase()}async function Wh$(A){let{context:Q,entityId:$,card:w}=A,B=new Date().toISOString(),X=await Q.entityService.getEntity({entityType:Gw,id:$}),Y=kn(w,{status:"approved"}),W={...Yh$.fromMarkdown(Y.content).metadata,...Y.metadata,a2aEndpoint:w.url};if(X){let U={...X,content:Y.content,metadata:W,updated:B};return await Q.entityService.updateEntity({entity:U}),{entity:U,created:!1}}let K={id:$,entityType:Gw,content:Y.content,metadata:W,contentHash:"",visibility:"public",created:B,updated:B};return await Q.entityService.createEntity({entity:K}),{entity:K,created:!0}}function Ac2(A,Q=globalThis.fetch){let w=new zU;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 outbound calls. This adds a directory contact; it does not message the remote agent or grant it inbound trusted access. 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:eu2.shape,visibility:"trusted",sideEffects:"external",handler:async(B,X)=>{let Y=eu2.safeParse(B);if(!Y.success)return{success:!1,error:`Invalid input: ${Y.error.issues.map((U)=>`${U.path.join(".")}: ${U.message}`).join(", ")}`};let Z=Y.data,W=Zh$(Z.source.url);if(!W)return{success:!1,error:"Provide a valid remote agent domain or URL to connect.",code:"invalid_agent_url"};try{A.permissions.assertEntityActionAllowed(Gw,"create",X)}catch(U){return{success:!1,error:U instanceof Error?U.message:String(U)}}if(Z.confirmed){let U=Z.confirmationToken,G=w.validate(U,Z);if(G.status==="missing")return{success:!1,error:"No pending agent connection confirmation found. Please request connection again and confirm the new approval."};if(G.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 D=await Pn(W.fetchTarget,Q);if(!D)return{success:!1,error:`Could not verify an A2A Agent Card for ${W.domain}.`,code:"not_an_agent"};let q=Hh$(W.domain,D.url),{entity:J,created:F}=await Wh$({context:A,entityId:q,sourceUrl:Z.source.url,card:D});return{success:!0,data:{status:J.metadata.status,entityId:J.id,connected:!0,created:F,a2aEndpoint:D.url,skills:D.skills.map((I)=>({name:I.name,description:I.description,tags:I.tags}))}}}let K=w.create((U)=>({source:Z.source,confirmed:!0,confirmationToken:U}));return{needsConfirmation:!0,toolName:"agent_connect",summary:`Verify and connect agent ${W.domain}?`,preview:`This will fetch and validate ${W.domain}'s A2A Agent Card, then save the verified contact as approved for future outbound calls. It will not message the remote agent or grant it inbound trusted access.`,args:K}}}}C0();var Qc2=H.object({}),Kh$=H.object({agents:H.array(H.object({name:H.string(),url:H.string()}))}),M3A=new e7;async function Uh$(A,Q,$){let w=`https://${A}/.well-known/agent-directory.json`;try{let B=await Q(w,$?{signal:$}:void 0);if(!B.ok)return null;let X=Kh$.safeParse(await B.json());return X.success?X.data:null}catch{if($?.aborted)throw $.reason;return null}}async function b3A(A,Q=globalThis.fetch,$){let w=await A.entityService.listEntities({entityType:Gw}),B=w.filter((I)=>I.metadata.status==="approved"),X=A.domain?.toLowerCase(),Y=new Map,Z=0;for(let I of B){$?.throwIfAborted();let P=await Uh$(I.id,Q,$);if(!P){Z+=1;continue}for(let j of P.agents){let k=CP(j.url).toLowerCase();if(!k||k===X||k===I.id)continue;let f=Y.get(k)??new Set;f.add(I.id),Y.set(k,f)}}let W=new Map(w.map((I)=>[I.id,I])),K=new Date().toISOString(),U=[],G=new Set,D=0,q=0,J=0,F=0;for(let[I,P]of Y){$?.throwIfAborted();let j=W.get(I);if(j){let{frontmatter:x,body:O}=M3A.parseEntity(j),g=x.introducedBy??[];if(x.status!=="discovered"||g.length===0){J+=1;continue}let u=[...g,...[...P].filter((n)=>!g.includes(n))];if(u.length===g.length)continue;await A.entityService.updateEntity({entity:{...j,content:M3A.createAgentContent({...x,introducedBy:u,about:O.about,skills:O.skills,notes:O.notes}),updated:K}}),q+=1;continue}let k=await Pn(I,Q,$);if(!k){F+=1;continue}let f=kn(k,{status:"discovered",provenance:{introducedBy:[...P],hops:2}}),R=M3A.fromMarkdown(f.content);await A.entityService.createEntity({entity:{id:I,entityType:Gw,content:f.content,metadata:{...R.metadata,...f.metadata},visibility:"public",created:K,updated:K}}),D+=1,U.push(I);for(let x of P)G.add(x)}return{peersScanned:B.length,unreachablePeers:Z,created:D,updated:q,alreadyKnown:J,unverified:F,createdDomains:U,introducingPeers:[...G],observedAt:K}}function $c2(A,Q=globalThis.fetch){return{name:"agent_scan_directories",description:"Walk each approved agent's public directory at /.well-known/agent-directory.json and record second-order sightings: agents your peers list that you are not connected to. A sighting is saved as a discovered agent with provenance (which peers introduced it, hop count) and data from its own verified Agent Card. Re-scanning is idempotent: connected agents are skipped and repeat sightings only merge new introducers. Never approves anything; promotion stays with agent_connect.",inputSchema:Qc2.shape,visibility:"trusted",sideEffects:"external",handler:async($,w)=>{let B=Qc2.safeParse($);if(!B.success)return{success:!1,error:`Invalid input: ${B.error.message}`};try{A.permissions.assertEntityActionAllowed(Gw,"create",w)}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:String(Y)}}let X=await b3A(A,Q,w.signal);return{success:!0,data:{peersScanned:X.peersScanned,unreachablePeers:X.unreachablePeers,created:X.created,updated:X.updated,alreadyKnown:X.alreadyKnown,unverified:X.unverified}}}}}k4();C0();var Gh$=H.enum(["public","trusted"]),wc2=H.object({agent:H.string().min(1).describe("Saved agent id, domain, or URL whose inbound A2A trust to set."),level:Gh$.describe("Inbound A2A trust level. Use trusted to grant trusted inbound access, public to revoke it."),confirmed:H.boolean().optional(),confirmationToken:H.string().optional(),keyFingerprint:H.string().optional()}),Dh$=H.object({keys:H.array(H.unknown())}),qh$=H.object({kty:H.literal("OKP"),crv:H.literal("Ed25519"),x:H.string(),kid:H.string().optional(),alg:H.literal("EdDSA").optional()}).passthrough();function Bc2(A){return(CP(A)||A.trim()).toLowerCase()}async function zh$(A,Q){let $=Bc2(Q),w=await A.entityService.getEntity({entityType:Gw,id:$});if(!w)return null;let B=Bc2(w.metadata.a2aEndpoint??w.metadata.url);if(!B)return null;return{domain:B}}async function Vh$(A,Q){try{let $=await Q(`https://${A}/.well-known/jwks.json`);if(!$.ok)return null;let w=Dh$.safeParse(await $.json());if(!w.success)return null;let B=w.data.keys.map((X)=>qh$.safeParse(X)).find((X)=>X.success);if(!B?.success)return null;return _XA(B.data)}catch{return null}}function Xc2(A,Q=globalThis.fetch){let w=new zU;return{name:"agent_set_trust_level",description:"Grant or revoke inbound A2A trust for a saved contact; this is the only tool for inbound trust changes. To revoke, call directly with level public\u2014no key fingerprint or preliminary lookup is needed. To grant, use level trusted; the tool resolves and pins the peer key. This does not add or remove directory contacts or change outbound calling. Requires confirmation.",inputSchema:wc2.shape,visibility:"anchor",sideEffects:"external",handler:async(B)=>{let X=wc2.safeParse(B);if(!X.success)return{success:!1,error:`Invalid input: ${X.error.issues.map((D)=>`${D.path.join(".")}: ${D.message}`).join(", ")}`};let Y=UY();if(!Y)return{success:!1,error:"Auth service is required to set inbound A2A trust.",code:"auth_service_unavailable"};let Z=await zh$(A,X.data.agent);if(!Z)return{success:!1,error:`No saved agent contact found for ${X.data.agent}. Connect the agent before setting inbound trust.`,code:"agent_not_found"};let W=X.data;if(W.confirmed){let D=w.validate(W.confirmationToken,W);if(D.status==="missing")return{success:!1,error:"No pending agent trust confirmation found. Please request the trust change again and confirm the new approval."};if(D.status==="mismatch")return{success:!1,error:"Confirmed agent trust arguments do not match the pending approval. Please request the trust change again and confirm the new approval."};if(W.level==="trusted"){if(!W.keyFingerprint)return{success:!1,error:"Missing key fingerprint for trusted A2A grant."};let q=await Y.grantA2APeerTrust({domain:Z.domain,keyFingerprint:W.keyFingerprint,grantedLevel:"trusted"});return{success:!0,data:{agent:Z.domain,level:q.grantedLevel,keyFingerprint:q.keyFingerprint}}}return await Y.revokeA2APeerTrust(Z.domain),{success:!0,data:{agent:Z.domain,level:"public"}}}let K=W.level==="trusted"?await Vh$(Z.domain,Q):void 0;if(W.level==="trusted"&&!K)return{success:!1,error:`Could not fetch an A2A signing key from ${Z.domain}.`,code:"jwks_unavailable"};let U=w.create((D)=>({agent:Z.domain,level:W.level,confirmed:!0,confirmationToken:D,...K?{keyFingerprint:K}:{}})),G=W.level==="trusted";return{needsConfirmation:!0,toolName:"agent_set_trust_level",summary:G?`Grant inbound trusted A2A access to ${Z.domain}?`:`Revoke inbound trusted A2A access from ${Z.domain}?`,preview:G?`This will grant inbound trusted A2A access to ${Z.domain} and pin key fingerprint ${K}. It will not add or remove the directory contact.`:`This will revoke inbound trusted A2A access from ${Z.domain}. The directory contact remains saved for outbound calls.`,args:U}}}}var FM0=H.object({notifyOnNewAgents:H.boolean().default(!1).describe("Notify when directory scans discover new agents")}).strict();class O3A extends p6{fetchFn;constructor(A,Q={}){super("agent",fn,Q,FM0);this.fetchFn=A}async onRegister(A){A.recurringChecks.register({id:"directory-scan",cadence:"daily",deliverAlerts:this.config.notifyOnNewAgents,run:async({signal:Q})=>{let $=await b3A(A,this.fetchFn,Q);if($.created===0||!this.config.notifyOnNewAgents)return{};let w=[...$.createdDomains].sort(),B=[...$.introducingPeers].sort(),X=`${$.created} agent${$.created===1?"":"s"}`;return{alerts:[{dedupeKey:`sightings:${e6(`${$.observedAt}\x00${w.join("\x00")}`)}`,title:"New agent sightings",body:`${X} sighted through ${B.join(", ")}`}]}}})}async getTools(){return[Ac2(this.getContext(),this.fetchFn),$c2(this.getContext(),this.fetchFn),Xc2(this.getContext(),this.fetchFn)]}}function f3A(A={}){return new O3A(void 0,A)}KA();KA();C0();var LT=H.object({name:H.string(),description:H.string(),tags:H.array(H.string()),examples:H.array(H.string())}),Yc2=LT,c50=qB.extend({entityType:H.literal(k9),metadata:Yc2});KA();class xn extends UQ{constructor(){super({entityType:k9,purpose:"A capability advertised by a remote agent.",schema:c50,frontmatterSchema:LT})}fromMarkdown(A){let Q=this.parseFrontMatter(A,LT);return{content:A,entityType:k9,metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}KA();C0();var Jh$=H.object({skills:H.array(LT).max(8)}),Zc2=K2({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:Jh$,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
10818
10818
 
10819
10819
  Given knowledge domains, CONSOLIDATE related topics into broader skills.
10820
10820
  There should be FEWER skills than topics \u2014 combine related domains.
@@ -10964,9 +10964,9 @@ Context:
10964
10964
  ${JSON.stringify(w,null,2)}
10965
10965
 
10966
10966
  Draft SWOT:
10967
- ${JSON.stringify($,null,2)}`}function MM0(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function uh$(A,Q){let $=["strengths","weaknesses","opportunities","threats"];for(let w of $){let B=new Set(A[w].map((X)=>X.theme.trim().toLowerCase()));for(let X of Q[w]){let Y=X.sourceTheme.trim().toLowerCase();if(!B.has(Y))throw Error(`SWOT refinement invented theme "${X.sourceTheme}" in ${w}`)}}}class bM0{logger;context;adapter=new EP;constructor(A,Q){this.logger=A,this.context=Q}validateAndParse(A){let Q=v3A.safeParse(A??{});return Q.success?Q.data:null}async process(A,Q,$){await $.report({progress:0.2,message:"Building SWOT context"});let w=await y3A(this.context),B;if(w.summary.brainSkillCount+w.summary.approvedAgentCount+w.summary.discoveredAgentCount===0)B={strengths:[],weaknesses:[],opportunities:[],threats:[]};else{await $.report({progress:0.6,message:"Synthesizing SWOT analysis"});let{object:K}=await this.context.ai.generateObject(await gh$(this.context,w),C3A),U=C3A.parse(K);await $.report({progress:0.75,message:"Refining SWOT language"});let G=await this.context.ai.generateObject(await mh$(this.context,w,U),PM0);B=PM0.parse(G.object),uh$(U,B)}let Y=new Date().toISOString(),Z=this.adapter.createSwotContent({strengths:MM0(B.strengths),weaknesses:MM0(B.weaknesses),opportunities:MM0(B.opportunities),threats:MM0(B.threats),derivedAt:Y});await $.report({progress:0.9,message:"Saving SWOT entity"});let W=await this.context.entityService.getEntity({entityType:"swot",id:"swot"});if(W)await this.context.entityService.updateEntity({entity:{...W,content:Z,metadata:{derivedAt:Y}}});else await this.context.entityService.createEntity({entity:{id:"swot",entityType:"swot",content:Z,metadata:{derivedAt:Y}}});return this.logger.info("SWOT derivation complete",{derivedAt:Y,brainSkillCount:w.summary.brainSkillCount,approvedAgentCount:w.summary.approvedAgentCount,discoveredAgentCount:w.summary.discoveredAgentCount}),{entityId:"swot"}}}C0();import{jsxDEV as uZ}from"preact/jsx-dev-runtime";var OM0=H.object({title:H.string(),detail:H.string().optional()}),ch$=H.discriminatedUnion("status",[H.object({status:H.literal("generating")}),H.object({status:H.literal("ready"),strengths:H.array(OM0).default([]),weaknesses:H.array(OM0).default([]),opportunities:H.array(OM0).default([]),threats:H.array(OM0).default([]),derivedAt:H.string()})]);function ph$({items:A}){if(A.length===0)return uZ("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return uZ("ul",{class:"swot-list",children:A.map((Q)=>uZ("li",{class:"swot-item",children:[uZ("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?uZ("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 fM0({title:A,tone:Q,items:$}){return uZ("section",{class:`swot-cell is-${Q}`,children:[uZ("div",{class:"swot-head",children:A},void 0,!1,void 0,this),uZ(ph$,{items:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function m3A({data:A}){let Q=ch$.safeParse(A);if(!Q.success||Q.data.status==="generating")return uZ("div",{"data-swot-widget":!0,children:uZ("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let $=Q.data;return uZ("div",{"data-swot-widget":!0,children:uZ("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[uZ(fM0,{title:"Strengths",tone:"s",items:$.strengths},void 0,!1,void 0,this),uZ(fM0,{title:"Weaknesses",tone:"w",items:$.weaknesses},void 0,!1,void 0,this),uZ(fM0,{title:"Opportunities",tone:"o",items:$.opportunities},void 0,!1,void 0,this),uZ(fM0,{title:"Threats",tone:"t",items:$.threats},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var u3A={name:"@brains/assessment",version:"0.2.0-alpha.183",description:"Assessment outputs and capability-profile analysis",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var dh$=H.object({status:H.enum(["ready","generating"])}),c3A=new EP;class p3A extends S6{entityType="swot";schema=Rn;adapter=c3A;initialSyncComplete=!1;constructor(){super("swot",u3A,{},XY)}async onRegister(A){let Q=new bM0(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q),A.eval.registerHandler("deriveSwot",async()=>{let X=XH.from(async()=>{});if(!X)throw Error("Expected progress reporter to be created");await Q.process({reason:"eval"},"eval-swot-derive",X);let Y=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!Y)throw Error("Expected SWOT entity to be created during eval");return c3A.parseSwotContent(Y.content).frontmatter});let $=async(X)=>{try{return await A.jobs.enqueue({type:"derive",data:{reason:X},options:{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${X}`}}})}catch(Y){return this.logger.error("Failed to queue SWOT derivation",{error:Y,reason:X}),null}},w=async(X)=>{if(!await A.entityService.getEntity({entityType:"swot",id:"swot"}))await $(X)};A.messaging.subscribe("sync:initial:completed",async()=>{return this.initialSyncComplete=!0,await w("initial-missing-entity"),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"swot",pluginId:this.id,title:"SWOT",group:"network",section:"secondary",priority:14,rendererName:"SwotWidget",digestProvider:(X)=>{let{status:Y}=dh$.parse(X);return{digest:[{label:"SWOT",value:Y==="ready"?"Ready":"Generating",tone:Y==="ready"?"good":"warn"}]}},component:m3A,dataProvider:async()=>{let X=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!X)return{status:"generating"};let{frontmatter:Y}=c3A.parseSwotContent(X.content);return{status:"ready",...Y}}}}),{success:!0}});let B=async(X)=>{let{entityType:Y}=X.payload;if(!this.initialSyncComplete)return{success:!0};if(Y!=="agent"&&Y!=="skill")return{success:!0};return await $("entity-change"),{success:!0}};A.messaging.subscribe("entity:created",B),A.messaging.subscribe("entity:updated",B),A.messaging.subscribe("entity:deleted",B)}}function l3A(){return new p3A}KA();y9();C0();var Xe5=new EP,Nc2=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),_c2=H.enum(["discovered","approved"]),ih$=H.object({name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),brainName:H.string(),url:H.string().url(),did:H.string().optional(),status:_c2,discoveredAt:H.string().datetime()}),nh$=qB.extend({entityType:H.literal("agent"),metadata:H.object({name:H.string(),url:H.string().url(),status:_c2,slug:H.string()})}),d3A=H.object({name:H.string(),description:H.string(),tags:H.array(H.string()),examples:H.array(H.string())}),rh$=qB.extend({entityType:H.literal("skill"),metadata:d3A}),oh$=H.object({about:H.string(),skills:H.array(Nc2),notes:H.string()});function sh$(A){if(!Array.isArray(A)||A.length===0)return"";return A.map(($)=>{let w=$.tags.length>0?` [${$.tags.join(", ")}]`:"";return`- ${$.name}: ${$.description}${w}`}).join(`
10967
+ ${JSON.stringify($,null,2)}`}function MM0(A){return A.map((Q)=>Q.detail===null?{title:Q.title}:{title:Q.title,detail:Q.detail})}function uh$(A,Q){let $=["strengths","weaknesses","opportunities","threats"];for(let w of $){let B=new Set(A[w].map((X)=>X.theme.trim().toLowerCase()));for(let X of Q[w]){let Y=X.sourceTheme.trim().toLowerCase();if(!B.has(Y))throw Error(`SWOT refinement invented theme "${X.sourceTheme}" in ${w}`)}}}class bM0{logger;context;adapter=new EP;constructor(A,Q){this.logger=A,this.context=Q}validateAndParse(A){let Q=v3A.safeParse(A??{});return Q.success?Q.data:null}async process(A,Q,$){await $.report({progress:0.2,message:"Building SWOT context"});let w=await y3A(this.context),B;if(w.summary.brainSkillCount+w.summary.approvedAgentCount+w.summary.discoveredAgentCount===0)B={strengths:[],weaknesses:[],opportunities:[],threats:[]};else{await $.report({progress:0.6,message:"Synthesizing SWOT analysis"});let{object:K}=await this.context.ai.generateObject(await gh$(this.context,w),C3A),U=C3A.parse(K);await $.report({progress:0.75,message:"Refining SWOT language"});let G=await this.context.ai.generateObject(await mh$(this.context,w,U),PM0);B=PM0.parse(G.object),uh$(U,B)}let Y=new Date().toISOString(),Z=this.adapter.createSwotContent({strengths:MM0(B.strengths),weaknesses:MM0(B.weaknesses),opportunities:MM0(B.opportunities),threats:MM0(B.threats),derivedAt:Y});await $.report({progress:0.9,message:"Saving SWOT entity"});let W=await this.context.entityService.getEntity({entityType:"swot",id:"swot"});if(W)await this.context.entityService.updateEntity({entity:{...W,content:Z,metadata:{derivedAt:Y}}});else await this.context.entityService.createEntity({entity:{id:"swot",entityType:"swot",content:Z,metadata:{derivedAt:Y}}});return this.logger.info("SWOT derivation complete",{derivedAt:Y,brainSkillCount:w.summary.brainSkillCount,approvedAgentCount:w.summary.approvedAgentCount,discoveredAgentCount:w.summary.discoveredAgentCount}),{entityId:"swot"}}}C0();import{jsxDEV as uZ}from"preact/jsx-dev-runtime";var OM0=H.object({title:H.string(),detail:H.string().optional()}),ch$=H.discriminatedUnion("status",[H.object({status:H.literal("generating")}),H.object({status:H.literal("ready"),strengths:H.array(OM0).default([]),weaknesses:H.array(OM0).default([]),opportunities:H.array(OM0).default([]),threats:H.array(OM0).default([]),derivedAt:H.string()})]);function ph$({items:A}){if(A.length===0)return uZ("p",{class:"swot-empty",children:"\u2014"},void 0,!1,void 0,this);return uZ("ul",{class:"swot-list",children:A.map((Q)=>uZ("li",{class:"swot-item",children:[uZ("b",{children:Q.title},void 0,!1,void 0,this),Q.detail?uZ("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 fM0({title:A,tone:Q,items:$}){return uZ("section",{class:`swot-cell is-${Q}`,children:[uZ("div",{class:"swot-head",children:A},void 0,!1,void 0,this),uZ(ph$,{items:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function m3A({data:A}){let Q=ch$.safeParse(A);if(!Q.success||Q.data.status==="generating")return uZ("div",{"data-swot-widget":!0,children:uZ("p",{class:"muted",children:"generating assessment\u2026"},void 0,!1,void 0,this)},void 0,!1,void 0,this);let $=Q.data;return uZ("div",{"data-swot-widget":!0,children:uZ("div",{class:"swot",role:"grid","aria-label":"SWOT analysis of agent network",children:[uZ(fM0,{title:"Strengths",tone:"s",items:$.strengths},void 0,!1,void 0,this),uZ(fM0,{title:"Weaknesses",tone:"w",items:$.weaknesses},void 0,!1,void 0,this),uZ(fM0,{title:"Opportunities",tone:"o",items:$.opportunities},void 0,!1,void 0,this),uZ(fM0,{title:"Threats",tone:"t",items:$.threats},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)}var u3A={name:"@brains/assessment",version:"0.2.0-alpha.184",description:"Assessment outputs and capability-profile analysis",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var dh$=H.object({status:H.enum(["ready","generating"])}),c3A=new EP;class p3A extends S6{entityType="swot";schema=Rn;adapter=c3A;initialSyncComplete=!1;constructor(){super("swot",u3A,{},XY)}async onRegister(A){let Q=new bM0(this.logger.child("SwotDerivationHandler"),A);A.jobs.registerHandler("derive",Q),A.eval.registerHandler("deriveSwot",async()=>{let X=XH.from(async()=>{});if(!X)throw Error("Expected progress reporter to be created");await Q.process({reason:"eval"},"eval-swot-derive",X);let Y=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!Y)throw Error("Expected SWOT entity to be created during eval");return c3A.parseSwotContent(Y.content).frontmatter});let $=async(X)=>{try{return await A.jobs.enqueue({type:"derive",data:{reason:X},options:{source:this.id,priority:10,deduplication:"coalesce",deduplicationKey:"swot",metadata:{operationType:"data_processing",operationTarget:`swot:${X}`}}})}catch(Y){return this.logger.error("Failed to queue SWOT derivation",{error:Y,reason:X}),null}},w=async(X)=>{if(!await A.entityService.getEntity({entityType:"swot",id:"swot"}))await $(X)};A.messaging.subscribe("sync:initial:completed",async()=>{return this.initialSyncComplete=!0,await w("initial-missing-entity"),{success:!0}}),A.messaging.subscribe("system:plugins:ready",async()=>{return await A.messaging.send({type:"dashboard:register-widget",payload:{id:"swot",pluginId:this.id,title:"SWOT",group:"network",section:"secondary",priority:14,rendererName:"SwotWidget",digestProvider:(X)=>{let{status:Y}=dh$.parse(X);return{digest:[{label:"SWOT",value:Y==="ready"?"Ready":"Generating",tone:Y==="ready"?"good":"warn"}]}},component:m3A,dataProvider:async()=>{let X=await A.entityService.getEntity({entityType:"swot",id:"swot"});if(!X)return{status:"generating"};let{frontmatter:Y}=c3A.parseSwotContent(X.content);return{status:"ready",...Y}}}}),{success:!0}});let B=async(X)=>{let{entityType:Y}=X.payload;if(!this.initialSyncComplete)return{success:!0};if(Y!=="agent"&&Y!=="skill")return{success:!0};return await $("entity-change"),{success:!0}};A.messaging.subscribe("entity:created",B),A.messaging.subscribe("entity:updated",B),A.messaging.subscribe("entity:deleted",B)}}function l3A(){return new p3A}KA();y9();C0();var Xe5=new EP,Nc2=H.object({name:H.string(),description:H.string(),tags:H.array(H.string())}),_c2=H.enum(["discovered","approved"]),ih$=H.object({name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),brainName:H.string(),url:H.string().url(),did:H.string().optional(),status:_c2,discoveredAt:H.string().datetime()}),nh$=qB.extend({entityType:H.literal("agent"),metadata:H.object({name:H.string(),url:H.string().url(),status:_c2,slug:H.string()})}),d3A=H.object({name:H.string(),description:H.string(),tags:H.array(H.string()),examples:H.array(H.string())}),rh$=qB.extend({entityType:H.literal("skill"),metadata:d3A}),oh$=H.object({about:H.string(),skills:H.array(Nc2),notes:H.string()});function sh$(A){if(!Array.isArray(A)||A.length===0)return"";return A.map(($)=>{let w=$.tags.length>0?` [${$.tags.join(", ")}]`:"";return`- ${$.name}: ${$.description}${w}`}).join(`
10968
10968
  `)}function ah$(A){if(!A.trim())return[];return A.split(`
10969
- `).map((Q)=>Q.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/)).filter((Q)=>Q!==null).map((Q)=>({name:Q[1]??"",description:Q[2]??"",tags:Q[3]?Q[3].split(",").map(($)=>$.trim()).filter(Boolean):[]}))}var th$=new d$(oh$,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:sh$,parser:ah$},{key:"notes",label:"Notes",type:"string"}]});class Pc2 extends UQ{constructor(){super({entityType:"agent",purpose:"An agent entity used for SWOT evaluation.",schema:nh$,frontmatterSchema:ih$})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=th$.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 kc2 extends UQ{constructor(){super({entityType:"skill",purpose:"A skill entity used for SWOT evaluation.",schema:rh$,frontmatterSchema:d3A})}fromMarkdown(A){let Q=this.parseFrontMatter(A,d3A);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var Ye5=new Pc2,Ze5=new kc2,eh$=H.object({name:H.string(),description:H.string(),tags:H.array(H.string()),examples:H.array(H.string())}),He5=H.object({skills:H.array(eh$),agents:H.array(H.object({id:H.string().optional(),name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),brainName:H.string(),url:H.url(),did:H.string().optional(),status:H.enum(["discovered","approved"]),discoveredAt:H.string().datetime().optional(),about:H.string(),skills:H.array(Nc2),notes:H.string().default("")}))});var AE$=H.object({}).strict();function xM0(A={}){return AE$.parse(A),[l3A()]}KA();C0();C0();var i3A=H.object({enabled:H.boolean().default(!0),pdsEndpoint:H.url().default("https://bsky.social").describe("AT Protocol PDS service endpoint"),identifier:H.string().optional().describe("PDS login identifier, usually a handle or account DID"),repoDid:H.string().optional().describe("DID of the PDS repo that owns records"),appPassword:H.string().optional().describe("App password for prototype authentication; supply via ${ENV_VAR} interpolation, never a committed literal"),anchorDid:H.string().optional().describe("Optional human/operator DID referenced from records; defaults to did:web:<site-host>:anchor when omitted"),brainDid:H.string().optional().describe("Optional public brain DID referenced from records; defaults to did:web:<site-host> when omitted")});C0();var QE$=H.looseObject({message:H.string()}),$E$=H.looseObject({did:H.string(),handle:H.string(),accessJwt:H.string(),refreshJwt:H.string()}),n3A=H.looseObject({uri:H.string(),cid:H.string()}),wE$=n3A.extend({value:H.record(H.string(),H.unknown())}),BE$=H.looseObject({$type:H.literal("blob").optional(),ref:H.looseObject({$link:H.string()}),mimeType:H.string(),size:H.number().int().nonnegative()}).transform((A)=>({...A.$type!==void 0?{$type:A.$type}:{},ref:{$link:A.ref.$link},mimeType:A.mimeType,size:A.size})),XE$=H.looseObject({blob:BE$});function YE$(A){return A.replace(/\/+$/,"")}var ZE$=(A,Q)=>fetch(A,Q);async function l50(A,Q){let $=await A.text(),w;try{w=$.length>0?JSON.parse($):void 0}catch{if(!A.ok)throw Error(`AT Protocol request failed with ${A.status}`);throw Error("Failed to parse JSON")}if(!A.ok){let B=QE$.safeParse(w);throw Error(B.success?B.data.message:`AT Protocol request failed with ${A.status}`)}return Q.parse(w)}class d50{pdsEndpoint;identifier;appPassword;fetchFn;session;constructor(A){this.pdsEndpoint=YE$(A.pdsEndpoint),this.identifier=A.identifier,this.appPassword=A.appPassword,this.fetchFn=A.fetch??ZE$}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 l50(A,$E$);return this.session=Q,Q}async createRecord(A){let Q=await this.getSession(),$=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 l50($,n3A)}async putRecord(A){let Q=await this.getSession(),$=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 l50($,n3A)}async getRecord(A){let Q=new URLSearchParams({repo:A.repo,collection:A.collection,rkey:A.rkey}),$=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.getRecord?${Q.toString()}`,{method:"GET"});return l50($,wE$)}async uploadBlob(A){let Q=await this.getSession(),$=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 l50($,XE$)}async getSession(){return this.session??=await this.createSession(),this.session}}function _T(A){return A?.startsWith("did:web:")??!1}function RM0(A){if(!_T(A))return;let Q=A.slice(8);if(!Q)return;let[$]=Q.split(":");if(!$)return;try{return decodeURIComponent($)}catch{return $}}function Mc2(A){if(!_T(A))return;let Q=A.slice(8);if(!Q)return;let[,...$]=Q.split(":");if($.length===0)return"/.well-known/did.json";return`/${$.map((B)=>{try{return decodeURIComponent(B)}catch{return B}}).join("/")}/did.json`}function bc2(A){return A.replace(/\/+$/,"")}function i50(A){return`did:web:${encodeURIComponent(A)}`}function vM0(A){return`${i50(A)}:anchor`}function r3A(A){return{"@context":["https://www.w3.org/ns/did/v1"],id:A}}function Oc2(A,Q){let $=A.identifier?.startsWith("did:")?void 0:A.identifier?[`at://${A.identifier}`]:void 0;return{...r3A(Q),...$&&{alsoKnownAs:$},service:[{id:"#atproto_pds",type:"AtprotoPersonalDataServer",serviceEndpoint:bc2(A.pdsEndpoint)}]}}function fc2(A){if(!_T(A.brainDid))return null;return Oc2(A,A.brainDid)}function jc2(A,Q){if(!A||!Q)return;let $=RM0(A),w=Mc2(A);if(!$||!w)return;return{path:w,hostname:$,document:Q}}function CM0(A){let Q=[],$=jc2(A.brainDid,fc2(A));if($)Q.push($);if(_T(A.anchorDid)&&A.anchorDid!==A.brainDid){let w=jc2(A.anchorDid,r3A(A.anchorDid));if(w)Q.push(w)}return Q}function o3A(A,Q){let $=[];if(!A.brainDid){let w=i50(Q);$.push({path:"/.well-known/did.json",hostname:Q,document:Oc2(A,w)})}if(!A.anchorDid){let w=vM0(Q);$.push({path:"/anchor/did.json",hostname:Q,document:r3A(w)})}return $}function HE$(A,Q){if(!A)return;try{return new URL(A,Q).toString()}catch{return}}function WE$(A){let Q=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,200);return Q.length>0?Q:"skill"}function xc2(A,Q){let $=A[Q];return typeof $==="string"&&$.length>0?$:void 0}function Rc2(A,Q){let $=A[Q];if(!Array.isArray($))return;let w=$.filter((B)=>typeof B==="string"&&B.length>0);return w.length>0?w:void 0}function KE$(A){let Q=A.metadata,$=xc2(Q,"name"),w=xc2(Q,"description");if(!$||!w)return;let B=Rc2(Q,"tags"),X=Rc2(Q,"examples");return{id:WE$($),name:$,description:w,...B&&{tags:B},...X&&{examples:X}}}async function UE$(A){if(!A.entityService.hasEntityType("skill"))return[];return(await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}})).map(($)=>KE$($)).filter(($)=>$!==void 0).slice(0,100)}async function s3A(A,Q,$=new Date){let w=A.identity.get(),B=A.identity.getProfile(),X=await A.identity.getAppInfo(),Y=HE$(A.siteUrl??B.website,void 0);if(!Y)throw Error("AT Protocol brain card publishing requires siteUrl");let Z=new URL(Y).hostname,W=Q.brainDid??i50(Z),K=Q.anchorDid??vM0(Z);if(_T(W)){if(RM0(W)!==Z)throw Error("AT Protocol brain card did:web host must match siteUrl host")}let U=await UE$(A);return{$type:"ai.rizom.brain.card",siteUrl:Y,brain:{did:W,name:w.name,role:w.role,purpose:w.purpose,values:w.values},anchor:{did:K,name:B.name,kind:B.kind},skills:U,model:X.model,version:X.version,createdAt:$.toISOString(),updatedAt:$.toISOString()}}var vc2={name:"@brains/atproto",version:"0.2.0-alpha.183",description:"AT Protocol integration for identity, publishing, discovery, and feeds",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Cc2=E8["ai.rizom.brain.card"],DE$=H.looseObject({did:H.string()}),qE$=H.looseObject({service:H.array(H.looseObject({id:H.string().optional(),type:H.string().optional(),serviceEndpoint:H.string().optional()})).optional()}),zE$="ai.rizom.brain.card",VE$="self",hc2=50;class a3A extends p6{deps;projectionRegistry;constructor(A={},Q={}){super("atproto",vc2,A,i3A);this.deps=Q,this.projectionRegistry=Q.projectionRegistry??aB.getInstance()}getWebRoutes(){if(!this.config.enabled)return[];let A=CM0(this.config),Q=[...!this.config.brainDid?["/.well-known/did.json"]:[],...!this.config.anchorDid?["/anchor/did.json"]:[]];return[...new Set([...A.map((w)=>w.path),...Q])].map((w)=>({path:w,method:"GET",public:!0,handler:(B)=>{let X=new URL(B.url).hostname,Y=[...CM0(this.config),...o3A(this.config,X)].filter((W)=>W.path===w),Z=Y.find((W)=>W.hostname===X)??Y[0];if(!Z)return new Response("Not found",{status:404});return new Response(JSON.stringify(Z.document),{headers:{"Content-Type":"application/did+json"}})}}))}async publishBrainCard(A,Q={}){let $=await s3A(A,this.config);o_(Cc2,$);let w=this.config.repoDid;if(Q.dryRun)return{record:$,dryRun:!0,...w&&{repo:w}};let B=this.resolveAppPassword();if(!this.config.identifier||!B)throw Error("AT Protocol publishing requires identifier and app password configuration");let X=this.createPdsClient(B),Y=await X.createSession(),Z=w??Y.did;if(!X.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let W=await X.putRecord({repo:Z,collection:"ai.rizom.brain.card",rkey:"self",validate:!1,record:$});return{record:$,repo:Z,uri:W.uri,cid:W.cid,dryRun:!1}}async publishEntity(A,Q){let $=this.projectionRegistry.get(Q.entityType);if(!$)throw Error(`No AT Protocol projection registered for ${Q.entityType}`);return this.publishProjectedEntity(A,Q,$)}async publishPost(A,Q){let $=this.projectionRegistry.get("post");if(!$)throw Error("No AT Protocol projection registered for post");return this.publishProjectedEntity(A,{entityType:"post",...Q},$)}async discoverBrainCards(A,Q){let $=[...new Set(Q.repos.map((X)=>X.trim()))].filter((X)=>X.length>0);if($.length===0)throw Error("AT Protocol discovery requires at least one repo DID or handle");if($.length>hc2)throw Error(`AT Protocol discovery accepts at most ${hc2} repos per batch`);let w=new Set,B=[];for(let X of $)try{let Y=await this.resolveRepoPdsEndpoint(X),Z=this.createPublicPdsClient(Y.pdsEndpoint);if(!Z.getRecord)throw Error("AT Protocol PDS client does not support record reads");let W=await Z.getRecord({repo:Y.repoDid,collection:zE$,rkey:VE$});o_(Cc2,W.value);let K=FE$(W.uri)??Y.repoDid,U=`${K}:${W.uri}:${W.cid}`;if(w.has(U)){B.push({repo:X,status:"skipped",repoDid:K,uri:W.uri,cid:W.cid,error:"Duplicate brain card in discovery batch"});continue}w.add(U),await A.messaging.send({type:O$0,payload:{repoDid:K,uri:W.uri,cid:W.cid,record:W.value},broadcast:!0}),B.push({repo:X,status:"discovered",repoDid:K,uri:W.uri,cid:W.cid})}catch(Y){B.push({repo:X,status:"skipped",error:aA(Y)})}return{discovered:B.filter((X)=>X.status==="discovered").length,skipped:B.filter((X)=>X.status==="skipped").length,results:B}}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:aA(Q)}),!1}}async getTools(){return[]}async publishProjectedEntity(A,Q,$){let w=await this.findPublishEntity(A,Q),B=Q.entityId??Q.slug;if(!B)throw Error(`${Q.entityType} publish requires entityId or slug`);if(!w)throw Error(`${Q.entityType} not found: ${B}`);if(w.visibility!=="public")throw Error(`Cannot publish non-public ${Q.entityType}: ${B}`);let X=this.config.repoDid;if(Q.dryRun){let D=await $.buildRecord({entity:w,context:A,config:this.config,...Q.topics&&{topics:Q.topics},dryRun:!0});return o_($.lexicon,D),{record:D,dryRun:!0,...X&&{repo:X}}}let Y=this.resolveAppPassword();if(!this.config.identifier||!Y)throw Error("AT Protocol publishing requires identifier and app password configuration");let Z=this.createPdsClient(Y),W=await Z.createSession(),K=X??W.did,U=await $.buildRecord({entity:w,context:A,config:this.config,client:Z,...Q.topics&&{topics:Q.topics}});if(o_($.lexicon,U),!Z.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let G=await Z.putRecord({repo:K,collection:$.collection,rkey:JE$(w.id),...$.validate!==void 0&&{validate:$.validate},record:U});return await $.onPublished?.({entity:w,context:A,record:U,uri:G.uri,cid:G.cid}),{record:U,repo:K,uri:G.uri,cid:G.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 d50({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 $=await this.resolveDidToPdsEndpoint(Q);if(!$)throw Error(`Could not resolve AT Protocol PDS for repo: ${Q}`);return{repoDid:Q,pdsEndpoint:$}}async resolveHandleToDid(A){let Q=new URL("/xrpc/com.atproto.identity.resolveHandle",this.config.pdsEndpoint);Q.searchParams.set("handle",A);let $=await this.fetch(Q.toString());if(!$.ok)return;let w=DE$.safeParse(await $.json());return w.success?w.data.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(IE$(A)):void 0,$=qE$.safeParse(Q);if(!$.success)return;return $.data.service?.find((B)=>B.id==="#atproto_pds"||B.type==="AtprotoPersonalDataServer")?.serviceEndpoint}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 d50({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A})}resolveAppPassword(){return this.config.appPassword}}function JE$(A){let Q=A.replace(/[^A-Za-z0-9._~:-]/g,"_").slice(0,512);return Q.length>0?Q:"self"}function FE$(A){return/^at:\/\/([^/]+)/.exec(A)?.[1]}function IE$(A){let Q=A.slice(8).split(":").map(decodeURIComponent),[$,...w]=Q;if(!$)throw Error(`Invalid did:web value: ${A}`);if(w.length===0)return`https://${$}/.well-known/did.json`;return`https://${$}/${w.join("/")}/did.json`}function hM0(A,Q){return new a3A(A,Q)}KA();C0();var EM0={name:"@brains/rover",version:"0.2.0-alpha.183",dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/atproto-registry":"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/doc":"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/playbooks":"workspace:*","@brains/portfolio":"workspace:*","@brains/products":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/rover-onboarding":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-content":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/topics":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*","@rizom/theme-default":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*","@rizom/site-rizom-ai":"workspace:*","@rizom/theme-rizom-ai":"workspace:*",typescript:"^7.0.2"},files:["src","brain.eval.yaml","env.schema.template"],main:"./src/index.ts",private:!0,scripts:{"build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/cms",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 . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix","start:core":"bun run build:ui && cd test-apps/core && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:default":"bun run build:ui && cd test-apps/default && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:full":"bun run build:ui && cd test-apps/full && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:rizom-ai":"bun run build:ui && cd test-apps/rizom-ai && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var NE$=H.looseObject({});class Ec2 extends p6{constructor(A={}){super("rover-profile",EM0,A,NE$)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",Iv)}}function Tc2(A={}){return new Ec2(A)}KA();C0();Q5();KA();KA();var n50=hN.extend(Iv.shape);class TM0{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,$){let w=$.entityService,[B,X,Y,Z]=await Promise.all([tm(w,n50),EP0(w,{entityType:"post",count:3,parse:kw0}),EP0(w,{entityType:"deck",count:3,parse:Rw0}),_w0(w)]),W={profile:B,posts:X,decks:Y,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:wGA(Z.cta),sections:Z.sections??{}};return Q.parse(W)}}KA();class yM0{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,$){let B={profile:await tm($.entityService,n50)};return Q.parse(B)}}import{jsxDEV as Y5,Fragment as kE$}from"preact/jsx-dev-runtime";var _E$="grid md:grid-cols-[14rem_1px_1fr] gap-y-2 gap-x-0 md:gap-16 items-start",PE$="border-t md:border-t-0 md:border-l border-rule-strong md:self-stretch",t3A=({number:A,title:Q,blurb:$,children:w})=>Y5("section",{className:"py-20 border-b border-rule px-6 md:px-12",children:Y5("div",{className:"max-w-6xl mx-auto",children:Y5("div",{className:_E$,children:[Y5(WWA,{title:Q,number:A,blurb:$},void 0,!1,void 0,this),Y5("div",{className:PE$,"aria-hidden":"true"},void 0,!1,void 0,this),Y5("div",{className:"mt-6 md:mt-0",children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e3A=({profile:A,posts:Q,decks:$,postsListUrl:w,decksListUrl:B,cta:X,sections:Y})=>{let Z=A.tagline?.length?A.tagline:A.description,W=Q.map((q)=>({id:q.id,url:q.url,title:q.metadata.title,date:q.metadata.publishedAt??q.created,description:q.frontmatter.excerpt,series:q.frontmatter.seriesName&&q.frontmatter.seriesIndex?{name:q.frontmatter.seriesName,index:q.frontmatter.seriesIndex}:void 0})),K=$.map((q)=>({id:q.id,url:q.url,title:q.frontmatter.title||q.id,date:q.frontmatter.publishedAt??q.created,description:q.frontmatter.description})),U=A.name||"Home",G=[A.intro,A.description,Z].find((q)=>q)??"Professional site",D=Boolean(A.description)||A.expertise!==void 0&&A.expertise.length>0;return Y5(kE$,{children:[Y5(C6,{title:U,description:G,ogType:"website"},void 0,!1,void 0,this),Y5("div",{className:"homepage-list bg-theme",children:[Y5("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:Y5("div",{className:"relative z-10 max-w-6xl mx-auto w-full",children:[A.name&&Y5("div",{className:"flex items-center gap-[0.6rem] mb-6 font-mono text-[0.7rem] font-medium uppercase tracking-[0.22em] text-accent",children:[Y5("span",{className:"w-[18px] h-px bg-accent","aria-hidden":"true"},void 0,!1,void 0,this),Y5("span",{children:A.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z&&Y5("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:rN0(Z,"italic font-normal text-accent [font-variation-settings:'opsz'_144,'SOFT'_80]")},void 0,!1,void 0,this),A.intro&&Y5("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:rN0(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y5(t3A,{number:"01",title:"Essays",blurb:Y.essays?.blurb,children:Y5(nN0,{items:W,viewAllUrl:w,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),K.length>0&&Y5(t3A,{number:"02",title:"Presentations",blurb:Y.presentations?.blurb,children:Y5(nN0,{items:K,viewAllUrl:B,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D&&Y5(t3A,{number:"03",title:"About",blurb:Y.about?.blurb,children:Y5("div",{className:"flex flex-col gap-8",children:[A.description&&Y5("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&&Y5(KWA,{subjects:A.expertise},void 0,!1,void 0,this),Y5("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",Y5("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),Y5(rHA,{cta:X,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 Iw,Fragment as jE$}from"preact/jsx-dev-runtime";var AVA=({profile:A})=>{let Q=`About ${A.name||"Me"}`,$=[A.description,A.intro].find((B)=>B)??"About page",w=A.expertise!==void 0&&A.expertise.length>0||Boolean(A.currentFocus)||Boolean(A.availability)||Boolean(A.email)||Boolean(A.website)||A.socialLinks!==void 0&&A.socialLinks.length>0;return Iw(jE$,{children:[Iw(C6,{title:Q,description:$,ogType:"profile"},void 0,!1,void 0,this),Iw("div",{className:"about-page bg-theme",children:[Iw("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:Iw("div",{className:"relative z-10 max-w-4xl mx-auto",children:[Iw("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&&Iw("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),Iw("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&Iw("section",{className:"content-section-reveal mb-20 md:mb-28",children:Iw(u4,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&Iw("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),Iw("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map((B,X)=>Iw("li",{className:I80({variant:"accent",size:"lg"}),children:B},X,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),Iw("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&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),Iw("p",{className:"text-lg text-theme leading-relaxed",children:A.availability},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(Boolean(A.email)||Boolean(A.website)||A.socialLinks!==void 0&&A.socialLinks.length>0)&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),Iw("div",{className:"space-y-4",children:[A.email&&Iw("p",{className:"text-lg",children:Iw("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&&Iw("p",{className:"text-lg",children:Iw("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&&Iw("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map((B,X)=>Iw(m4,{href:B.url,external:!0,variant:"secondary",size:"md",children:B.label?.length?B.label:B.platform},X,!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 cZ,Fragment as yc2}from"preact/jsx-dev-runtime";var QVA=()=>{return cZ(yc2,{children:[cZ(C6,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),cZ("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:cZ("div",{className:"text-center max-w-md",children:[cZ("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),cZ("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),cZ("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),cZ(m4,{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)},$VA=()=>{return cZ(yc2,{children:[cZ(C6,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),cZ("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:cZ("div",{className:"text-center max-w-md",children:[cZ("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),cZ("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),cZ("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),cZ(m4,{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)};C0();var gc2=H.object({label:H.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:H.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')")}),ME$={post:{label:"Post"},deck:{label:"Deck"}},Sc2=H.object({entityDisplay:H.object({post:gc2,deck:gc2}).default(ME$).describe("Display metadata for post and deck entity types used by the homepage")});var mc2={name:"@brains/site-professional",version:"0.2.0-alpha.183",description:"Professional site composition package",dependencies:{"@brains/blog":"workspace:*","@brains/decks":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},files:["src"],private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",typecheck:"tsc --noEmit"},type:"module"};var OE$=H.object({blurb:H.string().optional().describe("Short italic subtitle under the section title")}),fE$=H.object({heading:H.string(),buttonText:H.string(),buttonLink:H.string()}),uc2=H.looseObject({name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),description:H.string().optional(),avatar:H.string().optional(),website:H.string().optional(),email:H.string().optional(),socialLinks:H.array(H.object({platform:H.enum(["github","instagram","linkedin","email","website"]),url:H.string(),label:H.string().optional()})).optional(),tagline:H.string().optional(),intro:H.string().optional(),story:H.string().optional(),role:H.string().optional(),audience:H.string().optional(),expertise:H.array(H.string()).optional(),currentFocus:H.string().optional(),availability:H.string().optional(),desiredTone:H.string().optional()}),xE$=H.looseObject({id:H.string(),entityType:H.literal("post"),content:H.string(),created:H.string(),updated:H.string(),contentHash:H.string(),metadata:H.looseObject({title:H.string(),publishedAt:H.string().optional()}),frontmatter:H.looseObject({excerpt:H.string(),seriesName:H.string().optional(),seriesIndex:H.number().optional()}),body:H.string(),url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),seriesUrl:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional(),coverImageSrcset:H.string().optional(),coverImageSizes:H.string().optional()}),RE$=H.looseObject({id:H.string(),entityType:H.literal("deck"),content:H.string(),created:H.string(),updated:H.string(),contentHash:H.string(),metadata:H.looseObject({title:H.string(),publishedAt:H.string().optional()}),frontmatter:H.looseObject({title:H.string(),description:H.string().optional(),publishedAt:H.string().optional()}),body:H.string(),url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});class wVA extends p6{dependencies=["blog","decks"];constructor(A){super("professional-site",mc2,A,Sc2)}async onRegister(A){let Q=this.config.entityDisplay.post,$=this.config.entityDisplay.deck,w=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,B=`/${$.pluralName??$.label.toLowerCase()+"s"}`,X=new TM0(w,B);A.entities.registerDataSource(X);let Y=new yM0;A.entities.registerDataSource(Y);let Z=H.object({profile:uc2,posts:H.array(xE$),decks:H.array(RE$),postsListUrl:H.string(),decksListUrl:H.string(),cta:fE$,sections:H.record(H.string(),OE$)}),W=H.object({profile:uc2}),K=H.object({});A.templates.register({"homepage-list":K2({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:Z,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:e3A}}),about:K2({name:"about",description:"About page with full profile information",schema:W,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:AVA}}),"subscribe-thanks":K2({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:K,requiredPermission:"public",layout:{component:QVA}}),"subscribe-error":K2({name:"subscribe-error",description:"Newsletter subscription error page",schema:K,requiredPermission:"public",layout:{component:$VA}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function cc2(A){return new wVA(A??{})}var pc2=[{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 gM0}from"preact/jsx-dev-runtime";function lc2({sections:A,siteInfo:Q,slots:$,wordmark:w}){return gM0("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[gM0(tHA,{title:Q.title,navigation:Q.navigation.primary,showThemeToggle:!0,...Q.logo!==void 0?{logo:Q.logo}:{},...w!==void 0?{wordmark:w}:{}},void 0,!1,void 0,this),gM0("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),gM0(aHA,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,title:Q.title,tagline:Q.description,children:$?.getSlot("footer-top").map((B)=>B.render())},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var vE$={layouts:{default:lc2},routes:pc2,plugin:cc2,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"}}}},r50=vE$;var dc2=`/*
10969
+ `).map((Q)=>Q.match(/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/)).filter((Q)=>Q!==null).map((Q)=>({name:Q[1]??"",description:Q[2]??"",tags:Q[3]?Q[3].split(",").map(($)=>$.trim()).filter(Boolean):[]}))}var th$=new d$(oh$,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:sh$,parser:ah$},{key:"notes",label:"Notes",type:"string"}]});class Pc2 extends UQ{constructor(){super({entityType:"agent",purpose:"An agent entity used for SWOT evaluation.",schema:nh$,frontmatterSchema:ih$})}fromMarkdown(A){return{content:A,entityType:"agent"}}createAgentContent(A){let Q=th$.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 kc2 extends UQ{constructor(){super({entityType:"skill",purpose:"A skill entity used for SWOT evaluation.",schema:rh$,frontmatterSchema:d3A})}fromMarkdown(A){let Q=this.parseFrontMatter(A,d3A);return{content:A,entityType:"skill",metadata:Q}}createSkillContent(A){return this.buildMarkdown("",A)}}var Ye5=new Pc2,Ze5=new kc2,eh$=H.object({name:H.string(),description:H.string(),tags:H.array(H.string()),examples:H.array(H.string())}),He5=H.object({skills:H.array(eh$),agents:H.array(H.object({id:H.string().optional(),name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),brainName:H.string(),url:H.url(),did:H.string().optional(),status:H.enum(["discovered","approved"]),discoveredAt:H.string().datetime().optional(),about:H.string(),skills:H.array(Nc2),notes:H.string().default("")}))});var AE$=H.object({}).strict();function xM0(A={}){return AE$.parse(A),[l3A()]}KA();C0();C0();var i3A=H.object({enabled:H.boolean().default(!0),pdsEndpoint:H.url().default("https://bsky.social").describe("AT Protocol PDS service endpoint"),identifier:H.string().optional().describe("PDS login identifier, usually a handle or account DID"),repoDid:H.string().optional().describe("DID of the PDS repo that owns records"),appPassword:H.string().optional().describe("App password for prototype authentication; supply via ${ENV_VAR} interpolation, never a committed literal"),anchorDid:H.string().optional().describe("Optional human/operator DID referenced from records; defaults to did:web:<site-host>:anchor when omitted"),brainDid:H.string().optional().describe("Optional public brain DID referenced from records; defaults to did:web:<site-host> when omitted")});C0();var QE$=H.looseObject({message:H.string()}),$E$=H.looseObject({did:H.string(),handle:H.string(),accessJwt:H.string(),refreshJwt:H.string()}),n3A=H.looseObject({uri:H.string(),cid:H.string()}),wE$=n3A.extend({value:H.record(H.string(),H.unknown())}),BE$=H.looseObject({$type:H.literal("blob").optional(),ref:H.looseObject({$link:H.string()}),mimeType:H.string(),size:H.number().int().nonnegative()}).transform((A)=>({...A.$type!==void 0?{$type:A.$type}:{},ref:{$link:A.ref.$link},mimeType:A.mimeType,size:A.size})),XE$=H.looseObject({blob:BE$});function YE$(A){return A.replace(/\/+$/,"")}var ZE$=(A,Q)=>fetch(A,Q);async function l50(A,Q){let $=await A.text(),w;try{w=$.length>0?JSON.parse($):void 0}catch{if(!A.ok)throw Error(`AT Protocol request failed with ${A.status}`);throw Error("Failed to parse JSON")}if(!A.ok){let B=QE$.safeParse(w);throw Error(B.success?B.data.message:`AT Protocol request failed with ${A.status}`)}return Q.parse(w)}class d50{pdsEndpoint;identifier;appPassword;fetchFn;session;constructor(A){this.pdsEndpoint=YE$(A.pdsEndpoint),this.identifier=A.identifier,this.appPassword=A.appPassword,this.fetchFn=A.fetch??ZE$}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 l50(A,$E$);return this.session=Q,Q}async createRecord(A){let Q=await this.getSession(),$=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 l50($,n3A)}async putRecord(A){let Q=await this.getSession(),$=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 l50($,n3A)}async getRecord(A){let Q=new URLSearchParams({repo:A.repo,collection:A.collection,rkey:A.rkey}),$=await this.fetchFn(`${this.pdsEndpoint}/xrpc/com.atproto.repo.getRecord?${Q.toString()}`,{method:"GET"});return l50($,wE$)}async uploadBlob(A){let Q=await this.getSession(),$=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 l50($,XE$)}async getSession(){return this.session??=await this.createSession(),this.session}}function _T(A){return A?.startsWith("did:web:")??!1}function RM0(A){if(!_T(A))return;let Q=A.slice(8);if(!Q)return;let[$]=Q.split(":");if(!$)return;try{return decodeURIComponent($)}catch{return $}}function Mc2(A){if(!_T(A))return;let Q=A.slice(8);if(!Q)return;let[,...$]=Q.split(":");if($.length===0)return"/.well-known/did.json";return`/${$.map((B)=>{try{return decodeURIComponent(B)}catch{return B}}).join("/")}/did.json`}function bc2(A){return A.replace(/\/+$/,"")}function i50(A){return`did:web:${encodeURIComponent(A)}`}function vM0(A){return`${i50(A)}:anchor`}function r3A(A){return{"@context":["https://www.w3.org/ns/did/v1"],id:A}}function Oc2(A,Q){let $=A.identifier?.startsWith("did:")?void 0:A.identifier?[`at://${A.identifier}`]:void 0;return{...r3A(Q),...$&&{alsoKnownAs:$},service:[{id:"#atproto_pds",type:"AtprotoPersonalDataServer",serviceEndpoint:bc2(A.pdsEndpoint)}]}}function fc2(A){if(!_T(A.brainDid))return null;return Oc2(A,A.brainDid)}function jc2(A,Q){if(!A||!Q)return;let $=RM0(A),w=Mc2(A);if(!$||!w)return;return{path:w,hostname:$,document:Q}}function CM0(A){let Q=[],$=jc2(A.brainDid,fc2(A));if($)Q.push($);if(_T(A.anchorDid)&&A.anchorDid!==A.brainDid){let w=jc2(A.anchorDid,r3A(A.anchorDid));if(w)Q.push(w)}return Q}function o3A(A,Q){let $=[];if(!A.brainDid){let w=i50(Q);$.push({path:"/.well-known/did.json",hostname:Q,document:Oc2(A,w)})}if(!A.anchorDid){let w=vM0(Q);$.push({path:"/anchor/did.json",hostname:Q,document:r3A(w)})}return $}function HE$(A,Q){if(!A)return;try{return new URL(A,Q).toString()}catch{return}}function WE$(A){let Q=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,200);return Q.length>0?Q:"skill"}function xc2(A,Q){let $=A[Q];return typeof $==="string"&&$.length>0?$:void 0}function Rc2(A,Q){let $=A[Q];if(!Array.isArray($))return;let w=$.filter((B)=>typeof B==="string"&&B.length>0);return w.length>0?w:void 0}function KE$(A){let Q=A.metadata,$=xc2(Q,"name"),w=xc2(Q,"description");if(!$||!w)return;let B=Rc2(Q,"tags"),X=Rc2(Q,"examples");return{id:WE$($),name:$,description:w,...B&&{tags:B},...X&&{examples:X}}}async function UE$(A){if(!A.entityService.hasEntityType("skill"))return[];return(await A.entityService.listEntities({entityType:"skill",options:{filter:{visibilityScope:"public"}}})).map(($)=>KE$($)).filter(($)=>$!==void 0).slice(0,100)}async function s3A(A,Q,$=new Date){let w=A.identity.get(),B=A.identity.getProfile(),X=await A.identity.getAppInfo(),Y=HE$(A.siteUrl??B.website,void 0);if(!Y)throw Error("AT Protocol brain card publishing requires siteUrl");let Z=new URL(Y).hostname,W=Q.brainDid??i50(Z),K=Q.anchorDid??vM0(Z);if(_T(W)){if(RM0(W)!==Z)throw Error("AT Protocol brain card did:web host must match siteUrl host")}let U=await UE$(A);return{$type:"ai.rizom.brain.card",siteUrl:Y,brain:{did:W,name:w.name,role:w.role,purpose:w.purpose,values:w.values},anchor:{did:K,name:B.name,kind:B.kind},skills:U,model:X.model,version:X.version,createdAt:$.toISOString(),updatedAt:$.toISOString()}}var vc2={name:"@brains/atproto",version:"0.2.0-alpha.184",description:"AT Protocol integration for identity, publishing, discovery, and feeds",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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var Cc2=E8["ai.rizom.brain.card"],DE$=H.looseObject({did:H.string()}),qE$=H.looseObject({service:H.array(H.looseObject({id:H.string().optional(),type:H.string().optional(),serviceEndpoint:H.string().optional()})).optional()}),zE$="ai.rizom.brain.card",VE$="self",hc2=50;class a3A extends p6{deps;projectionRegistry;constructor(A={},Q={}){super("atproto",vc2,A,i3A);this.deps=Q,this.projectionRegistry=Q.projectionRegistry??aB.getInstance()}getWebRoutes(){if(!this.config.enabled)return[];let A=CM0(this.config),Q=[...!this.config.brainDid?["/.well-known/did.json"]:[],...!this.config.anchorDid?["/anchor/did.json"]:[]];return[...new Set([...A.map((w)=>w.path),...Q])].map((w)=>({path:w,method:"GET",public:!0,handler:(B)=>{let X=new URL(B.url).hostname,Y=[...CM0(this.config),...o3A(this.config,X)].filter((W)=>W.path===w),Z=Y.find((W)=>W.hostname===X)??Y[0];if(!Z)return new Response("Not found",{status:404});return new Response(JSON.stringify(Z.document),{headers:{"Content-Type":"application/did+json"}})}}))}async publishBrainCard(A,Q={}){let $=await s3A(A,this.config);o_(Cc2,$);let w=this.config.repoDid;if(Q.dryRun)return{record:$,dryRun:!0,...w&&{repo:w}};let B=this.resolveAppPassword();if(!this.config.identifier||!B)throw Error("AT Protocol publishing requires identifier and app password configuration");let X=this.createPdsClient(B),Y=await X.createSession(),Z=w??Y.did;if(!X.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let W=await X.putRecord({repo:Z,collection:"ai.rizom.brain.card",rkey:"self",validate:!1,record:$});return{record:$,repo:Z,uri:W.uri,cid:W.cid,dryRun:!1}}async publishEntity(A,Q){let $=this.projectionRegistry.get(Q.entityType);if(!$)throw Error(`No AT Protocol projection registered for ${Q.entityType}`);return this.publishProjectedEntity(A,Q,$)}async publishPost(A,Q){let $=this.projectionRegistry.get("post");if(!$)throw Error("No AT Protocol projection registered for post");return this.publishProjectedEntity(A,{entityType:"post",...Q},$)}async discoverBrainCards(A,Q){let $=[...new Set(Q.repos.map((X)=>X.trim()))].filter((X)=>X.length>0);if($.length===0)throw Error("AT Protocol discovery requires at least one repo DID or handle");if($.length>hc2)throw Error(`AT Protocol discovery accepts at most ${hc2} repos per batch`);let w=new Set,B=[];for(let X of $)try{let Y=await this.resolveRepoPdsEndpoint(X),Z=this.createPublicPdsClient(Y.pdsEndpoint);if(!Z.getRecord)throw Error("AT Protocol PDS client does not support record reads");let W=await Z.getRecord({repo:Y.repoDid,collection:zE$,rkey:VE$});o_(Cc2,W.value);let K=FE$(W.uri)??Y.repoDid,U=`${K}:${W.uri}:${W.cid}`;if(w.has(U)){B.push({repo:X,status:"skipped",repoDid:K,uri:W.uri,cid:W.cid,error:"Duplicate brain card in discovery batch"});continue}w.add(U),await A.messaging.send({type:O$0,payload:{repoDid:K,uri:W.uri,cid:W.cid,record:W.value},broadcast:!0}),B.push({repo:X,status:"discovered",repoDid:K,uri:W.uri,cid:W.cid})}catch(Y){B.push({repo:X,status:"skipped",error:aA(Y)})}return{discovered:B.filter((X)=>X.status==="discovered").length,skipped:B.filter((X)=>X.status==="skipped").length,results:B}}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:aA(Q)}),!1}}async getTools(){return[]}async publishProjectedEntity(A,Q,$){let w=await this.findPublishEntity(A,Q),B=Q.entityId??Q.slug;if(!B)throw Error(`${Q.entityType} publish requires entityId or slug`);if(!w)throw Error(`${Q.entityType} not found: ${B}`);if(w.visibility!=="public")throw Error(`Cannot publish non-public ${Q.entityType}: ${B}`);let X=this.config.repoDid;if(Q.dryRun){let D=await $.buildRecord({entity:w,context:A,config:this.config,...Q.topics&&{topics:Q.topics},dryRun:!0});return o_($.lexicon,D),{record:D,dryRun:!0,...X&&{repo:X}}}let Y=this.resolveAppPassword();if(!this.config.identifier||!Y)throw Error("AT Protocol publishing requires identifier and app password configuration");let Z=this.createPdsClient(Y),W=await Z.createSession(),K=X??W.did,U=await $.buildRecord({entity:w,context:A,config:this.config,client:Z,...Q.topics&&{topics:Q.topics}});if(o_($.lexicon,U),!Z.putRecord)throw Error("AT Protocol PDS client does not support record upserts");let G=await Z.putRecord({repo:K,collection:$.collection,rkey:JE$(w.id),...$.validate!==void 0&&{validate:$.validate},record:U});return await $.onPublished?.({entity:w,context:A,record:U,uri:G.uri,cid:G.cid}),{record:U,repo:K,uri:G.uri,cid:G.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 d50({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 $=await this.resolveDidToPdsEndpoint(Q);if(!$)throw Error(`Could not resolve AT Protocol PDS for repo: ${Q}`);return{repoDid:Q,pdsEndpoint:$}}async resolveHandleToDid(A){let Q=new URL("/xrpc/com.atproto.identity.resolveHandle",this.config.pdsEndpoint);Q.searchParams.set("handle",A);let $=await this.fetch(Q.toString());if(!$.ok)return;let w=DE$.safeParse(await $.json());return w.success?w.data.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(IE$(A)):void 0,$=qE$.safeParse(Q);if(!$.success)return;return $.data.service?.find((B)=>B.id==="#atproto_pds"||B.type==="AtprotoPersonalDataServer")?.serviceEndpoint}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 d50({pdsEndpoint:this.config.pdsEndpoint,identifier:this.config.identifier??"",appPassword:A})}resolveAppPassword(){return this.config.appPassword}}function JE$(A){let Q=A.replace(/[^A-Za-z0-9._~:-]/g,"_").slice(0,512);return Q.length>0?Q:"self"}function FE$(A){return/^at:\/\/([^/]+)/.exec(A)?.[1]}function IE$(A){let Q=A.slice(8).split(":").map(decodeURIComponent),[$,...w]=Q;if(!$)throw Error(`Invalid did:web value: ${A}`);if(w.length===0)return`https://${$}/.well-known/did.json`;return`https://${$}/${w.join("/")}/did.json`}function hM0(A,Q){return new a3A(A,Q)}KA();C0();var EM0={name:"@brains/rover",version:"0.2.0-alpha.184",dependencies:{"@brains/a2a":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/atproto-registry":"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/doc":"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/playbooks":"workspace:*","@brains/portfolio":"workspace:*","@brains/products":"workspace:*","@brains/prompt":"workspace:*","@brains/rizom-ecosystem":"workspace:*","@brains/rover-onboarding":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-content":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/topics":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@brains/wishlist":"workspace:*","@rizom/theme-default":"workspace:*"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/typescript-config":"workspace:*","@rizom/site-rizom-ai":"workspace:*","@rizom/theme-rizom-ai":"workspace:*",typescript:"^7.0.2"},files:["src","brain.eval.yaml","env.schema.template"],main:"./src/index.ts",private:!0,scripts:{"build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/cms",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 . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix","start:core":"bun run build:ui && cd test-apps/core && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:default":"bun run build:ui && cd test-apps/default && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:full":"bun run build:ui && cd test-apps/full && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:rizom-ai":"bun run build:ui && cd test-apps/rizom-ai && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var NE$=H.looseObject({});class Ec2 extends p6{constructor(A={}){super("rover-profile",EM0,A,NE$)}async onRegister(A){A.entities.extendFrontmatterSchema("anchor-profile",Iv)}}function Tc2(A={}){return new Ec2(A)}KA();C0();Q5();KA();KA();var n50=hN.extend(Iv.shape);class TM0{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,$){let w=$.entityService,[B,X,Y,Z]=await Promise.all([tm(w,n50),EP0(w,{entityType:"post",count:3,parse:kw0}),EP0(w,{entityType:"deck",count:3,parse:Rw0}),_w0(w)]),W={profile:B,posts:X,decks:Y,postsListUrl:this.postsListUrl,decksListUrl:this.decksListUrl,cta:wGA(Z.cta),sections:Z.sections??{}};return Q.parse(W)}}KA();class yM0{id="professional:about";name="About Page DataSource";description="Fetches full profile data for the about page";async fetch(A,Q,$){let B={profile:await tm($.entityService,n50)};return Q.parse(B)}}import{jsxDEV as Y5,Fragment as kE$}from"preact/jsx-dev-runtime";var _E$="grid md:grid-cols-[14rem_1px_1fr] gap-y-2 gap-x-0 md:gap-16 items-start",PE$="border-t md:border-t-0 md:border-l border-rule-strong md:self-stretch",t3A=({number:A,title:Q,blurb:$,children:w})=>Y5("section",{className:"py-20 border-b border-rule px-6 md:px-12",children:Y5("div",{className:"max-w-6xl mx-auto",children:Y5("div",{className:_E$,children:[Y5(WWA,{title:Q,number:A,blurb:$},void 0,!1,void 0,this),Y5("div",{className:PE$,"aria-hidden":"true"},void 0,!1,void 0,this),Y5("div",{className:"mt-6 md:mt-0",children:w},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),e3A=({profile:A,posts:Q,decks:$,postsListUrl:w,decksListUrl:B,cta:X,sections:Y})=>{let Z=A.tagline?.length?A.tagline:A.description,W=Q.map((q)=>({id:q.id,url:q.url,title:q.metadata.title,date:q.metadata.publishedAt??q.created,description:q.frontmatter.excerpt,series:q.frontmatter.seriesName&&q.frontmatter.seriesIndex?{name:q.frontmatter.seriesName,index:q.frontmatter.seriesIndex}:void 0})),K=$.map((q)=>({id:q.id,url:q.url,title:q.frontmatter.title||q.id,date:q.frontmatter.publishedAt??q.created,description:q.frontmatter.description})),U=A.name||"Home",G=[A.intro,A.description,Z].find((q)=>q)??"Professional site",D=Boolean(A.description)||A.expertise!==void 0&&A.expertise.length>0;return Y5(kE$,{children:[Y5(C6,{title:U,description:G,ogType:"website"},void 0,!1,void 0,this),Y5("div",{className:"homepage-list bg-theme",children:[Y5("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:Y5("div",{className:"relative z-10 max-w-6xl mx-auto w-full",children:[A.name&&Y5("div",{className:"flex items-center gap-[0.6rem] mb-6 font-mono text-[0.7rem] font-medium uppercase tracking-[0.22em] text-accent",children:[Y5("span",{className:"w-[18px] h-px bg-accent","aria-hidden":"true"},void 0,!1,void 0,this),Y5("span",{children:A.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z&&Y5("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:rN0(Z,"italic font-normal text-accent [font-variation-settings:'opsz'_144,'SOFT'_80]")},void 0,!1,void 0,this),A.intro&&Y5("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:rN0(A.intro,"italic text-accent")},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Y5(t3A,{number:"01",title:"Essays",blurb:Y.essays?.blurb,children:Y5(nN0,{items:W,viewAllUrl:w,viewAllLabel:"View all essays"},void 0,!1,void 0,this)},void 0,!1,void 0,this),K.length>0&&Y5(t3A,{number:"02",title:"Presentations",blurb:Y.presentations?.blurb,children:Y5(nN0,{items:K,viewAllUrl:B,viewAllLabel:"View all presentations"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D&&Y5(t3A,{number:"03",title:"About",blurb:Y.about?.blurb,children:Y5("div",{className:"flex flex-col gap-8",children:[A.description&&Y5("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&&Y5(KWA,{subjects:A.expertise},void 0,!1,void 0,this),Y5("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",Y5("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),Y5(rHA,{cta:X,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 Iw,Fragment as jE$}from"preact/jsx-dev-runtime";var AVA=({profile:A})=>{let Q=`About ${A.name||"Me"}`,$=[A.description,A.intro].find((B)=>B)??"About page",w=A.expertise!==void 0&&A.expertise.length>0||Boolean(A.currentFocus)||Boolean(A.availability)||Boolean(A.email)||Boolean(A.website)||A.socialLinks!==void 0&&A.socialLinks.length>0;return Iw(jE$,{children:[Iw(C6,{title:Q,description:$,ogType:"profile"},void 0,!1,void 0,this),Iw("div",{className:"about-page bg-theme",children:[Iw("header",{className:"hero-bg-pattern relative w-full py-16 md:py-24 px-6 md:px-12 bg-theme overflow-hidden",children:Iw("div",{className:"relative z-10 max-w-4xl mx-auto",children:[Iw("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&&Iw("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),Iw("div",{className:"container mx-auto px-6 md:px-12 max-w-4xl py-12 md:py-16",children:[A.story&&Iw("section",{className:"content-section-reveal mb-20 md:mb-28",children:Iw(u4,{markdown:A.story},void 0,!1,void 0,this)},void 0,!1,void 0,this),w&&Iw("div",{className:"content-section-reveal grid md:grid-cols-2 gap-x-16 gap-y-12",children:[A.expertise&&A.expertise.length>0&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Expertise"},void 0,!1,void 0,this),Iw("ul",{className:"flex flex-wrap gap-3",children:A.expertise.map((B,X)=>Iw("li",{className:I80({variant:"accent",size:"lg"}),children:B},X,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A.currentFocus&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Current Focus"},void 0,!1,void 0,this),Iw("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&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Availability"},void 0,!1,void 0,this),Iw("p",{className:"text-lg text-theme leading-relaxed",children:A.availability},void 0,!1,void 0,this)]},void 0,!0,void 0,this),(Boolean(A.email)||Boolean(A.website)||A.socialLinks!==void 0&&A.socialLinks.length>0)&&Iw("section",{children:[Iw("h2",{className:"text-sm tracking-widest uppercase text-theme-muted mb-6",children:"Contact"},void 0,!1,void 0,this),Iw("div",{className:"space-y-4",children:[A.email&&Iw("p",{className:"text-lg",children:Iw("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&&Iw("p",{className:"text-lg",children:Iw("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&&Iw("div",{className:"flex flex-wrap gap-4 mt-4",children:A.socialLinks.map((B,X)=>Iw(m4,{href:B.url,external:!0,variant:"secondary",size:"md",children:B.label?.length?B.label:B.platform},X,!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 cZ,Fragment as yc2}from"preact/jsx-dev-runtime";var QVA=()=>{return cZ(yc2,{children:[cZ(C6,{title:"Thanks for subscribing!",description:"You've successfully subscribed to the newsletter."},void 0,!1,void 0,this),cZ("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:cZ("div",{className:"text-center max-w-md",children:[cZ("div",{className:"text-6xl mb-6",children:"\uD83C\uDF89"},void 0,!1,void 0,this),cZ("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Thanks for subscribing!"},void 0,!1,void 0,this),cZ("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),cZ(m4,{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)},$VA=()=>{return cZ(yc2,{children:[cZ(C6,{title:"Subscription failed",description:"There was a problem with your subscription."},void 0,!1,void 0,this),cZ("div",{className:"min-h-[60vh] flex items-center justify-center px-6",children:cZ("div",{className:"text-center max-w-md",children:[cZ("div",{className:"text-6xl mb-6",children:"\uD83D\uDE22"},void 0,!1,void 0,this),cZ("h1",{className:"text-3xl font-semibold mb-4 text-heading",children:"Something went wrong"},void 0,!1,void 0,this),cZ("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),cZ(m4,{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)};C0();var gc2=H.object({label:H.string().describe("Display label for entity type (e.g., 'Essay')"),pluralName:H.string().optional().describe("URL path segment (defaults to label.toLowerCase() + 's')")}),ME$={post:{label:"Post"},deck:{label:"Deck"}},Sc2=H.object({entityDisplay:H.object({post:gc2,deck:gc2}).default(ME$).describe("Display metadata for post and deck entity types used by the homepage")});var mc2={name:"@brains/site-professional",version:"0.2.0-alpha.184",description:"Professional site composition package",dependencies:{"@brains/blog":"workspace:*","@brains/decks":"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":"^1.3.14","bun-types":"^1.3.14",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},files:["src"],private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",typecheck:"tsc --noEmit"},type:"module"};var OE$=H.object({blurb:H.string().optional().describe("Short italic subtitle under the section title")}),fE$=H.object({heading:H.string(),buttonText:H.string(),buttonLink:H.string()}),uc2=H.looseObject({name:H.string(),kind:H.enum(["professional","team","collective"]),organization:H.string().optional(),description:H.string().optional(),avatar:H.string().optional(),website:H.string().optional(),email:H.string().optional(),socialLinks:H.array(H.object({platform:H.enum(["github","instagram","linkedin","email","website"]),url:H.string(),label:H.string().optional()})).optional(),tagline:H.string().optional(),intro:H.string().optional(),story:H.string().optional(),role:H.string().optional(),audience:H.string().optional(),expertise:H.array(H.string()).optional(),currentFocus:H.string().optional(),availability:H.string().optional(),desiredTone:H.string().optional()}),xE$=H.looseObject({id:H.string(),entityType:H.literal("post"),content:H.string(),created:H.string(),updated:H.string(),contentHash:H.string(),metadata:H.looseObject({title:H.string(),publishedAt:H.string().optional()}),frontmatter:H.looseObject({excerpt:H.string(),seriesName:H.string().optional(),seriesIndex:H.number().optional()}),body:H.string(),url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),seriesUrl:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional(),coverImageSrcset:H.string().optional(),coverImageSizes:H.string().optional()}),RE$=H.looseObject({id:H.string(),entityType:H.literal("deck"),content:H.string(),created:H.string(),updated:H.string(),contentHash:H.string(),metadata:H.looseObject({title:H.string(),publishedAt:H.string().optional()}),frontmatter:H.looseObject({title:H.string(),description:H.string().optional(),publishedAt:H.string().optional()}),body:H.string(),url:H.string().optional(),typeLabel:H.string().optional(),listUrl:H.string().optional(),listLabel:H.string().optional(),coverImageUrl:H.string().optional(),ogImageUrl:H.string().optional(),coverImageWidth:H.number().optional(),coverImageHeight:H.number().optional()});class wVA extends p6{dependencies=["blog","decks"];constructor(A){super("professional-site",mc2,A,Sc2)}async onRegister(A){let Q=this.config.entityDisplay.post,$=this.config.entityDisplay.deck,w=`/${Q.pluralName??Q.label.toLowerCase()+"s"}`,B=`/${$.pluralName??$.label.toLowerCase()+"s"}`,X=new TM0(w,B);A.entities.registerDataSource(X);let Y=new yM0;A.entities.registerDataSource(Y);let Z=H.object({profile:uc2,posts:H.array(xE$),decks:H.array(RE$),postsListUrl:H.string(),decksListUrl:H.string(),cta:fE$,sections:H.record(H.string(),OE$)}),W=H.object({profile:uc2}),K=H.object({});A.templates.register({"homepage-list":K2({name:"homepage-list",description:"Professional homepage with essays and presentations",schema:Z,dataSourceId:"professional:homepage-list",requiredPermission:"public",layout:{component:e3A}}),about:K2({name:"about",description:"About page with full profile information",schema:W,dataSourceId:"professional:about",requiredPermission:"public",layout:{component:AVA}}),"subscribe-thanks":K2({name:"subscribe-thanks",description:"Newsletter subscription success page",schema:K,requiredPermission:"public",layout:{component:QVA}}),"subscribe-error":K2({name:"subscribe-error",description:"Newsletter subscription error page",schema:K,requiredPermission:"public",layout:{component:$VA}})}),this.logger.info("Professional site plugin registered successfully")}async getTools(){return[]}async getResources(){return[]}}function cc2(A){return new wVA(A??{})}var pc2=[{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 gM0}from"preact/jsx-dev-runtime";function lc2({sections:A,siteInfo:Q,slots:$,wordmark:w}){return gM0("div",{className:"flex flex-col min-h-screen bg-theme overflow-x-clip",children:[gM0(tHA,{title:Q.title,navigation:Q.navigation.primary,showThemeToggle:!0,...Q.logo!==void 0?{logo:Q.logo}:{},...w!==void 0?{wordmark:w}:{}},void 0,!1,void 0,this),gM0("main",{className:"flex-grow flex flex-col bg-theme",children:A},void 0,!1,void 0,this),gM0(aHA,{primaryNavigation:Q.navigation.primary,secondaryNavigation:Q.navigation.secondary,copyright:Q.copyright,socialLinks:Q.socialLinks,title:Q.title,tagline:Q.description,children:$?.getSlot("footer-top").map((B)=>B.render())},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var vE$={layouts:{default:lc2},routes:pc2,plugin:cc2,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"}}}},r50=vE$;var dc2=`/*
10970
10970
  * Default theme \u2014 simplified editorial base inspired by the Rizom family.
10971
10971
  *
10972
10972
  * This theme is intentionally less branded than @brains/theme-rizom. It
@@ -12977,7 +12977,7 @@ function drawGlowNode(ctx, x, y, r, color, op, light) {
12977
12977
  `+m.slice(L0+1);else l0+=m.slice(I0);return l0.slice(1)}function l1(m){let J0="",e=0;for(let z0=0;z0<m.length;e>=65536?z0+=2:z0++){e=O0(m,z0);let I0=b[e];if(!I0&&k0(e)){if(J0+=m[z0],e>=65536)J0+=m[z0+1]}else J0+=I0||a(e)}return J0}function j1(m,J0,e){let z0="",I0=m.tag;for(let M0=0,L0=e.length;M0<L0;M0+=1){let o0=e[M0];if(m.replacer)o0=m.replacer.call(e,String(M0),o0);if(v0(m,J0,o0,!1,!1)||typeof o0>"u"&&v0(m,J0,null,!1,!1)){if(z0!=="")z0+=","+(!m.condenseFlow?" ":"");z0+=m.dump}}m.tag=I0,m.dump="["+z0+"]"}function T0(m,J0,e,z0){let I0="",M0=m.tag;for(let L0=0,o0=e.length;L0<o0;L0+=1){let l0=e[L0];if(m.replacer)l0=m.replacer.call(e,String(L0),l0);if(v0(m,J0+1,l0,!0,!0,!1,!0)||typeof l0>"u"&&v0(m,J0+1,null,!0,!0,!1,!0)){if(!z0||I0!=="")I0+=i(m,J0);if(m.dump&&Z===m.dump.charCodeAt(0))I0+="-";else I0+="- ";I0+=m.dump}}m.tag=M0,m.dump=I0||"[]"}function R0(m,J0,e){let z0="",I0=m.tag,M0=Object.keys(e);for(let L0=0,o0=M0.length;L0<o0;L0+=1){let l0="";if(z0!=="")l0+=", ";if(m.condenseFlow)l0+='"';let YA=M0[L0],HA=e[YA];if(m.replacer)HA=m.replacer.call(e,YA,HA);if(!v0(m,J0,YA,!1,!1))continue;if(m.dump.length>1024)l0+="? ";if(l0+=m.dump+(m.condenseFlow?'"':"")+":"+(m.condenseFlow?"":" "),!v0(m,J0,HA,!1,!1))continue;l0+=m.dump,z0+=l0}m.tag=I0,m.dump="{"+z0+"}"}function _(m,J0,e,z0){let I0="",M0=m.tag,L0=Object.keys(e);if(m.sortKeys===!0)L0.sort();else if(typeof m.sortKeys==="function")L0.sort(m.sortKeys);else if(m.sortKeys)throw new Q("sortKeys must be a boolean or a function");for(let o0=0,l0=L0.length;o0<l0;o0+=1){let YA="";if(!z0||I0!=="")YA+=i(m,J0);let HA=L0[o0],gA=e[HA];if(m.replacer)gA=m.replacer.call(e,HA,gA);if(!v0(m,J0+1,HA,!0,!0,!0))continue;let L1=m.tag!==null&&m.tag!=="?"||m.dump&&m.dump.length>1024;if(L1)if(m.dump&&Z===m.dump.charCodeAt(0))YA+="?";else YA+="? ";if(YA+=m.dump,L1)YA+=i(m,J0);if(!v0(m,J0+1,gA,!0,L1))continue;if(m.dump&&Z===m.dump.charCodeAt(0))YA+=":";else YA+=": ";YA+=m.dump,I0+=YA}m.tag=M0,m.dump=I0||"{}"}function K0(m,J0,e){let z0=e?m.explicitTypes:m.implicitTypes;for(let I0=0,M0=z0.length;I0<M0;I0+=1){let L0=z0[I0];if((L0.instanceOf||L0.predicate)&&(!L0.instanceOf||typeof J0==="object"&&J0 instanceof L0.instanceOf)&&(!L0.predicate||L0.predicate(J0))){if(e)if(L0.multi&&L0.representName)m.tag=L0.representName(J0);else m.tag=L0.tag;else m.tag="?";if(L0.represent){let o0=m.styleMap[L0.tag]||L0.defaultStyle,l0;if(w.call(L0.represent)==="[object Function]")l0=L0.represent(J0,o0);else if(B.call(L0.represent,o0))l0=L0.represent[o0](J0,o0);else throw new Q("!<"+L0.tag+'> tag resolver accepts not "'+o0+'" style');m.dump=l0}return!0}}return!1}function v0(m,J0,e,z0,I0,M0,L0){if(m.tag=null,m.dump=e,!K0(m,e,!1))K0(m,e,!0);let o0=w.call(m.dump),l0=z0;if(z0)z0=m.flowLevel<0||m.flowLevel>J0;let YA=o0==="[object Object]"||o0==="[object Array]",HA,gA;if(YA)HA=m.duplicates.indexOf(e),gA=HA!==-1;if(m.tag!==null&&m.tag!=="?"||gA||m.indent!==2&&J0>0)I0=!1;if(gA&&m.usedDuplicates[HA])m.dump="*ref_"+HA;else{if(YA&&gA&&!m.usedDuplicates[HA])m.usedDuplicates[HA]=!0;if(o0==="[object Object]"){if(z0&&Object.keys(m.dump).length!==0){if(_(m,J0,m.dump,I0),gA)m.dump="&ref_"+HA+m.dump}else if(R0(m,J0,m.dump),gA)m.dump="&ref_"+HA+" "+m.dump}else if(o0==="[object Array]"){if(z0&&m.dump.length!==0){if(m.noArrayIndent&&!L0&&J0>0)T0(m,J0-1,m.dump,I0);else T0(m,J0,m.dump,I0);if(gA)m.dump="&ref_"+HA+m.dump}else if(j1(m,J0,m.dump),gA)m.dump="&ref_"+HA+" "+m.dump}else if(o0==="[object String]"){if(m.tag!=="?")s0(m,m.dump,J0,M0,l0)}else if(o0==="[object Undefined]")return!1;else{if(m.skipInvalid)return!1;throw new Q("unacceptable kind of an object to dump "+o0)}if(m.tag!==null&&m.tag!=="?"){let L1=encodeURI(m.tag[0]==="!"?m.tag.slice(1):m.tag).replace(/!/g,"%21");if(m.tag[0]==="!")L1="!"+L1;else if(L1.slice(0,18)==="tag:yaml.org,2002:")L1="!!"+L1.slice(18);else L1="!<"+L1+">";m.dump=L1+" "+m.dump}}return!0}function W0(m,J0){let e=[],z0=[];d(m,e,z0);let I0=z0.length;for(let M0=0;M0<I0;M0+=1)J0.duplicates.push(e[z0[M0]]);J0.usedDuplicates=Array(I0)}function d(m,J0,e){if(m!==null&&typeof m==="object"){let z0=J0.indexOf(m);if(z0!==-1){if(e.indexOf(z0)===-1)e.push(z0)}else if(J0.push(m),Array.isArray(m))for(let I0=0,M0=m.length;I0<M0;I0+=1)d(m[I0],J0,e);else{let I0=Object.keys(m);for(let M0=0,L0=I0.length;M0<L0;M0+=1)d(m[I0[M0]],J0,e)}}}function U0(m,J0){J0=J0||{};let e=new H0(J0);if(!e.noRefs)W0(m,e);let z0=m;if(e.replacer)z0=e.replacer.call({"":z0},"",z0);if(v0(e,0,z0,!0,!0))return e.dump+`
12978
12978
  `;return""}return EVA.dump=U0,EVA}var ql2;function bl$(){if(ql2)return pZ;ql2=1;let A=jl$(),Q=Ml$();function $(w,B){return function(){throw Error("Function yaml."+w+" is removed in js-yaml 4. Use yaml."+B+" instead, which is now safe by default.")}}return pZ.Type=ZW(),pZ.Schema=os2(),pZ.FAILSAFE_SCHEMA=es2(),pZ.JSON_SCHEMA=Ba2(),pZ.CORE_SCHEMA=Xa2(),pZ.DEFAULT_SCHEMA=ZIA(),pZ.load=A.load,pZ.loadAll=A.loadAll,pZ.dump=Q.dump,pZ.YAMLException=hB0(),pZ.types={binary:Ha2(),float:wa2(),map:ts2(),null:Aa2(),pairs:Ka2(),set:Ua2(),timestamp:Ya2(),bool:Qa2(),int:$a2(),merge:Za2(),omap:Wa2(),seq:as2(),str:ss2()},pZ.safeLoad=$("safeLoad","load"),pZ.safeLoadAll=$("safeLoadAll","loadAll"),pZ.safeDump=$("safeDump","dump"),pZ}var D2B=bl$(),q2B=p0.record(p0.string(),p0.unknown()),z2B=p0.object({slug:p0.string(),title:p0.string(),type:p0.string(),entityId:p0.string(),contentHash:p0.string()});function zl2(A){if(!A)return[];return Array.isArray(A)?A:[A]}function Ol$(A,Q){let $=[...zl2(A),...zl2(Q)];return $.length>0?$:void 0}function Vl2(A){if(!A)return[];return Array.isArray(A)?A:[A]}function fl$(A,Q){let $=[...Vl2(A),...Vl2(Q)];return $.length>0?$:void 0}function xl$(A,Q){if(!Q||Q.length===0)return A;let $=[...A],w=new Map;for(let[B,X]of $.entries())w.set(X.id,B);for(let B of Q){let X=w.get(B.id);if(X!==void 0){$[X]=B;continue}w.set(B.id,$.length),$.push(B)}return $}function Rl$(A,Q={}){if(Object.keys(Q).length===0)return A;let{layouts:$,entityDisplay:w,staticAssets:B,themeOverride:X,headScripts:Y}=Q,Z=Object.hasOwn(Q,"plugin")?Q.plugin:A.plugin,W=$?{...A.layouts,...$}:A.layouts,K=w?{...A.entityDisplay,...w}:A.entityDisplay,U=B?{...A.staticAssets??{},...B}:A.staticAssets,G=[A.themeOverride,X].filter(Boolean).join(`
12979
12979
 
12980
- `),D=[...A.headScripts??[],...Y??[]],q=Ol$(A.content,Q.content),J=fl$(A.sections,Q.sections);return{layouts:W,routes:xl$(A.routes,Q.routes),...Z?{plugin:Z}:{},entityDisplay:K,...q?{content:q}:{},...J?{sections:J}:{},...G?{themeOverride:G}:{},...D.length>0?{headScripts:D}:{},...U&&Object.keys(U).length>0?{staticAssets:U}:{}}}var V2B=p0.string(),vl$=p0.looseObject({id:p0.string().min(1)}),Cl$=p0.looseObject({label:p0.string().min(1)}),hl$=p0.looseObject({layouts:p0.record(p0.string(),p0.unknown()),plugin:p0.custom((A)=>typeof A==="function").optional(),routes:p0.array(vl$),entityDisplay:p0.record(p0.string(),Cl$),content:p0.unknown().optional(),themeOverride:p0.string().optional(),headScripts:p0.array(p0.string()).optional(),staticAssets:p0.record(p0.string(),p0.string()).optional()}),J2B=p0.custom((A)=>hl$.safeParse(A).success);class Ga2 extends Ds2{templateGroups;dataSources;constructor(A,Q,$,w=[]){super(A,Q);this.templateGroups=$,this.dataSources=w}async register(A,Q){for(let $ of this.templateGroups)A.registerTemplates($.templates,$.namespace);for(let $ of this.dataSources)A.getDataSourceRegistry().register($);return{tools:[],resources:[]}}}function El$(A){if(!A.runtime?.templates)return[];return[{namespace:A.runtime.contentNamespace,templates:A.runtime.templates}]}function Tl$(A){if(!A.runtime?.templates&&!A.runtime?.dataSources?.length)return;return(Q)=>new Ga2(A.packageName,{...A.themeProfile?{themeProfile:A.themeProfile}:{},...Q??{}},El$(A),A.runtime?.dataSources)}function Da2(A){let Q=Tl$(A);return Rl$(tFA,{layouts:{default:A.layout},routes:A.routes,...A.entityDisplay?{entityDisplay:A.entityDisplay}:{},...A.content?{content:A.content}:{},...A.sections?{sections:A.sections}:{},headScripts:[aFA(A.themeProfile)],...Q?{plugin:Q}:{},...A.themeOverride?{themeOverride:A.themeOverride}:{}})}var qa2=`/*
12980
+ `),D=Y??A.headScripts??[],q=Ol$(A.content,Q.content),J=fl$(A.sections,Q.sections);return{layouts:W,routes:xl$(A.routes,Q.routes),...Z?{plugin:Z}:{},entityDisplay:K,...q?{content:q}:{},...J?{sections:J}:{},...G?{themeOverride:G}:{},...D.length>0?{headScripts:D}:{},...U&&Object.keys(U).length>0?{staticAssets:U}:{}}}var V2B=p0.string(),vl$=p0.looseObject({id:p0.string().min(1)}),Cl$=p0.looseObject({label:p0.string().min(1)}),hl$=p0.looseObject({layouts:p0.record(p0.string(),p0.unknown()),plugin:p0.custom((A)=>typeof A==="function").optional(),routes:p0.array(vl$),entityDisplay:p0.record(p0.string(),Cl$),content:p0.unknown().optional(),themeOverride:p0.string().optional(),headScripts:p0.array(p0.string()).optional(),staticAssets:p0.record(p0.string(),p0.string()).optional()}),J2B=p0.custom((A)=>hl$.safeParse(A).success);class Ga2 extends Ds2{templateGroups;dataSources;constructor(A,Q,$,w=[]){super(A,Q);this.templateGroups=$,this.dataSources=w}async register(A,Q){for(let $ of this.templateGroups)A.registerTemplates($.templates,$.namespace);for(let $ of this.dataSources)A.getDataSourceRegistry().register($);return{tools:[],resources:[]}}}function El$(A){if(!A.runtime?.templates)return[];return[{namespace:A.runtime.contentNamespace,templates:A.runtime.templates}]}function Tl$(A){if(!A.runtime?.templates&&!A.runtime?.dataSources?.length)return;return(Q)=>new Ga2(A.packageName,{...A.themeProfile?{themeProfile:A.themeProfile}:{},...Q??{}},El$(A),A.runtime?.dataSources)}function Da2(A){let Q=Tl$(A);return Rl$(tFA,{layouts:{default:A.layout},routes:A.routes,...A.entityDisplay?{entityDisplay:A.entityDisplay}:{},...A.content?{content:A.content}:{},...A.sections?{sections:A.sections}:{},headScripts:[aFA(A.themeProfile)],...Q?{plugin:Q}:{},...A.themeOverride?{themeOverride:A.themeOverride}:{}})}var qa2=`/*
12981
12981
  * Rizom brand theme \u2014 amber + purple bioluminescent palette.
12982
12982
  *
12983
12983
  * Shared by the Rizom site family. The site runtime sets
@@ -13981,7 +13981,7 @@ facts, owners, or tasks. Return only the required structured JSON.`});C0();var Z
13981
13981
  `);return this.truncateContent(w||Q||Qr(A))}truncateContent(A){if(A.length<=ra2)return A;let Q=A.slice(0,ra2-1),$=Q.search(/\s\S*$/);return`${($>0?Q.slice(0,$):Q).trimEnd()}\u2026`}isSummaryEntity(A){return A.entityType===j9}isDecisionEntity(A){return A.entityType===RG}getEntitySpaceId(A){let Q=A.metadata;if("spaceId"in Q&&typeof Q.spaceId==="string")return Q.spaceId;return YV(Q)}}var Ed$=5,Td$=3;function VIA(A){A.messaging.subscribe(Lx,async(Q)=>{let $=ws.parse(Q.payload);return{success:!0,data:await BO0(A,$)}})}async function BO0(A,Q){let $=c5(Q.userPermissionLevel);if(!Q.channelId)return oa2(A,Q,{visibilityScope:$,reason:"no-channel-context",items:[]}),{items:[]};let w=new $r(A),B=await w.retrieve({query:Q.message,conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,limit:Ed$,visibilityScope:$}),X=B.results.length===0?await w.retrieve({conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,limit:Td$,visibilityScope:$}):void 0,Y=B.results.length>0,Z=Y?B.results:X?.results??[];return oa2(A,Q,{visibilityScope:$,spaceId:B.spaceId??X?.spaceId,reason:Z.length>0?"memory-injected":"no-same-space-memory",items:Z.map((W)=>yd$(W,Y))}),{items:Z.map(gd$)}}function oa2(A,Q,$){A.logger.info("Conversation memory agent context audit",{conversationId:Q.conversationId,interfaceType:Q.interfaceType,channelId:Q.channelId,channelName:Q.channelName,userPermissionLevel:Q.userPermissionLevel,visibilityScope:$.visibilityScope,spaceId:$.spaceId,reason:$.reason,itemCount:$.items.length,items:$.items})}function yd$(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 gd$(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();bH();var ta2=H.union([H.enum(["public","shared","restricted"]),H.literal("private")]).optional().transform((A)=>{if(A===void 0)return"public";if(A==="private")return"restricted";return A}),ea2=H.enum(["user","assistant"]),Sd$=H.object({actorId:H.string(),canonicalId:H.string().optional(),interfaceType:H.string(),role:ea2,displayName:H.string().optional(),username:H.string().optional(),isBot:H.boolean().optional()}),md$=H.object({messageId:H.string().optional(),channelId:H.string().optional(),channelName:H.string().optional(),threadId:H.string().optional(),metadata:H.record(H.string(),H.unknown()).optional()}),FIA=H.object({role:ea2,content:H.string(),timestamp:H.string().datetime().optional(),actor:Sd$.optional(),source:md$.optional()}),ud$=H.object({conversationId:H.string().default("eval-conversation"),messages:H.array(FIA)}),cd$=H.object({conversationId:H.string()}),pd$=H.object({conversationId:H.string().default("eval-conversation"),interfaceType:H.string().default("eval"),channelId:H.string().default("eval-channel"),channelName:H.string().optional(),projectionDecision:H.enum(["update","append"]).default("update"),existingSummary:H.string().optional(),existingMessageCount:H.number().int().min(0).default(0),messages:H.array(FIA)}),XO0=H.object({actorId:H.string(),canonicalId:H.string().optional(),displayName:H.string().optional()}),ld$=XO0.extend({roles:H.array(H.enum(["user","assistant","system"])).default(["user"]),sourceActorIds:H.array(H.string()).optional()}),dd$=H.object({actorId:H.string().optional(),canonicalId:H.string().optional(),displayName:H.string()}),At2=H.object({id:H.string(),entityType:H.enum(["summary","decision","action-item"]),content:H.string(),excerpt:H.string().optional(),score:H.number().optional(),conversationId:H.string(),interfaceType:H.string(),channelId:H.string(),channelName:H.string().optional(),updated:H.string().datetime().optional(),visibility:ta2,status:H.string().optional(),participants:H.array(ld$).optional(),decidedBy:H.array(XO0).optional(),mentionedBy:H.array(XO0).optional(),assignedTo:H.array(dd$).optional(),requestedBy:H.array(XO0).optional()}),id$=H.object({query:H.string().optional(),conversationId:H.string().optional(),interfaceType:H.string().optional(),channelId:H.string().optional(),limit:H.number().int().min(1).optional(),includeOtherSpaces:H.boolean().optional(),actorId:H.string().optional(),canonicalId:H.string().optional(),visibilityScope:ta2.optional(),memory:H.array(At2).optional()}),nd$=H.object({conversationId:H.string().default("eval-conversation"),message:H.string(),interfaceType:H.string().default("eval"),channelId:H.string().optional(),channelName:H.string().optional(),userPermissionLevel:H.enum(["anchor","trusted","public"]).default("trusted"),memory:H.array(At2).optional()}),rd$=H.object({conversationId:H.string().default("eval-conversation"),existingSummary:H.string().optional(),existingMessageCount:H.number().int().min(0).default(0),messages:H.array(FIA)});function Qt2(A){let{context:Q,logger:$,config:w}=A;Q.eval.registerHandler("summarizeMessages",async(B)=>{let X=ud$.parse(B),Y=JIA(X.messages,X.conversationId),W=await new tn(Q,$,w).extract(Y);return W.entries.map((K)=>{let U=W.decisions.filter((D)=>D.timeRange.start>=K.timeRange.start).filter((D)=>D.timeRange.end<=K.timeRange.end).map((D)=>D.text),G=W.actionItems.filter((D)=>D.timeRange.start>=K.timeRange.start).filter((D)=>D.timeRange.end<=K.timeRange.end).map((D)=>D.text);return{...K,decisions:U,actionItems:G,keyPointsText:K.keyPoints.join(`
13982
13982
  `),decisionsText:U.join(`
13983
13983
  `),actionItemsText:G.join(`
13984
- `)}})}),Q.eval.registerHandler("decideProjection",async(B)=>{let X=rd$.parse(B),Y=JIA(X.messages,X.conversationId),Z=X.existingSummary?sa2({conversationId:X.conversationId,content:X.existingSummary,messageCount:X.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null;return new zf(Q,$,w).decideProjection(Y,Z)}),Q.eval.registerHandler("retrieveMemory",async(B)=>{let X=id$.parse(B),Y=X.memory?aa2(Q,X.memory):Q;return new $r(Y).retrieve(X)}),Q.eval.registerHandler("buildAgentContext",async(B)=>{let X=nd$.parse(B),Y=X.memory?aa2(Q,X.memory):Q;return BO0(Y,X)}),Q.eval.registerHandler("projectMessages",async(B)=>{let X=pd$.parse(B),Y=JIA(X.messages,X.conversationId),Z=od$({conversationId:X.conversationId,interfaceType:X.interfaceType,channelId:X.channelId,channelName:X.channelName,messages:Y}),W=X.existingSummary?sa2({conversationId:X.conversationId,content:X.existingSummary,messageCount:X.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null,K=[],U=[],G=sd$({context:Q,conversation:Z,messages:Y,existing:W,upserted:K,deleted:U,projectionDecision:X.projectionDecision});return{result:await new zf(G,$,w).projectConversation(X.conversationId),summaries:K.filter((J)=>J.entityType==="summary"),decisions:K.filter((J)=>J.entityType==="decision"),actionItems:K.filter((J)=>J.entityType==="action-item"),deleted:U}}),Q.eval.registerHandler("projectConversation",async(B)=>{let X=cd$.parse(B);return new zf(Q,$,w).projectConversation(X.conversationId)})}function sa2(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 JIA(A,Q){return A.map(($,w)=>{let B=$.timestamp??new Date(Date.UTC(2026,0,1,0,w)).toISOString();return{id:`eval-message-${w+1}`,conversationId:Q,role:$.role,content:$.content,timestamp:B,metadata:{...$.actor?{actor:$.actor}:{},...$.source?{source:$.source}:{}}}})}function od$(A){let Q=A.messages[0],$=A.messages[A.messages.length-1],w=Q?.timestamp??"2026-01-01T00:00:00.000Z",B=$?.timestamp??w;return{id:A.conversationId,sessionId:A.conversationId,interfaceType:A.interfaceType,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},startedAt:w,lastActiveAt:B,createdAt:w,updatedAt:B,metadata:{}}}function sd$(A){let Q=YV(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:$})=>$==="summary"?A.existing:null,listEntities:async()=>[],deleteEntity:async($)=>{return A.deleted.push($),!0},upsertEntity:async({entity:$})=>{return A.upserted.push($),{entityId:$.id,jobId:"eval-upsert",created:!0,skipped:!1}}}}}function aa2(A,Q){let $=Q.map(ad$),w=$.map((B,X)=>({entity:B,score:Q[X]?.score??1,excerpt:Q[X]?.excerpt??Qr(B)}));return{...A,entityService:{...A.entityService,search:async()=>w,listEntities:async({entityType:B})=>$.filter((X)=>X.entityType===B)}}}function ad$(A){if(A.entityType==="summary")return td$(A);if(A.entityType==="decision")return ed$(A);return Ai$(A)}function IIA(A){let Q=A.updated??"2026-01-01T00:00:00.000Z";return{id:A.id,content:A.content,contentHash:e6(A.content),visibility:A.visibility,created:Q,updated:Q}}function td$(A){return{...IIA(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 ed$(A){return{...IIA(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:YV(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 Ai$(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...IIA(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:YV(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 $t2={name:"@brains/conversation-memory",version:"0.2.0-alpha.183",description:"Plugin for deriving durable conversation memory",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.19.43",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},main:"./src/index.ts",private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var $i$=new pq,wi$=new on,Bi$=new sn,Xi$=H.object({conversationId:H.string()});class LIA extends S6{entityType=j9;schema=TB0;adapter=$i$;constructor(A={}){super(nb0,$t2,A,GIA)}getConfig(){return this.config}getTemplates(){return{"summary-list":Ma2,"summary-detail":ba2,"ai-response":Oa2}}getDataSources(){return[new zIA(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:j9,job:{type:Va2,handler:new eb0(A,this.logger,this.config)},initialSync:{shouldEnqueue:async()=>A.spaces.length>0&&!await Uv(A,j9,{outputVisibility:this.config.memoryVisibility}),jobData:{mode:"rebuild-all",reason:"initial-sync"},jobOptions:{source:HIA,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:nb0}}},sourceChange:{sourceKind:Ie,sourceTypes:[Ie],shouldEnqueue:(Q)=>this.shouldEnqueueConversationProjection(A,Q),events:[Im],jobData:(Q)=>{let{conversationId:$}=this.parseConversationMessagePayload(Q);return{mode:"conversation",conversationId:$,reason:"message-added"}},jobOptions:(Q)=>{let{conversationId:$}=this.parseConversationMessagePayload(Q);return{priority:5,delayMs:this.config.projectionDelayMs,source:HIA,deduplication:"skip",deduplicationKey:`conversation-memory:${$}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${$}`,pluginId:nb0}}}}}]}parseConversationMessagePayload(A){return Xi$.parse(A)}async shouldEnqueueConversationProjection(A,Q){let{conversationId:$}=this.parseConversationMessagePayload(Q),w=await A.conversations.get($);if(!w)return!1;return vT({conversation:w,spaces:A.spaces}).eligible}async onRegister(A){A.entities.register(RG,yB0,wi$),A.entities.register(cq,gB0,Bi$),Ra2({context:A,pluginId:this.id}),Ca2({context:A,pluginId:this.id}),pa2({context:A,pluginId:this.id}),ia2({context:A,pluginId:this.id,config:this.config}),VIA(A),Qt2({context:A,logger:this.logger,config:this.config})}}function NIA(A={}){return new LIA(A)}KA();C0();C0();y9();var wt2=H.object({label:H.string(),href:H.string()}),Bt2=H.object({label:H.string(),title:H.string(),detail:H.string()}),Yi$=H.object({eyebrow:H.string(),name:H.string(),sub:H.string()}),Zi$=H.object({tone:H.enum(["capture","synthesis","share"]),title:H.string(),text:H.string()}),_IA=H.object({captures:H.number(),links:H.number(),topics:H.number(),summaries:H.number(),peers:H.number()}),wr=H.object({eyebrow:H.string(),headline:H.string(),intro:H.string(),primaryCta:wt2,secondaryCta:wt2,inputs:H.array(Bt2).min(1),outputs:H.array(Bt2).min(1),core:Yi$,legend:H.array(Zi$).min(1)}),PIA=wr.extend({counts:_IA}),Xt2={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."}]},Yt2=new d$(wr,{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 YO0(A){return Yt2.parse(A)}function Zt2(A){return Yt2.format(A)}C0();var Hi$=H.looseObject({query:H.object({routeId:H.string().default("home"),sectionId:H.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}),Wi$={captures:"note",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class kIA{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,$){let w=Hi$.parse(A??{}),B=await this.fetchContent($,w.query.routeId,w.query.sectionId),X=await this.fetchCounts($);return Q.parse({...B,counts:X})}async fetchContent(A,Q,$){let w=await A.entityService.getEntity({entityType:"site-content",id:`${Q}:${$}`});if(!w?.content)return Xt2;return wr.parse(YO0(w.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(Wi$).map(async([$,w])=>[$,await this.countOrZero(A,w)]));return _IA.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 x1}from"preact/jsx-dev-runtime";var Ht2=H.object({label:H.string(),href:H.string()}),Ki$=H.object({label:H.string(),value:H.string(),note:H.string()}),Ui$=H.object({eyebrow:H.string(),headline:H.string(),intro:H.string(),primaryCta:Ht2,secondaryCta:Ht2,signals:H.array(Ki$)}),Gi$=H.object({phase:H.string(),title:H.string(),text:H.string()}),Di$=H.object({eyebrow:H.string(),title:H.string(),intro:H.string(),steps:H.array(Gi$)}),qi$=H.object({label:H.string(),title:H.string(),text:H.string()}),zi$=H.object({title:H.string(),intro:H.string(),cards:H.array(qi$)}),Vi$=H.object({title:H.string(),intro:H.string(),points:H.array(H.string())}),Ji$={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."]},Fi$="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function Wt2({href:A,label:Q}){return x1("a",{href:A,className:Fi$,children:Q},void 0,!1,void 0,this)}function Ii$({siteInfo:A,children:Q}){let $=[...A.navigation.primary,...A.navigation.secondary],w=A.cta??{buttonText:"Start here",buttonLink:"/about"};return x1(aVA,{children:[x1("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:[x1("a",{href:"/",className:"font-nav text-[20px]","aria-label":"Relay home",children:[x1("span",{className:"font-bold text-theme",children:"relay"},void 0,!1,void 0,this),x1("span",{className:"font-bold text-accent",children:"."},void 0,!1,void 0,this),x1("span",{className:"text-theme-muted",children:"brain"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"flex items-center gap-5 md:gap-8",children:[x1("div",{className:"hidden items-center gap-6 md:flex",children:$.map((B)=>x1(Wt2,{...B},`${B.href}-${B.label}`,!1,void 0,this))},void 0,!1,void 0,this),x1("a",{href:w.buttonLink,className:"rounded-[999px] border border-theme px-4 py-2 font-body text-[13px] font-semibold text-theme transition-colors hover:border-accent hover:text-accent md:px-5",children:w.buttonText},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("main",{children:Q},void 0,!1,void 0,this),x1("footer",{className:"relative z-[1] border-t border-theme-light px-6 py-8 md:px-10 xl:px-20",children:x1("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[x1("div",{children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.22em] text-theme-light",children:A.copyright},void 0,!1,void 0,this),x1("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),x1("div",{className:"flex flex-wrap items-center gap-5",children:[$.map((B)=>x1(Wt2,{...B},`footer-${B.href}-${B.label}`,!1,void 0,this)),x1("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 Li$=({sections:A,siteInfo:Q})=>x1(Ii$,{siteInfo:Q,children:A},void 0,!1,void 0,this);function Ni$({eyebrow:A,headline:Q,intro:$,primaryCta:w,secondaryCta:B,signals:X}){return x1(pn,{className:"min-h-[92vh] pt-[152px] pb-20 md:pt-[190px]",children:x1("div",{className:"grid gap-10 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-end",children:[x1("div",{children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),x1("h1",{className:"mt-7 max-w-[980px] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),x1("p",{className:"mt-7 max-w-[720px] font-body text-body-lg text-theme-muted",children:$},void 0,!1,void 0,this),x1("div",{className:"mt-10 flex flex-col gap-3 sm:flex-row",children:[x1(YB0,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),x1(YB0,{href:B.href,size:"lg",variant:"secondary",children:B.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("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:[x1("p",{className:"font-label text-label-xs uppercase tracking-[0.24em] text-theme-light",children:"Live relay signals"},void 0,!1,void 0,this),x1("div",{className:"mt-5 grid gap-3",children:X.map((Y)=>x1("div",{className:"rounded-[22px] border border-card-divider bg-bg-muted p-5",children:[x1("div",{className:"flex items-center justify-between gap-4",children:[x1("p",{className:"font-label text-label-xs uppercase tracking-[0.18em] text-secondary",children:Y.label},void 0,!1,void 0,this),x1("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),x1("p",{className:"mt-4 font-display text-display-sm text-theme",children:Y.value},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-body text-body-xs text-theme-muted",children:Y.note},void 0,!1,void 0,this)]},Y.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 _i$({eyebrow:A,title:Q,intro:$,steps:w}){return x1(pn,{id:"operating-loop",className:"py-section",children:[x1("div",{className:"max-w-[840px]",children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-secondary",children:A},void 0,!1,void 0,this),x1("h2",{className:"mt-5 font-display text-display-md text-theme",children:Q},void 0,!1,void 0,this),x1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:w.map((B)=>x1("article",{className:"min-h-[300px] rounded-[28px] border border-card-panel-border bg-card-panel-bg p-6",children:[x1("p",{className:"font-label text-label-sm text-accent",children:B.phase},void 0,!1,void 0,this),x1("h3",{className:"mt-16 font-display text-display-sm text-theme",children:B.title},void 0,!1,void 0,this),x1("p",{className:"mt-4 font-body text-body-sm text-theme-muted",children:B.text},void 0,!1,void 0,this)]},B.phase,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Pi$({title:A,intro:Q,cards:$}){return x1(pn,{className:"py-section",children:x1("div",{className:"rounded-[36px] border border-theme-light bg-bg-muted p-6 md:p-10",children:x1("div",{className:"grid gap-8 lg:grid-cols-[360px_1fr]",children:[x1("div",{children:[x1("h2",{className:"font-display text-display-md text-theme",children:A},void 0,!1,void 0,this),x1("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),x1("div",{className:"grid gap-4",children:$.map((w)=>x1("article",{className:"rounded-[24px] border border-card-divider bg-bg-subtle/70 p-5",children:[x1("p",{className:"font-label text-label-xs uppercase tracking-[0.22em] text-accent",children:w.label},void 0,!1,void 0,this),x1("h3",{className:"mt-3 font-nav text-heading-lg text-theme",children:w.title},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-body text-body-sm text-theme-muted",children:w.text},void 0,!1,void 0,this)]},w.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ki$({title:A,intro:Q,points:$}){return x1(pn,{className:"min-h-[78vh] pt-[150px] pb-section md:pt-[190px]",children:[x1("div",{className:"max-w-[920px]",children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:"Relay model"},void 0,!1,void 0,this),x1("h1",{className:"mt-6 font-display text-display-lg text-theme",children:A},void 0,!1,void 0,this),x1("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),x1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:$.map((w)=>x1("div",{className:"rounded-[24px] border border-card-panel-current-border bg-card-panel-current-bg p-6 font-body text-body-md text-theme",children:w},w,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ji$=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},Mi$=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),uB0=(A,Q,$=`${Q}s`)=>`${Mi$(A)} ${A===1?Q:$}`;function bi$({eyebrow:A,headline:Q,intro:$,primaryCta:w,secondaryCta:B,inputs:X,outputs:Y,core:Z,legend:W,counts:K}){let U=[{key:"captures",className:"top-[-10px] left-1/2 -translate-x-1/2",label:uB0(K.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:uB0(K.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:uB0(K.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:uB0(K.summaries,"summary","summaries")}];return x1(pn,{className:"pt-[150px] pb-section md:pt-[190px]",id:"diagram",children:[x1("div",{className:"mx-auto max-w-[1040px] text-center",children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),x1("h1",{className:"mx-auto mt-7 max-w-[22ch] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),x1("p",{className:"mx-auto mt-7 max-w-[64ch] font-body text-body-lg text-theme-muted",children:$},void 0,!1,void 0,this),x1("div",{className:"mt-10 flex flex-col justify-center gap-3 sm:flex-row",children:[x1(YB0,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),x1(YB0,{href:B.href,size:"lg",variant:"secondary",children:B.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("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:[x1("div",{className:"grid items-center gap-8 lg:grid-cols-[1fr_1.4fr_1fr]",children:[x1("div",{className:"flex flex-col gap-3.5",children:X.map((G)=>x1("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:[x1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:G.label},void 0,!1,void 0,this),x1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:G.title},void 0,!1,void 0,this),x1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:G.detail},void 0,!1,void 0,this)]},`${G.label}-${G.title}`,!0,void 0,this))},void 0,!1,void 0,this),x1("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:[x1("div",{className:"absolute inset-0 rounded-full border border-dashed border-accent/30"},void 0,!1,void 0,this),x1("div",{className:"absolute inset-6 animate-spin rounded-full border border-dashed border-secondary/40 [animation-duration:28s]"},void 0,!1,void 0,this),U.map((G)=>x1("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 ${G.className}`,children:G.label},G.key,!1,void 0,this)),x1("div",{className:"relative z-[1] px-6 text-center",children:[x1("p",{className:"font-label text-[10px] uppercase tracking-[0.28em] text-accent",children:Z.eyebrow},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-display text-[36px] leading-none text-theme",children:Z.name},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-body text-[13px] text-theme-muted",children:Z.sub},void 0,!1,void 0,this),x1("p",{className:"mt-4 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light",children:[uB0(K.links,"link")," indexed"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"flex flex-col gap-3.5",children:Y.map((G)=>x1("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:[x1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:G.label},void 0,!1,void 0,this),x1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:G.title},void 0,!1,void 0,this),x1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:G.detail},void 0,!1,void 0,this)]},`${G.label}-${G.title}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"mt-14 grid gap-4 border-t border-theme-light pt-8 md:grid-cols-3",children:W.map((G)=>x1("div",{className:"text-left",children:[x1("h2",{className:"font-display text-[16px] font-medium text-theme",children:[x1("span",{className:`mr-2.5 inline-block h-3 w-3 rounded-[3px] align-middle ${ji$(G.tone)}`},void 0,!1,void 0,this),G.title]},void 0,!0,void 0,this),x1("p",{className:"mt-1.5 font-body text-[13px] leading-[1.6] text-theme-muted",children:G.text},void 0,!1,void 0,this)]},G.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Oi$=K2({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:PIA,formatter:{parse:(A)=>PIA.parse({...YO0(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>Zt2(wr.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:bi$}}),fi$=(A)=>Ni$(Ui$.parse(A)),xi$=(A)=>_i$(Di$.parse(A)),Ri$=(A)=>Pi$(zi$.parse(A)),vi$=(A)=>ki$(Vi$.parse(A)),Kt2={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},Ut2={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:fi$,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...Kt2,label:"Primary CTA"},secondaryCta:{...Kt2,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:xi$,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:Ri$,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:vi$,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},Ci$=[{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:Ji$}]}],Gt2=Da2({packageName:"@brains/relay/site",themeProfile:"studio",layout:Li$,routes:Ci$,runtime:{contentNamespace:"relay-site",templates:{"home-diagram":Oi$},dataSources:[new kIA]}});var Dt2={name:"@brains/relay",version:"0.2.0-alpha.183",description:"Relay brain model \u2014 collaborative knowledge management",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/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@rizom/site-rizom":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},files:["src","brain.eval.yaml","env.schema.template"],private:!0,scripts:{"build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/cms",eval:"brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix","start:core":"bun run build:ui && cd test-apps/core && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:default":"bun run build:ui && cd test-apps/default && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:docs":"bun run build:ui && cd test-apps/docs && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:full":"bun run build:ui && cd test-apps/full && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var qt2=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","web-chat","discord","a2a"],zt2=[...qt2,"image","site-info","site-content","site-builder"],Ti$=[...zt2,"docs","decks"],yi$=["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."],gi$=vM({name:"relay",version:Dt2.version,model:"gpt-5.6-luna",reasoningEffort:"low",site:Gt2,theme:nn,presets:{core:qt2,default:zt2,full:Ti$},evalDisable:["webserver","web-chat","mcp","discord"],agentInstructions:yi$,capabilities:[["prompt",JT,void 0],["note",QT,{}],["link",wT,{}],["image",M10,void 0],["topics",Uj0,{includeEntityTypes:["note","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",NIA,{memoryVisibility:"shared"}],["docs",Ew0,void 0],["decks",vw0,void 0],["agents",LM0,void 0],["assessment",xM0,void 0],["auth-service",VQ0,void 0],["notifications",Tj0,void 0],["email-resend",rL0,void 0],["cms",KT,{}],["dashboard",$f,void 0],["directory-sync",wE,{seedContent:!0,seedContentPath:Ei$(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",uE,{definitions:Ut2}],["rizom-ecosystem",FT,void 0],["site-info",cE,void 0],["site-builder",mE,{}]],interfaces:[["mcp",Jb,()=>({})],["discord",$O,()=>({captureUrls:!0})],["a2a",Fd,()=>({})],["webserver",HO,()=>({})],["web-chat",Jd,()=>({})]],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"}}}),Vt2=gi$;import{readFileSync as Is$}from"fs";import{join as Ls$}from"path";import{execSync as Ns$}from"child_process";import{parseArgs as ui$}from"util";var ci$={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 ZV(A,Q){let $=A[Q];return typeof $==="string"?$:void 0}function Vf(A,Q){let $=A[Q];return typeof $==="boolean"?$:void 0}function Jt2(A){let{values:Q,positionals:$}=ui$({args:A,options:ci$,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:$[0]??"help",args:$.slice(1),flags:{model:ZV(Q,"model"),domain:ZV(Q,"domain"),"content-repo":ZV(Q,"content-repo"),backend:ZV(Q,"backend"),"push-to":ZV(Q,"push-to"),"ai-api-key":ZV(Q,"ai-api-key"),"no-interactive":Vf(Q,"no-interactive"),preview:Vf(Q,"preview"),deploy:Vf(Q,"deploy"),regen:Vf(Q,"regen"),all:Vf(Q,"all"),only:ZV(Q,"only"),"dry-run":Vf(Q,"dry-run"),"startup-check":Vf(Q,"startup-check"),"storage-dir":ZV(Q,"storage-dir"),yes:Vf(Q,"yes"),remote:ZV(Q,"remote"),token:ZV(Q,"token"),outputDir:ZV(Q,"outputDir")}}}cB0();import{mkdirSync as Ws$}from"fs";import{join as Ks$}from"path";import{execSync as Us$}from"child_process";var HO0={name:"@rizom/brain",version:"0.2.0-alpha.183",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/sdk":"^1.29.0","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20",postcss:"^8.5.15",preact:"^10.27.2","preact-render-to-string":"^6.7.0",tailwindcss:"^4.3.1",zod:"^4.1.8"},devDependencies:{"@brains/app":"workspace:*","@brains/build-tools":"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-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@rizom/theme-default":"workspace:*","@types/bun":"^1.3.14",rolldown:"^1.0.0","rolldown-plugin-dts":"^0.27.4",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},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"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","playwright-core":"^1.61.0","react-devtools-core":"^7.0.1",sharp:"^0.35.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","dev:start":"bun scripts/build.ts && bun dist/brain.js start",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};import{mkdirSync as vt2,writeFileSync as lB0,chmodSync as dB0,existsSync as hIA,readFileSync as EIA}from"fs";import{basename as TIA,dirname as yIA,join as xB,resolve as _n$}from"path";import{fileURLToPath as Pn$}from"url";var Ft2=`ARG BUN_VERSION=1.3.10
13984
+ `)}})}),Q.eval.registerHandler("decideProjection",async(B)=>{let X=rd$.parse(B),Y=JIA(X.messages,X.conversationId),Z=X.existingSummary?sa2({conversationId:X.conversationId,content:X.existingSummary,messageCount:X.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null;return new zf(Q,$,w).decideProjection(Y,Z)}),Q.eval.registerHandler("retrieveMemory",async(B)=>{let X=id$.parse(B),Y=X.memory?aa2(Q,X.memory):Q;return new $r(Y).retrieve(X)}),Q.eval.registerHandler("buildAgentContext",async(B)=>{let X=nd$.parse(B),Y=X.memory?aa2(Q,X.memory):Q;return BO0(Y,X)}),Q.eval.registerHandler("projectMessages",async(B)=>{let X=pd$.parse(B),Y=JIA(X.messages,X.conversationId),Z=od$({conversationId:X.conversationId,interfaceType:X.interfaceType,channelId:X.channelId,channelName:X.channelName,messages:Y}),W=X.existingSummary?sa2({conversationId:X.conversationId,content:X.existingSummary,messageCount:X.existingMessageCount,projectionVersion:w.projectionVersion,visibility:w.memoryVisibility}):null,K=[],U=[],G=sd$({context:Q,conversation:Z,messages:Y,existing:W,upserted:K,deleted:U,projectionDecision:X.projectionDecision});return{result:await new zf(G,$,w).projectConversation(X.conversationId),summaries:K.filter((J)=>J.entityType==="summary"),decisions:K.filter((J)=>J.entityType==="decision"),actionItems:K.filter((J)=>J.entityType==="action-item"),deleted:U}}),Q.eval.registerHandler("projectConversation",async(B)=>{let X=cd$.parse(B);return new zf(Q,$,w).projectConversation(X.conversationId)})}function sa2(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 JIA(A,Q){return A.map(($,w)=>{let B=$.timestamp??new Date(Date.UTC(2026,0,1,0,w)).toISOString();return{id:`eval-message-${w+1}`,conversationId:Q,role:$.role,content:$.content,timestamp:B,metadata:{...$.actor?{actor:$.actor}:{},...$.source?{source:$.source}:{}}}})}function od$(A){let Q=A.messages[0],$=A.messages[A.messages.length-1],w=Q?.timestamp??"2026-01-01T00:00:00.000Z",B=$?.timestamp??w;return{id:A.conversationId,sessionId:A.conversationId,interfaceType:A.interfaceType,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},startedAt:w,lastActiveAt:B,createdAt:w,updatedAt:B,metadata:{}}}function sd$(A){let Q=YV(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:$})=>$==="summary"?A.existing:null,listEntities:async()=>[],deleteEntity:async($)=>{return A.deleted.push($),!0},upsertEntity:async({entity:$})=>{return A.upserted.push($),{entityId:$.id,jobId:"eval-upsert",created:!0,skipped:!1}}}}}function aa2(A,Q){let $=Q.map(ad$),w=$.map((B,X)=>({entity:B,score:Q[X]?.score??1,excerpt:Q[X]?.excerpt??Qr(B)}));return{...A,entityService:{...A.entityService,search:async()=>w,listEntities:async({entityType:B})=>$.filter((X)=>X.entityType===B)}}}function ad$(A){if(A.entityType==="summary")return td$(A);if(A.entityType==="decision")return ed$(A);return Ai$(A)}function IIA(A){let Q=A.updated??"2026-01-01T00:00:00.000Z";return{id:A.id,content:A.content,contentHash:e6(A.content),visibility:A.visibility,created:Q,updated:Q}}function td$(A){return{...IIA(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 ed$(A){return{...IIA(A),entityType:"decision",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:YV(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 Ai$(A){let Q=A.status==="done"||A.status==="dropped"?A.status:"open";return{...IIA(A),entityType:"action-item",metadata:{conversationId:A.conversationId,channelId:A.channelId,...A.channelName?{channelName:A.channelName}:{},interfaceType:A.interfaceType,spaceId:YV(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 $t2={name:"@brains/conversation-memory",version:"0.2.0-alpha.184",description:"Plugin for deriving durable conversation memory",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.19.43",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts"},main:"./src/index.ts",private:!0,scripts:{eval:"cd evals && bun run brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var $i$=new pq,wi$=new on,Bi$=new sn,Xi$=H.object({conversationId:H.string()});class LIA extends S6{entityType=j9;schema=TB0;adapter=$i$;constructor(A={}){super(nb0,$t2,A,GIA)}getConfig(){return this.config}getTemplates(){return{"summary-list":Ma2,"summary-detail":ba2,"ai-response":Oa2}}getDataSources(){return[new zIA(this.logger.child("SummaryDataSource"))]}getDerivedEntityProjections(A){if(!this.config.enableProjection)return[];return[{id:"conversation-memory-projection",targetType:j9,job:{type:Va2,handler:new eb0(A,this.logger,this.config)},initialSync:{shouldEnqueue:async()=>A.spaces.length>0&&!await Uv(A,j9,{outputVisibility:this.config.memoryVisibility}),jobData:{mode:"rebuild-all",reason:"initial-sync"},jobOptions:{source:HIA,deduplication:"coalesce",deduplicationKey:"conversation-memory:rebuild-all:initial-sync",metadata:{operationType:"data_processing",operationTarget:"conversation-memory:rebuild-all",pluginId:nb0}}},sourceChange:{sourceKind:Ie,sourceTypes:[Ie],shouldEnqueue:(Q)=>this.shouldEnqueueConversationProjection(A,Q),events:[Im],jobData:(Q)=>{let{conversationId:$}=this.parseConversationMessagePayload(Q);return{mode:"conversation",conversationId:$,reason:"message-added"}},jobOptions:(Q)=>{let{conversationId:$}=this.parseConversationMessagePayload(Q);return{priority:5,delayMs:this.config.projectionDelayMs,source:HIA,deduplication:"skip",deduplicationKey:`conversation-memory:${$}`,metadata:{operationType:"data_processing",operationTarget:`conversation-memory:${$}`,pluginId:nb0}}}}}]}parseConversationMessagePayload(A){return Xi$.parse(A)}async shouldEnqueueConversationProjection(A,Q){let{conversationId:$}=this.parseConversationMessagePayload(Q),w=await A.conversations.get($);if(!w)return!1;return vT({conversation:w,spaces:A.spaces}).eligible}async onRegister(A){A.entities.register(RG,yB0,wi$),A.entities.register(cq,gB0,Bi$),Ra2({context:A,pluginId:this.id}),Ca2({context:A,pluginId:this.id}),pa2({context:A,pluginId:this.id}),ia2({context:A,pluginId:this.id,config:this.config}),VIA(A),Qt2({context:A,logger:this.logger,config:this.config})}}function NIA(A={}){return new LIA(A)}KA();C0();C0();y9();var wt2=H.object({label:H.string(),href:H.string()}),Bt2=H.object({label:H.string(),title:H.string(),detail:H.string()}),Yi$=H.object({eyebrow:H.string(),name:H.string(),sub:H.string()}),Zi$=H.object({tone:H.enum(["capture","synthesis","share"]),title:H.string(),text:H.string()}),_IA=H.object({captures:H.number(),links:H.number(),topics:H.number(),summaries:H.number(),peers:H.number()}),wr=H.object({eyebrow:H.string(),headline:H.string(),intro:H.string(),primaryCta:wt2,secondaryCta:wt2,inputs:H.array(Bt2).min(1),outputs:H.array(Bt2).min(1),core:Yi$,legend:H.array(Zi$).min(1)}),PIA=wr.extend({counts:_IA}),Xt2={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."}]},Yt2=new d$(wr,{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 YO0(A){return Yt2.parse(A)}function Zt2(A){return Yt2.format(A)}C0();var Hi$=H.looseObject({query:H.object({routeId:H.string().default("home"),sectionId:H.string().default("diagram")}).default({routeId:"home",sectionId:"diagram"})}),Wi$={captures:"note",links:"link",topics:"topic",summaries:"summary",peers:"agent"};class kIA{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,$){let w=Hi$.parse(A??{}),B=await this.fetchContent($,w.query.routeId,w.query.sectionId),X=await this.fetchCounts($);return Q.parse({...B,counts:X})}async fetchContent(A,Q,$){let w=await A.entityService.getEntity({entityType:"site-content",id:`${Q}:${$}`});if(!w?.content)return Xt2;return wr.parse(YO0(w.content))}async fetchCounts(A){let Q=await Promise.all(Object.entries(Wi$).map(async([$,w])=>[$,await this.countOrZero(A,w)]));return _IA.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 x1}from"preact/jsx-dev-runtime";var Ht2=H.object({label:H.string(),href:H.string()}),Ki$=H.object({label:H.string(),value:H.string(),note:H.string()}),Ui$=H.object({eyebrow:H.string(),headline:H.string(),intro:H.string(),primaryCta:Ht2,secondaryCta:Ht2,signals:H.array(Ki$)}),Gi$=H.object({phase:H.string(),title:H.string(),text:H.string()}),Di$=H.object({eyebrow:H.string(),title:H.string(),intro:H.string(),steps:H.array(Gi$)}),qi$=H.object({label:H.string(),title:H.string(),text:H.string()}),zi$=H.object({title:H.string(),intro:H.string(),cards:H.array(qi$)}),Vi$=H.object({title:H.string(),intro:H.string(),points:H.array(H.string())}),Ji$={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."]},Fi$="font-body text-[15px] text-theme-muted transition-colors hover:text-theme";function Wt2({href:A,label:Q}){return x1("a",{href:A,className:Fi$,children:Q},void 0,!1,void 0,this)}function Ii$({siteInfo:A,children:Q}){let $=[...A.navigation.primary,...A.navigation.secondary],w=A.cta??{buttonText:"Start here",buttonLink:"/about"};return x1(aVA,{children:[x1("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:[x1("a",{href:"/",className:"font-nav text-[20px]","aria-label":"Relay home",children:[x1("span",{className:"font-bold text-theme",children:"relay"},void 0,!1,void 0,this),x1("span",{className:"font-bold text-accent",children:"."},void 0,!1,void 0,this),x1("span",{className:"text-theme-muted",children:"brain"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"flex items-center gap-5 md:gap-8",children:[x1("div",{className:"hidden items-center gap-6 md:flex",children:$.map((B)=>x1(Wt2,{...B},`${B.href}-${B.label}`,!1,void 0,this))},void 0,!1,void 0,this),x1("a",{href:w.buttonLink,className:"rounded-[999px] border border-theme px-4 py-2 font-body text-[13px] font-semibold text-theme transition-colors hover:border-accent hover:text-accent md:px-5",children:w.buttonText},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("main",{children:Q},void 0,!1,void 0,this),x1("footer",{className:"relative z-[1] border-t border-theme-light px-6 py-8 md:px-10 xl:px-20",children:x1("div",{className:"flex flex-col gap-4 md:flex-row md:items-center md:justify-between",children:[x1("div",{children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.22em] text-theme-light",children:A.copyright},void 0,!1,void 0,this),x1("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),x1("div",{className:"flex flex-wrap items-center gap-5",children:[$.map((B)=>x1(Wt2,{...B},`footer-${B.href}-${B.label}`,!1,void 0,this)),x1("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 Li$=({sections:A,siteInfo:Q})=>x1(Ii$,{siteInfo:Q,children:A},void 0,!1,void 0,this);function Ni$({eyebrow:A,headline:Q,intro:$,primaryCta:w,secondaryCta:B,signals:X}){return x1(pn,{className:"min-h-[92vh] pt-[152px] pb-20 md:pt-[190px]",children:x1("div",{className:"grid gap-10 lg:grid-cols-[minmax(0,1fr)_420px] lg:items-end",children:[x1("div",{children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),x1("h1",{className:"mt-7 max-w-[980px] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),x1("p",{className:"mt-7 max-w-[720px] font-body text-body-lg text-theme-muted",children:$},void 0,!1,void 0,this),x1("div",{className:"mt-10 flex flex-col gap-3 sm:flex-row",children:[x1(YB0,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),x1(YB0,{href:B.href,size:"lg",variant:"secondary",children:B.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("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:[x1("p",{className:"font-label text-label-xs uppercase tracking-[0.24em] text-theme-light",children:"Live relay signals"},void 0,!1,void 0,this),x1("div",{className:"mt-5 grid gap-3",children:X.map((Y)=>x1("div",{className:"rounded-[22px] border border-card-divider bg-bg-muted p-5",children:[x1("div",{className:"flex items-center justify-between gap-4",children:[x1("p",{className:"font-label text-label-xs uppercase tracking-[0.18em] text-secondary",children:Y.label},void 0,!1,void 0,this),x1("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),x1("p",{className:"mt-4 font-display text-display-sm text-theme",children:Y.value},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-body text-body-xs text-theme-muted",children:Y.note},void 0,!1,void 0,this)]},Y.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 _i$({eyebrow:A,title:Q,intro:$,steps:w}){return x1(pn,{id:"operating-loop",className:"py-section",children:[x1("div",{className:"max-w-[840px]",children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-secondary",children:A},void 0,!1,void 0,this),x1("h2",{className:"mt-5 font-display text-display-md text-theme",children:Q},void 0,!1,void 0,this),x1("p",{className:"mt-5 font-body text-body-md text-theme-muted",children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:w.map((B)=>x1("article",{className:"min-h-[300px] rounded-[28px] border border-card-panel-border bg-card-panel-bg p-6",children:[x1("p",{className:"font-label text-label-sm text-accent",children:B.phase},void 0,!1,void 0,this),x1("h3",{className:"mt-16 font-display text-display-sm text-theme",children:B.title},void 0,!1,void 0,this),x1("p",{className:"mt-4 font-body text-body-sm text-theme-muted",children:B.text},void 0,!1,void 0,this)]},B.phase,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Pi$({title:A,intro:Q,cards:$}){return x1(pn,{className:"py-section",children:x1("div",{className:"rounded-[36px] border border-theme-light bg-bg-muted p-6 md:p-10",children:x1("div",{className:"grid gap-8 lg:grid-cols-[360px_1fr]",children:[x1("div",{children:[x1("h2",{className:"font-display text-display-md text-theme",children:A},void 0,!1,void 0,this),x1("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),x1("div",{className:"grid gap-4",children:$.map((w)=>x1("article",{className:"rounded-[24px] border border-card-divider bg-bg-subtle/70 p-5",children:[x1("p",{className:"font-label text-label-xs uppercase tracking-[0.22em] text-accent",children:w.label},void 0,!1,void 0,this),x1("h3",{className:"mt-3 font-nav text-heading-lg text-theme",children:w.title},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-body text-body-sm text-theme-muted",children:w.text},void 0,!1,void 0,this)]},w.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)}function ki$({title:A,intro:Q,points:$}){return x1(pn,{className:"min-h-[78vh] pt-[150px] pb-section md:pt-[190px]",children:[x1("div",{className:"max-w-[920px]",children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:"Relay model"},void 0,!1,void 0,this),x1("h1",{className:"mt-6 font-display text-display-lg text-theme",children:A},void 0,!1,void 0,this),x1("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),x1("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:$.map((w)=>x1("div",{className:"rounded-[24px] border border-card-panel-current-border bg-card-panel-current-bg p-6 font-body text-body-md text-theme",children:w},w,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var ji$=(A)=>{switch(A){case"capture":return"bg-accent";case"synthesis":return"bg-secondary";case"share":return"bg-accent-bright"}},Mi$=(A)=>new Intl.NumberFormat("en",{notation:A>999?"compact":"standard"}).format(A),uB0=(A,Q,$=`${Q}s`)=>`${Mi$(A)} ${A===1?Q:$}`;function bi$({eyebrow:A,headline:Q,intro:$,primaryCta:w,secondaryCta:B,inputs:X,outputs:Y,core:Z,legend:W,counts:K}){let U=[{key:"captures",className:"top-[-10px] left-1/2 -translate-x-1/2",label:uB0(K.captures,"capture")},{key:"topics",className:"top-1/2 right-[-28px] -translate-y-1/2",label:uB0(K.topics,"topic")},{key:"peers",className:"bottom-[-10px] left-1/2 -translate-x-1/2",label:uB0(K.peers,"peer brain")},{key:"summaries",className:"top-1/2 left-[-28px] -translate-y-1/2",label:uB0(K.summaries,"summary","summaries")}];return x1(pn,{className:"pt-[150px] pb-section md:pt-[190px]",id:"diagram",children:[x1("div",{className:"mx-auto max-w-[1040px] text-center",children:[x1("p",{className:"font-label text-label-sm uppercase tracking-[0.28em] text-accent",children:A},void 0,!1,void 0,this),x1("h1",{className:"mx-auto mt-7 max-w-[22ch] font-display text-display-lg text-theme",children:Q},void 0,!1,void 0,this),x1("p",{className:"mx-auto mt-7 max-w-[64ch] font-body text-body-lg text-theme-muted",children:$},void 0,!1,void 0,this),x1("div",{className:"mt-10 flex flex-col justify-center gap-3 sm:flex-row",children:[x1(YB0,{href:w.href,size:"lg",variant:"primary-strong",children:w.label},void 0,!1,void 0,this),x1(YB0,{href:B.href,size:"lg",variant:"secondary",children:B.label},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("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:[x1("div",{className:"grid items-center gap-8 lg:grid-cols-[1fr_1.4fr_1fr]",children:[x1("div",{className:"flex flex-col gap-3.5",children:X.map((G)=>x1("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:[x1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:G.label},void 0,!1,void 0,this),x1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:G.title},void 0,!1,void 0,this),x1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:G.detail},void 0,!1,void 0,this)]},`${G.label}-${G.title}`,!0,void 0,this))},void 0,!1,void 0,this),x1("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:[x1("div",{className:"absolute inset-0 rounded-full border border-dashed border-accent/30"},void 0,!1,void 0,this),x1("div",{className:"absolute inset-6 animate-spin rounded-full border border-dashed border-secondary/40 [animation-duration:28s]"},void 0,!1,void 0,this),U.map((G)=>x1("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 ${G.className}`,children:G.label},G.key,!1,void 0,this)),x1("div",{className:"relative z-[1] px-6 text-center",children:[x1("p",{className:"font-label text-[10px] uppercase tracking-[0.28em] text-accent",children:Z.eyebrow},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-display text-[36px] leading-none text-theme",children:Z.name},void 0,!1,void 0,this),x1("p",{className:"mt-2 font-body text-[13px] text-theme-muted",children:Z.sub},void 0,!1,void 0,this),x1("p",{className:"mt-4 font-label text-[10px] uppercase tracking-[0.18em] text-theme-light",children:[uB0(K.links,"link")," indexed"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"flex flex-col gap-3.5",children:Y.map((G)=>x1("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:[x1("p",{className:"font-label text-[10px] uppercase tracking-[0.22em] text-secondary",children:G.label},void 0,!1,void 0,this),x1("h2",{className:"mt-1.5 font-display text-[18px] font-medium text-theme",children:G.title},void 0,!1,void 0,this),x1("p",{className:"mt-1 font-body text-[13px] leading-[1.5] text-theme-muted",children:G.detail},void 0,!1,void 0,this)]},`${G.label}-${G.title}`,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x1("div",{className:"mt-14 grid gap-4 border-t border-theme-light pt-8 md:grid-cols-3",children:W.map((G)=>x1("div",{className:"text-left",children:[x1("h2",{className:"font-display text-[16px] font-medium text-theme",children:[x1("span",{className:`mr-2.5 inline-block h-3 w-3 rounded-[3px] align-middle ${ji$(G.tone)}`},void 0,!1,void 0,this),G.title]},void 0,!0,void 0,this),x1("p",{className:"mt-1.5 font-body text-[13px] leading-[1.6] text-theme-muted",children:G.text},void 0,!1,void 0,this)]},G.title,!0,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var Oi$=K2({name:"home-diagram",description:"Relay homepage system diagram with live entity counts",schema:PIA,formatter:{parse:(A)=>PIA.parse({...YO0(A),counts:{captures:0,links:0,topics:0,summaries:0,peers:0}}),format:(A)=>Zt2(wr.parse(A))},dataSourceId:"relay-site:home-counts",requiredPermission:"public",layout:{component:bi$}}),fi$=(A)=>Ni$(Ui$.parse(A)),xi$=(A)=>_i$(Di$.parse(A)),Ri$=(A)=>Pi$(zi$.parse(A)),vi$=(A)=>ki$(Vi$.parse(A)),Kt2={type:"object",label:"CTA",fields:{label:{type:"string",label:"Label"},href:{type:"string",label:"Href"}}},Ut2={namespace:"relay-site",sections:{"home-hero":{title:"Home hero",description:"Relay homepage hero section",layout:fi$,fields:{eyebrow:{type:"string",label:"Eyebrow"},headline:{type:"string",label:"Headline"},intro:{type:"string",label:"Intro"},primaryCta:{...Kt2,label:"Primary CTA"},secondaryCta:{...Kt2,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:xi$,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:Ri$,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:vi$,fields:{title:{type:"string",label:"Title"},intro:{type:"string",label:"Intro"},points:{type:"array",label:"Points",minItems:1,items:{type:"string",label:"Point"}}}}}},Ci$=[{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:Ji$}]}],Gt2=Da2({packageName:"@brains/relay/site",themeProfile:"studio",layout:Li$,routes:Ci$,runtime:{contentNamespace:"relay-site",templates:{"home-diagram":Oi$},dataSources:[new kIA]}});var Dt2={name:"@brains/relay",version:"0.2.0-alpha.184",description:"Relay brain model \u2014 collaborative knowledge management",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/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/webserver":"workspace:*","@rizom/site-rizom":"workspace:*",preact:"^10.27.2"},devDependencies:{"@brains/ai-evaluation":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./env-schema":"./src/env-schema.ts"},files:["src","brain.eval.yaml","env.schema.template"],private:!0,scripts:{"build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/cms",eval:"brain-eval",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix","start:core":"bun run build:ui && cd test-apps/core && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:default":"bun run build:ui && cd test-apps/default && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:docs":"bun run build:ui && cd test-apps/docs && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start","start:full":"bun run build:ui && cd test-apps/full && INIT_CWD=$PWD bun run $([ -t 1 ] && echo --elide-lines=0) --filter @rizom/brain dev:start",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var qt2=["prompt","directory-sync","note","link","topics","conversation-memory","agents","assessment","auth-service","notifications","email-resend","cms","dashboard","mcp","webserver","web-chat","discord","a2a"],zt2=[...qt2,"image","site-info","site-content","site-builder"],Ti$=[...zt2,"docs","decks"],yi$=["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."],gi$=vM({name:"relay",version:Dt2.version,model:"gpt-5.6-luna",reasoningEffort:"low",site:Gt2,theme:nn,presets:{core:qt2,default:zt2,full:Ti$},evalDisable:["webserver","web-chat","mcp","discord"],agentInstructions:yi$,capabilities:[["prompt",JT,void 0],["note",QT,{}],["link",wT,{}],["image",M10,void 0],["topics",Uj0,{includeEntityTypes:["note","link","summary","agent","swot","deck","doc","anchor-profile","brain-character"],extractableStatuses:["published","draft"]}],["conversation-memory",NIA,{memoryVisibility:"shared"}],["docs",Ew0,void 0],["decks",vw0,void 0],["agents",LM0,void 0],["assessment",xM0,void 0],["auth-service",VQ0,void 0],["notifications",Tj0,void 0],["email-resend",rL0,void 0],["cms",KT,{}],["dashboard",$f,void 0],["directory-sync",wE,{seedContent:!0,seedContentPath:Ei$(import.meta.dir,"..","seed-content"),initialSync:!0}],["site-content",uE,{definitions:Ut2}],["rizom-ecosystem",FT,void 0],["site-info",cE,void 0],["site-builder",mE,{}]],interfaces:[["mcp",Jb,()=>({})],["discord",$O,()=>({captureUrls:!0})],["a2a",Fd,()=>({})],["webserver",HO,()=>({})],["web-chat",Jd,()=>({})]],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"}}}),Vt2=gi$;import{readFileSync as Is$}from"fs";import{join as Ls$}from"path";import{execSync as Ns$}from"child_process";import{parseArgs as ui$}from"util";var ci$={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 ZV(A,Q){let $=A[Q];return typeof $==="string"?$:void 0}function Vf(A,Q){let $=A[Q];return typeof $==="boolean"?$:void 0}function Jt2(A){let{values:Q,positionals:$}=ui$({args:A,options:ci$,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:$[0]??"help",args:$.slice(1),flags:{model:ZV(Q,"model"),domain:ZV(Q,"domain"),"content-repo":ZV(Q,"content-repo"),backend:ZV(Q,"backend"),"push-to":ZV(Q,"push-to"),"ai-api-key":ZV(Q,"ai-api-key"),"no-interactive":Vf(Q,"no-interactive"),preview:Vf(Q,"preview"),deploy:Vf(Q,"deploy"),regen:Vf(Q,"regen"),all:Vf(Q,"all"),only:ZV(Q,"only"),"dry-run":Vf(Q,"dry-run"),"startup-check":Vf(Q,"startup-check"),"storage-dir":ZV(Q,"storage-dir"),yes:Vf(Q,"yes"),remote:ZV(Q,"remote"),token:ZV(Q,"token"),outputDir:ZV(Q,"outputDir")}}}cB0();import{mkdirSync as Ws$}from"fs";import{join as Ks$}from"path";import{execSync as Us$}from"child_process";var HO0={name:"@rizom/brain",version:"0.2.0-alpha.184",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/sdk":"^1.29.0","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20",postcss:"^8.5.15",preact:"^10.27.2","preact-render-to-string":"^6.7.0",tailwindcss:"^4.3.1",zod:"^4.1.8"},devDependencies:{"@brains/app":"workspace:*","@brains/build-tools":"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-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@rizom/theme-default":"workspace:*","@types/bun":"^1.3.14",rolldown:"^1.0.0","rolldown-plugin-dts":"^0.27.4",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},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"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","playwright-core":"^1.61.0","react-devtools-core":"^7.0.1",sharp:"^0.35.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","dev:start":"bun scripts/build.ts && bun dist/brain.js start",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};import{mkdirSync as vt2,writeFileSync as lB0,chmodSync as dB0,existsSync as hIA,readFileSync as EIA}from"fs";import{basename as TIA,dirname as yIA,join as xB,resolve as _n$}from"path";import{fileURLToPath as Pn$}from"url";var Ft2=`ARG BUN_VERSION=1.3.10
13985
13985
  FROM oven/bun:\${BUN_VERSION}-slim AS runtime
13986
13986
 
13987
13987
  WORKDIR /app