import type { IMatrixContext } from '../engine/core/IMatrixContext';
import { MatrixActor, type DeepBindingDescriptor } from '../core/MatrixActor';
import type { IChildAddedPayload } from '../engine/remoting/IChildAddedPayload';
import type { IChildRemovedPayload } from '../engine/remoting/IChildRemovedPayload';
import { type ActivityFrame } from './ActivityFrame';
/**
 * Detail payload emitted with mx-capability-request.
 * Used by parent shells to drive escalation UX across composed boundaries.
 */
export interface CapabilityRequestDetail {
    domain: string;
    requestedRight: string;
    component: string;
    action: string;
    error: unknown;
}
/** Oracle snapshot types (FP-42) — mirrored in daemon/src/services/oracle/types.ts */
export type OracleSnapshotAcceptsEntry = {
    op: string;
    params: Array<[string, string]>;
};
export type OracleSnapshotNode = {
    mount: string;
    tag: string;
    description?: string;
    accepts: OracleSnapshotAcceptsEntry[];
    emits: string[];
    tokens: Record<string, {
        default: string;
        description: string;
    }>;
    cognitiveState: Record<string, unknown>;
    children: OracleSnapshotNode[];
};
/** Actor class constructor type. */
export type ActorConstructor = new () => MatrixActor;
/** Registration options for register() factory. */
export interface IRegisterOptions {
    /** HTML template string for shadow DOM */
    template?: string;
    /** Observed attributes */
    observedAttributes?: string[];
    /** Tracked component IDs for CQRS view pattern */
    tracks?: string[];
}
export declare abstract class MatrixActorHtmlElement extends HTMLElement {
    /**
     * Index signature for dynamic handler access.
     * Enables type-safe lookup of onFoo handlers by name.
     */
    [key: string]: unknown;
    /** Commands this element accepts (Pattern A: all-in-one). Override in subclass. */
    static accepts: Record<string, unknown>;
    /** Events this element emits (Pattern A: all-in-one). Override in subclass. */
    static emits: Record<string, unknown>;
    /**
     * Theme tokens this element declares support for.
     * Each key is a token name (without --mx- prefix), value is metadata.
     * Surfaced in $introspect and oracle snapshots for AI discoverability.
     */
    static tokens: Record<string, {
        default: string;
        description: string;
    }>;
    /**
     * Human-readable self-description of this component.
     * Surfaced in oracle snapshots so agents know what this component IS,
     * not just what operations it accepts.
     *
     * Override in subclasses:
     *   static description = "Real-time stock ticker for TSLA. Set rules to fire events on price patterns.";
     */
    static description?: string;
    /** Template string for shadow DOM. Override in subclass. */
    static template?: string;
    /** Optional CSS string for reactive render shells. */
    static styles?: string;
    /** Optional initial state seed copied into actor state on mount. */
    static state?: Record<string, unknown>;
    /**
     * Fact domains this component should hydrate and subscribe to on mount.
     *
     * Components can override with:
     *   static factDomains = ['market.tsla', 'portfolio.main'];
     */
    static factDomains: string[];
    /** Tracked component IDs for CQRS view pattern. */
    static tracks?: string[];
    /**
     * Module URL where this element class was defined.
     * Set to import.meta.url for ghost rendering support.
     */
    static moduleUrl?: string;
    /** How long to wait for context before warning (ms). */
    static contextTimeoutMs: number;
    /** End-to-end timeout for $prompt round trip (ms). Override per-class or set globally. */
    static promptTimeoutMs: number;
    /**
     * Layout-only flag for transparent container components.
     *
     * When true, child elements skip past this component when searching for
     * their parent shell. The component IS an actor (has accepts/emits, receives
     * context, is network-controllable), but it does NOT parent the elements
     * placed in its light DOM slots. Those children register with the next
     * non-layout ancestor instead, preserving mount paths.
     *
     * Example: <mx-split> owns layout (drag handle, sizing) but doesn't
     * parent the children placed in slot="before"/slot="after".
     */
    static _layoutOnly: boolean;
    /** The internal headless actor (composition-with-delegation). */
    protected _actor: MatrixActor | null;
    /** The context received from parent or runtime. */
    protected _context: IMatrixContext | null;
    /** Children waiting for context. */
    private _pendingChildren;
    /** Whether we've received context. */
    _contextReceived: boolean;
    /** Whether we're connected to DOM. */
    protected _connected: boolean;
    /** Pending dispose flag for detecting DOM moves vs removals. */
    protected _pendingDispose: boolean;
    /** Promise that resolves when element is ready. */
    readonly ready: Promise<void>;
    private _resolveReady;
    /** Timeout handle for orphan detection. */
    private _orphanTimeout?;
    /** Shell-level subscriptions (unsubscribed on context change). */
    private _shellSubs;
    /** Fact-plane subscriptions (unsubscribed on remount/disconnect). */
    private _factUnsubs;
    /** Epoch token that invalidates stale async fact hydration work. */
    private _factEpoch;
    /** Remote mount for proxy/clone mode. */
    protected _remoteMount: string | null;
    /** Agent session ID for this component — persists across $prompt calls within a page session. */
    protected _agentSessionId: string | null;
    /** Accumulated activity frames for the current request (cleared on terminal phase). */
    protected _activityFrames: ActivityFrame[];
    /** Whether activity is currently in progress (between first frame and terminal phase). */
    private _activityActive;
    /** Root context for federation (propagated through component tree). */
    private _rootContext;
    /** Context object to propagate to children. */
    private _contextToPropagate;
    /** Version counter for factory-created component tags (custom elements can't be re-registered). */
    private readonly _factoryVersions;
    /** Microtask batching gate for render(state) updates. */
    private _renderPending;
    /** Guard to avoid re-attaching delegated listeners. */
    private _delegatedEventsWired;
    constructor();
    /**
     * Get the separate actor class for Pattern B.
     * Override in subclass to use a separate actor class.
     * Default: returns null → Pattern A (all-in-one, DynamicActor created).
     */
    static getActorClass(): ActorConstructor | null;
    /**
     * Get the custom element tag for creating child DOM elements.
     * Override in subclass to enable auto-creating DOM elements for dynamic children.
     */
    static getChildTag(_componentClassName: string): string | null;
    /**
     * Register a custom element for a MatrixActor class (Pattern B shortcut).
     * Used by the DSL compiler to create element wrappers for actor classes.
     *
     * @param tagName - Custom element tag name (e.g., 'my-component')
     * @param ActorClass - MatrixActor subclass
     * @param options - Template, observed attributes
     */
    static register(tagName: string, ActorClass: ActorConstructor, options?: IRegisterOptions): void;
    /**
     * Optional: observed attributes from actor class.
     */
    static get observedAttributes(): string[];
    /** Get the component's name/id. */
    get name(): string;
    /** Get the mount path. */
    get mountPath(): string;
    /** Get the derived mount path from root context. */
    get derivedMount(): string;
    /** Get the tab-qualified root name. */
    get root(): string;
    /** @deprecated Use `root` instead. */
    get realm(): string;
    /** Get the wrapped actor. */
    get actor(): MatrixActor | null;
    /** Backward-compatible getter used by parent shells as mount guard (!el.component). */
    get component(): MatrixActor | null;
    /** Reactive state delegate for shells (mirrors MatrixActor.state). */
    get state(): Readonly<Record<string, unknown>>;
    /** Reactive state delegate for shells (mirrors MatrixActor.setState). */
    setState(patch: Partial<Record<string, unknown>>): void;
    /** Backward-compatible alias for ready promise (FabricElement compat). */
    get contextReady(): Promise<void>;
    /** Check if this element is in proxy/clone mode. */
    get isProxyMode(): boolean;
    /** Get the remote mount path (if in proxy/clone mode). */
    get remoteMount(): string | null;
    connectedCallback(): void;
    disconnectedCallback(): void;
    attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
    /**
     * Receive context from parent or runtime.
     * Triggers actor creation and bootstrap.
     */
    _receiveContext(context: IMatrixContext | Record<string, unknown>, existingActor?: MatrixActor): Promise<void>;
    /**
     * Provide context to this element (called by runtime for root elements).
     */
    mount(context: IMatrixContext): Promise<void>;
    /**
     * Backward-compatible API for setting context (FabricElement compat).
     */
    setContext(context: IMatrixContext): void;
    /**
     * Register a pending child element.
     */
    _registerPendingChild(child: MatrixActorHtmlElement): void;
    /**
     * Create the internal actor instance.
     * Pattern B: uses getActorClass() to get a separate actor class.
     * Pattern A: creates a DynamicActor with accepts/emits from the element class.
     */
    private _createActor;
    /**
     * Render template to shadow DOM.
     * Checks element class first, then actor class.
     */
    protected _renderTemplate(): Promise<void>;
    /**
     * Wait for custom elements in a node to be defined.
     */
    private _waitForCustomElements;
    /**
     * Schedule a reactive render using microtask batching.
     * Multiple setState()/emit() calls in one sync turn collapse into one DOM diff.
     */
    private _scheduleRender;
    /**
     * Evaluate render(state) if present.
     * Returns null for legacy components with no render() method.
     */
    private _evaluateRender;
    /**
     * Event delegation for data-action handlers so morphdom updates never orphan listeners.
     */
    private _wireDelegatedEvents;
    private _renderCanvas;
    private _resolveTemplateAndStyles;
    private _hasRenderMethod;
    private _applyStaticStateSeed;
    private _cloneState;
    /**
     * Fire-and-forget: reads persisted state from the context's state-store service.
     * Merges KV state over the static seed and triggers re-render via morphdom.
     * Only runs for reactive components (those with render(state)) that haven't opted out.
     *
     * The state-store service is environment-agnostic — browser contexts get a
     * RemoteStateStore (RequestReply to daemon), daemon contexts get direct KV access.
     * Components never know or care where persisted state lives.
     */
    private _hydrateFromKv;
    /**
     * Called during mount for each declared fact domain with existing data.
     * Override in subclasses to merge snapshot data into component state.
     */
    protected onFactLoaded(_domain: string, _data: unknown, _revision: number): void | Promise<void>;
    /**
     * Called when a subscribed fact domain receives an update after mount.
     * Override in subclasses to react to streaming fact changes.
     */
    protected onFactUpdated(_domain: string, _data: unknown): void | Promise<void>;
    /**
     * Resolve and sanitize the declared fact domains for this component class.
     */
    private _resolveFactDomains;
    /**
     * Start mount-time fact hydration and live subscription wiring.
     */
    private _startFactLifecycle;
    /**
     * Read initial fact snapshots asynchronously after mount.
     */
    private _hydrateFacts;
    /**
     * Poll for fact changes when the context has no push subscription hook.
     * Uses hydration revision as baseline to avoid duplicate mount-time updates.
     */
    private _startFactPolling;
    /**
     * Invoke the subclass fact-loaded hook with error isolation.
     */
    private _invokeFactLoaded;
    /**
     * Invoke the subclass fact-updated hook with error isolation.
     */
    private _invokeFactUpdated;
    /**
     * Wire shell accept handlers to transport topics.
     * Handlers on element class (onSetData, onSortBy, etc.) receive messages.
     * Only applies for Pattern A (all-in-one) where handlers live on the element.
     */
    protected _wireShellAccepts(): void;
    /**
     * Wire self-tracking for Pattern B shells.
     * Subscribes to the actor's own $events topic and dispatches
     * to shell on<Event>() handlers (e.g., onFlowCompleted, onExampleLoaded).
     */
    private _wireSelfTracking;
    /**
     * Wire shell track handlers to tracked component events.
     * Sources: HTML tracks attribute + static tracks property.
     * Handler discovery: on<Event>() and on<Event>From<Id>() methods.
     */
    private _wireShellTracks;
    /**
     * Discover handler methods using naming convention.
     */
    private _discoverHandlerMethods;
    /**
     * Enable autoview: subscribe to tracked domain's $structureChanged events
     * and auto-spawn/remove matching child view components.
     *
     * Only activates when both `autoview` and `tracks` attributes are present.
     * Spec rules: R-AV1 through R-AV5 (FP-20c-2).
     */
    private _enableAutoView;
    /**
     * Spawn a view element for a domain child.
     * R-AV2: Convention is domain tag `X` → view tag `X-view`.
     * R-AV3: Missing view tag logs warning but doesn't throw.
     * R-AV5: View children are added to light DOM (external-owned).
     */
    private _spawnViewFor;
    /**
     * Remove an auto-spawned view child.
     */
    private _removeViewFor;
    /**
     * Resolve domain tag to view tag.
     * R-AV2: Convention: `X` → `X-view`. Custom mappings override.
     */
    protected _resolveViewTag(domainTag: string): string;
    /**
     * Wire up child shells in shadow DOM.
     * GAP 8 FIX: Only discovers DIRECT child shells — stops at shell boundaries.
     */
    private _wireChildren;
    /**
     * Get direct child shells from shadow DOM.
     * Stops at shell boundaries — does NOT recurse into nested shells.
     * This prevents grandchild elements from being parented to grandparent.
     */
    _getDirectChildShells(): MatrixActorHtmlElement[];
    /**
     * Return the semantic state this component exposes to the oracle.
     * Override in subclasses to expose meaningful state.
     * Never include DOM refs, caches, or internal bookkeeping here.
     */
    getCognitiveState(): Record<string, unknown>;
    /**
     * Build an OracleTreeNode for this component and its children.
     * Children are discovered via _getDirectChildShells() (same-process, direct call).
     * The result is serialized into the oracle system prompt as s-expressions.
     */
    snapshotTreeForOracle(): Promise<OracleSnapshotNode>;
    /**
     * Framework op handler: snapshot.tree.oracle.
     * Wired as a framework op so it's available on ALL components (Pattern A and B).
     * Any component can be oracle-snapshotted for the "any actor is thinkable" architecture.
     */
    onSnapshotTreeOracle(_payload: Record<string, unknown>): Promise<unknown>;
    /**
     * Framework op handler: $prompt (ADR-022: Event-Driven Prompt Architecture).
     *
     * Send a natural language prompt to this component. The component builds its
     * own snapshot, forwards to the daemon, subscribes to agent events, and relays
     * them to its own $events stream. Returns an ACK immediately — the actual
     * result arrives as a $agentResponse event.
     *
     * The agent's tools are scoped to this component's subtree.
     */
    on$prompt(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
    /**
     * Framework op handler: $cancel (ADR-022).
     * Forwards cancel to the daemon agent for this component.
     */
    on$Cancel(payload: Record<string, unknown>): Promise<Record<string, unknown>>;
    /**
     * Framework op handler: $activity (activityTo push delivery).
     * Receives ActivityFrame from daemon when a prompted agent emits events.
     *
     * Default behavior:
     * - Toggles `data-activity-active` / `data-activity-phase` attributes for CSS feedback
     * - Accumulates frames in `_activityFrames[]` (protected, subclass-readable)
     * - Calls lifecycle hooks: `onActivityStarted()`, `onActivityFrame()`, `onActivityEnded()`
     *
     * Subclasses override for custom activity handling (e.g. ChatApp renders progress).
     * When overriding, call `super.on$Activity(payload)` to preserve accumulation + hooks.
     */
    on$Activity(payload: ActivityFrame): void;
    /**
     * Hook: called when activity starts (first non-terminal $activity frame received).
     * Override in subclasses for custom UI (e.g. show cancel button, pulse status dot).
     */
    protected onActivityStarted(_firstFrame: ActivityFrame): void;
    /**
     * Hook: called for every $activity frame during an active request.
     * Override in subclasses for real-time activity display.
     */
    protected onActivityFrame(_frame: ActivityFrame): void;
    /**
     * Hook: called when activity ends (terminal phase: done, error, cancelled).
     * Receives all accumulated frames from the completed request.
     * Override in subclasses for post-hoc summaries.
     */
    protected onActivityEnded(_frames: ActivityFrame[]): void;
    /**
     * Resolve the bus root from the closest matrix-dsl-host element.
     * Protected so subclasses (e.g. ChatApp) can override.
     */
    protected _resolveDaemonRoot(): string;
    /** @deprecated Use _resolveDaemonRoot. */
    protected _resolveDaemonRealm(): string;
    /**
     * Resolve the local root from context transport or session info.
     * Protected so subclasses (e.g. ChatApp) can override.
     */
    protected _resolveLocalRoot(): string;
    /** @deprecated Use _resolveLocalRoot. */
    protected _resolveLocalRealm(): string;
    /**
     * Subscribe to events from a child shell.
     * Uses handler cascade: declarative bindings → specific → generic.
     */
    private _subscribeToChildEvents;
    /**
     * $style — Set arbitrary CSS properties on this element's host.
     * AI-addressable: send to any actor's $inbox.
     *
     * Payload: { props: Record<string, string> }
     * Example: { props: { 'background': 'red', '--custom-var': 'blue' } }
     */
    on$Style(payload: {
        props: Record<string, string>;
    }): void;
    /**
     * $source-code — Return this component's source code via constructor.toString().
     * Works for all components: LLM-created (readable JS), built-in (compiled JS).
     */
    on$SourceCode(): {
        source: string;
        tag: string;
        mount: string;
    };
    /**
     * factory.create-from-code — DOM-aware override.
     *
     * Evals a JavaScript class string extending MatrixActorHtmlElement,
     * registers it as a custom element with a versioned tag name,
     * creates the DOM element, and mounts it on the bus via $join handshake.
     *
     * Subclasses override _insertFactoryElement() for custom DOM placement.
     */
    onFactoryCreateFromCode(payload: {
        name: string;
        code: string;
    }): Promise<Record<string, unknown>>;
    /**
     * Insert a factory-created element into the DOM.
     * Override in subclass for custom placement (e.g., ChatMessageList wraps in a message div).
     */
    protected _insertFactoryElement(el: HTMLElement, _name: string): void;
    /**
     * factory.load — Load a saved component from ComponentStoreActor.
     *
     * Browser-side: resolves the daemon root, invokes component.get-source
     * cross-root on daemon.system.component-store, then delegates to
     * onFactoryCreateFromCode for DOM eval + mount.
     */
    onFactoryLoad(payload: {
        name: string;
    }): Promise<Record<string, unknown>>;
    /**
     * factory.create-from-url — Fetch source code from a URL, delegate to factory.create-from-code.
     *
     * Browser-only. The URL must return a raw class string (not an ES module).
     * Payload: { name, url }
     */
    onFactoryCreateFromUrl(payload: {
        name: string;
        url: string;
    }): Promise<Record<string, unknown>>;
    /**
     * component.save — Extract source from a running child and persist it.
     *
     * Browser-side: invokes $source-code on the child, then sends
     * component.persist cross-root to daemon.system.component-store.
     */
    onComponentSave(payload: {
        mount: string;
        name?: string;
        description?: string;
    }): Promise<Record<string, unknown>>;
    /**
     * $tokens — Set Matrix theme tokens (--mx-* CSS custom properties) on this element.
     * These cascade to all children via CSS custom property inheritance,
     * piercing shadow DOM boundaries automatically.
     *
     * Payload: { tokens: Record<string, string> }
     * Example: { tokens: { 'color-primary': '#e11d48' } } → sets --mx-color-primary
     */
    on$Tokens(payload: {
        tokens: Record<string, string>;
    }): void;
    /**
     * Walk the DOM tree (including shadow roots) and forward $tokens
     * to every descendant MatrixActorHtmlElement.
     */
    private _broadcastTokensToDescendants;
    /**
     * Subscribe to lifecycle events for dynamic children.
     */
    private _subscribeToDynamicChildren;
    /**
     * Handle a dynamically added child by creating a DOM element.
     */
    protected _handleChildAdded(payload: IChildAddedPayload): Promise<void>;
    /**
     * Handle a dynamically removed child by removing its DOM element.
     */
    protected _handleChildRemoved(payload: IChildRemovedPayload): void;
    /**
     * Wire bindings from the template to ANY descendant's events.
     * Delegates to internal actor if available, otherwise wires on element.
     */
    _wireDeepBindings(bindings: DeepBindingDescriptor[]): void;
    /**
     * Send a command to a child by name.
     *
     * Publishes MxEnvelope to child's $inbox + legacy per-op (removed in 20b-6).
     */
    sendToChild(childName: string, command: string, payload?: unknown): void;
    /**
     * Send a command to this element's own actor via the transport bus.
     * CQRS pattern: shell → actor via bus, not direct method calls.
     */
    sendToSelf(command: string, payload?: unknown): void;
    /**
     * Emit an event from this element via MxEnvelope to $events.
     */
    emit(event: string, payload?: unknown): void;
    /**
     * Publish a fact to the shared fact plane via the backing actor.
     */
    publishFact(domain: string, data: Record<string, unknown>): Promise<number>;
    /**
     * Read the latest fact snapshot from the shared fact plane.
     */
    readFact(domain: string): Promise<{
        data: unknown;
        revision: number;
    } | null>;
    /**
     * Subscribe to fact updates from the shared fact plane.
     */
    subscribeFact(domain: string, handler: (data: unknown) => void): () => void;
    /**
     * Send a command with two calling conventions:
     * 1. (target, command, data) — to child or relative path
     * 2. (command, data) — to first tracked domain component
     */
    sendCommand(toOrCmd: string, cmdOrData?: string | unknown, data?: unknown): void;
    /**
     * Forward a command to the remote mount via transport (proxy mode).
     */
    protected _forwardToRemote(command: string, payload?: unknown): void;
    /**
     * Bootstrap hook — called after context is ready.
     * Override in subclass for initialization logic.
     */
    protected onBootstrap(): Promise<void>;
    /**
     * Context updated hook — called after context change or remount.
     * Override in subclass for context-specific subscriptions.
     */
    protected _onContextUpdated(_context: IMatrixContext): Promise<void>;
    /**
     * Find the nearest parent shell.
     * Traverses up through shadow DOM boundaries via ShadowRoot.host.
     */
    private _findParentShell;
    /**
     * Bridge DOM attributes to actor.
     */
    private _bridgeAttributes;
    /** Start orphan detection timer. */
    private _startOrphanDetection;
    /** Clear orphan detection timeout. */
    private _clearOrphanTimeout;
    /** Clear shell-level subscriptions. */
    private _clearShellSubs;
    /** Clear fact-plane subscriptions and invalidate pending hydration work. */
    private _clearFactSubs;
    /** Add a shell-level subscription for automatic cleanup. */
    protected _addShellSub(unsub: () => void): void;
    /** Lowercase first character. */
    private _lcFirst;
}
//# sourceMappingURL=MatrixActorHtmlElement.d.ts.map
