/**
 * Worker composition root — assembles the embedded runtime, controller, and
 * worker-port adapter inside a Web Worker. Sits on the runtime side of the
 * worker boundary; consumed from the worker entry script.
 */
import { AgentEventKind } from '../../contracts/agent-api.js';
import { WorkerMessageKind } from '../../contracts/wire.js';
import { composeEmbeddedAgentRuntime } from '../index.js';
import { createEmbeddedAgentDispatch } from './dispatch.js';
import { attachEmbeddedAgent } from './worker-global.js';
import { attachEmbeddedAgentDispatchToWorkerPort, createWorkerPortHostToolExecutorWithOptions } from './worker-port.js';
/** Build the worker-side client adapter that proxies host requests over the port. */
export function createEmbeddedAgentWorkerHostToolExecutor(port = self, options) {
    return createWorkerPortHostToolExecutorWithOptions(port, options);
}
/** Attach a controller for `runtime` to `port` and return its binding. */
export function attachEmbeddedAgentDispatch(runtime, hostToolExecutor, registry, port = self) {
    const controller = createEmbeddedAgentDispatch({
        runtime,
        hostToolExecutor
    });
    const portBinding = attachEmbeddedAgentDispatchToWorkerPort(port, controller, registry);
    return {
        controller,
        dispose() {
            portBinding.dispose();
            controller.dispose();
        }
    };
}
/**
 * Build the closure that every composition root wires into
 * `createDefaultHostTools({ emitChildAgentEvent: ... })`. Centralizes
 * the `AgentEventMessage` + `AgentChildLoopEvent` envelope
 * construction so composition roots don't hand-roll it.
 */
export function createChildAgentEventEmitter(port) {
    return (toolCallId, subagentType, subagentName, event, metadata) => {
        const message = {
            kind: WorkerMessageKind.AgentEvent,
            event: {
                kind: AgentEventKind.ChildAgentEvent,
                toolCallId,
                subagentType,
                subagentName,
                ...(metadata?.model ? { subagentModel: metadata.model } : {}),
                ...(metadata?.thinkingLevel ? { subagentThinkingLevel: metadata.thinkingLevel } : {}),
                event
            }
        };
        port.postMessage(message);
    };
}
/** Bring up an embedded runtime inside the worker and bind it to the port. */
export async function createEmbeddedAgentWorkerBinding(options, port = self, registry) {
    const { runtime } = await composeEmbeddedAgentRuntime(options);
    const binding = attachEmbeddedAgent(runtime, port, registry);
    return {
        runtime,
        dispose() {
            binding.dispose();
        }
    };
}
//# sourceMappingURL=embedded-agent-worker.js.map