/**
 * Worker-global boundary — wires the worker's `self` (or any `WorkerPort`)
 * to a runtime + controller pair. Lives on the worker side of the boundary
 * and is the single place that owns disposal of all three sub-bindings.
 */
import { WorkerMessageKind } from '../../contracts/wire.js';
import { createDefaultToolRegistry } from '../host-tools/index.js';
import { createEmbeddedAgentDispatch } from './dispatch.js';
import { attachEmbeddedAgentDispatchToWorkerPort, createWorkerPortHostToolExecutorWithOptions } from './worker-port.js';
/** Bind `runtime` to `port` with a controller and the worker-port adapter. */
export function attachEmbeddedAgent(runtime, port, registry = createDefaultToolRegistry()) {
    const portHostToolExecutor = createWorkerPortHostToolExecutorWithOptions(port, {
        registry,
        onProtocolError(event) {
            const message = {
                kind: WorkerMessageKind.AgentEvent,
                event
            };
            port.postMessage(message);
        }
    });
    const controller = createEmbeddedAgentDispatch({
        runtime,
        hostToolExecutor: portHostToolExecutor.hostToolExecutor
    });
    const portBinding = attachEmbeddedAgentDispatchToWorkerPort(port, controller, registry);
    return {
        dispose() {
            portBinding.dispose();
            portHostToolExecutor.dispose();
            controller.dispose();
        }
    };
}
/** Convenience overload that defaults the port to the worker `self`. */
export function attachEmbeddedAgentToGlobal(runtime, globalPort = self, registry) {
    return attachEmbeddedAgent(runtime, globalPort, registry);
}
//# sourceMappingURL=worker-global.js.map