@rizom/brain 0.2.0-alpha.145 → 0.2.0-alpha.146
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 +853 -1000
- package/dist/entities.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/plugins.d.ts +2 -0
- package/dist/plugins.js +2 -2
- package/dist/plugins.js.map +4 -4
- package/dist/services.js.map +1 -1
- package/dist/site.js +5 -5
- package/dist/site.js.map +4 -4
- package/dist/ui/cms-app.js +506 -0
- package/dist/ui/cms-app.js.map +299 -0
- package/package.json +1 -1
package/dist/plugins.js
CHANGED
|
@@ -185,7 +185,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
185
185
|
`+F.slice(C,p),C=p+1;m=U$}if($$+=`
|
|
186
186
|
`,F.length-C>B&&m>C)$$+=F.slice(C,m)+`
|
|
187
187
|
`+F.slice(m+1);else $$+=F.slice(C);return $$.slice(1)}function VU(F){let B="",x=0;for(let E=0;E<F.length;x>=65536?E+=2:E++){x=l$(F,E);let C=D$[x];if(!C&&I4(x)){if(B+=F[E],x>=65536)B+=F[E+1]}else B+=C||S$(x)}return B}function U1(F,B,x){let E="",C=F.tag;for(let p=0,m=x.length;p<m;p+=1){let U$=x[p];if(F.replacer)U$=F.replacer.call(x,String(p),U$);if(v(F,B,U$,!1,!1)||typeof U$>"u"&&v(F,B,null,!1,!1)){if(E!=="")E+=","+(!F.condenseFlow?" ":"");E+=F.dump}}F.tag=C,F.dump="["+E+"]"}function g(F,B,x,E){let C="",p=F.tag;for(let m=0,U$=x.length;m<U$;m+=1){let $$=x[m];if(F.replacer)$$=F.replacer.call(x,String(m),$$);if(v(F,B+1,$$,!0,!0,!1,!0)||typeof $$>"u"&&v(F,B+1,null,!0,!0,!1,!0)){if(!E||C!=="")C+=M(F,B);if(F.dump&&J===F.dump.charCodeAt(0))C+="-";else C+="- ";C+=F.dump}}F.tag=p,F.dump=C||"[]"}function S(F,B,x){let E="",C=F.tag,p=Object.keys(x);for(let m=0,U$=p.length;m<U$;m+=1){let $$="";if(E!=="")$$+=", ";if(F.condenseFlow)$$+='"';let G$=p[m],V$=x[G$];if(F.replacer)V$=F.replacer.call(x,G$,V$);if(!v(F,B,G$,!1,!1))continue;if(F.dump.length>1024)$$+="? ";if($$+=F.dump+(F.condenseFlow?'"':"")+":"+(F.condenseFlow?"":" "),!v(F,B,V$,!1,!1))continue;$$+=F.dump,E+=$$}F.tag=C,F.dump="{"+E+"}"}function H(F,B,x,E){let C="",p=F.tag,m=Object.keys(x);if(F.sortKeys===!0)m.sort();else if(typeof F.sortKeys==="function")m.sort(F.sortKeys);else if(F.sortKeys)throw new U("sortKeys must be a boolean or a function");for(let U$=0,$$=m.length;U$<$$;U$+=1){let G$="";if(!E||C!=="")G$+=M(F,B);let V$=m[U$],F$=x[V$];if(F.replacer)F$=F.replacer.call(x,V$,F$);if(!v(F,B+1,V$,!0,!0,!0))continue;let g$=F.tag!==null&&F.tag!=="?"||F.dump&&F.dump.length>1024;if(g$)if(F.dump&&J===F.dump.charCodeAt(0))G$+="?";else G$+="? ";if(G$+=F.dump,g$)G$+=M(F,B);if(!v(F,B+1,F$,!0,g$))continue;if(F.dump&&J===F.dump.charCodeAt(0))G$+=":";else G$+=": ";G$+=F.dump,C+=G$}F.tag=p,F.dump=C||"{}"}function Q(F,B,x){let E=x?F.explicitTypes:F.implicitTypes;for(let C=0,p=E.length;C<p;C+=1){let m=E[C];if((m.instanceOf||m.predicate)&&(!m.instanceOf||typeof B==="object"&&B instanceof m.instanceOf)&&(!m.predicate||m.predicate(B))){if(x)if(m.multi&&m.representName)F.tag=m.representName(B);else F.tag=m.tag;else F.tag="?";if(m.represent){let U$=F.styleMap[m.tag]||m.defaultStyle,$$;if(X.call(m.represent)==="[object Function]")$$=m.represent(B,U$);else if(D.call(m.represent,U$))$$=m.represent[U$](B,U$);else throw new U("!<"+m.tag+'> tag resolver accepts not "'+U$+'" style');F.dump=$$}return!0}}return!1}function v(F,B,x,E,C,p,m){if(F.tag=null,F.dump=x,!Q(F,x,!1))Q(F,x,!0);let U$=X.call(F.dump),$$=E;if(E)E=F.flowLevel<0||F.flowLevel>B;let G$=U$==="[object Object]"||U$==="[object Array]",V$,F$;if(G$)V$=F.duplicates.indexOf(x),F$=V$!==-1;if(F.tag!==null&&F.tag!=="?"||F$||F.indent!==2&&B>0)C=!1;if(F$&&F.usedDuplicates[V$])F.dump="*ref_"+V$;else{if(G$&&F$&&!F.usedDuplicates[V$])F.usedDuplicates[V$]=!0;if(U$==="[object Object]"){if(E&&Object.keys(F.dump).length!==0){if(H(F,B,F.dump,C),F$)F.dump="&ref_"+V$+F.dump}else if(S(F,B,F.dump),F$)F.dump="&ref_"+V$+" "+F.dump}else if(U$==="[object Array]"){if(E&&F.dump.length!==0){if(F.noArrayIndent&&!m&&B>0)g(F,B-1,F.dump,C);else g(F,B,F.dump,C);if(F$)F.dump="&ref_"+V$+F.dump}else if(U1(F,B,F.dump),F$)F.dump="&ref_"+V$+" "+F.dump}else if(U$==="[object String]"){if(F.tag!=="?")e6(F,F.dump,B,p,$$)}else if(U$==="[object Undefined]")return!1;else{if(F.skipInvalid)return!1;throw new U("unacceptable kind of an object to dump "+U$)}if(F.tag!==null&&F.tag!=="?"){let g$=encodeURI(F.tag[0]==="!"?F.tag.slice(1):F.tag).replace(/!/g,"%21");if(F.tag[0]==="!")g$="!"+g$;else if(g$.slice(0,18)==="tag:yaml.org,2002:")g$="!!"+g$.slice(18);else g$="!<"+g$+">";F.dump=g$+" "+F.dump}}return!0}function j(F,B){let x=[],E=[];L(F,x,E);let C=E.length;for(let p=0;p<C;p+=1)B.duplicates.push(x[E[p]]);B.usedDuplicates=Array(C)}function L(F,B,x){if(F!==null&&typeof F==="object"){let E=B.indexOf(F);if(E!==-1){if(x.indexOf(E)===-1)x.push(E)}else if(B.push(F),Array.isArray(F))for(let C=0,p=F.length;C<p;C+=1)L(F[C],B,x);else{let C=Object.keys(F);for(let p=0,m=C.length;p<m;p+=1)L(F[C[p]],B,x)}}}function u(F,B){B=B||{};let x=new d$(B);if(!x.noRefs)j(F,x);let E=F;if(x.replacer)E=x.replacer.call({"":E},"",E);if(v(x,0,E,!0,!0))return x.dump+`
|
|
188
|
-
`;return""}return uZ.dump=u,uZ}var Nw;function EQ(){if(Nw)return e$;Nw=1;let $=SQ(),U=jQ();function G(X,D){return function(){throw Error("Function yaml."+X+" is removed in js-yaml 4. Use yaml."+D+" instead, which is now safe by default.")}}return e$.Type=W4(),e$.Schema=Mw(),e$.FAILSAFE_SCHEMA=vw(),e$.JSON_SCHEMA=Sw(),e$.CORE_SCHEMA=jw(),e$.DEFAULT_SCHEMA=hZ(),e$.load=$.load,e$.loadAll=$.loadAll,e$.dump=U.dump,e$.YAMLException=$D(),e$.types={binary:kw(),float:gw(),map:Bw(),null:Tw(),pairs:bw(),set:rw(),timestamp:Ew(),bool:zw(),int:Lw(),merge:Cw(),omap:xw(),seq:Iw(),str:Qw()},e$.safeLoad=G("safeLoad","load"),e$.safeLoadAll=G("safeLoadAll","loadAll"),e$.safeDump=G("safeDump","dump"),e$}var qy=EQ();var _y=W.record(W.string(),W.unknown());var py=W.object({slug:W.string(),title:W.string(),type:W.string(),entityId:W.string(),contentHash:W.string()});function mZ($){return`preview.${$.trim().replace(/^https?:\/\//,"")}`}var CQ=W.string(),kQ=W.looseObject({id:W.string().min(1)}),xQ=W.looseObject({label:W.string().min(1)}),bQ=W.looseObject({layouts:W.record(W.string(),W.unknown()),plugin:W.custom(($)=>typeof $==="function").optional(),routes:W.array(kQ),entityDisplay:W.record(W.string(),xQ),content:W.unknown().optional(),themeOverride:W.string().optional(),headScripts:W.array(W.string()).optional(),staticAssets:W.record(W.string(),W.string()).optional()}),rQ=W.custom(($)=>bQ.safeParse($).success);import{webcrypto as mw}from"crypto";var hw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var uQ=128,w6,p1;function hQ($){if($<0)throw RangeError("Wrong ID size");try{if(!w6||w6.length<$)w6=Buffer.allocUnsafe($*uQ),mw.getRandomValues(w6),p1=0;else if(p1+$>w6.length)mw.getRandomValues(w6),p1=0}catch(U){throw w6=void 0,U}p1+=$}function yw($=21){hQ($|=0);let U="";for(let G=p1-$;G<p1;G++)U+=hw[w6[G]&63];return U}function l6($=12){return yw($)}var yZ=W.enum(["file_operations","content_operations","data_processing","batch_processing"]),mQ=W.object({pluginId:W.string().optional(),progressToken:W.union([W.string(),W.number()]).optional(),operationType:yZ,operationTarget:W.string().optional(),interfaceType:W.string().optional(),conversationId:W.string().optional(),channelId:W.string().optional(),silent:W.boolean().optional()}),l1=W.object({pluginId:W.string().optional(),progressToken:W.union([W.string(),W.number()]).optional(),operationType:yZ,operationTarget:W.string().optional(),interfaceType:W.string().optional(),conversationId:W.string().optional(),channelId:W.string().optional(),silent:W.boolean().optional(),rootJobId:W.string()}),Tf=W.enum(["none","skip","replace","coalesce"]);var fZ=W.enum(["pending","processing","completed","failed"]),fw=W.enum(["completed","failed"]);var yQ=W.object({id:W.string(),type:W.string(),status:fZ,data:W.unknown(),result:W.unknown().optional(),lastError:W.string().optional().nullable(),attempts:W.number(),maxRetries:W.number(),priority:W.number(),createdAt:W.date(),updatedAt:W.date(),processedAt:W.date().optional().nullable(),completedAt:W.date().optional().nullable(),failedAt:W.date().optional().nullable()}),fQ=W.object({jobId:W.string(),type:W.string(),status:fw,result:W.unknown().optional(),error:W.string().optional()}),pw=W.object({success:W.literal(!1),error:W.string().optional()}),pZ=W.object({id:W.string(),type:W.enum(["job","batch"]),status:fZ,message:W.string().optional(),progress:W.object({current:W.number(),total:W.number(),percentage:W.number()}).optional(),aggregationKey:W.string().optional(),batchDetails:W.object({totalOperations:W.number(),completedOperations:W.number(),failedOperations:W.number(),currentOperation:W.string().optional(),errors:W.array(W.string()).optional()}).optional(),jobDetails:W.object({jobType:W.string(),priority:W.number(),retryCount:W.number()}).optional(),metadata:l1});import{createClient as Fl}from"@libsql/client";var a=Symbol.for("drizzle:entityKind");function Y4($,U){if(!$||typeof $!=="object")return!1;if($ instanceof U)return!0;if(!Object.prototype.hasOwnProperty.call(U,a))throw Error(`Class "${U.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 G=Object.getPrototypeOf($).constructor;if(G)while(G){if(a in G&&G[a]===U[a])return!0;G=Object.getPrototypeOf(G)}return!1}class K6{constructor($,U){this.table=$,this.config=U,this.name=U.name,this.keyAsName=U.keyAsName,this.notNull=U.notNull,this.default=U.default,this.defaultFn=U.defaultFn,this.onUpdateFn=U.onUpdateFn,this.hasDefault=U.hasDefault,this.primary=U.primaryKey,this.isUnique=U.isUnique,this.uniqueName=U.uniqueName,this.uniqueType=U.uniqueType,this.dataType=U.dataType,this.columnType=U.columnType,this.generated=U.generated,this.generatedIdentity=U.generatedIdentity}static[a]="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($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class lZ{static[a]="ColumnBuilder";config;constructor($,U,G){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:U,columnType:G,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}var E4=Symbol.for("drizzle:Name");function lw($,...U){return $(...U)}function iw($,U){return`${$[E4]}_${U.join("_")}_unique`}class UD extends K6{constructor($,U){if(!U.uniqueName)U.uniqueName=iw($,[U.name]);super($,U);this.table=$}static[a]="PgColumn"}class pQ extends UD{static[a]="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($){return this.indexConfig.opClass=$,this}}class lQ extends UD{static[a]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,U){super($,U);this.enum=U.enum}getSQLType(){return this.enum.enumName}}var nw=Symbol.for("drizzle:isPgEnum");function cw($){return!!$&&typeof $==="function"&&nw in $&&$[nw]===!0}class iQ extends UD{static[a]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,U){super($,U);this.enum=U.enum}getSQLType(){return this.enum.enumName}}class k0{static[a]="Subquery";constructor($,U,G,X=!1,D=[]){this._={brand:"Subquery",sql:$,selectedFields:U,alias:G,isWith:X,usedTables:D}}}var dw="0.45.2";var iZ,nZ,ow={startActiveSpan($,U){if(!iZ)return U();if(!nZ)nZ=iZ.trace.getTracer("drizzle-orm",dw);return lw((G,X)=>X.startActiveSpan($,(D)=>{try{return U(D)}catch(V){throw D.setStatus({code:G.SpanStatusCode.ERROR,message:V instanceof Error?V.message:"Unknown error"}),V}finally{D.end()}}),iZ,nZ)}};var i1=Symbol.for("drizzle:ViewBaseConfig");var cZ=Symbol.for("drizzle:Schema"),aw=Symbol.for("drizzle:Columns"),sw=Symbol.for("drizzle:ExtraConfigColumns"),dZ=Symbol.for("drizzle:OriginalName"),oZ=Symbol.for("drizzle:BaseName"),DD=Symbol.for("drizzle:IsAlias"),tw=Symbol.for("drizzle:ExtraConfigBuilder"),nQ=Symbol.for("drizzle:IsDrizzleTable");class x${static[a]="Table";static Symbol={Name:E4,Schema:cZ,OriginalName:dZ,Columns:aw,ExtraConfigColumns:sw,BaseName:oZ,IsAlias:DD,ExtraConfigBuilder:tw};[E4];[dZ];[cZ];[aw];[sw];[oZ];[DD]=!1;[nQ]=!0;[tw]=void 0;constructor($,U,G){this[E4]=this[dZ]=$,this[cZ]=U,this[oZ]=G}}function cQ($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function dQ($){let U={sql:"",params:[]};for(let G of $)if(U.sql+=G.sql,U.params.push(...G.params),G.typings?.length){if(!U.typings)U.typings=[];U.typings.push(...G.typings)}return U}class z4{static[a]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new b$([this])}}class b${constructor($){this.queryChunks=$;for(let U of $)if(Y4(U,x$)){let G=U[x$.Symbol.Schema];this.usedTables.push(G===void 0?U[x$.Symbol.Name]:G+"."+U[x$.Symbol.Name])}}static[a]="SQL";decoder=ew;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return ow.startActiveSpan("drizzle.buildSQL",(U)=>{let G=this.buildQueryFromSourceParams(this.queryChunks,$);return U?.setAttributes({"drizzle.query.text":G.sql,"drizzle.query.params":JSON.stringify(G.params)}),G})}buildQueryFromSourceParams($,U){let G=Object.assign({},U,{inlineParams:U.inlineParams||this.shouldInlineParams,paramStartIndex:U.paramStartIndex||{value:0}}),{casing:X,escapeName:D,escapeParam:V,prepareTyping:Z,inlineParams:J,paramStartIndex:P}=G;return dQ($.map((Y)=>{if(Y4(Y,z4))return{sql:Y.value.join(""),params:[]};if(Y4(Y,x0))return{sql:D(Y.value),params:[]};if(Y===void 0)return{sql:"",params:[]};if(Array.isArray(Y)){let w=[new z4("(")];for(let[K,q]of Y.entries())if(w.push(q),K<Y.length-1)w.push(new z4(", "));return w.push(new z4(")")),this.buildQueryFromSourceParams(w,G)}if(Y4(Y,b$))return this.buildQueryFromSourceParams(Y.queryChunks,{...G,inlineParams:J||Y.shouldInlineParams});if(Y4(Y,x$)){let w=Y[x$.Symbol.Schema],K=Y[x$.Symbol.Name];return{sql:w===void 0||Y[DD]?D(K):D(w)+"."+D(K),params:[]}}if(Y4(Y,K6)){let w=X.getColumnCasing(Y);if(U.invokeSource==="indexes")return{sql:D(w),params:[]};let K=Y.table[x$.Symbol.Schema];return{sql:Y.table[DD]||K===void 0?D(Y.table[x$.Symbol.Name])+"."+D(w):D(K)+"."+D(Y.table[x$.Symbol.Name])+"."+D(w),params:[]}}if(Y4(Y,U3)){let w=Y[i1].schema,K=Y[i1].name;return{sql:w===void 0||Y[i1].isAlias?D(K):D(w)+"."+D(K),params:[]}}if(Y4(Y,aZ)){if(Y4(Y.value,b0))return{sql:V(P.value++,Y),params:[Y],typings:["none"]};let w=Y.value===null?null:Y.encoder.mapToDriverValue(Y.value);if(Y4(w,b$))return this.buildQueryFromSourceParams([w],G);if(J)return{sql:this.mapInlineParam(w,G),params:[]};let K=["none"];if(Z)K=[Z(Y.encoder)];return{sql:V(P.value++,w),params:[w],typings:K}}if(Y4(Y,b0))return{sql:V(P.value++,Y),params:[Y],typings:["none"]};if(Y4(Y,b$.Aliased)&&Y.fieldAlias!==void 0)return{sql:D(Y.fieldAlias),params:[]};if(Y4(Y,k0)){if(Y._.isWith)return{sql:D(Y._.alias),params:[]};return this.buildQueryFromSourceParams([new z4("("),Y._.sql,new z4(") "),new x0(Y._.alias)],G)}if(cw(Y)){if(Y.schema)return{sql:D(Y.schema)+"."+D(Y.enumName),params:[]};return{sql:D(Y.enumName),params:[]}}if(cQ(Y)){if(Y.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([Y.getSQL()],G);return this.buildQueryFromSourceParams([new z4("("),Y.getSQL(),new z4(")")],G)}if(J)return{sql:this.mapInlineParam(Y,G),params:[]};return{sql:V(P.value++,Y),params:[Y],typings:["none"]}}))}mapInlineParam($,{escapeString:U}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return U($);if(typeof $==="object"){let G=$.toString();if(G==="[object Object]")return U(JSON.stringify($));return U(G)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new b$.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class x0{constructor($){this.value=$}static[a]="Name";brand;getSQL(){return new b$([this])}}var ew={mapFromDriverValue:($)=>$},$3={mapToDriverValue:($)=>$},wp={...ew,...$3};class aZ{constructor($,U=$3){this.value=$,this.encoder=U}static[a]="Param";brand;getSQL(){return new b$([this])}}function i6($,...U){let G=[];if(U.length>0||$.length>0&&$[0]!=="")G.push(new z4($[0]));for(let[X,D]of U.entries())G.push(D,new z4($[X+1]));return new b$(G)}(($)=>{function U(){return new b$([])}$.empty=U;function G(P){return new b$(P)}$.fromList=G;function X(P){return new b$([new z4(P)])}$.raw=X;function D(P,Y){let w=[];for(let[K,q]of P.entries()){if(K>0&&Y!==void 0)w.push(Y);w.push(q)}return new b$(w)}$.join=D;function V(P){return new x0(P)}$.identifier=V;function Z(P){return new b0(P)}$.placeholder=Z;function J(P,Y){return new aZ(P,Y)}$.param=J})(i6||(i6={}));(($)=>{class U{constructor(G,X){this.sql=G,this.fieldAlias=X}static[a]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new U(this.sql,this.fieldAlias)}}$.Aliased=U})(b$||(b$={}));class b0{constructor($){this.name=$}static[a]="Placeholder";getSQL(){return new b$([this])}}var oQ=Symbol.for("drizzle:IsDrizzleView");class U3{static[a]="View";[i1];[oQ]=!0;constructor({name:$,schema:U,selectedFields:G,query:X}){this[i1]={name:$,originalName:$,schema:U,selectedFields:G,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new b$([this])}}K6.prototype.getSQL=function(){return new b$([this])};x$.prototype.getSQL=function(){return new b$([this])};k0.prototype.getSQL=function(){return new b$([this])};function y4($,U){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:U}}var sZ=typeof TextDecoder>"u"?null:new TextDecoder;class tZ{static[a]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,U){if(this.reference=()=>{let{name:G,columns:X,foreignColumns:D}=$();return{name:G,columns:X,foreignTable:D[0].table,foreignColumns:D}},U)this._onUpdate=U.onUpdate,this._onDelete=U.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new D3($,this)}}class D3{constructor($,U){this.table=$,this.reference=U.reference,this.onUpdate=U._onUpdate,this.onDelete=U._onDelete}static[a]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:U,foreignColumns:G}=this.reference(),X=U.map((Z)=>Z.name),D=G.map((Z)=>Z.name),V=[this.table[E4],...X,G[0].table[E4],...D];return $??`${V.join("_")}_fk`}}function G3($,U){return`${$[E4]}_${U.join("_")}_unique`}class f$ extends lZ{static[a]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,U={}){return this.foreignKeyConfigs.push({ref:$,actions:U}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,U){return this.config.generated={as:$,type:"always",mode:U?.mode??"virtual"},this}buildForeignKeys($,U){return this.foreignKeyConfigs.map(({ref:G,actions:X})=>{return((D,V)=>{let Z=new tZ(()=>{let J=D();return{columns:[$],foreignColumns:[J]}});if(V.onUpdate)Z.onUpdate(V.onUpdate);if(V.onDelete)Z.onDelete(V.onDelete);return Z.build(U)})(G,X)})}}class p$ extends K6{constructor($,U){if(!U.uniqueName)U.uniqueName=G3($,[U.name]);super($,U);this.table=$}static[a]="SQLiteColumn"}class X3 extends f${static[a]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new V3($,this.config)}}class V3 extends p${static[a]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let U=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return BigInt(U.toString("utf8"))}return BigInt(sZ.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class Z3 extends f${static[a]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new J3($,this.config)}}class J3 extends p${static[a]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let U=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return JSON.parse(U.toString("utf8"))}return JSON.parse(sZ.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class W3 extends f${static[a]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Y3($,this.config)}}class Y3 extends p${static[a]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}function P3($,U){let{name:G,config:X}=y4($,U);if(X?.mode==="json")return new Z3(G);if(X?.mode==="bigint")return new X3(G);return new W3(G)}class H3 extends f${static[a]="SQLiteCustomColumnBuilder";constructor($,U,G){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=U,this.config.customTypeParams=G}build($){return new w3($,this.config)}}class w3 extends p${static[a]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,U){super($,U);this.sqlName=U.customTypeParams.dataType(U.fieldConfig),this.mapTo=U.customTypeParams.toDriver,this.mapFrom=U.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function r0($){return(U,G)=>{let{name:X,config:D}=y4(U,G);return new H3(X,D,$)}}class u0 extends f${static[a]="SQLiteBaseIntegerBuilder";constructor($,U,G){super($,U,G);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class h0 extends p${static[a]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class K3 extends u0{static[a]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new O3($,this.config)}}class O3 extends h0{static[a]="SQLiteInteger"}class q3 extends u0{static[a]="SQLiteTimestampBuilder";constructor($,U){super($,"date","SQLiteTimestamp");this.config.mode=U}defaultNow(){return this.default(i6`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new A3($,this.config)}}class A3 extends h0{static[a]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let U=$.getTime();if(this.config.mode==="timestamp")return Math.floor(U/1000);return U}}class _3 extends u0{static[a]="SQLiteBooleanBuilder";constructor($,U){super($,"boolean","SQLiteBoolean");this.config.mode=U}build($){return new F3($,this.config)}}class F3 extends h0{static[a]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function P4($,U){let{name:G,config:X}=y4($,U);if(X?.mode==="timestamp"||X?.mode==="timestamp_ms")return new q3(G,X.mode);if(X?.mode==="boolean")return new _3(G,X.mode);return new K3(G)}class R3 extends f${static[a]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new N3($,this.config)}}class N3 extends p${static[a]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class M3 extends f${static[a]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Q3($,this.config)}}class Q3 extends p${static[a]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class I3 extends f${static[a]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new B3($,this.config)}}class B3 extends p${static[a]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function v3($,U){let{name:G,config:X}=y4($,U),D=X?.mode;return D==="number"?new M3(G):D==="bigint"?new I3(G):new R3(G)}class T3 extends f${static[a]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new z3($,this.config)}}class z3 extends p${static[a]="SQLiteReal";getSQLType(){return"real"}}function L3($){return new T3($??"")}class g3 extends f${static[a]="SQLiteTextBuilder";constructor($,U){super($,"string","SQLiteText");this.config.enumValues=U.enum,this.config.length=U.length}build($){return new S3($,this.config)}}class S3 extends p${static[a]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,U){super($,U)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class j3 extends f${static[a]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new E3($,this.config)}}class E3 extends p${static[a]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}function O$($,U={}){let{name:G,config:X}=y4($,U);if(X.mode==="json")return new j3(G);return new g3(G,X)}function C3(){return{blob:P3,customType:r0,integer:P4,numeric:v3,real:L3,text:O$}}var eZ=Symbol.for("drizzle:SQLiteInlineForeignKeys");class GD extends x${static[a]="SQLiteTable";static Symbol=Object.assign({},x$.Symbol,{InlineForeignKeys:eZ});[x$.Symbol.Columns];[eZ]=[];[x$.Symbol.ExtraConfigBuilder]=void 0}function aQ($,U,G,X,D=$){let V=new GD($,X,D),Z=typeof U==="function"?U(C3()):U,J=Object.fromEntries(Object.entries(Z).map(([Y,w])=>{let K=w;K.setName(Y);let q=K.build(V);return V[eZ].push(...K.buildForeignKeys(q,V)),[Y,q]})),P=Object.assign(V,J);if(P[x$.Symbol.Columns]=J,P[x$.Symbol.ExtraConfigColumns]=J,G)P[GD.Symbol.ExtraConfigBuilder]=G;return P}var f4=($,U,G)=>{return aQ($,U,G)};class k3{constructor($,U){this.name=$,this.value=U}static[a]="SQLiteCheckBuilder";brand;build($){return new x3($,this)}}class x3{constructor($,U){this.table=$,this.name=U.name,this.value=U.value}static[a]="SQLiteCheck";name;value}function b3($,U){return new k3($,U)}class r3{constructor($,U){this.name=$,this.unique=U}static[a]="SQLiteIndexBuilderOn";on(...$){return new u3(this.name,$,this.unique)}}class u3{static[a]="SQLiteIndexBuilder";config;constructor($,U,G){this.config={name:$,columns:U,unique:G,where:void 0}}where($){return this.config.where=$,this}build($){return new h3(this.config,$)}}class h3{static[a]="SQLiteIndex";config;constructor($,U){this.config={...$,table:U}}}function C4($){return new r3($,!1)}function m0(...$){if($[0].columns)return new $J($[0].columns,$[0].name);return new $J($)}class $J{static[a]="SQLitePrimaryKeyBuilder";columns;name;constructor($,U){this.columns=$,this.name=U}build($){return new m3($,this.columns,this.name)}}class m3{constructor($,U,G){this.table=$,this.columns=U,this.name=G}static[a]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[GD.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var y3=f4("job_queue",{id:O$("id").primaryKey().$defaultFn(()=>l6()),type:O$("type").notNull(),data:O$("data").notNull(),result:O$("result",{mode:"json"}),source:O$("source"),metadata:O$("metadata",{mode:"json"}).$type().notNull(),status:O$("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:P4("priority").notNull().default(0),retryCount:P4("retryCount").notNull().default(0),maxRetries:P4("maxRetries").notNull().default(3),lastError:O$("lastError"),createdAt:P4("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:P4("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:P4("startedAt"),completedAt:P4("completedAt")},($)=>({queueReadyIdx:C4("idx_job_queue_ready").on($.status,$.priority,$.scheduledFor),jobTypeIdx:C4("idx_job_queue_type").on($.type,$.status),jobSourceIdx:C4("idx_job_queue_source").on($.source)}));var zl=W.looseObject({deduplicationKey:W.string().optional()});var tl=W.preprocess(($)=>{if(typeof $!=="string")return $;return JSON.parse($)},W.record(W.string(),W.unknown()));var Ui=W.record(W.string(),W.unknown());var sQ=W.object({id:W.string(),type:W.string(),data:W.string(),status:W.enum(["pending","processing","completed","failed"]),source:W.string().nullable(),priority:W.number(),retryCount:W.number(),maxRetries:W.number(),lastError:W.string().nullable(),createdAt:W.number(),scheduledFor:W.number(),startedAt:W.number().nullable(),completedAt:W.number().nullable(),metadata:l1,result:W.unknown().nullable().optional()});function UJ($,U,G){return async(X)=>{let{type:D,data:V,toolContext:Z=null,options:J}=X,{metadata:P,...Y}=J??{},w={source:U,...J?.rootJobId&&{rootJobId:J.rootJobId},...Y,metadata:{operationType:"data_processing",pluginId:U,...Z&&{interfaceType:Z.interfaceType,channelId:Z.channelId},...P}},K=G&&!D.includes(":")?`${U}:${D}`:D;return $.enqueue({type:K,data:V,options:w})}}function DJ($,U){return async(G,X)=>{let D=l6(),V=G.map((J)=>({...J,type:J.type.includes(":")?J.type:`${U}:${J.type}`})),Z={...X,source:U,rootJobId:D,metadata:{...X?.metadata,operationType:"batch_processing",pluginId:U}};return await $.enqueueBatch(V,Z,D,U),D}}function GJ($,U){return(G,X)=>{let D=G.includes(":")?G:`${U}:${G}`;$.registerHandler(D,X,U)}}var tQ=W.custom(($)=>typeof $==="object"&&$!==null&&("safeParse"in $)),eQ=W.object({name:W.string(),schema:tQ});function f3($){return eQ.safeParse($).success}function $I($){if(!$)return;return{status:$.status,message:$.message,lastCheck:$.lastCheck?.toISOString(),details:$.details}}function p3($){return{model:$.model,version:$.version,uptime:$.uptime,entities:$.entities,entityCounts:$.entityCounts,embeddings:$.embeddings,ai:$.ai,daemons:$.daemons.map((U)=>({name:U.name,pluginId:U.pluginId,status:U.status,health:$I(U.health)})),endpoints:$.endpoints,interactions:$.interactions}}import{createClient as gi}from"@libsql/client";var y0=f4("conversations",{id:O$("id").primaryKey(),sessionId:O$("session_id").notNull(),interfaceType:O$("interface_type").notNull(),channelId:O$("channel_id").notNull(),started:O$("started").notNull(),lastActive:O$("last_active").notNull(),metadata:O$("metadata"),created:O$("created").notNull(),updated:O$("updated").notNull()},($)=>({sessionIdx:C4("idx_conversations_session").on($.sessionId),channelIdx:C4("idx_conversations_channel").on($.channelId),interfaceSessionIdx:C4("idx_conversations_interface_session").on($.interfaceType,$.sessionId),interfaceChannelIdx:C4("idx_conversations_interface_channel").on($.interfaceType,$.channelId)})),l3=f4("messages",{id:O$("id").primaryKey(),conversationId:O$("conversation_id").notNull().references(()=>y0.id,{onDelete:"cascade"}),role:O$("role").notNull(),content:O$("content").notNull(),timestamp:O$("timestamp").notNull(),metadata:O$("metadata")},($)=>({conversationIdx:C4("idx_messages_conversation").on($.conversationId),timestampIdx:C4("idx_messages_timestamp").on($.timestamp)})),i3=f4("summary_tracking",{conversationId:O$("conversation_id").primaryKey().references(()=>y0.id,{onDelete:"cascade"}),lastSummarizedAt:O$("last_summarized_at"),lastMessageId:O$("last_message_id"),messagesSinceSummary:P4("messages_since_summary").default(0),updated:O$("updated").notNull()});var UI=W.preprocess(($)=>{if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return}},W.record(W.string(),W.unknown())).catch({});function VD($){return UI.parse($)}var f0=W.object({actorId:W.string(),canonicalId:W.string().optional(),interfaceType:W.string(),role:k6,displayName:W.string().optional(),username:W.string().optional(),isBot:W.boolean().optional()}),p0=W.object({messageId:W.string().optional(),channelId:W.string().optional(),channelName:W.string().optional(),threadId:W.string().optional(),metadata:W.record(W.string(),W.unknown()).optional()}),DI=W.looseObject({actor:f0.optional(),source:p0.optional()});var GI=W.object({id:W.string(),conversationId:W.string(),role:W.string(),content:W.string(),timestamp:W.string(),metadata:W.string().nullable()}),XI=W.object({conversationId:W.string(),messageCount:W.number(),messages:W.array(GI),windowStart:W.number(),windowEnd:W.number(),windowSize:W.number(),timestamp:W.string()});var n1=W.record(W.string(),W.unknown());var JI=W.object({id:W.string(),sessionId:W.string(),interfaceType:W.string(),channelId:W.string(),channelName:W.string().optional(),startedAt:W.string(),lastActiveAt:W.string(),createdAt:W.string(),updatedAt:W.string(),metadata:n1}),WI=W.object({id:W.string(),conversationId:W.string(),role:k6,content:W.string(),timestamp:W.string(),metadata:n1});function YI($){let U=k6.safeParse($);return U.success?U.data:"user"}function l0($){let U=VD($.metadata),G=typeof U.channelName==="string"?U.channelName:void 0;return{id:$.id,sessionId:$.sessionId,interfaceType:$.interfaceType,channelId:$.channelId,channelName:G,startedAt:$.started,lastActiveAt:$.lastActive,createdAt:$.created,updatedAt:$.updated,metadata:U}}function n3($){return{id:$.id,conversationId:$.conversationId,role:YI($.role),content:$.content,timestamp:$.timestamp,metadata:VD($.metadata)}}var XJ=W.object({name:W.string(),role:W.string(),purpose:W.string(),values:W.array(W.string())}),VJ=W.object({name:W.string(),kind:W.enum(["professional","team","collective"]),organization:W.string().optional(),description:W.string().optional(),avatar:W.string().optional(),website:W.string().optional(),email:W.string().optional(),socialLinks:W.array(W.object({platform:W.enum(["github","instagram","linkedin","email","website"]),url:W.string(),label:W.string().optional()})).optional()});function c3($){return XJ.parse($)}function d3($){return VJ.parse($)}function o3($){return async()=>{return p3(await $.getAppInfo())}}function a3($,U){return{get:()=>c3($.getIdentity()),getProfile:()=>d3($.getProfile()),getAppInfo:U}}function s3($,U,G){let X=$.getMessageBus();return{send:async(V)=>{return X.send({...V,sender:U})},subscribe:(V,Z)=>{if(f3(V)){let J=V,P=Z,Y=async(w)=>{let K=J.schema.safeParse(w.payload);if(!K.success)return G.warn(`Invalid payload for channel ${J.name}`,{error:K.error.message}),{noop:!0};let{payload:q,...O}=w;return P(K.data,O)};return X.subscribe(J.name,Y)}return X.subscribe(V,Z)}}}function t3($,U){let G=$.getJobQueueService();return{...$.jobs,enqueue:UJ(G,U,!0),enqueueBatch:DJ($.jobs,U),registerHandler:GJ(G,U)}}function e3($){let U=$.getPermissionService();return{assertEntityActionAllowed:(G,X,D)=>{U.assertEntityActionAllowed(G,X,D.userPermissionLevel)}}}function $K($){return{get:async(U)=>{let X=await $.getConversationService().getConversation(U);return X?l0(X):null},search:async(U)=>{return(await $.getConversationService().searchConversations(U)).map(l0)},list:async(U)=>{return(await $.getConversationService().listConversations(U)).map(l0)},getMessages:async(U,G)=>{return(await $.getConversationService().getMessages(U,G)).map(n3)},countMessages:async(U)=>{return $.getConversationService().countMessages(U)}}}function UK($,U){return{registerHandler:(G,X)=>{$.registerEvalHandler(U,G,X)}}}function DK($){return{register:(U,G)=>{$.getInsightsRegistry().register(U,G)}}}function GK($,U){return{register:(G)=>{$.registerEndpoint({...G,pluginId:U})}}}function XK($,U){return{register:(G)=>{$.registerInteraction({...G,pluginId:U})}}}function c1($,U,G){let X=$.getEntityService(),D=$.getLogger().child(U),V=$.getDomain(),Z=$.getLocalSiteUrl(),J=$.shouldPreferLocalUrls(),P=$.getThemeCSS(),Y=o3($),w=$.getAttachmentRegistry(),K=$.getRuntimeUploadRegistry(),q=$.getRuntimeState();return{pluginId:U,logger:D,entityService:X,identity:a3($,Y),appInfo:Y,judge:(O)=>$.judge(O),domain:V,siteUrl:V?`https://${V}`:void 0,localSiteUrl:Z,previewUrl:V?`https://${mZ(V)}`:void 0,preferLocalUrls:J,themeCSS:P,entityDisplay:G?.entityDisplay,spaces:$.getSpaces(),permissions:e3($),messaging:s3($,U,D),jobs:t3($,U),attachments:w,uploads:K,runtimeState:q,conversations:$K($),dataDir:$.getDataDir(),eval:UK($,U),insights:DK($),endpoints:GK($,U),interactions:XK($,U)}}import{createClient as Bn}from"@libsql/client";var i0=f4("entities",{id:O$("id").notNull(),entityType:O$("entityType").notNull(),content:O$("content").notNull(),contentHash:O$("contentHash").notNull(),visibility:O$("visibility",{enum:["public","shared","restricted"]}).notNull().default("public"),metadata:O$("metadata",{mode:"json"}).$type().notNull().default(i6`'{}'`),created:P4("created").notNull().$defaultFn(()=>Date.now()),updated:P4("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:m0({columns:[$.id,$.entityType]}),visibilityCheck:b3("entities_visibility_check",i6`${$.visibility} IN ('public', 'shared', 'restricted')`)}});import{createClient as Cn}from"@libsql/client";var VK=r0({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var n0=f4("embeddings",{entityId:O$("entity_id").notNull(),entityType:O$("entity_type").notNull(),embedding:VK("embedding").notNull(),contentHash:O$("content_hash").notNull()},($)=>{return{pk:m0({columns:[$.entityId,$.entityType]})}});var PI=W.enum(["public","shared","restricted"]),ZD=W.union([PI,W.literal("private")]).optional().transform(($)=>{if($===void 0)return"public";if($==="private")return"restricted";return $});function c0($){if($==="anchor")return"restricted";if($==="trusted")return"shared";return"public"}var JJ=W.object({id:W.string(),entityType:W.string(),content:W.string(),created:W.string().datetime(),updated:W.string().datetime(),visibility:ZD,metadata:W.record(W.string(),W.unknown()),contentHash:W.string()}),KI=W.enum(["public","shared","restricted"]),OI=W.object({id:W.string(),entityType:W.string(),content:W.string(),created:W.string().datetime(),updated:W.string().datetime(),visibility:W.union([KI,W.literal("private")]).optional().transform(($)=>{if($===void 0)return"public";if($==="private")return"restricted";return $}),metadata:W.record(W.string(),W.unknown()),contentHash:W.string()}),JK=W.object({}),qI=W.object({mediaType:W.string(),url:W.string(),downloadUrl:W.string().optional(),previewUrl:W.string().optional(),filename:W.string().optional(),sizeBytes:W.number().optional(),source:W.object({entityType:W.string().optional(),entityId:W.string().optional(),attachmentType:W.string().optional()}).optional()});var on=W.object({id:W.string().min(1,"Entity ID is required"),entityType:W.string().min(1,"Entity type is required"),contentHash:W.string().min(1,"Content hash is required"),operation:W.enum(["create","update"])});var $c=W.object({limit:W.number().int().positive().optional().default(20),offset:W.number().int().min(0).optional().default(0),types:W.array(W.string()).optional().default([]),excludeTypes:W.array(W.string()).optional().default([]),weight:W.record(W.string(),W.number()).optional(),visibilityScope:W.enum(["public","shared","restricted"]).optional(),includeUngenerated:W.boolean().optional().default(!1),minScore:W.number().min(0).optional()}),Uc=W.preprocess(($)=>{if(typeof $!=="string")return $;return JSON.parse($)},W.record(W.string(),W.unknown()));var jJ=ND(gJ(),1);function ZG($,U){if(Object.keys(U).length===0)return $;let G=Object.fromEntries(Object.entries(U).filter(([,X])=>X!==void 0));return jJ.default.stringify($,G)}function SJ($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(SJ);if($!==null&&typeof $==="object"){let U={};for(let[G,X]of Object.entries($))U[G]=SJ(X);return U}return $}function qD($,U){let{content:G,data:X}=jJ.default($),D=SJ(X);return{content:G.trim(),metadata:U.parse(D)}}var ic=W.object({visibility:W.enum(["public","shared","restricted","private"]).optional().transform(($)=>{if($===void 0)return"public";return $==="private"?"restricted":$})});var oc=W.looseObject({issues:W.array(W.looseObject({message:W.string()}))});var Gd=W.record(W.string(),W.unknown());var Mz=W.object({field:W.string(),direction:W.enum(["asc","desc"]),nullsFirst:W.boolean().optional()}),Hd=W.object({limit:W.number().int().positive().optional(),offset:W.number().int().min(0).optional().default(0),sortFields:W.array(Mz).optional(),filter:W.object({metadata:W.record(W.string(),W.unknown()).optional(),visibilityScope:W.enum(["public","shared","restricted"]).optional()}).optional(),publishedOnly:W.boolean().optional()});var Nd=W.custom(($)=>typeof $==="object"&&$!==null&&!Array.isArray($));var Md=W.object({id:W.string().min(1),entityType:W.string().min(1),contentHash:W.string().min(1)});var Sz=ND(gJ(),1);var cd=E0();var Go=W.record(W.string(),W.unknown());var kz=W.object({currentPage:W.number(),totalPages:W.number(),totalItems:W.number(),pageSize:W.number(),hasNextPage:W.boolean(),hasPrevPage:W.boolean()});function xz($){return $.replace(/:/g,"-")}function bz($){return $.split(/[:.-]/).map((U)=>U.charAt(0).toUpperCase()+U.slice(1)).join(" ")}var EJ=new Map;async function Tq($,U,G){let X=EJ.get(U);if(X!==void 0)return X;let D=xz(U),V;try{V=await $.getEntity({entityType:"prompt",id:D})}catch{return G}if(V?.content){let Z=qD(V.content,W.record(W.string(),W.unknown())).content;return EJ.set(U,Z),Z}try{let Z=bz(U),J=ZG(G,{title:Z,target:U});await $.createEntity({entity:{id:D,entityType:"prompt",content:J,metadata:{title:Z,target:U,slug:D}}})}catch{}return EJ.set(U,G),G}function JG($){let U=$.getEntityService(),G=$.getEntityRegistry(),X=$.getDataSourceRegistry();return{register:(D,V,Z,J)=>{G.registerEntityType(D,V,Z,J)},getAdapter:(D)=>{try{return G.getAdapter(D)}catch{return}},extendFrontmatterSchema:(D,V)=>{G.extendFrontmatterSchema(D,V)},getEffectiveFrontmatterSchema:(D)=>{return G.getEffectiveFrontmatterSchema(D)},registerCreateInterceptor:(D,V)=>{G.registerCreateInterceptor(D,V)},registerUploadSaveHandler:(D)=>{G.registerUploadSaveHandler(D)},update:async(D)=>{return U.updateEntity({entity:D})},registerDataSource:(D)=>{X.register(D)}}}function WG($){return{resolve:(U,G)=>{return Tq($,U,G)}}}function zq($,U,G){let X=c1($,U,G),D=$.getEntityService();return{...X,entityService:D,entities:JG($),ai:{query:(V,Z)=>$.query(V,Z),generate:async(V)=>{return $.generateContent(V)},generateObject:async(V,Z)=>{return $.generateObject(V,Z)},generateImage:async(V,Z)=>{return $.generateImage(V,Z)},canGenerateImages:()=>{return $.canGenerateImages()}},prompts:WG(D),permissions:X.permissions}}function gq($,U,G){let X=!1,D=!1;if($.jobs.registerHandler(G.job.type,G.job.handler),G.initialSync){let V=G.initialSync;$.messaging.subscribe("sync:initial:completed",async()=>{if(X)return{success:!0};if(X=!0,!(await V.shouldEnqueue?.()??!0))return U.info("Skipping derived entity projection initial sync",{projectionId:G.id,targetType:G.targetType}),{success:!0};return D=await Lq($,U,G,V.jobData,uz(V.jobOptions),"initial-sync"),{success:!0}})}if(G.sourceChange){let V=G.sourceChange,Z=new Set(V.sourceTypes),J=V.events??["entity:created","entity:updated"],P=async(Y)=>{if(V.requireInitialSync&&!X)return{success:!0};let w=Y.payload,K=rz(V,w);if(!K||!Z.has("*")&&!Z.has(K))return{success:!0};if(!(await V.shouldEnqueue?.(w)??!0))return{success:!0};let O=await V.jobData(w);if(!O)return{success:!0};return await Lq($,U,G,O,V.jobOptions?.(w),"source-change"),{success:!0}};for(let Y of J)$.messaging.subscribe(Y,P)}return{hasObservedInitialSync:()=>X,hasQueuedInitialSync:()=>D}}function rz($,U){if($.sourceType)return $.sourceType;if($.sourceKind&&$.sourceKind!=="entity")return $.sourceKind;return U.entityType}async function Lq($,U,G,X,D,V){try{return await $.jobs.enqueue({type:G.job.type,data:X,...D?{options:D}:{}}),U.info("Queued derived entity projection",{projectionId:G.id,targetType:G.targetType,reason:V}),!0}catch(Z){return U.error("Failed to queue derived entity projection",{projectionId:G.id,targetType:G.targetType,reason:V,error:m4(Z)}),!1}}function uz($){return typeof $==="function"?$():$}var wa=W.object({});class YG extends C6{type="entity";entityActionPolicy;derivedEntityProjectionControllers=new Map;constructor($,U,G,X,D){super($,U,G,X);if(D!==void 0)this.entityActionPolicy=D}async register($,U){let G=zq($,this.id,U);if(this.context=G,this.setupMessageHandlers(G),G.entities.register(this.entityType,this.schema,this.adapter,this.getEntityTypeConfig()),this.interceptCreate!==YG.prototype.interceptCreate)G.entities.registerCreateInterceptor(this.entityType,(P,Y)=>this.interceptCreate(P,Y,G));let X=this.createGenerationHandler(G);if(X)G.jobs.registerHandler(`${this.entityType}:generation`,X);let D=this.getTemplates();if(D&&Object.keys(D).length>0)$.registerTemplates(D,this.id);let V=this.getDataSources();for(let P of V)G.entities.registerDataSource(P);let Z=this.getDerivedEntityProjections(G);for(let P of Z){let Y=gq(G,this.logger,P);this.derivedEntityProjectionControllers.set(P.id,Y)}await this.onRegister(this.context);let J=await this.getInstructions();return{tools:[],resources:[],...J&&{instructions:J}}}async interceptCreate($,U,G){return{kind:"continue",input:$}}createGenerationHandler($){return null}getTemplates(){return null}getDataSources(){return[]}getEntityTypeConfig(){return}getDerivedEntityProjections($){return[]}getDerivedEntityProjectionController($){return this.derivedEntityProjectionControllers.get($)}}class Sq extends YG{hooks;constructor($,U,G,X,D){super($,U,G,X);this.hooks=D}get entityType(){return this.hooks.getEntityType()}get schema(){return this.hooks.getSchema()}get adapter(){return this.hooks.getAdapter()}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getEntityTypeConfig(){return this.hooks.getEntityTypeConfig()}getDataSources(){return this.hooks.getDataSources()}getInstructions(){return this.hooks.getInstructions()}interceptCreate($,U,G){return this.hooks.interceptCreate($,U,G)}}class CJ{type="entity";id;version;packageName;description;delegate;constructor($,U,G,X){if(this.id=$,this.version=U.version,this.packageName=U.name,U.description!==void 0)this.description=U.description;this.delegate=new Sq($,U,G,X,{getEntityType:()=>this.entityType,getSchema:()=>this.schema,getAdapter:()=>this.adapter,onRegister:(D)=>this.onRegister(D),onReady:(D)=>this.onReady(D),onShutdown:()=>this.onShutdown(),getEntityTypeConfig:()=>this.getEntityTypeConfig(),getDataSources:()=>this.getDataSources(),getInstructions:()=>this.getInstructions(),interceptCreate:(D,V,Z)=>this.interceptCreate(D,V,Z)})}register($,U){return this.delegate.register($,U)}async onRegister($){}async onReady($){}async onShutdown(){}async getInstructions(){return}getEntityTypeConfig(){return}getDataSources(){return[]}async interceptCreate($,U,G){return{kind:"continue",input:$}}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function jq($){return RV($)}function Eq($){if(!$)return;return{...$.userPermissionLevel&&{userPermissionLevel:$.userPermissionLevel},...$.interfaceType&&{interfaceType:$.interfaceType},...$.channelId&&{channelId:$.channelId},...$.channelName&&{channelName:$.channelName},...$.actor&&{actor:$.actor},...$.source&&{source:$.source},...$.attachments&&{attachments:$.attachments}}}function Cq($){return{chat:async(U,G,X)=>{return jq(await $.chat(U,G,Eq(X)))},confirmPendingAction:async(U,G,X,D)=>{let V=Eq(D);if(!V)throw Error("Confirmation requires caller context.");return jq(await $.confirmPendingAction(U,G,X,V))},invalidate:()=>{$.invalidateAgent()}}}function kq($,U,G){let X=c1($,U,G),D=$.getMCPService(),V=$.getPermissionService(),Z=Cq($.getAgentService());return{...X,mcpTransport:D,agent:Z,permissions:{...X.permissions,getUserLevel:(J,P,Y)=>{return V.determineUserLevel(J,P,Y)}},daemons:{register:(J,P)=>{let Y=`${U}:${J}`;$.registerDaemon(Y,P,U),X.logger.debug(`Registered daemon: ${Y}`)}},conversations:{...X.conversations,start:async(J)=>{return $.getConversationService().startConversation(J)},addMessage:async(J)=>{await $.getConversationService().addMessage(J)},updateMetadata:async(J)=>{return $.getConversationService().updateConversationMetadata(J)},delete:async(J)=>{return $.getConversationService().deleteConversation(J)}},tools:{listForPermissionLevel:(J)=>{return $.listToolsForPermissionLevel(J)}},apiRoutes:{getRoutes:()=>{return $.getPluginApiRoutes()},getMessageBus:()=>{return $.getMessageBus()}},webRoutes:{getRoutes:()=>{return $.getPluginWebRoutes()}},plugins:{has:(J)=>$.hasPlugin(J)}}}var hz=3600000;class AD extends C6{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=hz;async register($,U){let G=kq($,this.id,U);if(this.context=G,this.initializeDaemon(),this.daemon)await this.registerDaemon(G);return this.setupMessageHandlers(G),await this.onRegister(G),this.getCapabilities()}async onRegister($){}async registerDaemon($){if(!this.daemon)return;$.daemons.register(this.id,this.daemon),$.logger.debug(`Registered daemon for interface: ${this.id}`)}createDaemon(){return}requiresDaemonStartup(){return!1}getWebRoutes(){return[]}initializeDaemon(){let $=this.createDaemon();if($)this.daemon=$}async handleProgressEvent($,U){}cleanupExpiredEntries(){let $=Date.now(),U=[];for(let[G,X]of this.jobTrackingEntries)if($-X.createdAt>this.jobTrackingTtlMs)U.push(G);for(let G of U)this.jobTrackingEntries.delete(G)}ownsJob($,U){return this.jobTrackingEntries.has($)||U!==void 0&&this.jobTrackingEntries.has(U)}getJobTracking($,U){let G=this.jobTrackingEntries.get($);if(G)return G.info;if(U){let X=this.jobTrackingEntries.get(U);if(X)return X.info}return}setJobTracking($,U){this.cleanupExpiredEntries(),this.jobTrackingEntries.set($,{info:U,createdAt:Date.now()})}removeJobTracking($){this.jobTrackingEntries.delete($)}async createJobWithTracking($,U){let X=await this.getContext().jobs.enqueue($);return this.setJobTracking(X,U),X}async createBatchWithTracking($,U,G){let D=await this.getContext().jobs.enqueueBatch($,G);return this.setJobTracking(D,U),D}}class xq extends AD{hooks;constructor($,U,G,X,D){super($,U,G,X);this.hooks=D}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getTools(){return this.hooks.getTools()}getResources(){return this.hooks.getResources()}getInstructions(){return this.hooks.getInstructions()}getWebRoutes(){return this.hooks.getWebRoutes()}requiresDaemonStartup(){return this.hooks.requiresDaemonStartup()}}class _D{type="interface";id;version;packageName;description;delegate;constructor($,U,G,X){if(this.id=$,this.version=U.version,this.packageName=U.name,U.description!==void 0)this.description=U.description;this.delegate=new xq($,U,G,X,{onRegister:(D)=>this.onRegister(D),onReady:(D)=>this.onReady(D),onShutdown:()=>this.onShutdown(),getTools:()=>this.getTools(),getResources:()=>this.getResources(),getInstructions:()=>this.getInstructions(),getWebRoutes:()=>this.getWebRoutes(),requiresDaemonStartup:()=>this.requiresDaemonStartup()})}register($,U){return this.delegate.register($,U)}async onRegister($){}async onReady($){}async onShutdown(){}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}getWebRoutes(){return[]}requiresDaemonStartup(){return!1}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function bq($,U){$.messaging.subscribe("job-progress",async(G)=>{try{let X=pZ.safeParse(G.payload);if(!X.success)return U.onInvalidSchema(),{success:!1};let D=X.data;return await U.onProgress(D,D.metadata),{success:!0}}catch(X){return U.onError(X),{success:!1}}})}function rq($){let U=$.status==="completed"?"\u2705":"\u274C",G=$.status==="completed"?"completed":"failed",X=$.metadata.operationType.replace(/_/g," "),D=$.metadata.operationTarget?`: ${$.metadata.operationTarget}`:"",V=`${U} **${X}${D}** ${G}`;if($.message)V+=`
|
|
188
|
+
`;return""}return uZ.dump=u,uZ}var Nw;function EQ(){if(Nw)return e$;Nw=1;let $=SQ(),U=jQ();function G(X,D){return function(){throw Error("Function yaml."+X+" is removed in js-yaml 4. Use yaml."+D+" instead, which is now safe by default.")}}return e$.Type=W4(),e$.Schema=Mw(),e$.FAILSAFE_SCHEMA=vw(),e$.JSON_SCHEMA=Sw(),e$.CORE_SCHEMA=jw(),e$.DEFAULT_SCHEMA=hZ(),e$.load=$.load,e$.loadAll=$.loadAll,e$.dump=U.dump,e$.YAMLException=$D(),e$.types={binary:kw(),float:gw(),map:Bw(),null:Tw(),pairs:bw(),set:rw(),timestamp:Ew(),bool:zw(),int:Lw(),merge:Cw(),omap:xw(),seq:Iw(),str:Qw()},e$.safeLoad=G("safeLoad","load"),e$.safeLoadAll=G("safeLoadAll","loadAll"),e$.safeDump=G("safeDump","dump"),e$}var qy=EQ();var _y=W.record(W.string(),W.unknown());var py=W.object({slug:W.string(),title:W.string(),type:W.string(),entityId:W.string(),contentHash:W.string()});function mZ($){return`preview.${$.trim().replace(/^https?:\/\//,"")}`}var CQ=W.string(),kQ=W.looseObject({id:W.string().min(1)}),xQ=W.looseObject({label:W.string().min(1)}),bQ=W.looseObject({layouts:W.record(W.string(),W.unknown()),plugin:W.custom(($)=>typeof $==="function").optional(),routes:W.array(kQ),entityDisplay:W.record(W.string(),xQ),content:W.unknown().optional(),themeOverride:W.string().optional(),headScripts:W.array(W.string()).optional(),staticAssets:W.record(W.string(),W.string()).optional()}),rQ=W.custom(($)=>bQ.safeParse($).success);import{webcrypto as mw}from"crypto";var hw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var uQ=128,w6,p1;function hQ($){if($<0)throw RangeError("Wrong ID size");try{if(!w6||w6.length<$)w6=Buffer.allocUnsafe($*uQ),mw.getRandomValues(w6),p1=0;else if(p1+$>w6.length)mw.getRandomValues(w6),p1=0}catch(U){throw w6=void 0,U}p1+=$}function yw($=21){hQ($|=0);let U="";for(let G=p1-$;G<p1;G++)U+=hw[w6[G]&63];return U}function l6($=12){return yw($)}var yZ=W.enum(["file_operations","content_operations","data_processing","batch_processing"]),mQ=W.object({pluginId:W.string().optional(),progressToken:W.union([W.string(),W.number()]).optional(),operationType:yZ,operationTarget:W.string().optional(),interfaceType:W.string().optional(),conversationId:W.string().optional(),channelId:W.string().optional(),silent:W.boolean().optional()}),l1=W.object({pluginId:W.string().optional(),progressToken:W.union([W.string(),W.number()]).optional(),operationType:yZ,operationTarget:W.string().optional(),interfaceType:W.string().optional(),conversationId:W.string().optional(),channelId:W.string().optional(),silent:W.boolean().optional(),rootJobId:W.string()}),Tf=W.enum(["none","skip","replace","coalesce"]);var fZ=W.enum(["pending","processing","completed","failed"]),fw=W.enum(["completed","failed"]);var yQ=W.object({id:W.string(),type:W.string(),status:fZ,data:W.unknown(),result:W.unknown().optional(),lastError:W.string().optional().nullable(),attempts:W.number(),maxRetries:W.number(),priority:W.number(),createdAt:W.date(),updatedAt:W.date(),processedAt:W.date().optional().nullable(),completedAt:W.date().optional().nullable(),failedAt:W.date().optional().nullable()}),fQ=W.object({jobId:W.string(),type:W.string(),status:fw,result:W.unknown().optional(),error:W.string().optional()}),pw=W.object({success:W.literal(!1),error:W.string().optional()}),pZ=W.object({id:W.string(),type:W.enum(["job","batch"]),status:fZ,message:W.string().optional(),progress:W.object({current:W.number(),total:W.number(),percentage:W.number()}).optional(),aggregationKey:W.string().optional(),batchDetails:W.object({totalOperations:W.number(),completedOperations:W.number(),failedOperations:W.number(),currentOperation:W.string().optional(),errors:W.array(W.string()).optional()}).optional(),jobDetails:W.object({jobType:W.string(),priority:W.number(),retryCount:W.number()}).optional(),metadata:l1});import{createClient as Fl}from"@libsql/client";var a=Symbol.for("drizzle:entityKind");function Y4($,U){if(!$||typeof $!=="object")return!1;if($ instanceof U)return!0;if(!Object.prototype.hasOwnProperty.call(U,a))throw Error(`Class "${U.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 G=Object.getPrototypeOf($).constructor;if(G)while(G){if(a in G&&G[a]===U[a])return!0;G=Object.getPrototypeOf(G)}return!1}class K6{constructor($,U){this.table=$,this.config=U,this.name=U.name,this.keyAsName=U.keyAsName,this.notNull=U.notNull,this.default=U.default,this.defaultFn=U.defaultFn,this.onUpdateFn=U.onUpdateFn,this.hasDefault=U.hasDefault,this.primary=U.primaryKey,this.isUnique=U.isUnique,this.uniqueName=U.uniqueName,this.uniqueType=U.uniqueType,this.dataType=U.dataType,this.columnType=U.columnType,this.generated=U.generated,this.generatedIdentity=U.generatedIdentity}static[a]="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($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class lZ{static[a]="ColumnBuilder";config;constructor($,U,G){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:U,columnType:G,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}var E4=Symbol.for("drizzle:Name");function lw($,...U){return $(...U)}function iw($,U){return`${$[E4]}_${U.join("_")}_unique`}class UD extends K6{constructor($,U){if(!U.uniqueName)U.uniqueName=iw($,[U.name]);super($,U);this.table=$}static[a]="PgColumn"}class pQ extends UD{static[a]="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($){return this.indexConfig.opClass=$,this}}class lQ extends UD{static[a]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,U){super($,U);this.enum=U.enum}getSQLType(){return this.enum.enumName}}var nw=Symbol.for("drizzle:isPgEnum");function cw($){return!!$&&typeof $==="function"&&nw in $&&$[nw]===!0}class iQ extends UD{static[a]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,U){super($,U);this.enum=U.enum}getSQLType(){return this.enum.enumName}}class k0{static[a]="Subquery";constructor($,U,G,X=!1,D=[]){this._={brand:"Subquery",sql:$,selectedFields:U,alias:G,isWith:X,usedTables:D}}}var dw="0.45.2";var iZ,nZ,ow={startActiveSpan($,U){if(!iZ)return U();if(!nZ)nZ=iZ.trace.getTracer("drizzle-orm",dw);return lw((G,X)=>X.startActiveSpan($,(D)=>{try{return U(D)}catch(V){throw D.setStatus({code:G.SpanStatusCode.ERROR,message:V instanceof Error?V.message:"Unknown error"}),V}finally{D.end()}}),iZ,nZ)}};var i1=Symbol.for("drizzle:ViewBaseConfig");var cZ=Symbol.for("drizzle:Schema"),aw=Symbol.for("drizzle:Columns"),sw=Symbol.for("drizzle:ExtraConfigColumns"),dZ=Symbol.for("drizzle:OriginalName"),oZ=Symbol.for("drizzle:BaseName"),DD=Symbol.for("drizzle:IsAlias"),tw=Symbol.for("drizzle:ExtraConfigBuilder"),nQ=Symbol.for("drizzle:IsDrizzleTable");class x${static[a]="Table";static Symbol={Name:E4,Schema:cZ,OriginalName:dZ,Columns:aw,ExtraConfigColumns:sw,BaseName:oZ,IsAlias:DD,ExtraConfigBuilder:tw};[E4];[dZ];[cZ];[aw];[sw];[oZ];[DD]=!1;[nQ]=!0;[tw]=void 0;constructor($,U,G){this[E4]=this[dZ]=$,this[cZ]=U,this[oZ]=G}}function cQ($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function dQ($){let U={sql:"",params:[]};for(let G of $)if(U.sql+=G.sql,U.params.push(...G.params),G.typings?.length){if(!U.typings)U.typings=[];U.typings.push(...G.typings)}return U}class z4{static[a]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new b$([this])}}class b${constructor($){this.queryChunks=$;for(let U of $)if(Y4(U,x$)){let G=U[x$.Symbol.Schema];this.usedTables.push(G===void 0?U[x$.Symbol.Name]:G+"."+U[x$.Symbol.Name])}}static[a]="SQL";decoder=ew;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return ow.startActiveSpan("drizzle.buildSQL",(U)=>{let G=this.buildQueryFromSourceParams(this.queryChunks,$);return U?.setAttributes({"drizzle.query.text":G.sql,"drizzle.query.params":JSON.stringify(G.params)}),G})}buildQueryFromSourceParams($,U){let G=Object.assign({},U,{inlineParams:U.inlineParams||this.shouldInlineParams,paramStartIndex:U.paramStartIndex||{value:0}}),{casing:X,escapeName:D,escapeParam:V,prepareTyping:Z,inlineParams:J,paramStartIndex:P}=G;return dQ($.map((Y)=>{if(Y4(Y,z4))return{sql:Y.value.join(""),params:[]};if(Y4(Y,x0))return{sql:D(Y.value),params:[]};if(Y===void 0)return{sql:"",params:[]};if(Array.isArray(Y)){let w=[new z4("(")];for(let[K,q]of Y.entries())if(w.push(q),K<Y.length-1)w.push(new z4(", "));return w.push(new z4(")")),this.buildQueryFromSourceParams(w,G)}if(Y4(Y,b$))return this.buildQueryFromSourceParams(Y.queryChunks,{...G,inlineParams:J||Y.shouldInlineParams});if(Y4(Y,x$)){let w=Y[x$.Symbol.Schema],K=Y[x$.Symbol.Name];return{sql:w===void 0||Y[DD]?D(K):D(w)+"."+D(K),params:[]}}if(Y4(Y,K6)){let w=X.getColumnCasing(Y);if(U.invokeSource==="indexes")return{sql:D(w),params:[]};let K=Y.table[x$.Symbol.Schema];return{sql:Y.table[DD]||K===void 0?D(Y.table[x$.Symbol.Name])+"."+D(w):D(K)+"."+D(Y.table[x$.Symbol.Name])+"."+D(w),params:[]}}if(Y4(Y,U3)){let w=Y[i1].schema,K=Y[i1].name;return{sql:w===void 0||Y[i1].isAlias?D(K):D(w)+"."+D(K),params:[]}}if(Y4(Y,aZ)){if(Y4(Y.value,b0))return{sql:V(P.value++,Y),params:[Y],typings:["none"]};let w=Y.value===null?null:Y.encoder.mapToDriverValue(Y.value);if(Y4(w,b$))return this.buildQueryFromSourceParams([w],G);if(J)return{sql:this.mapInlineParam(w,G),params:[]};let K=["none"];if(Z)K=[Z(Y.encoder)];return{sql:V(P.value++,w),params:[w],typings:K}}if(Y4(Y,b0))return{sql:V(P.value++,Y),params:[Y],typings:["none"]};if(Y4(Y,b$.Aliased)&&Y.fieldAlias!==void 0)return{sql:D(Y.fieldAlias),params:[]};if(Y4(Y,k0)){if(Y._.isWith)return{sql:D(Y._.alias),params:[]};return this.buildQueryFromSourceParams([new z4("("),Y._.sql,new z4(") "),new x0(Y._.alias)],G)}if(cw(Y)){if(Y.schema)return{sql:D(Y.schema)+"."+D(Y.enumName),params:[]};return{sql:D(Y.enumName),params:[]}}if(cQ(Y)){if(Y.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([Y.getSQL()],G);return this.buildQueryFromSourceParams([new z4("("),Y.getSQL(),new z4(")")],G)}if(J)return{sql:this.mapInlineParam(Y,G),params:[]};return{sql:V(P.value++,Y),params:[Y],typings:["none"]}}))}mapInlineParam($,{escapeString:U}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return U($);if(typeof $==="object"){let G=$.toString();if(G==="[object Object]")return U(JSON.stringify($));return U(G)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new b$.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class x0{constructor($){this.value=$}static[a]="Name";brand;getSQL(){return new b$([this])}}var ew={mapFromDriverValue:($)=>$},$3={mapToDriverValue:($)=>$},wp={...ew,...$3};class aZ{constructor($,U=$3){this.value=$,this.encoder=U}static[a]="Param";brand;getSQL(){return new b$([this])}}function i6($,...U){let G=[];if(U.length>0||$.length>0&&$[0]!=="")G.push(new z4($[0]));for(let[X,D]of U.entries())G.push(D,new z4($[X+1]));return new b$(G)}(($)=>{function U(){return new b$([])}$.empty=U;function G(P){return new b$(P)}$.fromList=G;function X(P){return new b$([new z4(P)])}$.raw=X;function D(P,Y){let w=[];for(let[K,q]of P.entries()){if(K>0&&Y!==void 0)w.push(Y);w.push(q)}return new b$(w)}$.join=D;function V(P){return new x0(P)}$.identifier=V;function Z(P){return new b0(P)}$.placeholder=Z;function J(P,Y){return new aZ(P,Y)}$.param=J})(i6||(i6={}));(($)=>{class U{constructor(G,X){this.sql=G,this.fieldAlias=X}static[a]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new U(this.sql,this.fieldAlias)}}$.Aliased=U})(b$||(b$={}));class b0{constructor($){this.name=$}static[a]="Placeholder";getSQL(){return new b$([this])}}var oQ=Symbol.for("drizzle:IsDrizzleView");class U3{static[a]="View";[i1];[oQ]=!0;constructor({name:$,schema:U,selectedFields:G,query:X}){this[i1]={name:$,originalName:$,schema:U,selectedFields:G,query:X,isExisting:!X,isAlias:!1}}getSQL(){return new b$([this])}}K6.prototype.getSQL=function(){return new b$([this])};x$.prototype.getSQL=function(){return new b$([this])};k0.prototype.getSQL=function(){return new b$([this])};function y4($,U){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:U}}var sZ=typeof TextDecoder>"u"?null:new TextDecoder;class tZ{static[a]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,U){if(this.reference=()=>{let{name:G,columns:X,foreignColumns:D}=$();return{name:G,columns:X,foreignTable:D[0].table,foreignColumns:D}},U)this._onUpdate=U.onUpdate,this._onDelete=U.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new D3($,this)}}class D3{constructor($,U){this.table=$,this.reference=U.reference,this.onUpdate=U._onUpdate,this.onDelete=U._onDelete}static[a]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:U,foreignColumns:G}=this.reference(),X=U.map((Z)=>Z.name),D=G.map((Z)=>Z.name),V=[this.table[E4],...X,G[0].table[E4],...D];return $??`${V.join("_")}_fk`}}function G3($,U){return`${$[E4]}_${U.join("_")}_unique`}class f$ extends lZ{static[a]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,U={}){return this.foreignKeyConfigs.push({ref:$,actions:U}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,U){return this.config.generated={as:$,type:"always",mode:U?.mode??"virtual"},this}buildForeignKeys($,U){return this.foreignKeyConfigs.map(({ref:G,actions:X})=>{return((D,V)=>{let Z=new tZ(()=>{let J=D();return{columns:[$],foreignColumns:[J]}});if(V.onUpdate)Z.onUpdate(V.onUpdate);if(V.onDelete)Z.onDelete(V.onDelete);return Z.build(U)})(G,X)})}}class p$ extends K6{constructor($,U){if(!U.uniqueName)U.uniqueName=G3($,[U.name]);super($,U);this.table=$}static[a]="SQLiteColumn"}class X3 extends f${static[a]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new V3($,this.config)}}class V3 extends p${static[a]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let U=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return BigInt(U.toString("utf8"))}return BigInt(sZ.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class Z3 extends f${static[a]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new J3($,this.config)}}class J3 extends p${static[a]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let U=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return JSON.parse(U.toString("utf8"))}return JSON.parse(sZ.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class W3 extends f${static[a]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Y3($,this.config)}}class Y3 extends p${static[a]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}function P3($,U){let{name:G,config:X}=y4($,U);if(X?.mode==="json")return new Z3(G);if(X?.mode==="bigint")return new X3(G);return new W3(G)}class H3 extends f${static[a]="SQLiteCustomColumnBuilder";constructor($,U,G){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=U,this.config.customTypeParams=G}build($){return new w3($,this.config)}}class w3 extends p${static[a]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,U){super($,U);this.sqlName=U.customTypeParams.dataType(U.fieldConfig),this.mapTo=U.customTypeParams.toDriver,this.mapFrom=U.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function r0($){return(U,G)=>{let{name:X,config:D}=y4(U,G);return new H3(X,D,$)}}class u0 extends f${static[a]="SQLiteBaseIntegerBuilder";constructor($,U,G){super($,U,G);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class h0 extends p${static[a]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class K3 extends u0{static[a]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new O3($,this.config)}}class O3 extends h0{static[a]="SQLiteInteger"}class q3 extends u0{static[a]="SQLiteTimestampBuilder";constructor($,U){super($,"date","SQLiteTimestamp");this.config.mode=U}defaultNow(){return this.default(i6`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new A3($,this.config)}}class A3 extends h0{static[a]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let U=$.getTime();if(this.config.mode==="timestamp")return Math.floor(U/1000);return U}}class _3 extends u0{static[a]="SQLiteBooleanBuilder";constructor($,U){super($,"boolean","SQLiteBoolean");this.config.mode=U}build($){return new F3($,this.config)}}class F3 extends h0{static[a]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function P4($,U){let{name:G,config:X}=y4($,U);if(X?.mode==="timestamp"||X?.mode==="timestamp_ms")return new q3(G,X.mode);if(X?.mode==="boolean")return new _3(G,X.mode);return new K3(G)}class R3 extends f${static[a]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new N3($,this.config)}}class N3 extends p${static[a]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class M3 extends f${static[a]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Q3($,this.config)}}class Q3 extends p${static[a]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class I3 extends f${static[a]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new B3($,this.config)}}class B3 extends p${static[a]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function v3($,U){let{name:G,config:X}=y4($,U),D=X?.mode;return D==="number"?new M3(G):D==="bigint"?new I3(G):new R3(G)}class T3 extends f${static[a]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new z3($,this.config)}}class z3 extends p${static[a]="SQLiteReal";getSQLType(){return"real"}}function L3($){return new T3($??"")}class g3 extends f${static[a]="SQLiteTextBuilder";constructor($,U){super($,"string","SQLiteText");this.config.enumValues=U.enum,this.config.length=U.length}build($){return new S3($,this.config)}}class S3 extends p${static[a]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,U){super($,U)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class j3 extends f${static[a]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new E3($,this.config)}}class E3 extends p${static[a]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}function O$($,U={}){let{name:G,config:X}=y4($,U);if(X.mode==="json")return new j3(G);return new g3(G,X)}function C3(){return{blob:P3,customType:r0,integer:P4,numeric:v3,real:L3,text:O$}}var eZ=Symbol.for("drizzle:SQLiteInlineForeignKeys");class GD extends x${static[a]="SQLiteTable";static Symbol=Object.assign({},x$.Symbol,{InlineForeignKeys:eZ});[x$.Symbol.Columns];[eZ]=[];[x$.Symbol.ExtraConfigBuilder]=void 0}function aQ($,U,G,X,D=$){let V=new GD($,X,D),Z=typeof U==="function"?U(C3()):U,J=Object.fromEntries(Object.entries(Z).map(([Y,w])=>{let K=w;K.setName(Y);let q=K.build(V);return V[eZ].push(...K.buildForeignKeys(q,V)),[Y,q]})),P=Object.assign(V,J);if(P[x$.Symbol.Columns]=J,P[x$.Symbol.ExtraConfigColumns]=J,G)P[GD.Symbol.ExtraConfigBuilder]=G;return P}var f4=($,U,G)=>{return aQ($,U,G)};class k3{constructor($,U){this.name=$,this.value=U}static[a]="SQLiteCheckBuilder";brand;build($){return new x3($,this)}}class x3{constructor($,U){this.table=$,this.name=U.name,this.value=U.value}static[a]="SQLiteCheck";name;value}function b3($,U){return new k3($,U)}class r3{constructor($,U){this.name=$,this.unique=U}static[a]="SQLiteIndexBuilderOn";on(...$){return new u3(this.name,$,this.unique)}}class u3{static[a]="SQLiteIndexBuilder";config;constructor($,U,G){this.config={name:$,columns:U,unique:G,where:void 0}}where($){return this.config.where=$,this}build($){return new h3(this.config,$)}}class h3{static[a]="SQLiteIndex";config;constructor($,U){this.config={...$,table:U}}}function C4($){return new r3($,!1)}function m0(...$){if($[0].columns)return new $J($[0].columns,$[0].name);return new $J($)}class $J{static[a]="SQLitePrimaryKeyBuilder";columns;name;constructor($,U){this.columns=$,this.name=U}build($){return new m3($,this.columns,this.name)}}class m3{constructor($,U,G){this.table=$,this.columns=U,this.name=G}static[a]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[GD.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var y3=f4("job_queue",{id:O$("id").primaryKey().$defaultFn(()=>l6()),type:O$("type").notNull(),data:O$("data").notNull(),result:O$("result",{mode:"json"}),source:O$("source"),metadata:O$("metadata",{mode:"json"}).$type().notNull(),status:O$("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:P4("priority").notNull().default(0),retryCount:P4("retryCount").notNull().default(0),maxRetries:P4("maxRetries").notNull().default(3),lastError:O$("lastError"),createdAt:P4("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:P4("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:P4("startedAt"),completedAt:P4("completedAt")},($)=>({queueReadyIdx:C4("idx_job_queue_ready").on($.status,$.priority,$.scheduledFor),jobTypeIdx:C4("idx_job_queue_type").on($.type,$.status),jobSourceIdx:C4("idx_job_queue_source").on($.source)}));var zl=W.looseObject({deduplicationKey:W.string().optional()});var tl=W.preprocess(($)=>{if(typeof $!=="string")return $;return JSON.parse($)},W.record(W.string(),W.unknown()));var Ui=W.record(W.string(),W.unknown());var sQ=W.object({id:W.string(),type:W.string(),data:W.string(),status:W.enum(["pending","processing","completed","failed"]),source:W.string().nullable(),priority:W.number(),retryCount:W.number(),maxRetries:W.number(),lastError:W.string().nullable(),createdAt:W.number(),scheduledFor:W.number(),startedAt:W.number().nullable(),completedAt:W.number().nullable(),metadata:l1,result:W.unknown().nullable().optional()});function UJ($,U,G){return async(X)=>{let{type:D,data:V,toolContext:Z=null,options:J}=X,{metadata:P,...Y}=J??{},w={source:U,...J?.rootJobId&&{rootJobId:J.rootJobId},...Y,metadata:{operationType:"data_processing",pluginId:U,...Z&&{interfaceType:Z.interfaceType,channelId:Z.channelId},...P}},K=G&&!D.includes(":")?`${U}:${D}`:D;return $.enqueue({type:K,data:V,options:w})}}function DJ($,U){return async(G,X)=>{let D=l6(),V=G.map((J)=>({...J,type:J.type.includes(":")?J.type:`${U}:${J.type}`})),Z={...X,source:U,rootJobId:D,metadata:{...X?.metadata,operationType:"batch_processing",pluginId:U}};return await $.enqueueBatch(V,Z,D,U),D}}function GJ($,U){return(G,X)=>{let D=G.includes(":")?G:`${U}:${G}`;$.registerHandler(D,X,U)}}var tQ=W.custom(($)=>typeof $==="object"&&$!==null&&("safeParse"in $)),eQ=W.object({name:W.string(),schema:tQ});function f3($){return eQ.safeParse($).success}function $I($){if(!$)return;return{status:$.status,message:$.message,lastCheck:$.lastCheck?.toISOString(),details:$.details}}function p3($){return{model:$.model,version:$.version,uptime:$.uptime,entities:$.entities,entityCounts:$.entityCounts,embeddings:$.embeddings,ai:$.ai,daemons:$.daemons.map((U)=>({name:U.name,pluginId:U.pluginId,status:U.status,health:$I(U.health)})),endpoints:$.endpoints,interactions:$.interactions}}import{createClient as gi}from"@libsql/client";var y0=f4("conversations",{id:O$("id").primaryKey(),sessionId:O$("session_id").notNull(),interfaceType:O$("interface_type").notNull(),channelId:O$("channel_id").notNull(),started:O$("started").notNull(),lastActive:O$("last_active").notNull(),metadata:O$("metadata"),created:O$("created").notNull(),updated:O$("updated").notNull()},($)=>({sessionIdx:C4("idx_conversations_session").on($.sessionId),channelIdx:C4("idx_conversations_channel").on($.channelId),interfaceSessionIdx:C4("idx_conversations_interface_session").on($.interfaceType,$.sessionId),interfaceChannelIdx:C4("idx_conversations_interface_channel").on($.interfaceType,$.channelId)})),l3=f4("messages",{id:O$("id").primaryKey(),conversationId:O$("conversation_id").notNull().references(()=>y0.id,{onDelete:"cascade"}),role:O$("role").notNull(),content:O$("content").notNull(),timestamp:O$("timestamp").notNull(),metadata:O$("metadata")},($)=>({conversationIdx:C4("idx_messages_conversation").on($.conversationId),timestampIdx:C4("idx_messages_timestamp").on($.timestamp)})),i3=f4("summary_tracking",{conversationId:O$("conversation_id").primaryKey().references(()=>y0.id,{onDelete:"cascade"}),lastSummarizedAt:O$("last_summarized_at"),lastMessageId:O$("last_message_id"),messagesSinceSummary:P4("messages_since_summary").default(0),updated:O$("updated").notNull()});var UI=W.preprocess(($)=>{if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return}},W.record(W.string(),W.unknown())).catch({});function VD($){return UI.parse($)}var f0=W.object({actorId:W.string(),canonicalId:W.string().optional(),interfaceType:W.string(),role:k6,displayName:W.string().optional(),username:W.string().optional(),isBot:W.boolean().optional()}),p0=W.object({messageId:W.string().optional(),channelId:W.string().optional(),channelName:W.string().optional(),threadId:W.string().optional(),metadata:W.record(W.string(),W.unknown()).optional()}),DI=W.looseObject({actor:f0.optional(),source:p0.optional()});var GI=W.object({id:W.string(),conversationId:W.string(),role:W.string(),content:W.string(),timestamp:W.string(),metadata:W.string().nullable()}),XI=W.object({conversationId:W.string(),messageCount:W.number(),messages:W.array(GI),windowStart:W.number(),windowEnd:W.number(),windowSize:W.number(),timestamp:W.string()});var n1=W.record(W.string(),W.unknown());var JI=W.object({id:W.string(),sessionId:W.string(),interfaceType:W.string(),channelId:W.string(),channelName:W.string().optional(),startedAt:W.string(),lastActiveAt:W.string(),createdAt:W.string(),updatedAt:W.string(),metadata:n1}),WI=W.object({id:W.string(),conversationId:W.string(),role:k6,content:W.string(),timestamp:W.string(),metadata:n1});function YI($){let U=k6.safeParse($);return U.success?U.data:"user"}function l0($){let U=VD($.metadata),G=typeof U.channelName==="string"?U.channelName:void 0;return{id:$.id,sessionId:$.sessionId,interfaceType:$.interfaceType,channelId:$.channelId,channelName:G,startedAt:$.started,lastActiveAt:$.lastActive,createdAt:$.created,updatedAt:$.updated,metadata:U}}function n3($){return{id:$.id,conversationId:$.conversationId,role:YI($.role),content:$.content,timestamp:$.timestamp,metadata:VD($.metadata)}}var XJ=W.object({name:W.string(),role:W.string(),purpose:W.string(),values:W.array(W.string())}),VJ=W.object({name:W.string(),kind:W.enum(["professional","team","collective"]),organization:W.string().optional(),description:W.string().optional(),avatar:W.string().optional(),website:W.string().optional(),email:W.string().optional(),socialLinks:W.array(W.object({platform:W.enum(["github","instagram","linkedin","email","website"]),url:W.string(),label:W.string().optional()})).optional()});function c3($){return XJ.parse($)}function d3($){return VJ.parse($)}function o3($){return async()=>{return p3(await $.getAppInfo())}}function a3($,U){return{get:()=>c3($.getIdentity()),getProfile:()=>d3($.getProfile()),getAppInfo:U}}function s3($,U,G){let X=$.getMessageBus();return{send:async(V)=>{return X.send({...V,sender:U})},subscribe:(V,Z)=>{if(f3(V)){let J=V,P=Z,Y=async(w)=>{let K=J.schema.safeParse(w.payload);if(!K.success)return G.warn(`Invalid payload for channel ${J.name}`,{error:K.error.message}),{noop:!0};let{payload:q,...O}=w;return P(K.data,O)};return X.subscribe(J.name,Y)}return X.subscribe(V,Z)}}}function t3($,U){let G=$.getJobQueueService();return{...$.jobs,enqueue:UJ(G,U,!0),enqueueBatch:DJ($.jobs,U),registerHandler:GJ(G,U)}}function e3($){let U=$.getPermissionService();return{assertEntityActionAllowed:(G,X,D)=>{U.assertEntityActionAllowed(G,X,D.userPermissionLevel)}}}function $K($){return{get:async(U)=>{let X=await $.getConversationService().getConversation(U);return X?l0(X):null},search:async(U)=>{return(await $.getConversationService().searchConversations(U)).map(l0)},list:async(U)=>{return(await $.getConversationService().listConversations(U)).map(l0)},getMessages:async(U,G)=>{return(await $.getConversationService().getMessages(U,G)).map(n3)},countMessages:async(U)=>{return $.getConversationService().countMessages(U)}}}function UK($,U){return{registerHandler:(G,X)=>{$.registerEvalHandler(U,G,X)}}}function DK($){return{register:(U,G)=>{$.getInsightsRegistry().register(U,G)}}}function GK($,U){return{register:(G)=>{$.registerEndpoint({...G,pluginId:U})}}}function XK($,U){return{register:(G)=>{$.registerInteraction({...G,pluginId:U})}}}function c1($,U,G){let X=$.getEntityService(),D=$.getLogger().child(U),V=$.getDomain(),Z=$.getLocalSiteUrl(),J=$.shouldPreferLocalUrls(),P=$.getThemeCSS(),Y=o3($),w=$.getAttachmentRegistry(),K=$.getRuntimeUploadRegistry(),q=$.getRuntimeState();return{pluginId:U,logger:D,entityService:X,identity:a3($,Y),appInfo:Y,judge:(O)=>$.judge(O),domain:V,siteUrl:V?`https://${V}`:void 0,localSiteUrl:Z,previewUrl:V?`https://${mZ(V)}`:void 0,preferLocalUrls:J,themeCSS:P,entityDisplay:G?.entityDisplay,spaces:$.getSpaces(),permissions:e3($),messaging:s3($,U,D),jobs:t3($,U),attachments:w,uploads:K,runtimeState:q,conversations:$K($),dataDir:$.getDataDir(),eval:UK($,U),insights:DK($),endpoints:GK($,U),interactions:XK($,U)}}import{createClient as Bn}from"@libsql/client";var i0=f4("entities",{id:O$("id").notNull(),entityType:O$("entityType").notNull(),content:O$("content").notNull(),contentHash:O$("contentHash").notNull(),visibility:O$("visibility",{enum:["public","shared","restricted"]}).notNull().default("public"),metadata:O$("metadata",{mode:"json"}).$type().notNull().default(i6`'{}'`),created:P4("created").notNull().$defaultFn(()=>Date.now()),updated:P4("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:m0({columns:[$.id,$.entityType]}),visibilityCheck:b3("entities_visibility_check",i6`${$.visibility} IN ('public', 'shared', 'restricted')`)}});import{createClient as Cn}from"@libsql/client";var VK=r0({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var n0=f4("embeddings",{entityId:O$("entity_id").notNull(),entityType:O$("entity_type").notNull(),embedding:VK("embedding").notNull(),contentHash:O$("content_hash").notNull()},($)=>{return{pk:m0({columns:[$.entityId,$.entityType]})}});var PI=W.enum(["public","shared","restricted"]),ZD=W.union([PI,W.literal("private")]).optional().transform(($)=>{if($===void 0)return"public";if($==="private")return"restricted";return $});function c0($){if($==="anchor")return"restricted";if($==="trusted")return"shared";return"public"}var JJ=W.object({id:W.string(),entityType:W.string(),content:W.string(),created:W.string().datetime(),updated:W.string().datetime(),visibility:ZD,metadata:W.record(W.string(),W.unknown()),contentHash:W.string()}),KI=W.enum(["public","shared","restricted"]),OI=W.object({id:W.string(),entityType:W.string(),content:W.string(),created:W.string().datetime(),updated:W.string().datetime(),visibility:W.union([KI,W.literal("private")]).optional().transform(($)=>{if($===void 0)return"public";if($==="private")return"restricted";return $}),metadata:W.record(W.string(),W.unknown()),contentHash:W.string()}),JK=W.object({}),qI=W.object({mediaType:W.string(),url:W.string(),downloadUrl:W.string().optional(),previewUrl:W.string().optional(),filename:W.string().optional(),sizeBytes:W.number().optional(),source:W.object({entityType:W.string().optional(),entityId:W.string().optional(),attachmentType:W.string().optional()}).optional()});var on=W.object({id:W.string().min(1,"Entity ID is required"),entityType:W.string().min(1,"Entity type is required"),contentHash:W.string().min(1,"Content hash is required"),operation:W.enum(["create","update"])});var $c=W.object({limit:W.number().int().positive().optional().default(20),offset:W.number().int().min(0).optional().default(0),types:W.array(W.string()).optional().default([]),excludeTypes:W.array(W.string()).optional().default([]),weight:W.record(W.string(),W.number()).optional(),visibilityScope:W.enum(["public","shared","restricted"]).optional(),includeUngenerated:W.boolean().optional().default(!1),minScore:W.number().min(0).optional()}),Uc=W.preprocess(($)=>{if(typeof $!=="string")return $;return JSON.parse($)},W.record(W.string(),W.unknown()));var jJ=ND(gJ(),1);function ZG($,U){if(Object.keys(U).length===0)return $;let G=Object.fromEntries(Object.entries(U).filter(([,X])=>X!==void 0));return jJ.default.stringify($,G)}function SJ($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(SJ);if($!==null&&typeof $==="object"){let U={};for(let[G,X]of Object.entries($))U[G]=SJ(X);return U}return $}function qD($,U){let{content:G,data:X}=jJ.default($),D=SJ(X);return{content:G.trim(),metadata:U.parse(D)}}var ic=W.object({visibility:W.enum(["public","shared","restricted","private"]).optional().transform(($)=>{if($===void 0)return"public";return $==="private"?"restricted":$})});var oc=W.looseObject({issues:W.array(W.looseObject({message:W.string()}))});var Gd=W.record(W.string(),W.unknown());var Mz=W.object({field:W.string(),direction:W.enum(["asc","desc"]),nullsFirst:W.boolean().optional()}),Hd=W.object({limit:W.number().int().positive().optional(),offset:W.number().int().min(0).optional().default(0),sortFields:W.array(Mz).optional(),filter:W.object({metadata:W.record(W.string(),W.unknown()).optional(),visibilityScope:W.enum(["public","shared","restricted"]).optional()}).optional(),publishedOnly:W.boolean().optional()});var Nd=W.custom(($)=>typeof $==="object"&&$!==null&&!Array.isArray($));var Md=W.object({id:W.string().min(1),entityType:W.string().min(1),contentHash:W.string().min(1)});var Sz=ND(gJ(),1);var cd=E0();var Go=W.record(W.string(),W.unknown());var kz=W.object({currentPage:W.number(),totalPages:W.number(),totalItems:W.number(),pageSize:W.number(),hasNextPage:W.boolean(),hasPrevPage:W.boolean()});function xz($){return $.replace(/:/g,"-")}function bz($){return $.split(/[:.-]/).map((U)=>U.charAt(0).toUpperCase()+U.slice(1)).join(" ")}var EJ=new Map;async function Tq($,U,G){let X=EJ.get(U);if(X!==void 0)return X;let D=xz(U),V;try{V=await $.getEntity({entityType:"prompt",id:D})}catch{return G}if(V?.content){let Z=qD(V.content,W.record(W.string(),W.unknown())).content;return EJ.set(U,Z),Z}try{let Z=bz(U),J=ZG(G,{title:Z,target:U});await $.createEntity({entity:{id:D,entityType:"prompt",content:J,metadata:{title:Z,target:U,slug:D}}})}catch{}return EJ.set(U,G),G}function JG($){let U=$.getEntityService(),G=$.getEntityRegistry(),X=$.getDataSourceRegistry();return{register:(D,V,Z,J)=>{G.registerEntityType(D,V,Z,J)},getAdapter:(D)=>{try{return G.getAdapter(D)}catch{return}},extendFrontmatterSchema:(D,V)=>{G.extendFrontmatterSchema(D,V)},getEffectiveFrontmatterSchema:(D)=>{return G.getEffectiveFrontmatterSchema(D)},registerCreateInterceptor:(D,V)=>{G.registerCreateInterceptor(D,V)},registerUploadSaveHandler:(D)=>{G.registerUploadSaveHandler(D)},getUploadSaveHandler:(D)=>{return G.getUploadSaveHandler(D)},update:async(D)=>{return U.updateEntity({entity:D})},registerDataSource:(D)=>{X.register(D)}}}function WG($){return{resolve:(U,G)=>{return Tq($,U,G)}}}function zq($,U,G){let X=c1($,U,G),D=$.getEntityService();return{...X,entityService:D,entities:JG($),ai:{query:(V,Z)=>$.query(V,Z),generate:async(V)=>{return $.generateContent(V)},generateObject:async(V,Z)=>{return $.generateObject(V,Z)},generateImage:async(V,Z)=>{return $.generateImage(V,Z)},canGenerateImages:()=>{return $.canGenerateImages()}},prompts:WG(D),permissions:X.permissions}}function gq($,U,G){let X=!1,D=!1;if($.jobs.registerHandler(G.job.type,G.job.handler),G.initialSync){let V=G.initialSync;$.messaging.subscribe("sync:initial:completed",async()=>{if(X)return{success:!0};if(X=!0,!(await V.shouldEnqueue?.()??!0))return U.info("Skipping derived entity projection initial sync",{projectionId:G.id,targetType:G.targetType}),{success:!0};return D=await Lq($,U,G,V.jobData,uz(V.jobOptions),"initial-sync"),{success:!0}})}if(G.sourceChange){let V=G.sourceChange,Z=new Set(V.sourceTypes),J=V.events??["entity:created","entity:updated"],P=async(Y)=>{if(V.requireInitialSync&&!X)return{success:!0};let w=Y.payload,K=rz(V,w);if(!K||!Z.has("*")&&!Z.has(K))return{success:!0};if(!(await V.shouldEnqueue?.(w)??!0))return{success:!0};let O=await V.jobData(w);if(!O)return{success:!0};return await Lq($,U,G,O,V.jobOptions?.(w),"source-change"),{success:!0}};for(let Y of J)$.messaging.subscribe(Y,P)}return{hasObservedInitialSync:()=>X,hasQueuedInitialSync:()=>D}}function rz($,U){if($.sourceType)return $.sourceType;if($.sourceKind&&$.sourceKind!=="entity")return $.sourceKind;return U.entityType}async function Lq($,U,G,X,D,V){try{return await $.jobs.enqueue({type:G.job.type,data:X,...D?{options:D}:{}}),U.info("Queued derived entity projection",{projectionId:G.id,targetType:G.targetType,reason:V}),!0}catch(Z){return U.error("Failed to queue derived entity projection",{projectionId:G.id,targetType:G.targetType,reason:V,error:m4(Z)}),!1}}function uz($){return typeof $==="function"?$():$}var wa=W.object({});class YG extends C6{type="entity";entityActionPolicy;derivedEntityProjectionControllers=new Map;constructor($,U,G,X,D){super($,U,G,X);if(D!==void 0)this.entityActionPolicy=D}async register($,U){let G=zq($,this.id,U);if(this.context=G,this.setupMessageHandlers(G),G.entities.register(this.entityType,this.schema,this.adapter,this.getEntityTypeConfig()),this.interceptCreate!==YG.prototype.interceptCreate)G.entities.registerCreateInterceptor(this.entityType,(P,Y)=>this.interceptCreate(P,Y,G));let X=this.createGenerationHandler(G);if(X)G.jobs.registerHandler(`${this.entityType}:generation`,X);let D=this.getTemplates();if(D&&Object.keys(D).length>0)$.registerTemplates(D,this.id);let V=this.getDataSources();for(let P of V)G.entities.registerDataSource(P);let Z=this.getDerivedEntityProjections(G);for(let P of Z){let Y=gq(G,this.logger,P);this.derivedEntityProjectionControllers.set(P.id,Y)}await this.onRegister(this.context);let J=await this.getInstructions();return{tools:[],resources:[],...J&&{instructions:J}}}async interceptCreate($,U,G){return{kind:"continue",input:$}}createGenerationHandler($){return null}getTemplates(){return null}getDataSources(){return[]}getEntityTypeConfig(){return}getDerivedEntityProjections($){return[]}getDerivedEntityProjectionController($){return this.derivedEntityProjectionControllers.get($)}}class Sq extends YG{hooks;constructor($,U,G,X,D){super($,U,G,X);this.hooks=D}get entityType(){return this.hooks.getEntityType()}get schema(){return this.hooks.getSchema()}get adapter(){return this.hooks.getAdapter()}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getEntityTypeConfig(){return this.hooks.getEntityTypeConfig()}getDataSources(){return this.hooks.getDataSources()}getInstructions(){return this.hooks.getInstructions()}interceptCreate($,U,G){return this.hooks.interceptCreate($,U,G)}}class CJ{type="entity";id;version;packageName;description;delegate;constructor($,U,G,X){if(this.id=$,this.version=U.version,this.packageName=U.name,U.description!==void 0)this.description=U.description;this.delegate=new Sq($,U,G,X,{getEntityType:()=>this.entityType,getSchema:()=>this.schema,getAdapter:()=>this.adapter,onRegister:(D)=>this.onRegister(D),onReady:(D)=>this.onReady(D),onShutdown:()=>this.onShutdown(),getEntityTypeConfig:()=>this.getEntityTypeConfig(),getDataSources:()=>this.getDataSources(),getInstructions:()=>this.getInstructions(),interceptCreate:(D,V,Z)=>this.interceptCreate(D,V,Z)})}register($,U){return this.delegate.register($,U)}async onRegister($){}async onReady($){}async onShutdown(){}async getInstructions(){return}getEntityTypeConfig(){return}getDataSources(){return[]}async interceptCreate($,U,G){return{kind:"continue",input:$}}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function jq($){return RV($)}function Eq($){if(!$)return;return{...$.userPermissionLevel&&{userPermissionLevel:$.userPermissionLevel},...$.interfaceType&&{interfaceType:$.interfaceType},...$.channelId&&{channelId:$.channelId},...$.channelName&&{channelName:$.channelName},...$.actor&&{actor:$.actor},...$.source&&{source:$.source},...$.attachments&&{attachments:$.attachments}}}function Cq($){return{chat:async(U,G,X)=>{return jq(await $.chat(U,G,Eq(X)))},confirmPendingAction:async(U,G,X,D)=>{let V=Eq(D);if(!V)throw Error("Confirmation requires caller context.");return jq(await $.confirmPendingAction(U,G,X,V))},invalidate:()=>{$.invalidateAgent()}}}function kq($,U,G){let X=c1($,U,G),D=$.getMCPService(),V=$.getPermissionService(),Z=Cq($.getAgentService());return{...X,mcpTransport:D,agent:Z,permissions:{...X.permissions,getUserLevel:(J,P,Y)=>{return V.determineUserLevel(J,P,Y)}},daemons:{register:(J,P)=>{let Y=`${U}:${J}`;$.registerDaemon(Y,P,U),X.logger.debug(`Registered daemon: ${Y}`)}},conversations:{...X.conversations,start:async(J)=>{return $.getConversationService().startConversation(J)},addMessage:async(J)=>{await $.getConversationService().addMessage(J)},updateMetadata:async(J)=>{return $.getConversationService().updateConversationMetadata(J)},delete:async(J)=>{return $.getConversationService().deleteConversation(J)}},tools:{listForPermissionLevel:(J)=>{return $.listToolsForPermissionLevel(J)}},apiRoutes:{getRoutes:()=>{return $.getPluginApiRoutes()},getMessageBus:()=>{return $.getMessageBus()}},webRoutes:{getRoutes:()=>{return $.getPluginWebRoutes()}},plugins:{has:(J)=>$.hasPlugin(J)}}}var hz=3600000;class AD extends C6{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=hz;async register($,U){let G=kq($,this.id,U);if(this.context=G,this.initializeDaemon(),this.daemon)await this.registerDaemon(G);return this.setupMessageHandlers(G),await this.onRegister(G),this.getCapabilities()}async onRegister($){}async registerDaemon($){if(!this.daemon)return;$.daemons.register(this.id,this.daemon),$.logger.debug(`Registered daemon for interface: ${this.id}`)}createDaemon(){return}requiresDaemonStartup(){return!1}getWebRoutes(){return[]}initializeDaemon(){let $=this.createDaemon();if($)this.daemon=$}async handleProgressEvent($,U){}cleanupExpiredEntries(){let $=Date.now(),U=[];for(let[G,X]of this.jobTrackingEntries)if($-X.createdAt>this.jobTrackingTtlMs)U.push(G);for(let G of U)this.jobTrackingEntries.delete(G)}ownsJob($,U){return this.jobTrackingEntries.has($)||U!==void 0&&this.jobTrackingEntries.has(U)}getJobTracking($,U){let G=this.jobTrackingEntries.get($);if(G)return G.info;if(U){let X=this.jobTrackingEntries.get(U);if(X)return X.info}return}setJobTracking($,U){this.cleanupExpiredEntries(),this.jobTrackingEntries.set($,{info:U,createdAt:Date.now()})}removeJobTracking($){this.jobTrackingEntries.delete($)}async createJobWithTracking($,U){let X=await this.getContext().jobs.enqueue($);return this.setJobTracking(X,U),X}async createBatchWithTracking($,U,G){let D=await this.getContext().jobs.enqueueBatch($,G);return this.setJobTracking(D,U),D}}class xq extends AD{hooks;constructor($,U,G,X,D){super($,U,G,X);this.hooks=D}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getTools(){return this.hooks.getTools()}getResources(){return this.hooks.getResources()}getInstructions(){return this.hooks.getInstructions()}getWebRoutes(){return this.hooks.getWebRoutes()}requiresDaemonStartup(){return this.hooks.requiresDaemonStartup()}}class _D{type="interface";id;version;packageName;description;delegate;constructor($,U,G,X){if(this.id=$,this.version=U.version,this.packageName=U.name,U.description!==void 0)this.description=U.description;this.delegate=new xq($,U,G,X,{onRegister:(D)=>this.onRegister(D),onReady:(D)=>this.onReady(D),onShutdown:()=>this.onShutdown(),getTools:()=>this.getTools(),getResources:()=>this.getResources(),getInstructions:()=>this.getInstructions(),getWebRoutes:()=>this.getWebRoutes(),requiresDaemonStartup:()=>this.requiresDaemonStartup()})}register($,U){return this.delegate.register($,U)}async onRegister($){}async onReady($){}async onShutdown(){}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}getWebRoutes(){return[]}requiresDaemonStartup(){return!1}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function bq($,U){$.messaging.subscribe("job-progress",async(G)=>{try{let X=pZ.safeParse(G.payload);if(!X.success)return U.onInvalidSchema(),{success:!1};let D=X.data;return await U.onProgress(D,D.metadata),{success:!0}}catch(X){return U.onError(X),{success:!1}}})}function rq($){let U=$.status==="completed"?"\u2705":"\u274C",G=$.status==="completed"?"completed":"failed",X=$.metadata.operationType.replace(/_/g," "),D=$.metadata.operationTarget?`: ${$.metadata.operationTarget}`:"",V=`${U} **${X}${D}** ${G}`;if($.message)V+=`
|
|
189
189
|
${$.message}`;return V}function uq($){let U=$.metadata.operationType.replace(/_/g," "),G=$.metadata.operationTarget?`: ${$.metadata.operationTarget}`:"",X=`\uD83D\uDD04 **${U}${G}**`;if($.progress&&$.progress.total>0)X+=` ${$.progress.current}/${$.progress.total} (${$.progress.percentage}%)`;if($.message)X+=`
|
|
190
190
|
${$.message}`;return X}var mz=W.enum(["tool:invoking","tool:completed","tool:failed"]),yz=W.object({toolName:W.string().min(1),conversationId:W.string().min(1),interfaceType:W.string().min(1),channelId:W.string().min(1).optional(),channelName:W.string().min(1).optional(),toolCallId:W.string().min(1).optional(),error:W.string().optional()}),fz=["tool:invoking","tool:completed","tool:failed"];function hq($,U){for(let G of fz)$.messaging.subscribe(G,async(X)=>{try{let D=mz.safeParse(X.type),V=yz.safeParse(X.payload);if(!D.success||!V.success)return U.onInvalidSchema(),{success:!1};return await U.onToolActivity({type:D.data,...V.data}),{success:!0}}catch(D){return U.onError(D),{success:!1}}})}function FD($,U){return{state:U,toolName:$.toolName,conversationId:$.conversationId,interfaceType:$.interfaceType,...$.channelId!==void 0&&{channelId:$.channelId},...$.channelName!==void 0&&{channelName:$.channelName},...$.error!==void 0&&{error:$.error}}}function mq($,U){return $.pendingConfirmations?.some((G)=>G.toolName===U)===!0||pz($.cards).some((G)=>G.toolName===U)}function pz($){return $?.filter((U)=>U.kind==="tool-approval"&&U.state==="approval-requested")??[]}var kJ=1e5,lz=[".md",".txt",".markdown"],iz=["text/plain","text/markdown","text/x-markdown"],nz=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi,cz=["meet.google.com","zoom.us","teams.microsoft.com","whereby.com","gather.town","calendly.com","cal.com","discord.com","discord.gg","cdn.discordapp.com","media.discordapp.net","giphy.com","tenor.com","wetransfer.com","file.io"],dz=W.object({captureUrls:W.boolean().default(!1),blockedUrlDomains:W.array(W.string()).default(cz)});function yq($,U){if(U&&iz.some((G)=>U.startsWith(G)))return!0;return lz.some((G)=>$.toLowerCase().endsWith(G))}function fq($){return $<=kJ}function pq($){if($.includes(0))return!1;try{return new TextDecoder("utf-8",{fatal:!0}).decode($),!0}catch{return!1}}function lq($,U){return`User uploaded a file "${$}":
|
|
191
191
|
|
|
@@ -193,5 +193,5 @@ ${U}`}function iq($,U){let G=$.match(nz)??[];return[...new Set(G)].filter((X)=>{
|
|
|
193
193
|
|
|
194
194
|
${U}`}extractCaptureableUrls($,U){let G=$.match(/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi)??[];return[...new Set(G)].filter((X)=>{try{let{hostname:D}=new URL(X);return!U.some((V)=>D===V||D.endsWith(`.${V}`))}catch{return!1}})}captureUrlViaAgent($,U,G,X,D){return this.messageDelegate.captureUrlViaAgentPublic($,U,G,X,D)}trackAgentResponseForJob($,U,G){this.messageDelegate.trackAgentResponseForJobPublic($,U,G)}registerProgressCallback($){this.messageDelegate.registerProgressCallback($)}unregisterProgressCallback(){this.messageDelegate.unregisterProgressCallback()}getProgressEvents(){return this.messageDelegate.getProgressEvents()}getActiveProgressEvents(){return this.messageDelegate.getActiveProgressEvents()}startProcessingInput($=null){this.messageDelegate.startProcessingInput($)}endProcessingInput(){this.messageDelegate.endProcessingInput()}getCurrentChannelId(){return this.messageDelegate.getCurrentChannelIdPublic()}ready(){return this.messageDelegate.ready()}shutdown(){return this.messageDelegate.shutdown?.()??Promise.resolve()}}var sz=W.object({name:W.string(),description:W.string(),schema:W.any(),basePrompt:W.string().optional(),useKnowledgeContext:W.boolean().optional(),requiredPermission:W.enum(["anchor","trusted","public"]),formatter:W.any().optional(),layout:W.object({component:W.any().optional(),fullscreen:W.boolean().optional()}).optional(),dataSourceId:W.string().optional()});class RD{static canGenerate($){return!!$.basePrompt&&!!$.dataSourceId&&$.dataSourceId.includes("ai-content")}static canFetch($){return!!$.dataSourceId&&!this.canGenerate($)}static canRender($){return!!$.layout?.component}static isStaticOnly($){return!this.canGenerate($)&&!this.canFetch($)}static getCapabilities($){return{canGenerate:this.canGenerate($),canFetch:this.canFetch($),canRender:this.canRender($),isStaticOnly:this.isStaticOnly($)}}static validate($){let U=[];if($.dataSourceId?.includes("ai-content")&&!$.basePrompt)U.push(`Template "${$.name}" has AI-content dataSourceId but no basePrompt. AI generation requires a basePrompt.`);if($.basePrompt&&(!$.dataSourceId||!$.dataSourceId.includes("ai-content")))U.push(`Template "${$.name}" has basePrompt but no AI-content dataSourceId. The basePrompt won't be used.`);return U}static logCapabilities($,U){let G=this.getCapabilities($),X=this.validate($);if(U)U.debug(`Template capabilities for "${$.name}":`,{...G,errors:X.length>0?X:void 0})}}var ez=W.enum(["anchor","trusted","public"]),$L=W.enum(["create","update","delete","extract","publish"]),GU=W.enum(["never","anchor","trusted","public"]),tq=W.strictObject({create:GU.optional(),update:GU.optional(),delete:GU.optional(),extract:GU.optional(),publish:GU.optional()}),UL=W.record(W.string(),tq);var DL=W.enum(["site-content-preview","site-content-production"]),GL=W.enum(["web","image","pdf"]),uJ=W.custom(($)=>typeof $==="function"),XL=W.object({name:W.string(),schema:W.any(),description:W.string().optional(),pluginId:W.string(),renderers:W.object({web:W.union([uJ,W.string()]).optional(),image:W.union([uJ,W.string()]).optional(),pdf:W.union([uJ,W.string()]).optional()})}),VL=W.object({enableContentGeneration:W.boolean().default(!1),outputDir:W.string(),workingDir:W.string().optional(),environment:W.enum(["preview","production"]).default("preview"),siteConfig:W.object({title:W.string(),description:W.string(),url:W.string().optional()}).optional()}),ZL=W.object({success:W.boolean(),routesBuilt:W.number(),errors:W.array(W.string()).optional(),warnings:W.array(W.string()).optional()});function eq($,U,G){let X=c1($,U,G),D=$.getEntityService(),V=$.getRenderService(),Z=$.getContentService();return{...X,entityService:D,entities:JG($),templates:{register:(J,P)=>{$.registerTemplates(J,P??U)},format:(J,P)=>{return Z.formatContent(J,P,{pluginId:U})},parse:(J,P)=>{return Z.parseContent(J,P,U)},resolve:async(J,P)=>{return await Z.resolveContent(J,P,U)},getCapabilities:(J)=>{let P=J.includes(":")?J:`${U}:${J}`,Y=$.getTemplate(P);if(!Y)return null;let w=RD.getCapabilities(Y);return{canGenerate:w.canGenerate,canFetch:w.canFetch,canRender:w.canRender,isStaticOnly:w.isStaticOnly}}},views:{get:(J)=>{return V.get(J)??void 0},list:()=>{return V.list()},hasRenderer:(J,P="web")=>{return V.hasRenderer(J,P)},getRenderer:(J,P="web")=>{return V.getRenderer(J,P)},validate:(J,P)=>{return V.validate(J,P)}},prompts:WG(D),registerInstructions:(J)=>{$.registerInstructions(U,J)}}}class hJ extends C6{type="service";getApiRoutes(){return[]}getWebRoutes(){return[]}async register($,U){let G=eq($,this.id,U);return this.context=G,this.setupMessageHandlers(G),await this.onRegister(G),this.getCapabilities()}get entityService(){return this.getContext().entityService}registerEntityType($,U,G,X){this.getContext().entities.register($,U,G,X)}async enqueueJob($){return this.getContext().jobs.enqueue($)}async enqueueBatch($,U){return this.getContext().jobs.enqueueBatch($,U)}async registerEntityTypes($){}async registerJobHandlers($){}async onRegister($){await this.registerEntityTypes($),await this.registerJobHandlers($)}}class $A extends hJ{hooks;constructor($,U,G,X,D){super($,U,G,X);this.hooks=D}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getTools(){return this.hooks.getTools()}getResources(){return this.hooks.getResources()}getInstructions(){return this.hooks.getInstructions()}}class mJ{type="service";id;version;packageName;description;delegate;constructor($,U,G,X){if(this.id=$,this.version=U.version,this.packageName=U.name,U.description!==void 0)this.description=U.description;this.delegate=new $A($,U,G,X,{onRegister:(D)=>this.onRegister(D),onReady:(D)=>this.onReady(D),onShutdown:()=>this.onShutdown(),getTools:()=>this.getTools(),getResources:()=>this.getResources(),getInstructions:()=>this.getInstructions()})}register($,U){return this.delegate.register($,U)}async onRegister($){}async onReady($){}async onShutdown(){}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}var UA=W.object({kind:W.string().min(1),id:W.string().min(1)}),WL=W.object({kind:W.literal("text"),filename:W.string().min(1),mediaType:W.string().min(1),content:W.string(),sizeBytes:W.number().nonnegative().optional(),source:UA.optional()}),YL=W.custom(($)=>$ instanceof Uint8Array),PL=W.object({kind:W.literal("file"),filename:W.string().min(1),mediaType:W.string().min(1),data:YL,sizeBytes:W.number().nonnegative().optional(),source:UA.optional()}),HL=W.discriminatedUnion("kind",[WL,PL]),wL=W.object({userPermissionLevel:W.enum(["anchor","trusted","public"]).optional(),interfaceType:W.string().optional(),channelId:W.string().optional(),channelName:W.string().optional(),actor:f0.optional(),source:p0.optional(),attachments:W.array(HL).optional()});var KL=W.object({status:W.enum(["healthy","warning","error","unknown"]),message:W.string().optional(),lastCheck:W.date().optional(),details:W.record(W.string(),W.unknown()).optional()}),DA=W.object({name:W.string(),pluginId:W.string(),status:W.string(),health:KL.optional()});import{McpServer as as,ResourceTemplate as ss}from"@modelcontextprotocol/sdk/server/mcp.js";var GA=W.object({interfaceType:W.string(),userId:W.string(),conversationId:W.string().optional(),channelId:W.string().optional(),channelName:W.string().optional(),runId:W.string().optional(),toolCallId:W.string().optional(),userPermissionLevel:W.enum(["anchor","trusted","public"]).optional()}),XA=W.strictObject({success:W.literal(!0),data:W.unknown().optional(),message:W.string().optional(),cached:W.literal(!0).optional()}),VA=W.strictObject({success:W.literal(!1),error:W.string(),code:W.string().optional()}),ZA=W.strictObject({needsConfirmation:W.literal(!0),toolName:W.string(),summary:W.string(),completionSummary:W.string().optional(),preview:W.string().optional(),args:W.unknown()}),yJ=W.union([XA,VA,ZA]);var ls=W.union([W.looseObject({success:W.literal(!0)}),W.object({success:W.literal(!1),error:W.string()})]);var OL=W.union([W.object({success:W.literal(!0),data:W.unknown(),message:W.string().optional()}),W.object({success:W.literal(!1),error:W.string(),code:W.string().optional()})]);var rt=W.object({id:W.string(),type:W.string(),version:W.string(),status:W.string()}),ut=W.object({name:W.string(),description:W.string()}),JA=W.enum(["anchor","trusted","public"]),fJ=W.object({label:W.string(),url:W.string(),pluginId:W.string(),priority:W.number().default(100),visibility:JA.default("public")}),qL=W.enum(["human","agent","admin","protocol"]),AL=W.enum(["available","coming-soon","disabled"]),pJ=W.object({id:W.string(),label:W.string(),description:W.string().optional(),href:W.string(),kind:qL,pluginId:W.string(),priority:W.number().default(100),visibility:JA.default("public"),status:AL.default("available")}),lJ=W.object({entityType:W.string(),count:W.number()}),ht=W.object({model:W.string(),version:W.string(),uptime:W.number(),entities:W.number(),entityCounts:W.array(lJ),embeddings:W.number(),ai:W.object({model:W.string(),embeddingModel:W.string()}),daemons:W.array(DA),endpoints:W.array(fJ),interactions:W.array(pJ)});var mt=W.object({id:W.string(),version:W.string(),type:W.enum(["core","entity","service","interface"]),description:W.string().optional(),dependencies:W.array(W.string()).optional(),packageName:W.string()});var _L=W.object({status:W.enum(["healthy","warning","error","unknown"]),message:W.string().optional(),lastCheck:W.string().optional(),details:W.record(W.string(),W.unknown()).optional()}),FL=W.object({name:W.string(),pluginId:W.string(),status:W.string(),health:_L.optional()}),RL=W.object({model:W.string(),version:W.string(),uptime:W.number(),entities:W.number(),entityCounts:W.array(lJ),embeddings:W.number(),ai:W.object({model:W.string(),embeddingModel:W.string()}),daemons:W.array(FL),endpoints:W.array(fJ),interactions:W.array(pJ)});var NL=W.union([W.object({success:W.boolean(),data:W.unknown().optional(),error:W.string().optional()}),W.object({noop:W.literal(!0)})]),ML=W.object({id:W.string(),timestamp:W.string(),type:W.string(),source:W.string(),target:W.string().optional(),metadata:n1.optional()});export{YR as urlCaptureConfigSchema,JR as toolSuccess,WR as toolError,PR as defineChannel,VR as createTool,ZR as createResource,D0 as ToolResultDataSchema,mJ as ServicePlugin,U0 as PendingConfirmationSchema,WI as MessageSchema,NL as MessageResponseSchema,rJ as MessageInterfacePlugin,_D as InterfacePlugin,n1 as ExtensionMetadataSchema,CJ as EntityPlugin,JI as ConversationSchema,wL as ChatContextSchema,XJ as BrainCharacterSchema,ML as BaseMessageSchema,RL as AppInfoSchema,VJ as AnchorProfileSchema,G0 as AgentResponseSchema};
|
|
195
195
|
|
|
196
|
-
//# debugId=
|
|
196
|
+
//# debugId=A84AAD43BD51979E64756E2164756E21
|
|
197
197
|
//# sourceMappingURL=plugins.js.map
|