UNPKG

trellis

Version:

Agentic State Engine — event-sourced causal graph with branching, decision traces, and realtime sync for AI-native applications

348 lines (345 loc) 9.19 kB
import { OntologyRegistry, agentOntology, builtinOntologies, createValidationMiddleware, projectOntology, teamOntology, validateEntity, validateStore } from "../chunk-ZLFCWNZF.js"; import { SqlJsKernelBackend } from "../chunk-HAXURL2E.js"; import { createKernelBackend } from "../chunk-GQTPDDJ7.js"; import { AgentHarness } from "../chunk-ZJ3NSF63.js"; import { DatalogRuntime, parseQuery, parseRule, parseSimple } from "../chunk-LTBGCNC4.js"; import { ExprEvaluator, attachStandardMiddleware, buildOntologyIndex, collectRollupRelatedIds, createLogicMiddleware, evalExpr, evaluateRollup, projectRelationFields } from "../chunk-SZ3VAB5P.js"; import { SqliteKernelBackend } from "../chunk-VRFPXKFZ.js"; import { TrellisKernel } from "../chunk-PVOECISX.js"; import { QueryEngine } from "../chunk-BYTAOXGW.js"; import { EAVStore, flatten, init_eav_store, jsonEntityFacts } from "../chunk-G3XIHPSQ.js"; import { EntityConflictError, RealtimeFieldError, effectiveFieldSync, filterDurableAttributes, findSchemaForType } from "../chunk-LEGH72HW.js"; import { OP_PREIMAGE_VERSION, PROVENANCE, canonicalOpBody, canonicalOpBodyFromOp, hashKernelOp, init_canonical_op, verifyOpHash } from "../chunk-RUMOVKR4.js"; import "../chunk-2ESYSVXG.js"; // src/core/index.ts init_eav_store(); init_canonical_op(); // src/core/plugins/registry.ts var EventBus = class { handlers = /* @__PURE__ */ new Map(); on(event, handler) { const set = this.handlers.get(event) ?? /* @__PURE__ */ new Set(); set.add(handler); this.handlers.set(event, set); } off(event, handler) { const set = this.handlers.get(event); if (set) { set.delete(handler); if (set.size === 0) this.handlers.delete(event); } } async emit(event, data) { const exact = this.handlers.get(event); if (exact) { for (const h of exact) await h(data); } for (const [pattern, handlers] of this.handlers) { if (pattern === event) continue; if (pattern.endsWith("*") && event.startsWith(pattern.slice(0, -1))) { for (const h of handlers) await h(data); } } } listEvents() { return [...this.handlers.keys()]; } clear() { this.handlers.clear(); } }; var PluginRegistry = class { plugins = /* @__PURE__ */ new Map(); eventBus = new EventBus(); workspaceConfig = {}; logs = []; /** * Register a plugin definition. Does not load it yet. */ register(def) { if (this.plugins.has(def.id)) { throw new Error(`Plugin "${def.id}" is already registered.`); } this.plugins.set(def.id, { def, loaded: false }); } /** * Unregister a plugin. Unloads it first if loaded. */ async unregister(id) { const entry = this.plugins.get(id); if (!entry) return; if (entry.loaded) await this.unload(id); this.plugins.delete(id); } /** * Load a plugin (call onLoad, register middleware/ontologies/rules/events). * Resolves dependencies first. */ async load(id, kernel, ontologyRegistry, queryEngine) { const entry = this.plugins.get(id); if (!entry) throw new Error(`Plugin "${id}" is not registered.`); if (entry.loaded) return; if (entry.def.dependencies) { for (const dep of entry.def.dependencies) { const depEntry = this.plugins.get(dep); if (!depEntry) { throw new Error(`Plugin "${id}" depends on "${dep}" which is not registered.`); } if (!depEntry.loaded) { await this.load(dep, kernel, ontologyRegistry, queryEngine); } } } if (entry.def.middleware && kernel) { for (const mw of entry.def.middleware) { kernel.addMiddleware(mw); } } if (entry.def.ontologies && ontologyRegistry) { for (const schema of entry.def.ontologies) { try { ontologyRegistry.register(schema); } catch { } } } if (entry.def.rules && queryEngine) { for (const rule of entry.def.rules) { queryEngine.addRule(rule); } } if (entry.def.eventHandlers) { for (const eh of entry.def.eventHandlers) { this.eventBus.on(eh.event, eh.handler); } } const ctx = this._buildContext(id); if (entry.def.onLoad) { await entry.def.onLoad(ctx); } entry.loaded = true; await this.eventBus.emit("plugin:loaded", { pluginId: id }); } /** * Unload a plugin (call onUnload, remove middleware/events). */ async unload(id) { const entry = this.plugins.get(id); if (!entry || !entry.loaded) return; const ctx = this._buildContext(id); if (entry.def.onUnload) { await entry.def.onUnload(ctx); } if (entry.def.eventHandlers) { for (const eh of entry.def.eventHandlers) { this.eventBus.off(eh.event, eh.handler); } } entry.loaded = false; await this.eventBus.emit("plugin:unloaded", { pluginId: id }); } /** * Load all registered plugins in dependency order. */ async loadAll(kernel, ontologyRegistry, queryEngine) { const order = this._resolveDependencyOrder(); for (const id of order) { await this.load(id, kernel, ontologyRegistry, queryEngine); } } /** * Unload all plugins in reverse order. */ async unloadAll() { const order = this._resolveDependencyOrder().reverse(); for (const id of order) { await this.unload(id); } } // ------------------------------------------------------------------------- // Queries // ------------------------------------------------------------------------- get(id) { return this.plugins.get(id)?.def; } isLoaded(id) { return this.plugins.get(id)?.loaded ?? false; } list() { return [...this.plugins.values()]; } listLoaded() { return [...this.plugins.values()].filter((e) => e.loaded).map((e) => e.def); } // ------------------------------------------------------------------------- // Event bus access // ------------------------------------------------------------------------- getEventBus() { return this.eventBus; } async emit(event, data) { await this.eventBus.emit(event, data); } on(event, handler) { this.eventBus.on(event, handler); } // ------------------------------------------------------------------------- // Workspace config // ------------------------------------------------------------------------- getWorkspaceConfig() { return this.workspaceConfig; } setWorkspaceConfig(config) { this.workspaceConfig = config; } getConfigValue(key) { return this.workspaceConfig.settings?.[key]; } setConfigValue(key, value) { if (!this.workspaceConfig.settings) this.workspaceConfig.settings = {}; this.workspaceConfig.settings[key] = value; } // ------------------------------------------------------------------------- // Logs // ------------------------------------------------------------------------- getLogs(pluginId) { if (pluginId) return this.logs.filter((l) => l.pluginId === pluginId); return [...this.logs]; } // ------------------------------------------------------------------------- // Internal // ------------------------------------------------------------------------- _buildContext(pluginId) { return { pluginId, on: (event, handler) => this.eventBus.on(event, handler), emit: (event, data) => { this.eventBus.emit(event, data); }, getConfig: (key) => this.getConfigValue(key), log: (message) => { this.logs.push({ pluginId, message, timestamp: (/* @__PURE__ */ new Date()).toISOString() }); } }; } _resolveDependencyOrder() { const visited = /* @__PURE__ */ new Set(); const order = []; const visit = (id, stack) => { if (visited.has(id)) return; if (stack.has(id)) throw new Error(`Circular dependency detected: ${[...stack, id].join(" \u2192 ")}`); stack.add(id); const entry = this.plugins.get(id); if (entry?.def.dependencies) { for (const dep of entry.def.dependencies) { visit(dep, stack); } } stack.delete(id); visited.add(id); order.push(id); }; for (const id of this.plugins.keys()) { visit(id, /* @__PURE__ */ new Set()); } return order; } }; export { AgentHarness, DatalogRuntime, EAVStore, EntityConflictError, EventBus, ExprEvaluator, OP_PREIMAGE_VERSION, OntologyRegistry, PROVENANCE, PluginRegistry, QueryEngine, RealtimeFieldError, SqlJsKernelBackend, SqliteKernelBackend, TrellisKernel, agentOntology, attachStandardMiddleware, buildOntologyIndex, builtinOntologies, canonicalOpBody, canonicalOpBodyFromOp, collectRollupRelatedIds, createKernelBackend, createLogicMiddleware, createValidationMiddleware, effectiveFieldSync, evalExpr, evaluateRollup, filterDurableAttributes, findSchemaForType, flatten, hashKernelOp, jsonEntityFacts, parseQuery, parseRule, parseSimple, projectOntology, projectRelationFields, teamOntology, validateEntity, validateStore, verifyOpHash };