/**
 * Product runtime facade — wraps a low-level adapter (which owns the agent
 * loop and session state) with the contract that worker/main-thread callers
 * see: snapshot/session-context emission and host-tool request fan-out.
 */
import { AgentEventKind } from '../contracts/agent-api.js';
/** Adapt a `EmbeddedAgentRuntimeAdapter` into the public runtime contract. */
export function createEmbeddedAgentRuntime(adapter, pendingHostToolRequests) {
    const listeners = new Set();
    const emit = (event) => {
        for (const listener of listeners) {
            try {
                listener(event);
            }
            catch (err) {
                console.warn('[embedded-agent-facade] listener threw:', err);
            }
        }
    };
    const emitSnapshot = () => {
        emit({
            kind: AgentEventKind.SnapshotUpdated,
            snapshot: adapter.getSnapshot()
        });
    };
    const emitSessionContext = () => {
        emit({
            context: adapter.getSessionContext(),
            kind: AgentEventKind.SessionContextUpdated
        });
    };
    const unsubscribeSnapshotSource = adapter.subscribeSnapshotSource(() => {
        emitSnapshot();
        emitSessionContext();
    });
    const unsubscribeHostToolRequests = pendingHostToolRequests.subscribe((request) => {
        emit({
            kind: AgentEventKind.HostToolRequest,
            request
        });
    });
    const unsubscribeExtraEvents = adapter.subscribeExtraEvents?.(emit) ?? (() => { });
    return {
        async abort() {
            await adapter.abort();
            emitSnapshot();
            emitSessionContext();
        },
        async configure(configuration) {
            await adapter.configure(configuration);
            emit({
                configuration,
                kind: AgentEventKind.ConfigurationUpdated
            });
        },
        dispose() {
            unsubscribeHostToolRequests();
            unsubscribeSnapshotSource();
            unsubscribeExtraEvents();
            pendingHostToolRequests.dispose();
            adapter.dispose();
        },
        getSnapshot() {
            return adapter.getSnapshot();
        },
        async resumeWithHostToolResult(result) {
            await adapter.resumeWithHostToolResult(result);
        },
        async submit(prompt, options) {
            await adapter.submit(prompt, options);
            emitSnapshot();
            emitSessionContext();
        },
        subscribe(listener) {
            listeners.add(listener);
            return () => {
                listeners.delete(listener);
            };
        }
    };
}
//# sourceMappingURL=embedded-agent-facade.js.map