{"version":3,"file":"agent.cjs","sources":["../../src/plugins/Agent.js"],"sourcesContent":["\"use strict\";\n\n/**\n * @module eleva/plugins/agent\n * @fileoverview Agent plugin for AI/agent integration with action registry,\n * command bus, audit logging, and state inspection. Uses the shared\n * `eleva.emitter` for event observation instead of a parallel system.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n * @typedef {import('eleva').ComponentContext} ComponentContext\n * @typedef {import('eleva').SetupResult} SetupResult\n * @typedef {import('eleva').ComponentProps} ComponentProps\n * @typedef {import('eleva').ChildrenMap} ChildrenMap\n * @typedef {import('eleva').MountResult} MountResult\n */\n\n// -----------------------------------------------------------------------------\n// Agent Type Definitions\n// -----------------------------------------------------------------------------\n\n/**\n * Audit log entry recorded for actions, commands, and emitter events.\n * @typedef {Object} AgentLogEntry\n * @property {\"action\" | \"command\" | \"event\"} type\n *           The category of the log entry.\n * @property {string} action\n *           The action name, command type, or emitter event name.\n * @property {unknown} payload\n *           The data associated with the entry.\n * @property {number} timestamp\n *           Unix timestamp of when the entry was recorded.\n * @property {string} source\n *           The originating context (e.g., \"global\").\n * @property {unknown} [result]\n *           The value returned by the handler (action entries only).\n *           Absent on command/event entries and when the handler throws.\n * @property {string} [error]\n *           The error message if the handler threw (action/command entries).\n *           Absent when the handler succeeds and on event entries.\n * @property {number} [durationMs]\n *           Wall-clock execution time in milliseconds (action/command entries).\n *           Absent on event entries.\n */\n\n/**\n * Filter options for querying the audit log.\n * @typedef {Object} AgentLogFilter\n * @property {\"action\" | \"command\" | \"event\"} [type]\n *           Filter by log entry type.\n * @property {number} [since]\n *           Filter entries after this timestamp.\n * @property {string} [action]\n *           Filter by action/event name.\n * @property {\"ok\" | \"error\"} [status]\n *           Filter by outcome: \"ok\" = entries without error, \"error\" = entries with error.\n */\n\n/**\n * Action schema describing the contract for a registered action.\n * @typedef {Object} AgentActionSchema\n * @property {Record<string, string>} [input]\n *           Expected input payload shape (key -> type name).\n * @property {string} [output]\n *           Expected return type name.\n * @property {string[]} [errors]\n *           Known error codes this action can produce.\n */\n\n/**\n * Permission rules for capability-based access control.\n * @typedef {Object} AgentPermissionRule\n * @property {string[]} [actions]\n *           Allowed action names.\n * @property {string[]} [commands]\n *           Allowed command types.\n */\n\n/**\n * Agent plugin configuration options.\n * @typedef {Object} AgentOptions\n * @property {number} [maxLogSize]\n *           Maximum number of audit log entries (default: 100).\n * @property {boolean} [enableInspection]\n *           Enable component tree inspection (default: true).\n * @property {AgentErrorHandler} [onError]\n *           Custom error handler function.\n * @property {Record<string, Function>} [actions]\n *           Pre-registered action handlers.\n * @property {Record<string, AgentPermissionRule>} [permissions]\n *           Capability-based access control per scope.\n * @property {string[]} [emitterEvents]\n *           Emitter event prefixes to capture in the audit log\n *           (e.g., [\"store:\", \"router:\"]). Empty array disables capture.\n * @property {boolean} [strictPermissions]\n *           When true, scope is mandatory for execute/dispatch and calls\n *           without a scope are denied. Default: false (scope is optional\n *           and calls without it are unrestricted).\n * @property {boolean} [validateSchemas]\n *           When true, `execute()` validates the payload against the action's\n *           schema before calling the handler. Missing required input fields\n *           throw a schema violation error. Default: false.\n */\n\n/**\n * Custom error handler for the agent plugin.\n * @callback AgentErrorHandler\n * @param {Error} error - The error that occurred (includes `error.code`).\n * @param {AgentErrorContext} context - Structured context about the error.\n * @returns {void}\n */\n\n/**\n * Structured error context passed to the onError callback.\n * @typedef {Object} AgentErrorContext\n * @property {\"execute\"|\"dispatch\"} method\n *           The method that generated the error. Only \"execute\" and \"dispatch\" call onError.\n * @property {string} code\n *           Machine-readable error code (e.g., \"AGENT_PERMISSION_DENIED\").\n * @property {string} [action]\n *           The action name involved (if applicable).\n * @property {string} [scope]\n *           The scope involved (if applicable).\n * @property {string} [commandType]\n *           The command type involved (if applicable).\n */\n\n/**\n * Capability manifest describing all available agent features for a given scope.\n * Returned by `agent.describe(scope?)`.\n * @typedef {Object} AgentCapabilityManifest\n * @property {Array<{name: string, schema: AgentActionSchema | null, allowed: boolean}>} actions\n *           All registered actions with their schemas and scope-based access.\n * @property {string[]} commands\n *           All registered command types.\n * @property {{ scope: string | null, actions: string[], commands: string[] } | null} permissions\n *           The resolved permission rules for the requested scope, or null if no scope.\n * @property {{ strictPermissions: boolean, maxLogSize: number, inspectionEnabled: boolean, validateSchemas: boolean }} config\n *           Current agent configuration.\n */\n\n/**\n * Command object dispatched through the command bus.\n * @typedef {Object} AgentCommand\n * @property {string} type\n *           The command type identifier.\n * @property {string} [target]\n *           Optional target component or agent.\n * @property {unknown} [payload]\n *           Optional data payload.\n */\n\n/**\n * Snapshot of the current application state.\n * @typedef {Object} AgentSnapshot\n * @property {number} timestamp\n *           When the snapshot was taken.\n * @property {Array<{name: string, hasSetup: boolean, hasChildren: boolean}>} components\n *           Registered component information.\n * @property {string[]} plugins\n *           Installed plugin names.\n */\n\n/**\n * Diff result comparing two snapshots.\n * @typedef {Object} AgentDiffResult\n * @property {string[]} added\n *           Component names present in snapshot B but not A.\n * @property {string[]} removed\n *           Component names present in snapshot A but not B.\n */\n\n/**\n * Descriptor returned by describeAction for agent introspection.\n * @typedef {Object} AgentActionDescriptor\n * @property {string} name\n *           The action name.\n * @property {AgentActionSchema | null} schema\n *           The action's contract schema, or null if none was provided.\n */\n\n/**\n * Result returned by `agent.inspect()` describing the component registry.\n * @typedef {Object} AgentInspectResult\n * @property {Array<{name: string, hasSetup: boolean, hasTemplate: boolean, hasChildren: boolean, hasStyle: boolean}>} components\n *           Registered component information with setup, template, children, and style flags.\n */\n\n/**\n * Extended error with a machine-readable `code` property.\n * All Agent plugin errors include `.code`; schema violations also include `.violations`.\n * @typedef {Object} AgentErrorFields\n * @property {string} code\n *           Machine-readable error code (e.g., \"AGENT_PERMISSION_DENIED\").\n * @property {string[]} [violations]\n *           Schema violation messages (present only on AGENT_SCHEMA_VIOLATION errors).\n */\n\n/**\n * The public API surface exposed as ctx.agent in components.\n * @typedef {Object} AgentApi\n * @property {(name: string, handler: Function, schema?: AgentActionSchema) => void} register\n * @property {(name: string) => void} unregister\n * @property {(name: string, payload?: unknown, scope?: string) => Promise<unknown>} execute\n * @property {(actions: Array<{action: string, payload?: unknown}>, scope?: string) => Promise<unknown[]>} executeBatch\n * @property {(actions: Array<{action: string, payload?: unknown}>, scope?: string) => Promise<unknown>} executeSequence\n * @property {(name: string) => boolean} hasAction\n * @property {(name: string) => AgentActionDescriptor | null} describeAction\n * @property {() => AgentActionDescriptor[]} listActions\n * @property {(scope?: string) => AgentCapabilityManifest} describe\n * @property {(command: AgentCommand, scope?: string) => Promise<void>} dispatch\n * @property {(type: string, handler: Function) => () => void} onCommand\n * @property {(filter?: AgentLogFilter) => AgentLogEntry[]} getLog\n * @property {() => void} clearLog\n * @property {import(\"../modules/Signal.js\").Signal<number>} actionCount\n * @property {import(\"../modules/Signal.js\").Signal<AgentLogEntry | null>} lastActivity\n * @property {() => AgentInspectResult} [inspect]\n * @property {() => AgentSnapshot} [snapshot]\n * @property {(a: AgentSnapshot, b: AgentSnapshot) => AgentDiffResult} [diff]\n */\n\n// ============================================================================\n// PLUGIN IMPLEMENTATION\n// ============================================================================\n\n/**\n * @class 🤖 AgentPlugin\n * @classdesc Agent integration plugin for Eleva.js providing AI/agent\n * capabilities through a focused API.\n *\n * Core Features:\n * - **Action Registry** — Register and execute callable actions with schemas\n * - **Command Bus** — Structured agent-to-component communication\n * - **Audit Log** — Automatic recording of actions, commands, and emitter events\n * - **Permissions** — Capability-based access control per scope\n * - **State Inspection** — Component tree inspection and snapshots (opt-in)\n *\n * Event observation is handled by the shared `eleva.emitter` (available as\n * `ctx.emitter` in every component). The audit log can optionally capture\n * emitter events via the `emitterEvents` option.\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(AgentPlugin, {\n *   maxLogSize: 200,\n *   actions: {\n *     greet: (payload) => `Hello, ${payload.name}!`\n *   },\n *   permissions: {\n *     \"ui-agent\": { actions: [\"greet\"], commands: [\"UPDATE_UI\"] }\n *   }\n * });\n *\n * @example\n * // Use in components — observe events via ctx.emitter, not ctx.agent\n * app.component(\"MyComponent\", {\n *   setup({ agent, emitter }) {\n *     agent.register(\"doSomething\", (payload) => payload.value * 2, {\n *       input: { value: \"number\" },\n *       output: \"number\"\n *     });\n *\n *     emitter.on(\"store:change\", (mutation) => {\n *       console.log(\"Store changed:\", mutation);\n *     });\n *\n *     return {};\n *   },\n *   template: () => `<div>Agent-powered component</div>`\n * });\n */\nexport const AgentPlugin = {\n  /**\n   * Unique identifier for the plugin.\n   * @type {string}\n   */\n  name: \"agent\",\n\n  /**\n   * Plugin version following semantic versioning.\n   * @type {string}\n   */\n  version: \"1.0.0\",\n\n  /**\n   * Plugin description.\n   * @type {string}\n   */\n  description:\n    \"Agent integration plugin providing action registry, command bus, audit logging, permissions, and state inspection for AI/agent workflows.\",\n\n  /**\n   * Installs the Agent plugin into the Eleva instance.\n   *\n   * @public\n   * @param {Eleva} eleva - The Eleva instance.\n   * @param {AgentOptions} options - Plugin configuration options.\n   * @returns {void}\n   * @description\n   * Creates an internal Agent instance and wraps `eleva.mount` and\n   * `eleva._mountComponents` to inject `ctx.agent` into every component's\n   * setup function. Hooks into `eleva.emitter` for cross-plugin audit log\n   * capture. Exposes the agent instance and convenience methods on the\n   * Eleva instance.\n   *\n   * @example\n   * // Basic installation\n   * app.use(AgentPlugin);\n   *\n   * // With options\n   * app.use(AgentPlugin, {\n   *   maxLogSize: 200,\n   *   enableInspection: true,\n   *   onError: (err, ctx) => console.error(ctx, err),\n   *   actions: { ping: () => \"pong\" },\n   *   permissions: { \"my-agent\": { actions: [\"ping\"] } },\n   *   emitterEvents: [\"store:\", \"router:\"]\n   * });\n   */\n  install(eleva, options = {}) {\n    // Idempotency guard — prevent stale wrapper chains on double-install\n    if (eleva._agent_originalMount) {\n      console.warn(\n        \"[AgentPlugin] Already installed. Uninstall first to reconfigure.\"\n      );\n      return;\n    }\n\n    const {\n      maxLogSize = 100,\n      enableInspection = true,\n      onError = null,\n      actions: preRegisteredActions = {},\n      permissions = {},\n      emitterEvents = [],\n      strictPermissions = false,\n      validateSchemas = false,\n    } = options;\n\n    // ==================================================================\n    // Shared Scoped-API State\n    // ==================================================================\n\n    /**\n     * Reference counts for actions registered via scoped APIs.\n     * Prevents one component's cleanup from removing an action\n     * that another component also registered.\n     * @type {Map<string, number>}\n     */\n    const _scopedActionRefCounts = new Map();\n\n    /**\n     * Snapshots of pre-existing global action handlers that were overwritten\n     * by scoped registrations. Used to restore on cleanup when ref count\n     * reaches zero.\n     * @type {Map<string, { handler: Function, schema: * }>}\n     */\n    const _globalActionSnapshots = new Map();\n\n    /**\n     * Flag to suppress snapshot updates during scoped register calls.\n     * Scoped register() calls baseApi.register() which hits the Agent\n     * class register() — this flag prevents that inner call from\n     * updating the snapshot with the scoped handler.\n     * @type {boolean}\n     */\n    let _inScopedRegister = false;\n\n    // ==================================================================\n    // Internal Agent Class\n    // ==================================================================\n\n    /**\n     * Internal Agent class managing all agent operations.\n     * Defined inside install for closure access to `eleva`.\n     *\n     * @private\n     */\n    class Agent {\n      constructor() {\n        /** @type {Map<string, Function>} */\n        this._actions = new Map();\n\n        /** @type {Map<string, AgentActionSchema | null>} */\n        this._schemas = new Map();\n\n        /** @type {Map<string, Set<Function>>} */\n        this._commandHandlers = new Map();\n\n        /** @type {AgentLogEntry[]} */\n        this._log = [];\n\n        /** @type {number} */\n        this._maxLogSize = maxLogSize;\n\n        /** @type {boolean} */\n        this._enableInspection = enableInspection;\n\n        /** @type {AgentErrorHandler|null} */\n        this._onError = onError;\n\n        /** @type {Record<string, AgentPermissionRule>} */\n        this._permissions = permissions;\n\n        /** @type {boolean} */\n        this._strictPermissions = strictPermissions;\n\n        /** @type {boolean} */\n        this._validateSchemas = validateSchemas;\n\n        /** @type {boolean} */\n        this._destroyed = false;\n\n        /** @type {(() => void)[]} */\n        this._emitterCleanups = [];\n\n        /** @type {import(\"../../modules/Signal.js\").Signal<number>} */\n        this._actionCountSignal = new eleva.signal(0);\n\n        /** @type {import(\"../../modules/Signal.js\").Signal<AgentLogEntry|null>} */\n        this._lastActivitySignal = new eleva.signal(null);\n\n        // Pre-register actions from options\n        this._registerInitialActions(preRegisteredActions);\n\n        // Hook into emitter for audit log capture\n        this._hookEmitter(emitterEvents);\n      }\n\n      // ----------------------------------------------------------------\n      // Initialization\n      // ----------------------------------------------------------------\n\n      /**\n       * Registers actions provided in the plugin options.\n       *\n       * @private\n       * @param {Record<string, Function>} actions - Map of action names to handlers.\n       * @returns {void}\n       */\n      _registerInitialActions(actions) {\n        Object.entries(actions).forEach(([name, handler]) => {\n          this.register(name, handler);\n        });\n      }\n\n      /**\n       * Hooks into eleva.emitter to capture events in the audit log.\n       *\n       * @private\n       * @param {string[]} prefixes - Event prefixes to capture.\n       * @returns {void}\n       */\n      _hookEmitter(prefixes) {\n        if (!prefixes.length || !eleva.emitter) {\n          return;\n        }\n\n        // For each prefix, subscribe to any event that starts with it.\n        // Since Emitter doesn't support wildcards, we wrap emitter.emit\n        // to intercept matching events.\n        const originalEmit = eleva.emitter.emit.bind(eleva.emitter);\n\n        const wrappedEmit = (event, ...args) => {\n          // Skip logging if agent has been destroyed (prevents side\n          // effects and memory growth when another wrapper still\n          // chains into this closure after Agent was uninstalled).\n          if (!this._destroyed) {\n            const shouldCapture = prefixes.some((p) => event.startsWith(p));\n            if (shouldCapture) {\n              this._addLogEntry({\n                type: \"event\",\n                action: event,\n                payload: args.length === 1 ? args[0] : args,\n                timestamp: Date.now(),\n                source: \"emitter\",\n              });\n            }\n          }\n          // Always call the original emit\n          return originalEmit(event, ...args);\n        };\n\n        eleva.emitter.emit = wrappedEmit;\n\n        // Store cleanup — only restore if emit is still our wrapper,\n        // to avoid clobbering another plugin's instrumentation.\n        this._emitterCleanups.push(() => {\n          if (eleva.emitter.emit === wrappedEmit) {\n            eleva.emitter.emit = originalEmit;\n          }\n        });\n      }\n\n      // ----------------------------------------------------------------\n      // Permissions\n      // ----------------------------------------------------------------\n\n      /**\n       * Checks if a scope has permission to execute an action or command.\n       *\n       * Default behaviour (strictPermissions = false):\n       * - No permissions configured → everything allowed (zero-config path)\n       * - No scope provided → unrestricted (trusted/internal call)\n       * - Scope provided → checked against rules\n       *\n       * Strict behaviour (strictPermissions = true):\n       * - No permissions configured → everything denied\n       * - No scope provided → denied (scope is mandatory)\n       * - Scope provided → checked against rules\n       *\n       * @private\n       * @param {string} scope - The scope/role to check.\n       * @param {\"actions\" | \"commands\"} kind - The permission kind.\n       * @param {string} name - The action or command name.\n       * @returns {boolean} True if allowed.\n       */\n      _checkPermission(scope, kind, name) {\n        const hasRules = Object.keys(this._permissions).length > 0;\n\n        if (this._strictPermissions) {\n          // Strict mode: scope is mandatory, rules are mandatory\n          if (!hasRules || !scope) {\n            return false;\n          }\n        } else {\n          // Default mode: no rules = allow all, no scope = unrestricted\n          if (!hasRules) {\n            return true;\n          }\n          if (!scope) {\n            return true;\n          }\n        }\n\n        const rule = this._permissions[scope];\n        if (!rule) {\n          return false;\n        }\n        const allowed = rule[kind];\n        if (!allowed) {\n          return false;\n        }\n        return allowed.includes(name);\n      }\n\n      // ----------------------------------------------------------------\n      // Destroyed Guard\n      // ----------------------------------------------------------------\n\n      /**\n       * Throws AGENT_DESTROYED if the agent has been destroyed.\n       * Called at the top of every mutating public method to prevent\n       * stale references from modifying state after teardown.\n       *\n       * @private\n       * @returns {void}\n       * @throws {Error} If the agent instance has been destroyed.\n       */\n      _assertAlive() {\n        if (this._destroyed) {\n          const error = new Error(\n            \"[AgentPlugin] Agent has been destroyed. Create a new instance via app.use(AgentPlugin).\"\n          );\n          error.code = \"AGENT_DESTROYED\";\n          throw error;\n        }\n      }\n\n      // ----------------------------------------------------------------\n      // Action Registry\n      // ----------------------------------------------------------------\n\n      /**\n       * Registers a callable action with an optional schema.\n       *\n       * @param {string} name - Unique action name.\n       * @param {Function} handler - The action handler function.\n       * @param {AgentActionSchema} [schema] - Optional action contract.\n       * @returns {void}\n       * @throws {Error} If handler is not a function or agent is destroyed.\n       */\n      register(name, handler, schema) {\n        this._assertAlive();\n        if (typeof handler !== \"function\") {\n          const error = new Error(\n            \"[AgentPlugin] Action handler must be a function\"\n          );\n          error.code = \"AGENT_HANDLER_NOT_FUNCTION\";\n          throw error;\n        }\n        // If a direct (non-scoped) global register overwrites a name with\n        // active scoped ownership, update the snapshot so cleanup restores\n        // the latest global handler instead of a stale one.\n        if (\n          !_inScopedRegister &&\n          _scopedActionRefCounts.has(name) &&\n          _globalActionSnapshots.has(name)\n        ) {\n          _globalActionSnapshots.set(name, { handler, schema: schema || null });\n        }\n        this._actions.set(name, handler);\n        this._schemas.set(name, schema || null);\n        this._actionCountSignal.value = this._actions.size;\n        if (eleva.emitter) {\n          try {\n            eleva.emitter.emit(\"agent:register\", {\n              name,\n              hasSchema: !!schema,\n              timestamp: Date.now(),\n            });\n          } catch (_) {\n            /* listener error must not break agent flow */\n          }\n        }\n      }\n\n      /**\n       * Removes a registered action.\n       *\n       * @param {string} name - The action name to remove.\n       * @returns {void}\n       */\n      unregister(name) {\n        this._assertAlive();\n        if (!this._actions.has(name)) {\n          console.warn(\n            `[AgentPlugin] Action \"${name}\" not found for unregister`\n          );\n          return;\n        }\n        this._actions.delete(name);\n        this._schemas.delete(name);\n        this._actionCountSignal.value = this._actions.size;\n        if (eleva.emitter) {\n          try {\n            eleva.emitter.emit(\"agent:unregister\", {\n              name,\n              timestamp: Date.now(),\n            });\n          } catch (_) {\n            /* listener error must not break agent flow */\n          }\n        }\n      }\n\n      /**\n       * Executes a registered action with optional scope-based permission check.\n       *\n       * Execution order: permission check → schema validation (if enabled) →\n       * handler invocation → audit log entry with outcome.\n       *\n       * @async\n       * @param {string} name - The action name to execute.\n       * @param {unknown} [payload] - Optional payload to pass to the handler.\n       * @param {string} [scope] - Optional scope for permission check.\n       * @returns {Promise<unknown>} The result of the action handler.\n       * @throws {Error} If the action is not found, permission denied, schema violation, or handler throws.\n       */\n      async execute(name, payload, scope) {\n        this._assertAlive();\n        if (!this._checkPermission(scope, \"actions\", name)) {\n          const error = new Error(\n            `[AgentPlugin] Permission denied: scope \"${scope}\" cannot execute \"${name}\"`\n          );\n          error.code = \"AGENT_PERMISSION_DENIED\";\n          if (this._onError) {\n            try {\n              this._onError(error, {\n                method: \"execute\",\n                code: \"AGENT_PERMISSION_DENIED\",\n                action: name,\n                scope,\n              });\n            } catch (_) {\n              /* onError must not alter agent flow */\n            }\n          }\n          throw error;\n        }\n\n        const handler = this._actions.get(name);\n\n        if (!handler) {\n          const error = new Error(`[AgentPlugin] Action \"${name}\" not found`);\n          error.code = \"AGENT_ACTION_NOT_FOUND\";\n          if (this._onError) {\n            try {\n              this._onError(error, {\n                method: \"execute\",\n                code: \"AGENT_ACTION_NOT_FOUND\",\n                action: name,\n              });\n            } catch (_) {\n              /* onError must not alter agent flow */\n            }\n          }\n          throw error;\n        }\n\n        // Schema validation (opt-in)\n        if (this._validateSchemas) {\n          const schema = this._schemas.get(name);\n          if (schema && schema.input) {\n            const violations = this._validatePayload(payload, schema.input);\n            if (violations.length > 0) {\n              const error = new Error(\n                `[AgentPlugin] Schema violation for \"${name}\": ${violations.join(\"; \")}`\n              );\n              error.code = \"AGENT_SCHEMA_VIOLATION\";\n              error.violations = violations;\n              if (this._onError) {\n                try {\n                  this._onError(error, {\n                    method: \"execute\",\n                    code: \"AGENT_SCHEMA_VIOLATION\",\n                    action: name,\n                  });\n                } catch (_) {\n                  /* onError must not alter agent flow */\n                }\n              }\n              throw error;\n            }\n          }\n        }\n\n        const startTime = Date.now();\n        try {\n          const result = await handler(payload);\n          const durationMs = Date.now() - startTime;\n          this._addLogEntry({\n            type: \"action\",\n            action: name,\n            payload,\n            timestamp: startTime,\n            source: scope || \"global\",\n            result,\n            durationMs,\n          });\n          if (eleva.emitter) {\n            try {\n              eleva.emitter.emit(\"agent:execute\", {\n                name,\n                payload,\n                result,\n                durationMs,\n                timestamp: startTime,\n              });\n            } catch (_) {\n              /* listener error must not break agent flow */\n            }\n          }\n          return result;\n        } catch (rawError) {\n          const error =\n            rawError instanceof Error ? rawError : new Error(String(rawError));\n          const durationMs = Date.now() - startTime;\n          this._addLogEntry({\n            type: \"action\",\n            action: name,\n            payload,\n            timestamp: startTime,\n            source: scope || \"global\",\n            error: error.message,\n            durationMs,\n          });\n          if (eleva.emitter) {\n            try {\n              eleva.emitter.emit(\"agent:execute:error\", {\n                name,\n                payload,\n                error: error.message,\n                durationMs,\n                timestamp: startTime,\n              });\n            } catch (_) {\n              /* listener error must not break agent flow */\n            }\n          }\n          if (!error.code) {\n            error.code = \"AGENT_HANDLER_ERROR\";\n          }\n          if (this._onError) {\n            try {\n              this._onError(error, {\n                method: \"execute\",\n                code: error.code,\n                action: name,\n              });\n            } catch (_) {\n              /* onError must not alter agent flow */\n            }\n          }\n          throw error;\n        }\n      }\n\n      /**\n       * Checks if an action is registered.\n       *\n       * @param {string} name - The action name to check.\n       * @returns {boolean} True if the action exists.\n       */\n      hasAction(name) {\n        return this._actions.has(name);\n      }\n\n      /**\n       * Returns the descriptor for a registered action.\n       *\n       * @param {string} name - The action name.\n       * @returns {AgentActionDescriptor | null} The descriptor, or null if not found.\n       */\n      describeAction(name) {\n        if (!this._actions.has(name)) {\n          return null;\n        }\n        return {\n          name,\n          schema: this._schemas.get(name) || null,\n        };\n      }\n\n      /**\n       * Lists all registered actions with their schemas.\n       *\n       * @returns {AgentActionDescriptor[]} Array of action descriptors.\n       */\n      listActions() {\n        const result = [];\n        this._actions.forEach((_, name) => {\n          result.push({\n            name,\n            schema: this._schemas.get(name) || null,\n          });\n        });\n        return result;\n      }\n\n      // ----------------------------------------------------------------\n      // Command Bus\n      // ----------------------------------------------------------------\n\n      /**\n       * Dispatches a structured command to registered handlers\n       * with optional scope-based permission check.\n       *\n       * @async\n       * @param {AgentCommand} command - The command to dispatch.\n       * @param {string} [scope] - Optional scope for permission check.\n       * @returns {Promise<void>}\n       */\n      async dispatch(command, scope) {\n        this._assertAlive();\n        if (!command || typeof command.type !== \"string\") {\n          const error = new Error(\n            \"[AgentPlugin] Command must have a string 'type'\"\n          );\n          error.code = \"AGENT_COMMAND_INVALID_TYPE\";\n          throw error;\n        }\n\n        if (!this._checkPermission(scope, \"commands\", command.type)) {\n          const error = new Error(\n            `[AgentPlugin] Permission denied: scope \"${scope}\" cannot dispatch \"${command.type}\"`\n          );\n          error.code = \"AGENT_PERMISSION_DENIED\";\n          if (this._onError) {\n            try {\n              this._onError(error, {\n                method: \"dispatch\",\n                code: \"AGENT_PERMISSION_DENIED\",\n                commandType: command.type,\n                scope,\n              });\n            } catch (_) {\n              /* onError must not alter agent flow */\n            }\n          }\n          throw error;\n        }\n\n        const startTime = Date.now();\n        const errors = [];\n\n        const handlers = this._commandHandlers.get(command.type);\n        if (handlers) {\n          for (const handler of handlers) {\n            try {\n              await handler(command);\n            } catch (rawHandlerError) {\n              const handlerError =\n                rawHandlerError instanceof Error\n                  ? rawHandlerError\n                  : new Error(String(rawHandlerError));\n              errors.push(handlerError.message);\n              if (!handlerError.code) {\n                handlerError.code = \"AGENT_HANDLER_ERROR\";\n              }\n              if (this._onError) {\n                try {\n                  this._onError(handlerError, {\n                    method: \"dispatch\",\n                    code: handlerError.code,\n                    commandType: command.type,\n                  });\n                } catch (_) {\n                  /* onError must not alter agent flow */\n                }\n              }\n            }\n          }\n        }\n\n        const durationMs = Date.now() - startTime;\n        const logEntry = {\n          type: \"command\",\n          action: command.type,\n          payload: command.payload,\n          timestamp: startTime,\n          source: command.target || scope || \"global\",\n          durationMs,\n        };\n        if (errors.length > 0) {\n          logEntry.error = errors.join(\"; \");\n        }\n        this._addLogEntry(logEntry);\n        if (eleva.emitter) {\n          try {\n            eleva.emitter.emit(\"agent:dispatch\", {\n              type: command.type,\n              target: command.target,\n              payload: command.payload,\n              errors: errors.length > 0 ? errors : undefined,\n              durationMs,\n              timestamp: startTime,\n            });\n          } catch (_) {\n            /* listener error must not break agent flow */\n          }\n        }\n      }\n\n      /**\n       * Registers a handler for a command type.\n       *\n       * @param {string} type - The command type to handle.\n       * @param {Function} handler - The handler function.\n       * @returns {() => void} Unsubscribe function.\n       * @throws {Error} If handler is not a function.\n       */\n      onCommand(type, handler) {\n        this._assertAlive();\n        if (typeof handler !== \"function\") {\n          const error = new Error(\n            \"[AgentPlugin] Command handler must be a function\"\n          );\n          error.code = \"AGENT_HANDLER_NOT_FUNCTION\";\n          throw error;\n        }\n\n        if (!this._commandHandlers.has(type)) {\n          this._commandHandlers.set(type, new Set());\n        }\n        this._commandHandlers.get(type).add(handler);\n\n        return () => {\n          const handlers = this._commandHandlers.get(type);\n          if (handlers) {\n            handlers.delete(handler);\n            if (handlers.size === 0) {\n              this._commandHandlers.delete(type);\n            }\n          }\n        };\n      }\n\n      // ----------------------------------------------------------------\n      // Audit Log\n      // ----------------------------------------------------------------\n\n      /**\n       * Adds an entry to the audit log with rotation.\n       *\n       * @private\n       * @param {AgentLogEntry} entry - The log entry to add.\n       * @returns {void}\n       */\n      _addLogEntry(entry) {\n        this._log.push(entry);\n        if (this._log.length > this._maxLogSize) {\n          this._log.shift();\n        }\n        this._lastActivitySignal.value = entry;\n      }\n\n      /**\n       * Returns audit log entries, optionally filtered.\n       *\n       * @param {AgentLogFilter} [filter] - Optional filter criteria.\n       * @returns {AgentLogEntry[]} Matching log entries.\n       */\n      getLog(filter) {\n        if (!filter) {\n          return [...this._log];\n        }\n\n        return this._log.filter((entry) => {\n          if (filter.type && entry.type !== filter.type) {\n            return false;\n          }\n          if (filter.since && entry.timestamp < filter.since) {\n            return false;\n          }\n          if (filter.action && entry.action !== filter.action) {\n            return false;\n          }\n          if (filter.status) {\n            const hasError = \"error\" in entry && entry.error != null;\n            if (filter.status === \"ok\" && hasError) return false;\n            if (filter.status === \"error\" && !hasError) return false;\n          }\n          return true;\n        });\n      }\n\n      /**\n       * Clears all audit log entries.\n       *\n       * @returns {void}\n       */\n      clearLog() {\n        this._assertAlive();\n        this._log = [];\n      }\n\n      // ----------------------------------------------------------------\n      // State Inspection\n      // ----------------------------------------------------------------\n\n      /**\n       * Inspects the component registry.\n       *\n       * @returns {AgentInspectResult} Component tree information.\n       */\n      inspect() {\n        if (this._destroyed) {\n          return { components: [] };\n        }\n        if (!this._enableInspection) {\n          console.warn(\n            \"[AgentPlugin] Inspection is disabled. Enable with { enableInspection: true }\"\n          );\n          return { components: [] };\n        }\n\n        const components = [];\n        if (eleva._components) {\n          eleva._components.forEach((def, name) => {\n            components.push({\n              name,\n              hasSetup: typeof def.setup === \"function\",\n              hasTemplate:\n                typeof def.template === \"function\" ||\n                typeof def.template === \"string\",\n              hasChildren:\n                !!def.children && Object.keys(def.children).length > 0,\n              hasStyle: !!def.style,\n            });\n          });\n        }\n\n        return { components };\n      }\n\n      /**\n       * Creates a serializable snapshot of the application state.\n       *\n       * Note: The plugin list uses `eleva.plugins` (the public Map maintained\n       * by each plugin's install/uninstall) as the sole authoritative source.\n       * Plugins that don't register there won't appear in the snapshot.\n       *\n       * @returns {AgentSnapshot} The snapshot object.\n       */\n      snapshot() {\n        if (this._destroyed) {\n          return { timestamp: Date.now(), components: [], plugins: [] };\n        }\n        if (!this._enableInspection) {\n          console.warn(\n            \"[AgentPlugin] Inspection is disabled. Enable with { enableInspection: true }\"\n          );\n          return { timestamp: Date.now(), components: [], plugins: [] };\n        }\n\n        const components = [];\n        if (eleva._components) {\n          eleva._components.forEach((def, name) => {\n            components.push({\n              name,\n              hasSetup: typeof def.setup === \"function\",\n              hasChildren:\n                !!def.children && Object.keys(def.children).length > 0,\n            });\n          });\n        }\n\n        // Use eleva.plugins (public Map, maintained by install/uninstall)\n        // as the sole authoritative source. This map is kept in sync by\n        // plugins that register there (Attr, Router, Agent) and accurately\n        // reflects the current install state. We avoid merging with\n        // eleva._plugins (core internal Map) because it is add-only and\n        // never pruned on uninstall, which would report stale entries.\n        // Plugins that don't register in eleva.plugins (e.g., StorePlugin)\n        // won't appear here — they can adopt the pattern independently.\n        const plugins = [];\n        if (eleva.plugins) {\n          eleva.plugins.forEach((_, name) => plugins.push(name));\n        }\n\n        return {\n          timestamp: Date.now(),\n          components,\n          plugins,\n        };\n      }\n\n      /**\n       * Compares two snapshots and returns what changed.\n       *\n       * @param {AgentSnapshot} snapshotA - The first snapshot.\n       * @param {AgentSnapshot} snapshotB - The second snapshot.\n       * @returns {AgentDiffResult} The diff result.\n       */\n      diff(snapshotA, snapshotB) {\n        const namesA = new Set((snapshotA.components || []).map((c) => c.name));\n        const namesB = new Set((snapshotB.components || []).map((c) => c.name));\n\n        const added = [];\n        const removed = [];\n\n        namesB.forEach((name) => {\n          if (!namesA.has(name)) {\n            added.push(name);\n          }\n        });\n\n        namesA.forEach((name) => {\n          if (!namesB.has(name)) {\n            removed.push(name);\n          }\n        });\n\n        return { added, removed };\n      }\n\n      // ----------------------------------------------------------------\n      // Schema Validation\n      // ----------------------------------------------------------------\n\n      /**\n       * Validates a payload against a schema's input definition.\n       *\n       * @private\n       * @param {unknown} payload - The payload to validate.\n       * @param {Record<string, string>} inputSchema - Expected input shape.\n       * @returns {string[]} Array of violation messages (empty if valid).\n       */\n      _validatePayload(payload, inputSchema) {\n        const violations = [];\n\n        if (payload == null || typeof payload !== \"object\") {\n          violations.push(\n            `expected object payload, got ${payload === null ? \"null\" : typeof payload}`\n          );\n          return violations;\n        }\n\n        for (const [field, expectedType] of Object.entries(inputSchema)) {\n          if (!(field in payload)) {\n            violations.push(`missing required field \"${field}\"`);\n          } else {\n            const actualType = typeof payload[field];\n            if (actualType !== expectedType) {\n              violations.push(\n                `field \"${field}\" expected ${expectedType}, got ${actualType}`\n              );\n            }\n          }\n        }\n\n        return violations;\n      }\n\n      // ----------------------------------------------------------------\n      // Composition Primitives\n      // ----------------------------------------------------------------\n\n      /**\n       * Executes multiple actions in parallel.\n       * All actions are started concurrently. If any action fails,\n       * the entire batch rejects with the first error.\n       *\n       * @async\n       * @param {Array<{action: string, payload?: unknown}>} actions - Actions to execute.\n       * @param {string} [scope] - Optional scope for permission check.\n       * @returns {Promise<unknown[]>} Array of results in the same order as input.\n       * @throws {Error} If any action fails (first error).\n       */\n      async executeBatch(actions, scope) {\n        this._assertAlive();\n        return Promise.all(\n          actions.map((item) => this.execute(item.action, item.payload, scope))\n        );\n      }\n\n      /**\n       * Executes actions sequentially, piping results.\n       * The result of each action becomes the payload of the next.\n       * The first action uses the payload from its entry; subsequent actions\n       * receive the previous action's result as their payload.\n       *\n       * @async\n       * @param {Array<{action: string, payload?: unknown}>} actions - Actions to execute in order.\n       * @param {string} [scope] - Optional scope for permission check.\n       * @returns {Promise<unknown>} The result of the last action in the sequence.\n       * @throws {Error} If any action in the sequence fails (stops immediately).\n       */\n      async executeSequence(actions, scope) {\n        this._assertAlive();\n        let result;\n        for (let i = 0; i < actions.length; i++) {\n          const item = actions[i];\n          const payload = i === 0 ? item.payload : result;\n          result = await this.execute(item.action, payload, scope);\n        }\n        return result;\n      }\n\n      // ----------------------------------------------------------------\n      // Capability Discovery\n      // ----------------------------------------------------------------\n\n      /**\n       * Returns a complete capability manifest describing all available\n       * agent features for a given scope.\n       *\n       * @param {string} [scope] - Optional scope to check permissions against.\n       * @returns {AgentCapabilityManifest} The capability manifest.\n       */\n      describe(scope) {\n        // Actions with per-action allowed flag\n        const actions = [];\n        this._actions.forEach((_, name) => {\n          actions.push({\n            name,\n            schema: this._schemas.get(name) || null,\n            allowed: this._checkPermission(scope, \"actions\", name),\n          });\n        });\n\n        // All registered command types\n        const commands = [...this._commandHandlers.keys()];\n\n        // Resolved permissions for the requested scope\n        let resolvedPermissions = null;\n        if (scope) {\n          const rule = this._permissions[scope];\n          resolvedPermissions = {\n            scope,\n            actions: rule && rule.actions ? [...rule.actions] : [],\n            commands: rule && rule.commands ? [...rule.commands] : [],\n          };\n        }\n\n        return {\n          actions,\n          commands,\n          permissions: resolvedPermissions,\n          config: {\n            strictPermissions: this._strictPermissions,\n            maxLogSize: this._maxLogSize,\n            inspectionEnabled: this._enableInspection,\n            validateSchemas: this._validateSchemas,\n          },\n        };\n      }\n\n      // ----------------------------------------------------------------\n      // Cleanup\n      // ----------------------------------------------------------------\n\n      /**\n       * Destroys the agent, clearing all internal state and\n       * restoring emitter hooks.\n       *\n       * @returns {void}\n       */\n      destroy() {\n        this._destroyed = true;\n        this._actions.clear();\n        this._schemas.clear();\n        this._commandHandlers.clear();\n        this._log = [];\n        this._emitterCleanups.forEach((fn) => fn());\n        this._emitterCleanups = [];\n        this._actionCountSignal.value = 0;\n        this._lastActivitySignal.value = null;\n        _scopedActionRefCounts.clear();\n        _globalActionSnapshots.clear();\n      }\n    }\n\n    // ==================================================================\n    // Instantiation\n    // ==================================================================\n\n    const agent = new Agent();\n\n    // ==================================================================\n    // Mount Wrapping (Context Injection)\n    // ==================================================================\n\n    /**\n     * Creates the ctx.agent API object for injection into components.\n     * Inspection methods are only included when enableInspection is true.\n     *\n     * @private\n     * @returns {AgentApi} The agent API surface.\n     */\n    const createAgentApi = () => {\n      /** @type {AgentApi} */\n      const api = {\n        // Action Registry\n        register: agent.register.bind(agent),\n        unregister: agent.unregister.bind(agent),\n        execute: agent.execute.bind(agent),\n        executeBatch: agent.executeBatch.bind(agent),\n        executeSequence: agent.executeSequence.bind(agent),\n        hasAction: agent.hasAction.bind(agent),\n        describeAction: agent.describeAction.bind(agent),\n        listActions: agent.listActions.bind(agent),\n        describe: agent.describe.bind(agent),\n\n        // Command Bus\n        dispatch: agent.dispatch.bind(agent),\n        onCommand: agent.onCommand.bind(agent),\n\n        // Audit Log\n        getLog: agent.getLog.bind(agent),\n        clearLog: agent.clearLog.bind(agent),\n\n        // Reactive Signals\n        actionCount: agent._actionCountSignal,\n        lastActivity: agent._lastActivitySignal,\n      };\n\n      // Only expose inspection methods when enabled\n      if (enableInspection) {\n        api.inspect = agent.inspect.bind(agent);\n        api.snapshot = agent.snapshot.bind(agent);\n        api.diff = agent.diff.bind(agent);\n      }\n\n      return api;\n    };\n\n    /**\n     * Creates a component-scoped agent API that tracks registrations\n     * for automatic cleanup on component unmount.\n     *\n     * @private\n     * @returns {{ api: AgentApi, cleanup: () => void }}\n     */\n    const createScopedAgentApi = () => {\n      const baseApi = createAgentApi();\n      /** @type {Set<string>} */\n      const registeredActions = new Set();\n      /** @type {Array<() => void>} */\n      const commandUnsubscribes = [];\n\n      const scopedApi = {\n        ...baseApi,\n        register(name, handler, schema) {\n          if (!registeredActions.has(name)) {\n            // Snapshot pre-existing global handler before first scoped overwrite\n            if (!_scopedActionRefCounts.has(name) && agent.hasAction(name)) {\n              _globalActionSnapshots.set(name, {\n                handler: agent._actions.get(name),\n                schema: agent._schemas.get(name),\n              });\n            }\n            registeredActions.add(name);\n            _scopedActionRefCounts.set(\n              name,\n              (_scopedActionRefCounts.get(name) || 0) + 1\n            );\n          }\n          _inScopedRegister = true;\n          try {\n            baseApi.register(name, handler, schema);\n          } finally {\n            _inScopedRegister = false;\n          }\n        },\n        unregister(name) {\n          if (registeredActions.has(name)) {\n            registeredActions.delete(name);\n            const count = (_scopedActionRefCounts.get(name) || 1) - 1;\n            if (count <= 0) {\n              _scopedActionRefCounts.delete(name);\n              const snapshot = _globalActionSnapshots.get(name);\n              if (snapshot) {\n                _globalActionSnapshots.delete(name);\n                baseApi.register(name, snapshot.handler, snapshot.schema);\n              } else {\n                baseApi.unregister(name);\n              }\n            } else {\n              _scopedActionRefCounts.set(name, count);\n            }\n          } else {\n            console.warn(\n              `[AgentPlugin] Scoped unregister ignored: \"${name}\" is not owned by this component`\n            );\n          }\n        },\n        onCommand(type, handler) {\n          const unsub = baseApi.onCommand(type, handler);\n          commandUnsubscribes.push(unsub);\n          return unsub;\n        },\n      };\n\n      const cleanup = () => {\n        for (const name of registeredActions) {\n          const count = (_scopedActionRefCounts.get(name) || 1) - 1;\n          if (count <= 0) {\n            _scopedActionRefCounts.delete(name);\n            const snapshot = _globalActionSnapshots.get(name);\n            if (snapshot) {\n              _globalActionSnapshots.delete(name);\n              agent.register(name, snapshot.handler, snapshot.schema);\n            } else if (agent.hasAction(name)) {\n              agent.unregister(name);\n            }\n          } else {\n            _scopedActionRefCounts.set(name, count);\n          }\n        }\n        registeredActions.clear();\n        for (const unsub of commandUnsubscribes) {\n          unsub();\n        }\n        commandUnsubscribes.length = 0;\n      };\n\n      return { api: scopedApi, cleanup };\n    };\n\n    // Store the original mount method\n    const originalMount = eleva.mount;\n\n    /**\n     * Overridden mount method that injects agent context into components.\n     *\n     * @param {HTMLElement} container - The DOM element to mount to.\n     * @param {string | ComponentDefinition} compName - Component name or definition.\n     * @param {ComponentProps} [props={}] - Optional component properties.\n     * @returns {Promise<MountResult>} The mount result.\n     */\n    eleva.mount = async (container, compName, props = {}) => {\n      const componentDef =\n        typeof compName === \"string\"\n          ? eleva._components.get(compName) || compName\n          : compName;\n\n      if (!componentDef || typeof componentDef !== \"object\") {\n        return await originalMount.call(eleva, container, compName, props);\n      }\n\n      const wrappedComponent = {\n        ...componentDef,\n        async setup(ctx) {\n          const { api, cleanup } = createScopedAgentApi();\n          /** @type {AgentApi} */\n          ctx.agent = api;\n\n          const originalSetup = componentDef.setup;\n          const result = originalSetup ? await originalSetup(ctx) : {};\n\n          const originalOnUnmount = result.onUnmount;\n          result.onUnmount = async (info) => {\n            try {\n              if (originalOnUnmount) {\n                await originalOnUnmount(info);\n              }\n            } finally {\n              cleanup();\n            }\n          };\n\n          return result;\n        },\n      };\n\n      return await originalMount.call(\n        eleva,\n        container,\n        wrappedComponent,\n        props\n      );\n    };\n\n    // Override _mountComponents for child component injection\n    const originalMountComponents = eleva._mountComponents;\n\n    /**\n     * Overridden _mountComponents that injects agent context into child components.\n     *\n     * @param {HTMLElement} container - The parent container element.\n     * @param {ChildrenMap} children - Map of selectors to component definitions.\n     * @param {MountResult[]} childInstances - Array to store mounted instances.\n     * @param {ComponentContext & SetupResult} context - Parent component context.\n     * @returns {Promise<void>}\n     */\n    eleva._mountComponents = async (\n      container,\n      children,\n      childInstances,\n      context\n    ) => {\n      const wrappedChildren = {};\n\n      for (const [selector, childComponent] of Object.entries(children)) {\n        const componentDef =\n          typeof childComponent === \"string\"\n            ? eleva._components.get(childComponent) || childComponent\n            : childComponent;\n\n        if (componentDef && typeof componentDef === \"object\") {\n          wrappedChildren[selector] = {\n            ...componentDef,\n            async setup(ctx) {\n              const { api, cleanup } = createScopedAgentApi();\n              /** @type {AgentApi} */\n              ctx.agent = api;\n\n              const originalSetup = componentDef.setup;\n              const result = originalSetup ? await originalSetup(ctx) : {};\n\n              const originalOnUnmount = result.onUnmount;\n              result.onUnmount = async (info) => {\n                try {\n                  if (originalOnUnmount) {\n                    await originalOnUnmount(info);\n                  }\n                } finally {\n                  cleanup();\n                }\n              };\n\n              return result;\n            },\n          };\n        } else {\n          wrappedChildren[selector] = childComponent;\n        }\n      }\n\n      return await originalMountComponents.call(\n        eleva,\n        container,\n        wrappedChildren,\n        childInstances,\n        context\n      );\n    };\n\n    // ==================================================================\n    // Expose on Eleva Instance\n    // ==================================================================\n\n    /** @type {Agent} */\n    eleva.agent = agent;\n\n    /** @type {(name: string, payload?: unknown, scope?: string) => Promise<unknown>} */\n    eleva.agentExecute = (name, payload, scope) => {\n      return agent.execute(name, payload, scope);\n    };\n\n    /** @type {(command: AgentCommand, scope?: string) => Promise<void>} */\n    eleva.agentDispatch = (command, scope) => {\n      return agent.dispatch(command, scope);\n    };\n\n    // Store original methods for cleanup (namespaced to avoid collision)\n    eleva._agent_originalMount = originalMount;\n    eleva._agent_originalMountComponents = originalMountComponents;\n\n    // Register plugin metadata\n    if (!eleva.plugins) {\n      eleva.plugins = new Map();\n    }\n    eleva.plugins.set(this.name, {\n      name: this.name,\n      version: this.version,\n      description: this.description,\n      options,\n    });\n  },\n\n  /**\n   * Uninstalls the Agent plugin from the Eleva instance.\n   *\n   * @public\n   * @param {Eleva} eleva - The Eleva instance.\n   * @returns {void}\n   * @description\n   * Restores the original Eleva methods, emitter hooks, and removes all\n   * plugin-specific functionality including the agent instance and\n   * convenience methods.\n   *\n   * @example\n   * AgentPlugin.uninstall(app);\n   */\n  uninstall(eleva) {\n    // Restore original mount method\n    if (eleva._agent_originalMount) {\n      eleva.mount = eleva._agent_originalMount;\n      delete eleva._agent_originalMount;\n    }\n\n    // Restore original _mountComponents method\n    if (eleva._agent_originalMountComponents) {\n      eleva._mountComponents = eleva._agent_originalMountComponents;\n      delete eleva._agent_originalMountComponents;\n    }\n\n    // Destroy and remove agent instance\n    if (eleva.agent) {\n      if (typeof eleva.agent.destroy === \"function\") {\n        eleva.agent.destroy();\n      }\n      delete eleva.agent;\n    }\n\n    // Remove convenience methods\n    if (eleva.agentExecute) {\n      delete eleva.agentExecute;\n    }\n    if (eleva.agentDispatch) {\n      delete eleva.agentDispatch;\n    }\n\n    // Remove plugin metadata\n    if (eleva.plugins) {\n      eleva.plugins.delete(\"agent\");\n    }\n  },\n};\n\n// Short name export for convenience\nexport { AgentPlugin as Agent };\n"],"names":["AgentPlugin","name","version","description","install","eleva","options","_agent_originalMount","console","warn","maxLogSize","enableInspection","onError","actions","preRegisteredActions","permissions","emitterEvents","strictPermissions","validateSchemas","_scopedActionRefCounts","Map","_globalActionSnapshots","_inScopedRegister","Agent","_registerInitialActions","Object","entries","forEach","handler","register","_hookEmitter","prefixes","length","emitter","originalEmit","emit","bind","wrappedEmit","event","args","_destroyed","shouldCapture","some","p","startsWith","_addLogEntry","type","action","payload","timestamp","Date","now","source","_emitterCleanups","push","_checkPermission","scope","kind","hasRules","keys","_permissions","_strictPermissions","rule","allowed","includes","_assertAlive","error","Error","code","schema","has","set","_actions","_schemas","_actionCountSignal","value","size","hasSchema","_","unregister","delete","execute","_onError","method","get","_validateSchemas","input","violations","_validatePayload","join","startTime","result","durationMs","rawError","String","message","hasAction","describeAction","listActions","dispatch","command","commandType","errors","handlers","_commandHandlers","rawHandlerError","handlerError","logEntry","target","undefined","onCommand","Set","add","entry","_log","_maxLogSize","shift","_lastActivitySignal","getLog","filter","since","status","hasError","clearLog","inspect","components","_enableInspection","_components","def","hasSetup","setup","hasTemplate","template","hasChildren","children","hasStyle","style","snapshot","plugins","diff","snapshotA","snapshotB","namesA","map","c","namesB","added","removed","inputSchema","field","expectedType","actualType","executeBatch","Promise","all","item","executeSequence","i","describe","commands","resolvedPermissions","config","inspectionEnabled","destroy","clear","fn","signal","agent","createAgentApi","api","actionCount","lastActivity","createScopedAgentApi","baseApi","registeredActions","commandUnsubscribes","scopedApi","count","unsub","cleanup","originalMount","mount","container","compName","props","componentDef","call","wrappedComponent","ctx","originalSetup","originalOnUnmount","onUnmount","info","originalMountComponents","_mountComponents","childInstances","context","wrappedChildren","selector","childComponent","agentExecute","agentDispatch","_agent_originalMountComponents","uninstall"],"mappings":";;;AAEA;;;;;AAKC;AAGD;AACA;AAEA;AACA;AACA;AAEA;;;;;;;;;AASC;AAGD;AACA;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsMC;AAGD;AACA;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+CaA,WAAAA,GAAc;AACzB;;;AAGC,MACDC,IAAAA,EAAM,OAAA;AAEN;;;AAGC,MACDC,OAAAA,EAAS,OAAA;AAET;;;AAGC,MACDC,WAAAA,EACE,2IAAA;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BC,MACDC,OAAAA,CAAAA,CAAQC,KAAK,EAAEC,OAAAA,GAAU,EAAE,EAAA;;QAEzB,IAAID,KAAAA,CAAME,oBAAoB,EAAE;AAC9BC,YAAAA,OAAAA,CAAQC,IAAI,CACV,kEAAA,CAAA;AAEF,YAAA;AACF,QAAA;AAEA,QAAA,MAAM,EACJC,UAAAA,GAAa,GAAG,EAChBC,gBAAAA,GAAmB,IA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