import Foundation

// Network.framework carries the TCP listener on Darwin; on Linux the TCP path is a BSD-socket
// mirror of the AF_UNIX path below (CLOUD_RUNTIME §3.1's approval-server seam) — same accept
// source, same `ByteConn` pipeline, so the HTTP/JSON-RPC dispatch is byte-identical.
#if canImport(Network)
import Network
#endif
#if canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#endif

// The libc socket surface differs in spelling across platforms; alias the few call sites the
// server needs so both bind paths read the same. `bind`/`close` are qualified through helpers
// because actor methods (`bind(host:)`) and connection methods (`close()`) shadow them.
// Three C libraries: Darwin (Apple), Glibc (Linux distro builds), Musl (the static-linux SDK —
// the runner image's fully-static amd64 build).
#if canImport(Darwin)
private let sockStreamType: Int32 = SOCK_STREAM
private func posixBind(_ fd: Int32, _ addr: UnsafePointer<sockaddr>, _ len: socklen_t) -> Int32 {
    Darwin.bind(fd, addr, len)
}
private func posixCloseFD(_ fd: Int32) { _ = Darwin.close(fd) }
private func writeNoSigpipe(_ fd: Int32, _ buf: UnsafeRawPointer, _ count: Int) -> Int {
    write(fd, buf, count)  // SO_NOSIGPIPE is set on the fd at init
}
#elseif canImport(Musl)
private let sockStreamType: Int32 = Int32(SOCK_STREAM)
private func posixBind(_ fd: Int32, _ addr: UnsafePointer<sockaddr>, _ len: socklen_t) -> Int32 {
    Musl.bind(fd, addr, len)
}
private func posixCloseFD(_ fd: Int32) { _ = Musl.close(fd) }
private func writeNoSigpipe(_ fd: Int32, _ buf: UnsafeRawPointer, _ count: Int) -> Int {
    // Linux has no SO_NOSIGPIPE; MSG_NOSIGNAL per send is the localized equivalent.
    send(fd, buf, count, Int32(MSG_NOSIGNAL))
}
#else
private let sockStreamType = Int32(SOCK_STREAM.rawValue)
private func posixBind(_ fd: Int32, _ addr: UnsafePointer<sockaddr>, _ len: socklen_t) -> Int32 {
    Glibc.bind(fd, addr, len)
}
private func posixCloseFD(_ fd: Int32) { _ = Glibc.close(fd) }
private func writeNoSigpipe(_ fd: Int32, _ buf: UnsafeRawPointer, _ count: Int) -> Int {
    // Linux has no SO_NOSIGPIPE; MSG_NOSIGNAL per send is the localized equivalent.
    send(fd, buf, count, Int32(MSG_NOSIGNAL))
}
#endif

/// Localhost HTTP MCP server hosted inside the app (ADAPTERS §1.2). Claude Code
/// is pointed at it via `--mcp-config` + `--permission-prompt-tool`; it exposes a
/// single tool `approve` whose call SUSPENDS until a human resolves the approval.
///
/// One server can serve all sessions: requests are authenticated by a per-session
/// bearer token, which keys the registered handler.
public actor MCPApprovalServer {
    public struct ApprovalCall: Sendable {
        public let toolName: String
        public let input: JSONValue
        public let toolUseID: String?
    }

    public enum Reply: Sendable {
        case allow(updatedInput: JSONValue)
        case deny(message: String)

        /// The confirmed wire shape: a JSON-stringified `{behavior,…}` object
        /// placed inside an MCP text content block — `behavior`/`message`/
        /// `updatedInput`, NOT `decision`/`reason` (ADAPTERS §1.2 ✅).
        public func wireJSON() -> String {
            switch self {
            case .allow(let updatedInput):
                return JSONValue.object([
                    "behavior": .string("allow"), "updatedInput": updatedInput,
                ]).canonicalString()
            case .deny(let message):
                return JSONValue.object([
                    "behavior": .string("deny"), "message": .string(message),
                ]).canonicalString()
            }
        }
    }

    /// A `check_conflict` tool call: the agent's task and the files/areas it expects to
    /// touch. The handler suspends (like `approve`) until Nucleic decides + the user
    /// answers, then returns a `ConflictReply` the agent reads to know how to proceed.
    public struct ConflictCall: Sendable {
        public let task: String
        public let files: [String]
    }

    public struct ConflictReply: Sendable {
        public let resolution: ConflictResolution

        public init(resolution: ConflictResolution) { self.resolution = resolution }

        /// Text-block JSON the agent reads. `conflict` is true unless there was no
        /// overlap; `action` + `message` tell it exactly what to do.
        public func wireJSON() -> String {
            switch resolution {
            case .noConflict:
                return JSONValue.object(["conflict": .bool(false)]).canonicalString()
            case .deferred:
                return conflictJSON(
                    "deferred",
                    "This task was added to the Nucleic to-do list because it conflicts with "
                        + "another active agent. Stop now and do NOT work on it.")
            case .cancelled:
                return conflictJSON(
                    "cancelled",
                    "The user cancelled this task because it conflicts with another active "
                        + "agent. Stop now and do NOT work on it.")
            case .proceed:
                return conflictJSON(
                    "proceed",
                    "This task conflicts with another active agent, but the user chose to "
                        + "proceed. You may continue.")
            }
        }

        private func conflictJSON(_ action: String, _ message: String) -> String {
            JSONValue.object([
                "conflict": .bool(true),
                "action": .string(action),
                "message": .string(message),
            ]).canonicalString()
        }
    }

    /// A `host_exec` tool call: the agent asks to run a shell command on the *host* machine,
    /// outside the sandbox container (e.g. to build/run a macOS binary the Linux container
    /// can't). The handler suspends (like `approve`) until the user approves and the host
    /// command finishes, then returns its output. Always gated; never auto-approved.
    public struct HostExecCall: Sendable {
        public let command: String
        /// The agent's stated justification for why this cannot run in the container. Required by
        /// the tool schema and enforced (non-empty, non-boilerplate) at the choke point; surfaced
        /// on the approval card as an *unverified claim* beside the command-derived summary.
        public let reason: String
        public init(command: String, reason: String = "") {
            self.command = command
            self.reason = reason
        }
    }

    public enum HostExecReply: Sendable {
        case denied(message: String)
        case ran(exitCode: Int32, stdout: String, stderr: String)

        /// Text-block JSON the agent reads back from the tool result.
        public func wireJSON() -> String {
            switch self {
            case .denied(let message):
                return JSONValue.object([
                    "denied": .bool(true), "message": .string(message),
                ]).canonicalString()
            case .ran(let exitCode, let stdout, let stderr):
                return JSONValue.object([
                    "exit_code": .number(Double(exitCode)),
                    "stdout": .string(stdout),
                    "stderr": .string(stderr),
                ]).canonicalString()
            }
        }
    }

    /// A `mac_vm_exec` tool call: the agent asks to run a shell command inside its session's isolated
    /// **macOS guest VM** (Apple Virtualization framework) — for Mac-only work like `xcodebuild`, an
    /// `xcrun simctl` simulator run, or `codesign`. Unlike `host_exec` (which escapes onto the one
    /// shared host), each session gets its own VM with its own Mac toolchain, so parallel Mac builds
    /// don't thrash the one shared host. The handler suspends (like `approve`) until the user
    /// approves and the in-VM command finishes, then returns its output. Always gated; never
    /// auto-approved.
    public struct MacVMExecCall: Sendable {
        public let command: String
        /// The agent's stated justification for why this needs the macOS VM (rather than the Linux
        /// container). Required by the schema and enforced at the choke point; surfaced on the approval
        /// card as an *unverified claim*.
        public let reason: String
        public init(command: String, reason: String = "") {
            self.command = command
            self.reason = reason
        }
    }

    public enum MacVMExecReply: Sendable {
        case denied(message: String)
        case ran(exitCode: Int32, stdout: String, stderr: String)

        /// Text-block JSON the agent reads back from the tool result (same shape as `host_exec`).
        public func wireJSON() -> String {
            switch self {
            case .denied(let message):
                return JSONValue.object([
                    "denied": .bool(true), "message": .string(message),
                ]).canonicalString()
            case .ran(let exitCode, let stdout, let stderr):
                return JSONValue.object([
                    "exit_code": .number(Double(exitCode)),
                    "stdout": .string(stdout),
                    "stderr": .string(stderr),
                ]).canonicalString()
            }
        }
    }

    /// A `mac_vm_computer` tool call: one **computer-use action** against the session's macOS VM —
    /// the agent driving the guest's GUI like its own Mac (Anthropic computer-use shape). The handler
    /// performs the action in the guest over SSH and returns a fresh screenshot so the agent can see
    /// the result. Runs inside the isolated, disposable VM, so — unlike `host_exec`/`mac_vm_exec` — it
    /// is NOT per-action approval-gated (a per-click prompt would make a navigation loop unusable);
    /// exposure is the opt-in boundary.
    public struct MacVMComputerCall: Sendable {
        /// The action verb: `screenshot`, `left_click`, `right_click`, `double_click`, `mouse_move`,
        /// `left_click_drag`, `type`, `key`, `scroll`, `cursor_position`, `launch_app`, `open_browser`,
        /// `wait`; plus the AX-semantic actions when the guest runs the native agent
        /// (docs/MACOS_VM_NATIVE_AGENT.md): `ax_dump`, `ax_element_at`, `ax_press`, `ax_set_value`,
        /// `ax_focus`.
        public let action: String
        /// Target point (screen pixels; the screenshot is 1:1 so the agent targets what it sees).
        public let x: Int?
        public let y: Int?
        /// Payload for `type` (literal text), `key` (a chord like `cmd+s`, `return`, `tab`),
        /// `launch_app` (an application name), `open_browser` (a short browser name like `chrome` or
        /// `firefox`), or `ax_press` (an optional AX action name to perform instead of the default
        /// `AXPress`, e.g. `AXShowMenu`).
        public let text: String?
        /// For the `ax_*` element actions: the element handle from the last `ax_dump`/`ax_element_at`.
        public let ref: String?
        /// For `ax_set_value`: the value to write into the element.
        public let value: String?
        /// For `scroll`: `up`/`down`/`left`/`right` and a click/step amount.
        public let scrollDirection: String?
        public let scrollAmount: Int?
        /// For `wait`: milliseconds to pause before the screenshot (e.g. let a window open).
        public let durationMs: Int?

        public init(
            action: String, x: Int? = nil, y: Int? = nil, text: String? = nil,
            ref: String? = nil, value: String? = nil,
            scrollDirection: String? = nil, scrollAmount: Int? = nil, durationMs: Int? = nil
        ) {
            self.action = action
            self.x = x
            self.y = y
            self.text = text
            self.ref = ref
            self.value = value
            self.scrollDirection = scrollDirection
            self.scrollAmount = scrollAmount
            self.durationMs = durationMs
        }
    }

    public enum MacVMComputerReply: Sendable {
        case denied(message: String)
        /// The action ran; `text` is a short summary (e.g. cursor position / screen size), and
        /// `imageBase64` is the post-action screenshot as base64 JPEG (nil only if capture failed).
        case ok(text: String, imageBase64: String?)

        /// Denial JSON for the text-only failure path.
        public func deniedJSON() -> String {
            if case .denied(let message) = self {
                return JSONValue.object([
                    "denied": .bool(true), "message": .string(message),
                ]).canonicalString()
            }
            return JSONValue.object([:]).canonicalString()
        }
    }

    /// A `mac_vm_clear_notifications` tool call: while driving the session's macOS VM via
    /// `mac_vm_computer`, a banner/alert has slid in and is obstructing part of the screen. This
    /// dismisses the on-screen notifications by killing the guest's NotificationCenter (which relaunches
    /// clean). No parameters — it always runs the same fixed `killall NotificationCenter`. Like the
    /// computer-use / lifecycle tools it is NOT approval-gated: the blast radius is the agent's own
    /// disposable VM. Replies with the same `{exit_code, stdout, stderr}` shape as `mac_vm_exec`.
    public struct MacVMClearNotificationsCall: Sendable {
        public init() {}
    }

    /// A `mac_vm_request_operator` tool call: the agent — while driving the session's macOS VM via
    /// `mac_vm_computer` — hits a step only a human can clear (a CAPTCHA, a login / 2FA prompt, an
    /// interactive OS dialog) and asks the *user* to take the wheel. Modeled on `host_exec`: the agent
    /// must justify the request (`reason`) and say exactly what it needs done (`instructions`). The
    /// handler suspends (like `host_exec`) until the user finishes operating the VM or declines, then
    /// returns the outcome. Always gated; never auto-approved.
    public struct MacVMOperatorCall: Sendable {
        /// The agent's stated justification for why a human is required (rather than the agent driving
        /// the VM itself). Required by the schema and enforced at the choke point; surfaced on the
        /// request card as an *unverified claim*.
        public let reason: String
        /// What, concretely, the agent needs the user to do in the VM (e.g. "solve the CAPTCHA in the
        /// Safari window, then click Continue"). Required; shown to the user in the walkthrough popup.
        public let instructions: String
        public init(reason: String = "", instructions: String = "") {
            self.reason = reason
            self.instructions = instructions
        }
    }

    public enum MacVMOperatorReply: Sendable {
        case denied(message: String)
        /// The user finished (or gave up on) the hand-off. `completed` is whether they say they did
        /// what was asked; `note` is an optional free-text message back to the agent.
        case resolved(completed: Bool, note: String)

        /// Text-block JSON the agent reads back from the tool result.
        public func wireJSON() -> String {
            switch self {
            case .denied(let message):
                return JSONValue.object([
                    "denied": .bool(true), "message": .string(message),
                ]).canonicalString()
            case .resolved(let completed, let note):
                return JSONValue.object([
                    "completed": .bool(completed), "note": .string(note),
                ]).canonicalString()
            }
        }
    }

    /// A `linux_container` tool call: the agent manages its OWN throwaway Linux container — the
    /// lightest rung of isolation below a VM. One tool, multiple `op`s: `create` brings up a fresh
    /// container from an image (defaulting to the agent's own sandbox image) and returns its `name`;
    /// `exec` runs a shell `command` inside a named container; `stop`/`remove` tear it down; `list`
    /// enumerates the containers this session created. The `create`/`exec`/`stop`/`remove` ops are
    /// approval-gated (like `host_exec`/`mac_vm_exec`); `list` is a read-only query.
    public struct ContainerToolCall: Sendable {
        /// One of: `create`, `exec`, `stop`, `remove`, `list`.
        public let op: String
        /// The container to act on (required for `exec`/`stop`/`remove`; ignored for `list`). For
        /// `create` it is an optional caller-chosen label (namespaced per session); nil → auto-named.
        public let name: String?
        /// For `create`: the OCI image reference to run; nil → the agent's own sandbox image.
        public let image: String?
        /// For `exec`: the shell command to run inside the container.
        public let command: String?
        /// For `exec`: the working directory inside the container; nil → the image default.
        public let workdir: String?
        /// The agent's stated justification, surfaced on the approval card as an *unverified claim*.
        public let reason: String
        public init(
            op: String, name: String? = nil, image: String? = nil, command: String? = nil,
            workdir: String? = nil, reason: String = ""
        ) {
            self.op = op
            self.name = name
            self.image = image
            self.command = command
            self.workdir = workdir
            self.reason = reason
        }
    }

    /// A Nucleic-managed Orchestra subagent request. Unlike Claude's native `Task` tool, this
    /// creates an ordinary Nucleic session so the app owns the worker lifecycle, transcript,
    /// sandbox/control routing, and model selection.
    public struct OrchestraSubagentCall: Sendable {
        public let task: String
        public let prompt: String
        public init(task: String, prompt: String) {
            self.task = task
            self.prompt = prompt
        }
    }

    /// A supervisor's `nucleic_reply_to_worker` call: the answer to a worker waiting in
    /// `nucleic_ask_supervisor`, addressed by the `worker_id` from the spawn ack.
    public struct OrchestraReplyToWorkerCall: Sendable {
        public let workerID: String
        public let reply: String
        public init(workerID: String, reply: String) {
            self.workerID = workerID
            self.reply = reply
        }
    }

    /// A worker's `nucleic_ask_supervisor` call. The worker's own identity is known from the run's
    /// token, so the tool carries only the question text.
    public struct OrchestraAskSupervisorCall: Sendable {
        public let question: String
        public init(question: String) {
            self.question = question
        }
    }

    public enum ContainerToolReply: Sendable {
        case denied(message: String)
        /// A `create`/`stop`/`remove`/`list` op succeeded. `name` echoes the affected container (empty
        /// for `list`); `names` lists the session's containers (for `list`); `message` is a short note.
        case ok(name: String, names: [String], message: String)
        /// An `exec` op ran to completion inside the container.
        case ran(exitCode: Int32, stdout: String, stderr: String)

        /// Text-block JSON the agent reads back from the tool result.
        public func wireJSON() -> String {
            switch self {
            case .denied(let message):
                return JSONValue.object([
                    "denied": .bool(true), "message": .string(message),
                ]).canonicalString()
            case .ok(let name, let names, let message):
                return JSONValue.object([
                    "ok": .bool(true),
                    "name": .string(name),
                    "names": .array(names.map { .string($0) }),
                    "message": .string(message),
                ]).canonicalString()
            case .ran(let exitCode, let stdout, let stderr):
                return JSONValue.object([
                    "exit_code": .number(Double(exitCode)),
                    "stdout": .string(stdout),
                    "stderr": .string(stderr),
                ]).canonicalString()
            }
        }
    }

    /// A `mac_vm_control` / `linux_vm_control` tool call: the agent manages the lifecycle of the
    /// isolated VM it booted for this session — `status` (a read-only query), `stop` (power off, keep
    /// the disk so the next command reboots), `suspend`/`resume` (freeze in RAM / thaw), `restart`
    /// (stop → reboot, reclaiming RAM), or `kill` (stop and delete the disk clone). One tool, one `op`.
    /// Not approval-gated: the blast radius is the agent's own disposable VM (exposure is the opt-in
    /// boundary, like the computer-use tools), and these ops only change that VM's power state.
    public struct VMControlCall: Sendable {
        /// One of: `status`, `stop`, `suspend`, `resume`, `restart`, `kill`.
        public let op: String
        public init(op: String) { self.op = op }
    }

    public enum VMControlReply: Sendable {
        case denied(message: String)
        /// The op completed. `state` is the VM's resulting lifecycle state — one of `running`,
        /// `suspended`, `stopped`, `removed`, or `absent`; `message` is a short human note.
        case ok(state: String, message: String)

        /// Text-block JSON the agent reads back from the tool result.
        public func wireJSON() -> String {
            switch self {
            case .denied(let message):
                return JSONValue.object([
                    "denied": .bool(true), "message": .string(message),
                ]).canonicalString()
            case .ok(let state, let message):
                return JSONValue.object([
                    "ok": .bool(true),
                    "state": .string(state),
                    "message": .string(message),
                ]).canonicalString()
            }
        }
    }

    /// A ground-truth report from the in-container `git` interceptor shim: the real git the
    /// agent ran (argv + cwd + exit code) in a Nucleic Control container. Delivered over a
    /// dedicated `POST /git-event` route (not an MCP tool), so the shim needs no MCP handshake.
    public struct GitReportCall: Sendable {
        public let argv: [String]
        public let cwd: String
        public let exitCode: Int
        public let subcommand: String?
        public let sessionID: String?
        public init(argv: [String], cwd: String, exitCode: Int, subcommand: String?, sessionID: String?) {
            self.argv = argv
            self.cwd = cwd
            self.exitCode = exitCode
            self.subcommand = subcommand
            self.sessionID = sessionID
        }
    }

    /// A ground-truth report from the in-container `gh` interceptor shim — the agentic GitHub
    /// action the agent ran (argv + cwd + exit code). Same shape and `POST /gh-event` transport as
    /// `GitReportCall`; the host classifies it via `GhCommandSummary`.
    public struct GhReportCall: Sendable {
        public let argv: [String]
        public let cwd: String
        public let exitCode: Int
        public let subcommand: String?
        public let sessionID: String?
        public init(argv: [String], cwd: String, exitCode: Int, subcommand: String?, sessionID: String?) {
            self.argv = argv
            self.cwd = cwd
            self.exitCode = exitCode
            self.subcommand = subcommand
            self.sessionID = sessionID
        }
    }

    /// A ground-truth report of one ordinary (non-git) command the in-container interceptor
    /// observed — from the output-capturing shim (`source == .shim`, carrying argv + a capped
    /// stdout/stderr head) or the bash command tracer (`source == .tracer`, a raw command line +
    /// metadata only). Delivered over `POST /command-event`. One HTTP request may carry many
    /// (the tracer batches a whole Bash tool call), so the route fans out to one call each.
    public struct CommandReportCall: Sendable {
        public enum Source: String, Sendable { case shim, tracer }
        /// The resolved command name (shim), or nil when only a raw command line is available
        /// (tracer) — the consumer derives it by tokenizing `commandLine`.
        public let command: String?
        /// Full argv (shim), or empty when only `commandLine` is available (tracer).
        public let argv: [String]
        /// The raw command line (tracer), or nil (shim).
        public let commandLine: String?
        public let cwd: String
        public let exitCode: Int
        /// Wall-clock duration in milliseconds, when the reporter measured it.
        public let durationMs: Int?
        /// Capped head of stdout / stderr (shim only; empty for the tracer).
        public let stdout: String
        public let stderr: String
        /// True when stdout/stderr exceeded the capture cap (shim).
        public let truncated: Bool
        public let source: Source
        public let sessionID: String?

        public init(
            command: String?, argv: [String], commandLine: String?, cwd: String, exitCode: Int,
            durationMs: Int?, stdout: String, stderr: String, truncated: Bool, source: Source,
            sessionID: String?
        ) {
            self.command = command
            self.argv = argv
            self.commandLine = commandLine
            self.cwd = cwd
            self.exitCode = exitCode
            self.durationMs = durationMs
            self.stdout = stdout
            self.stderr = stderr
            self.truncated = truncated
            self.source = source
            self.sessionID = sessionID
        }
    }

    public typealias Handler = @Sendable (ApprovalCall) async -> Reply
    public typealias ConflictHandler = @Sendable (ConflictCall) async -> ConflictReply
    public typealias HostExecHandler = @Sendable (HostExecCall) async -> HostExecReply
    public typealias MacVMExecHandler = @Sendable (MacVMExecCall) async -> MacVMExecReply
    public typealias MacVMComputerHandler = @Sendable (MacVMComputerCall) async -> MacVMComputerReply
    /// Clears the guest's on-screen notifications. Reuses ``MacVMExecReply`` — the fixed `killall
    /// NotificationCenter` returns the same `{exit_code, stdout, stderr}` shape as `mac_vm_exec`.
    public typealias MacVMClearNotificationsHandler = @Sendable (MacVMClearNotificationsCall) async -> MacVMExecReply
    public typealias MacVMOperatorHandler = @Sendable (MacVMOperatorCall) async -> MacVMOperatorReply
    public typealias ContainerToolHandler = @Sendable (ContainerToolCall) async -> ContainerToolReply
    public typealias OrchestraSubagentHandler = @Sendable (OrchestraSubagentCall) async -> OrchestraSubagentResult
    /// Supervisor-side: `nucleic_supervise` — blocks until worker events arrive, then drains them.
    public typealias OrchestraSuperviseServerHandler = @Sendable () async -> OrchestraSuperviseResult
    /// Supervisor-side: `nucleic_reply_to_worker` — answers a worker's pending question.
    public typealias OrchestraReplyToWorkerServerHandler = @Sendable (OrchestraReplyToWorkerCall) async -> OrchestraReplyResult
    /// Worker-side: `nucleic_ask_supervisor` — routes a question to the supervisor and blocks for the reply.
    public typealias OrchestraAskSupervisorServerHandler = @Sendable (OrchestraAskSupervisorCall) async -> OrchestraAskSupervisorResult
    public typealias VMControlHandler = @Sendable (VMControlCall) async -> VMControlReply
    /// Synchronous + non-gated: it just records the observed op and returns. No user approval,
    /// so a git report never blocks the agent's git call.
    public typealias GitReportHandler = @Sendable (GitReportCall) -> Void
    /// As `GitReportHandler`, for the `gh` interceptor's `POST /gh-event`.
    public typealias GhReportHandler = @Sendable (GhReportCall) -> Void
    /// As ``GitReportHandler``, for the non-git command interceptor (`POST /command-event`).
    public typealias CommandReportHandler = @Sendable (CommandReportCall) -> Void

    /// The dedicated POST path the `git` interceptor shim reports to — bearer-token gated like
    /// the MCP route, but a plain JSON POST rather than JSON-RPC.
    public static let gitEventPath = "/git-event"
    /// The dedicated POST path the `gh` interceptor shim reports to (sibling of `gitEventPath`).
    public static let ghEventPath = "/gh-event"
    /// The dedicated POST path the non-git command shims + bash tracer report to.
    public static let commandEventPath = CommandInterceptor.eventPath

    public static let toolName = "approve"
    /// Fully-qualified name passed to `--permission-prompt-tool`.
    public static let qualifiedToolName = "mcp__nucleic__approve"
    public static let conflictToolName = "check_conflict"
    /// Fully-qualified name — pre-allowed so the agent calls it without an approval round-trip.
    public static let qualifiedConflictToolName = "mcp__nucleic__check_conflict"
    public static let hostExecToolName = "host_exec"
    /// Fully-qualified name — pre-allowed via `--allowedTools` so the call reaches our handler
    /// directly (the handler is the sole gate); never routed through Claude's permission path,
    /// so `auto` mode can't auto-approve it. Only advertised when a handler is registered.
    public static let qualifiedHostExecToolName = "mcp__nucleic__host_exec"
    public static let macVMExecToolName = "mac_vm_exec"
    /// Fully-qualified name — pre-allowed like `host_exec` so the call reaches our handler directly
    /// (the handler is the sole gate). Only advertised when a handler is registered.
    public static let qualifiedMacVMExecToolName = "mcp__nucleic__mac_vm_exec"
    public static let macVMComputerToolName = "mac_vm_computer"
    /// Fully-qualified name — pre-allowed so the computer-use action reaches our handler directly
    /// (no per-action prompt). Only advertised when a handler is registered.
    public static let qualifiedMacVMComputerToolName = "mcp__nucleic__mac_vm_computer"
    public static let macVMClearNotificationsToolName = "mac_vm_clear_notifications"
    /// Fully-qualified name — pre-allowed like `mac_vm_computer` so the call reaches our handler directly
    /// (no per-call prompt; it only touches the agent's own disposable VM). Only advertised when a
    /// handler is registered.
    public static let qualifiedMacVMClearNotificationsToolName = "mcp__nucleic__mac_vm_clear_notifications"
    public static let macVMOperatorToolName = "mac_vm_request_operator"
    /// Fully-qualified name — pre-allowed like `host_exec` so the operator-help request reaches our
    /// handler directly (the handler is the sole gate). Only advertised when a handler is registered.
    public static let qualifiedMacVMOperatorToolName = "mcp__nucleic__mac_vm_request_operator"
    public static let linuxVMExecToolName = "linux_vm_exec"
    /// Fully-qualified name — pre-allowed like `mac_vm_exec` so the call reaches our handler directly
    /// (the handler is the sole gate). Only advertised when a handler is registered.
    public static let qualifiedLinuxVMExecToolName = "mcp__nucleic__linux_vm_exec"
    public static let linuxVMComputerToolName = "linux_vm_computer"
    /// Fully-qualified name — pre-allowed so the computer-use action reaches our handler directly
    /// (no per-action prompt). Only advertised when a handler is registered.
    public static let qualifiedLinuxVMComputerToolName = "mcp__nucleic__linux_vm_computer"
    public static let linuxContainerToolName = "linux_container"
    /// Fully-qualified name — pre-allowed so the container lifecycle op reaches our handler directly
    /// (the handler is the sole gate). Only advertised when a handler is registered.
    public static let qualifiedLinuxContainerToolName = "mcp__nucleic__linux_container"
    public static let macVMControlToolName = "mac_vm_control"
    /// Fully-qualified name — pre-allowed so the macOS-VM lifecycle op reaches our handler directly (no
    /// per-op prompt; the VM is the agent's own disposable one). Only advertised when a handler is
    /// registered.
    public static let qualifiedMacVMControlToolName = "mcp__nucleic__mac_vm_control"
    public static let linuxVMControlToolName = "linux_vm_control"
    /// Fully-qualified name — the Linux-VM sibling of ``qualifiedMacVMControlToolName``.
    public static let qualifiedLinuxVMControlToolName = "mcp__nucleic__linux_vm_control"
    public static let orchestraSubagentToolName = "nucleic_subagent"
    /// Fully-qualified name — pre-allowed in Orchestra so spawning goes through Nucleic's handler.
    public static let qualifiedOrchestraSubagentToolName = "mcp__nucleic__nucleic_subagent"
    /// Supervisor drive loop: block until worker events arrive, then drain them.
    public static let orchestraSuperviseToolName = "nucleic_supervise"
    public static let qualifiedOrchestraSuperviseToolName = "mcp__nucleic__nucleic_supervise"
    /// Supervisor answers a worker's `nucleic_ask_supervisor`.
    public static let orchestraReplyToWorkerToolName = "nucleic_reply_to_worker"
    public static let qualifiedOrchestraReplyToWorkerToolName = "mcp__nucleic__nucleic_reply_to_worker"
    /// Worker asks its supervisor and blocks for the reply.
    public static let orchestraAskSupervisorToolName = "nucleic_ask_supervisor"
    public static let qualifiedOrchestraAskSupervisorToolName = "mcp__nucleic__nucleic_ask_supervisor"

    #if canImport(Network)
    private var listener: NWListener?
    #else
    /// The listening TCP socket fd + its accept source (the Linux BSD-socket mirror of
    /// `listener`; same shape as the AF_UNIX pair below).
    private var tcpListenFD: Int32?
    private var tcpAcceptSource: DispatchSourceRead?
    #endif
    /// In-flight TCP bind, so concurrent `start(host:)` callers (the default once sessions share one
    /// control-container server via ``ApprovalServerRegistry``) join the SAME bind and all receive
    /// the real bound port. Without this, a second caller entering while the first is mid-bind saw a
    /// half-initialized listener and returned `port == 0`, which the agent's MCP config baked into an
    /// unreachable `:0` endpoint — stalling that session's first gated tool. Cleared when the bind
    /// settles (success or failure), so a failed bind can be retried.
    private var tcpStartTask: Task<UInt16, Error>?
    /// The interface the live TCP listener was bound to (`"127.0.0.1"` / `"0.0.0.0"`), nil when no
    /// TCP listener is bound. Lets ``start(host:)`` detect a run that needs a *wider* bind than the
    /// cached one (a loopback bind can't serve a containerized child over the VM gateway) and rebind
    /// instead of returning a port the child can never reach. Internal (not private) for tests.
    private(set) var boundTCPHost: String?
    private var handlers: [String: Handler] = [:]
    private var conflictHandlers: [String: ConflictHandler] = [:]
    private var hostExecHandlers: [String: HostExecHandler] = [:]
    private var macVMExecHandlers: [String: MacVMExecHandler] = [:]
    private var macVMComputerHandlers: [String: MacVMComputerHandler] = [:]
    private var macVMClearNotificationsHandlers: [String: MacVMClearNotificationsHandler] = [:]
    private var macVMOperatorHandlers: [String: MacVMOperatorHandler] = [:]
    private var linuxVMExecHandlers: [String: MacVMExecHandler] = [:]
    private var linuxVMComputerHandlers: [String: MacVMComputerHandler] = [:]
    private var linuxContainerHandlers: [String: ContainerToolHandler] = [:]
    private var orchestraSubagentHandlers: [String: OrchestraSubagentHandler] = [:]
    private var orchestraSuperviseHandlers: [String: OrchestraSuperviseServerHandler] = [:]
    private var orchestraReplyToWorkerHandlers: [String: OrchestraReplyToWorkerServerHandler] = [:]
    private var orchestraAskSupervisorHandlers: [String: OrchestraAskSupervisorServerHandler] = [:]
    private var macVMControlHandlers: [String: VMControlHandler] = [:]
    private var linuxVMControlHandlers: [String: VMControlHandler] = [:]
    private var gitReportHandlers: [String: GitReportHandler] = [:]
    private var ghReportHandlers: [String: GhReportHandler] = [:]
    private var commandReportHandlers: [String: CommandReportHandler] = [:]
    private var connectionTasks: [Int: Task<Void, Never>] = [:]
    private var nextConnectionID = 0
    /// In-flight `handle(_:)` tasks — one per request being served — indexed by id and by the
    /// request's bearer token. Handlers can suspend for a long time (an `approve` awaiting a human,
    /// a `nucleic_subagent` spawn awaiting a whole worker session), so when their session's run ends
    /// — the connection closes or the token unregisters — the task must be CANCELLED, not merely
    /// awaited: nobody can receive the response anymore, and a parked subagent spawn would otherwise
    /// go on to create and run a full worker for a dead supervisor. Entries remove themselves when
    /// the task finishes.
    private var handlerTasks: [UUID: Task<Void, Never>] = [:]
    private var handlerTaskIDsByToken: [String: Set<UUID>] = [:]
    /// How often an SSE-streamed `tools/call` response emits a keepalive comment while its handler
    /// is still running. A gated tool call can block for many minutes (a human answering `approve`,
    /// a `nucleic_subagent` spawn awaiting a whole worker session); the spawned CLI's HTTP client
    /// (Node/undici) aborts a request whose response stays byte-silent past its ~300s
    /// headers/body timeout — a layer *below* the MCP SDK, so the pinned `MCP_TOOL_TIMEOUT` never
    /// governs it. Emitting a keepalive well under that ceiling keeps the client's timeout (and
    /// every relay's idle clock) from ever firing on a legitimately long call. Set via ``init`` so a
    /// test can shorten it. See ``respondStreamingToolCall(_:on:)``.
    private let sseKeepaliveInterval: Duration
    public private(set) var port: UInt16 = 0
    /// The bound unix-socket path when started via ``start(unixSocketPath:)`` (nil for a TCP
    /// bind). Recorded so ``stop()`` can unlink the socket file it created.
    public private(set) var boundUnixSocketPath: String?
    /// The listening AF_UNIX socket fd + its accept source, for the unix-socket transport.
    private var unixListenFD: Int32?
    private var unixAcceptSource: DispatchSourceRead?
    /// `(dev, ino)` of the bound unix socket node, captured at bind time. Compared against the live
    /// file on each ``start(unixSocketPath:)`` to detect the socket being unlinked (a `/tmp`-style
    /// reaper, a container teardown) or replaced by a different inode — the desync that used to
    /// permanently brick a shared control server. Nil when no unix socket is bound.
    private var boundUnixSocketInode: (dev: dev_t, ino: ino_t)?

    /// `sseKeepaliveInterval` defaults to the production cadence; a test passes a short value to see
    /// several keepalive frames within its window (see ``sseKeepaliveInterval``).
    public init(sseKeepaliveInterval: Duration = .seconds(20)) {
        self.sseKeepaliveInterval = sseKeepaliveInterval
    }

    /// Returns the bound ephemeral port. `host` is the local interface to bind to;
    /// default loopback for host runs, `0.0.0.0` for sandbox runs so the containerized
    /// `claude` can reach the approval server over the VM gateway (bearer-token gated).
    @discardableResult
    public func start(host: String = "127.0.0.1") async throws -> UInt16 {
        #if canImport(Network)
        // Self-heal (the TCP mirror of `start(unixSocketPath:)`). The shared control-container
        // server is long-lived — on the default (non-vsock) transport it serves EVERY session in
        // the container over this one TCP bind — so it must not trust its first bind forever.
        // Keep the cached listener only while it is still `.ready` AND already serves the
        // requested interface (a wildcard bind serves loopback too; the reverse does not — a
        // loopback bind is unreachable from a containerized child over the VM gateway). A
        // listener that died post-`.ready` (network-stack transition, external cancel) would
        // otherwise keep publishing its stale port, which every new session baked into an
        // unreachable MCP config — surfacing as the CLI's opaque "Available MCP tools: none" and
        // poisoning ALL new sessions sharing the server until an app restart.
        if let existing = listener {
            let servesHost = boundTCPHost == host || boundTCPHost == "0.0.0.0"
            if existing.state == .ready, port != 0, servesHost { return port }
            invalidateTCPListener(existing)  // dead or too-narrow bind — rebind below
        }
        if let task = tcpStartTask { return try await task.value }  // bind in flight → join it
        let task = Task { [self] in try await bind(host: host) }
        tcpStartTask = task
        defer { tcpStartTask = nil }  // settle the single-flight (success or throw); allow a retry
        return try await task.value
        #else
        // Linux (runner): same self-heal contract over a BSD listener — the fd is only ever
        // closed by stop()/teardownTCPListener(), so a set fd is live; rebind when the cached
        // bind is missing or narrower than the run needs.
        if tcpListenFD != nil {
            let servesHost = boundTCPHost == host || boundTCPHost == "0.0.0.0"
            if port != 0, servesHost { return port }
            teardownTCPListener()  // too-narrow bind — rebind below
        }
        if let task = tcpStartTask { return try await task.value }  // bind in flight → join it
        let task = Task { [self] in try performTCPBind(host: host) }
        tcpStartTask = task
        defer { tcpStartTask = nil }  // settle the single-flight (success or throw); allow a retry
        return try await task.value
        #endif
    }

    #if canImport(Network)
    /// Drop the cached TCP bind because its listener is no longer usable — it died after `.ready`
    /// (`.failed` on a network-stack transition, an out-from-under cancel) or it's bound to a
    /// narrower interface than the run needs. Clears `listener`/`port`/`boundTCPHost` so the next
    /// ``start(host:)`` rebinds fresh instead of returning the stale port. Identity-checked so a
    /// listener that was already replaced (``stop()``, an earlier self-heal) can't clobber its
    /// successor's live bind. Established connections are independent of the listener and unaffected.
    private func invalidateTCPListener(_ dead: NWListener) {
        guard listener === dead else { return }
        listener = nil
        port = 0
        boundTCPHost = nil
        dead.cancel()
    }
    #else
    /// Linux counterpart of `invalidateTCPListener`: cancel the accept source (its cancel handler
    /// closes the listening fd) and clear the cached bind so the next ``start(host:)`` rebinds.
    private func teardownTCPListener() {
        tcpAcceptSource?.cancel()
        tcpAcceptSource = nil
        tcpListenFD = nil
        port = 0
        boundTCPHost = nil
    }

    /// BSD-socket TCP bind for Linux — the same primitives (and the same accept-source → adopt
    /// pipeline) as ``performUnixBind(path:)``, pointed at `host`:ephemeral. Returns the bound
    /// port. Synchronous, like the unix bind, so the actor never exposes a half-bound listener.
    private func performTCPBind(host: String) throws -> UInt16 {
        let fd = socket(AF_INET, sockStreamType, 0)
        guard fd >= 0 else {
            throw UnixSocketError("socket() failed: \(String(cString: strerror(errno)))")
        }
        _ = fcntl(fd, F_SETFD, FD_CLOEXEC)
        var one: Int32 = 1
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, socklen_t(MemoryLayout<Int32>.size))

        let raw = inet_addr(host)
        guard raw != in_addr_t(0xFFFF_FFFF) else {
            posixCloseFD(fd)
            throw UnixSocketError("bad bind host: \(host)")
        }
        var addr = sockaddr_in()
        addr.sin_family = sa_family_t(AF_INET)
        addr.sin_port = UInt16(0).bigEndian  // ephemeral
        addr.sin_addr = in_addr(s_addr: raw)
        let bindRC = withUnsafePointer(to: &addr) { ptr in
            ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                posixBind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
            }
        }
        guard bindRC == 0 else {
            let err = String(cString: strerror(errno))
            posixCloseFD(fd)
            throw UnixSocketError("bind(\(host):0) failed: \(err)")
        }
        guard listen(fd, 16) == 0 else {
            let err = String(cString: strerror(errno))
            posixCloseFD(fd)
            throw UnixSocketError("listen(\(host)) failed: \(err)")
        }
        var bound = sockaddr_in()
        var len = socklen_t(MemoryLayout<sockaddr_in>.size)
        let nameRC = withUnsafeMutablePointer(to: &bound) { ptr in
            ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &len) }
        }
        guard nameRC == 0 else {
            let err = String(cString: strerror(errno))
            posixCloseFD(fd)
            throw UnixSocketError("getsockname failed: \(err)")
        }
        let boundPort = UInt16(bigEndian: bound.sin_port)

        let source = DispatchSource.makeReadSource(
            fileDescriptor: fd, queue: .global(qos: .userInitiated))
        source.setEventHandler { [weak self] in
            let client = accept(fd, nil, nil)
            guard client >= 0 else { return }
            _ = fcntl(client, F_SETFD, FD_CLOEXEC)
            guard let self else {
                posixCloseFD(client)
                return
            }
            Task { await self.adopt(UnixSocketByteConn(fd: client)) }
        }
        source.setCancelHandler { posixCloseFD(fd) }
        source.resume()

        tcpListenFD = fd
        tcpAcceptSource = source
        port = boundPort
        boundTCPHost = host
        return boundPort
    }
    #endif

    /// Bind the server to a **unix domain socket** instead of a TCP port — the transport for a
    /// sandboxed agent, whose connection is relayed in over vsock (the framework's
    /// `UnixSocketConfiguration`). No IP listener means macOS raises no incoming-connection /
    /// local-network prompts. The HTTP/JSON-RPC dispatch is byte-for-byte identical to the TCP
    /// path; only the listening socket differs.
    ///
    /// A real `AF_UNIX` listener (not `NWListener` with a `.unix` endpoint, which Network.framework
    /// matches in-process and never materializes on disk) so the framework's host-side relay — an
    /// ordinary socket client — can connect to it. Any stale socket file at `path` (e.g. left by a
    /// crash) is removed first, since `bind` fails if the path already exists. Returns the bound path.
    @discardableResult
    public func start(unixSocketPath path: String) async throws -> String {
        // Self-heal (the core fix). A control container's approval server is long-lived and shared by
        // every session in the box, reached through this ONE socket; a single desync used to brick the
        // whole container — every new session's `claude` failing MCP init ("Available MCP tools: none")
        // and every running session stalling on its next gated call — until an app restart, because the
        // cached server trusted its first bind forever. So RE-VALIDATE on every call: keep the existing
        // listener ONLY when it's still a live listening socket AND the file at `path` is still the exact
        // socket node we bound. If the file was unlinked (a `/tmp`-style reaper, a container teardown) or
        // replaced by a different inode, or the fd died, drop the orphaned listener and rebind so this
        // call converges on a working socket. No `await` runs before the rebind, so concurrent callers on
        // this actor can't interleave a half-bound state.
        if unixListenFD != nil {
            if boundUnixSocketPath == path, unixListenerIsHealthy(path: path) {
                return path
            }
            teardownUnixListener()  // stale / desynced — rebind below
        }
        try performUnixBind(path: path)
        return path
    }

    /// Bind + listen a fresh AF_UNIX socket at `path` and wire its accept source, publishing
    /// `unixListenFD` / `unixAcceptSource` / `boundUnixSocketPath` / `boundUnixSocketInode`. The
    /// single bind site for both the first `start(unixSocketPath:)` and every self-heal rebind, so
    /// they can't drift. Synchronous (no suspension) so the actor never exposes a half-bound listener.
    private func performUnixBind(path: String) throws {
        let fm = FileManager.default
        try? fm.createDirectory(
            atPath: (path as NSString).deletingLastPathComponent,
            withIntermediateDirectories: true)
        try? fm.removeItem(atPath: path)  // a bind fails if the path already exists

        let fd = socket(AF_UNIX, sockStreamType, 0)
        guard fd >= 0 else {
            throw UnixSocketError("socket() failed: \(String(cString: strerror(errno)))")
        }
        _ = fcntl(fd, F_SETFD, FD_CLOEXEC)

        var addr = sockaddr_un()
        addr.sun_family = sa_family_t(AF_UNIX)
        let pathBytes = Array(path.utf8)
        let capacity = MemoryLayout.size(ofValue: addr.sun_path)
        guard pathBytes.count < capacity else {
            close(fd)
            throw UnixSocketError("socket path too long (\(pathBytes.count) ≥ \(capacity)): \(path)")
        }
        withUnsafeMutablePointer(to: &addr.sun_path) { raw in
            raw.withMemoryRebound(to: CChar.self, capacity: capacity) { dst in
                for (i, byte) in pathBytes.enumerated() { dst[i] = CChar(bitPattern: byte) }
                dst[pathBytes.count] = 0
            }
        }
        let bindRC = withUnsafePointer(to: &addr) { ptr in
            ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                posixBind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
            }
        }
        guard bindRC == 0 else {
            let err = String(cString: strerror(errno))
            close(fd)
            throw UnixSocketError("bind(\(path)) failed: \(err)")
        }
        // Only the host-side relay connects here; lock the socket to the owner.
        chmod(path, 0o600)
        guard listen(fd, 16) == 0 else {
            let err = String(cString: strerror(errno))
            close(fd)
            try? fm.removeItem(atPath: path)
            throw UnixSocketError("listen(\(path)) failed: \(err)")
        }

        // Accept off a background source so the actor never blocks; each accepted fd drives the same
        // HTTP/JSON-RPC serve loop as a TCP connection.
        let source = DispatchSource.makeReadSource(
            fileDescriptor: fd, queue: .global(qos: .userInitiated))
        source.setEventHandler { [weak self] in
            let client = accept(fd, nil, nil)
            guard client >= 0 else { return }
            _ = fcntl(client, F_SETFD, FD_CLOEXEC)
            guard let self else {
                close(client)
                return
            }
            Task { await self.adopt(UnixSocketByteConn(fd: client)) }
        }
        source.setCancelHandler { close(fd) }
        source.resume()

        unixListenFD = fd
        unixAcceptSource = source
        boundUnixSocketPath = path
        boundUnixSocketInode = Self.inode(ofPath: path)
    }

    /// Whether a unix-socket control endpoint is currently bound and listening at `path`. The
    /// containerized spawn path checks this (mirroring the TCP path's `port != 0` guard) so a
    /// desynced control socket fails the run loudly and retryably instead of surfacing only as the
    /// CLI's opaque "Available MCP tools: none" — and poisoning every session sharing the container.
    public func isUnixSocketListening(atPath path: String) -> Bool {
        boundUnixSocketPath == path && unixListenerIsHealthy(path: path)
    }

    /// Whether the current unix listener is still usable for `path`: we hold the listening fd AND the
    /// file at `path` is still the very socket node we bound (not unlinked, not replaced). The fd
    /// itself is only ever closed by ``stop()`` / ``teardownUnixListener()``, both of which also clear
    /// `unixListenFD`, so a set fd is always live — the failure modes that actually occur are the file
    /// being reaped (stat fails) or replaced by a fresh inode (identity mismatch), which is exactly
    /// what this checks. Cheap enough to run on every `start(unixSocketPath:)` so a shared server
    /// converges on a live socket instead of trusting a first bind a reaper or teardown may have voided.
    private func unixListenerIsHealthy(path: String) -> Bool {
        guard unixListenFD != nil, let bound = boundUnixSocketInode else { return false }
        guard let current = Self.inode(ofPath: path) else { return false }  // unlinked (reaped/torn down)
        return current == bound  // false → the path now points at a different socket node
    }

    /// Tear down the current unix listener without binding a replacement — cancels the accept source
    /// (its cancel handler closes the fd) and clears the bound-socket bookkeeping. Leaves any file at
    /// the path for ``performUnixBind(path:)`` to remove, so a rebind starts clean.
    private func teardownUnixListener() {
        unixAcceptSource?.cancel()
        unixAcceptSource = nil
        unixListenFD = nil
        boundUnixSocketInode = nil
    }

    /// `(st_dev, st_ino)` identity of the filesystem node at `path`, or nil if it doesn't exist.
    /// Used to detect a socket file unlinked or replaced out from under a live listener.
    private static func inode(ofPath path: String) -> (dev: dev_t, ino: ino_t)? {
        var st = stat()
        guard stat(path, &st) == 0 else { return nil }
        return (st.st_dev, st.st_ino)
    }

    #if canImport(Network)
    /// Bind a TCP listener and resume once it is `.ready` (or throw on failure). The connection-
    /// serving pipeline (``adopt(_:)`` → ``serve(_:)``) is transport-agnostic, so this drives the
    /// exact same HTTP/JSON-RPC dispatch as the unix-socket path. Returns the bound ephemeral port.
    ///
    /// `self.listener` and `self.port` are published only AFTER `.ready` — never before the await —
    /// so a concurrent caller can't observe a half-bound listener with a 0 port, and a `.failed`
    /// bind leaves both unset (no stale listener pinning a permanent port 0). The connection handler
    /// is wired before `start`; it captures `self` directly, so it works whether or not
    /// `self.listener` is assigned yet.
    private func bind(host: String) async throws -> UInt16 {
        let parameters = NWParameters.tcp
        parameters.requiredLocalEndpoint = NWEndpoint.hostPort(
            host: NWEndpoint.Host(host), port: .any)
        let listener = try NWListener(using: parameters)

        listener.newConnectionHandler = { [weak self] connection in
            guard let self else {
                connection.cancel()
                return
            }
            Task { await self.adopt(NWByteConn(connection)) }
        }

        let resumeOnce = OnceBox()
        // The handler stays installed for the listener's whole life: first it settles the bind
        // (resuming the continuation exactly once), then it keeps watching so a post-`.ready`
        // death — `.failed` on a network-stack transition, an out-from-under `.cancelled` —
        // invalidates the cached bind and the next `start(host:)` rebinds, instead of the dead
        // listener's stale port poisoning every new session that shares this server.
        do {
            try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
                listener.stateUpdateHandler = { [weak self, weak listener] state in
                    switch state {
                    case .ready:
                        if resumeOnce.claim() { cont.resume() }
                    case .waiting(let error):
                        // Only a bind-time failure; post-`.ready` waiting may recover — leave it.
                        if resumeOnce.claim() { cont.resume(throwing: error) }
                    case .failed(let error):
                        if resumeOnce.claim() {
                            cont.resume(throwing: error)
                        } else if let self, let listener {
                            Task { await self.invalidateTCPListener(listener) }
                        }
                    case .cancelled:
                        if resumeOnce.claim() {
                            cont.resume(throwing: CancellationError())
                        } else if let self, let listener {
                            Task { await self.invalidateTCPListener(listener) }
                        }
                    default:
                        break
                    }
                }
                listener.start(queue: .global(qos: .userInitiated))
            }
        } catch {
            // A `.waiting` bind failure leaves the listener alive and able to become ready later —
            // cancel it so an unpublished listener can't linger holding a socket nobody knows about.
            listener.cancel()
            throw error
        }
        // Ready and bound: publish atomically (no suspension between these and the return).
        self.listener = listener
        self.port = listener.port?.rawValue ?? 0
        self.boundTCPHost = host
        return self.port
    }
    #endif

    public func stop() {
        tcpStartTask?.cancel()
        tcpStartTask = nil
        #if canImport(Network)
        listener?.cancel()
        listener = nil
        #else
        tcpAcceptSource?.cancel()  // its cancel handler closes the listening fd
        tcpAcceptSource = nil
        tcpListenFD = nil
        #endif
        boundTCPHost = nil
        unixAcceptSource?.cancel()  // its cancel handler closes the listening fd
        unixAcceptSource = nil
        unixListenFD = nil
        boundUnixSocketInode = nil
        if let path = boundUnixSocketPath {
            try? FileManager.default.removeItem(atPath: path)
            boundUnixSocketPath = nil
        }
        for task in connectionTasks.values { task.cancel() }
        connectionTasks.removeAll()
        for task in handlerTasks.values { task.cancel() }
        handlerTasks.removeAll()
        handlerTaskIDsByToken.removeAll()
        handlers.removeAll()
        conflictHandlers.removeAll()
        hostExecHandlers.removeAll()
        macVMExecHandlers.removeAll()
        macVMComputerHandlers.removeAll()
        macVMOperatorHandlers.removeAll()
        orchestraSubagentHandlers.removeAll()
        gitReportHandlers.removeAll()
        ghReportHandlers.removeAll()
        commandReportHandlers.removeAll()
    }

    /// TEST-ONLY seam: cancel the live TCP listener *out from under* the cached bind — simulating
    /// the post-`.ready` death (a network-stack `.failed`, an external cancel) that the state
    /// watcher and ``start(host:)``'s re-validation exist to heal. Does NOT clear the cached
    /// `listener`/`port`, so tests can observe the watcher doing that itself. Internal for
    /// `@testable` access; never called from production code.
    func debugCancelTCPListenerOutFromUnder() {
        #if canImport(Network)
        listener?.cancel()
        #else
        tcpAcceptSource?.cancel()
        #endif
    }

    public func register(token: String, handler: @escaping Handler) {
        handlers[token] = handler
    }

    /// Register the per-session `check_conflict` handler under the same bearer token.
    public func registerConflict(token: String, handler: @escaping ConflictHandler) {
        conflictHandlers[token] = handler
    }

    /// Register the per-session `host_exec` handler. Registering it both advertises the tool
    /// in `tools/list` for this token and routes calls to the host runner (HOST_EXEC).
    public func registerHostExec(token: String, handler: @escaping HostExecHandler) {
        hostExecHandlers[token] = handler
    }

    /// Register the per-session `mac_vm_exec` handler. Registering it both advertises the tool in
    /// `tools/list` for this token and routes calls to the macOS-VM runner (see docs/MACOS_VM.md).
    public func registerMacVMExec(token: String, handler: @escaping MacVMExecHandler) {
        macVMExecHandlers[token] = handler
    }

    /// Register the per-session `mac_vm_computer` handler. Registering it both advertises the tool in
    /// `tools/list` for this token and routes computer-use actions to the macOS-VM GUI driver.
    public func registerMacVMComputer(token: String, handler: @escaping MacVMComputerHandler) {
        macVMComputerHandlers[token] = handler
    }

    /// Register the per-session `mac_vm_clear_notifications` handler — advertises the tool and routes the
    /// "dismiss on-screen notifications" action (a fixed `killall NotificationCenter`) to the VM runner.
    public func registerMacVMClearNotifications(
        token: String, handler: @escaping MacVMClearNotificationsHandler
    ) {
        macVMClearNotificationsHandlers[token] = handler
    }

    /// Register the per-session `mac_vm_request_operator` handler. Registering it both advertises the
    /// tool in `tools/list` for this token and routes operator-help requests to the assist coordinator.
    public func registerMacVMOperator(token: String, handler: @escaping MacVMOperatorHandler) {
        macVMOperatorHandlers[token] = handler
    }

    /// Register the per-session `linux_vm_exec` handler. Registering it both advertises the tool in
    /// `tools/list` for this token and routes calls to the Linux-VM runner (see docs/LINUX_VM.md).
    public func registerLinuxVMExec(token: String, handler: @escaping MacVMExecHandler) {
        linuxVMExecHandlers[token] = handler
    }

    /// Register the per-session `linux_vm_computer` handler — advertises the tool and routes
    /// computer-use actions to the Linux-VM GUI driver.
    public func registerLinuxVMComputer(token: String, handler: @escaping MacVMComputerHandler) {
        linuxVMComputerHandlers[token] = handler
    }

    /// Register the per-session `linux_container` handler — advertises the tool and routes the
    /// agent's container lifecycle ops (create/exec/stop/remove/list) to the container runner.
    public func registerLinuxContainer(token: String, handler: @escaping ContainerToolHandler) {
        linuxContainerHandlers[token] = handler
    }

    /// Register the per-session Nucleic-managed Orchestra subagent handler. Registering it advertises
    /// `nucleic_subagent` and routes worker spawning back into the app instead of Claude's native Task.
    public func registerOrchestraSubagent(token: String, handler: @escaping OrchestraSubagentHandler) {
        orchestraSubagentHandlers[token] = handler
    }

    /// Register the supervisor-side `nucleic_supervise` handler — advertises the tool and, on call,
    /// blocks until the supervisor's workers report events, then returns the drained batch.
    public func registerOrchestraSupervise(
        token: String, handler: @escaping OrchestraSuperviseServerHandler
    ) {
        orchestraSuperviseHandlers[token] = handler
    }

    /// Register the supervisor-side `nucleic_reply_to_worker` handler — advertises the tool and routes
    /// the supervisor's answer to a worker waiting in `nucleic_ask_supervisor`.
    public func registerOrchestraReplyToWorker(
        token: String, handler: @escaping OrchestraReplyToWorkerServerHandler
    ) {
        orchestraReplyToWorkerHandlers[token] = handler
    }

    /// Register the worker-side `nucleic_ask_supervisor` handler — advertises the tool and, on call,
    /// routes the worker's question to its supervisor and blocks until the supervisor replies (or the
    /// supervisor's run ends). Registered only for machine-spawned worker sessions.
    public func registerOrchestraAskSupervisor(
        token: String, handler: @escaping OrchestraAskSupervisorServerHandler
    ) {
        orchestraAskSupervisorHandlers[token] = handler
    }

    /// Register the per-session `mac_vm_control` handler — advertises the tool and routes the agent's
    /// macOS-VM lifecycle ops (status/stop/suspend/resume/restart/kill) to the VM manager.
    public func registerMacVMControl(token: String, handler: @escaping VMControlHandler) {
        macVMControlHandlers[token] = handler
    }

    /// Register the per-session `linux_vm_control` handler — the Linux-VM sibling of
    /// ``registerMacVMControl(token:handler:)``.
    public func registerLinuxVMControl(token: String, handler: @escaping VMControlHandler) {
        linuxVMControlHandlers[token] = handler
    }

    /// The `tools/list` entry for a VM lifecycle tool (`mac_vm_control` / `linux_vm_control`) — the two
    /// differ only by name and the guest-OS word in the prose, so they share one schema builder.
    /// `sibling` is the exec tool that boots the VM, named so the agent knows what it's controlling.
    private static func vmControlToolSchema(
        name: String, osLabel: String, sibling: String
    ) -> JSONValue {
        .object([
            "name": .string(name),
            "description": .string(
                "Manage the lifecycle of THIS session's isolated \(osLabel) VM — the one `\(sibling)` "
                    + "boots. Use it to free host resources or reset the VM without ending the session. "
                    + "One `op`: `status` reports whether the VM is running / suspended / stopped / "
                    + "absent (a free, read-only query); `stop` powers it off but keeps its disk, so the "
                    + "next command reboots it (frees its RAM); `suspend` freezes it in place (keeps the "
                    + "RAM but pauses the CPU) and `resume` thaws it instantly — the next command also "
                    + "auto-resumes; `restart` stops and reboots it in place (reclaims RAM a long-running "
                    + "VM holds); `kill` powers it off AND deletes its disk clone (the next command "
                    + "boots a fresh one — you lose any state you built up inside it). These ops act only "
                    + "on your own disposable VM, so they need NO approval. Returns {ok, state, message}. "
                    + "Concurrent VMs are hard-capped across ALL agents, so free your slot the moment "
                    + "the VM goes idle — even mid-turn, between two steps of the same task: `suspend` "
                    + "if you'll need it again soon (it keeps state and thaws in seconds), `stop` if "
                    + "you're done for a while — don't leave a VM running idle and blocking other "
                    + "agents. It's also torn down for you at session end."),
            "inputSchema": .object([
                "type": .string("object"),
                "properties": .object([
                    "op": .object([
                        "type": .string("string"),
                        "description": .string(
                            "One of: status, stop, suspend, resume, restart, kill."),
                    ])
                ]),
                "required": .array([.string("op")]),
            ]),
        ])
    }

    /// Register the per-session `git` interceptor report handler under the same bearer token.
    /// Called for the `POST /git-event` route the in-container shim uses.
    public func registerGitReport(token: String, handler: @escaping GitReportHandler) {
        gitReportHandlers[token] = handler
    }

    /// Register the per-session `gh` interceptor report handler under the same bearer token.
    /// Called for the `POST /gh-event` route the in-container shim uses.
    public func registerGhReport(token: String, handler: @escaping GhReportHandler) {
        ghReportHandlers[token] = handler
    }

    /// Register the per-session non-git command report handler (`POST /command-event`).
    public func registerCommandReport(token: String, handler: @escaping CommandReportHandler) {
        commandReportHandlers[token] = handler
    }

    public func unregister(token: String) {
        // The token's run is over: unwind its suspended calls first (a parked `nucleic_subagent`
        // spawn, a dangling `approve`) so nothing keeps working on behalf of the dead run. The
        // connection may well stay open — on a shared control-container server it carries other
        // sessions' traffic — so token unregistration, not connection close, is this signal.
        cancelHandlerTasks(token: token)
        handlers.removeValue(forKey: token)
        conflictHandlers.removeValue(forKey: token)
        hostExecHandlers.removeValue(forKey: token)
        macVMExecHandlers.removeValue(forKey: token)
        macVMComputerHandlers.removeValue(forKey: token)
        macVMClearNotificationsHandlers.removeValue(forKey: token)
        macVMOperatorHandlers.removeValue(forKey: token)
        linuxVMExecHandlers.removeValue(forKey: token)
        linuxVMComputerHandlers.removeValue(forKey: token)
        linuxContainerHandlers.removeValue(forKey: token)
        orchestraSubagentHandlers.removeValue(forKey: token)
        orchestraSuperviseHandlers.removeValue(forKey: token)
        orchestraReplyToWorkerHandlers.removeValue(forKey: token)
        orchestraAskSupervisorHandlers.removeValue(forKey: token)
        macVMControlHandlers.removeValue(forKey: token)
        linuxVMControlHandlers.removeValue(forKey: token)
        gitReportHandlers.removeValue(forKey: token)
        ghReportHandlers.removeValue(forKey: token)
        commandReportHandlers.removeValue(forKey: token)
    }

    /// The MCP server entry for `--mcp-config` (inline JSON). `host` is the address the
    /// child reaches the server at — loopback for host runs, the VM gateway IP for a
    /// containerized child (which can't see the host's `127.0.0.1`).
    public nonisolated func mcpConfigJSON(
        host: String = "127.0.0.1", port: UInt16, token: String
    ) -> String {
        JSONValue.object([
            "mcpServers": .object([
                "nucleic": .object([
                    "type": .string("http"),
                    "url": .string("http://\(host):\(port)/mcp"),
                    "headers": .object(["Authorization": .string("Bearer \(token)")]),
                ])
            ])
        ]).canonicalString()
    }

    // MARK: - Connection handling

    private func adopt(_ conn: any ByteConn) {
        let id = nextConnectionID
        nextConnectionID += 1
        let task = Task {
            await self.serve(conn)
            self.forget(id)
        }
        connectionTasks[id] = task
    }

    private func forget(_ id: Int) {
        connectionTasks.removeValue(forKey: id)
    }

    private func serve(_ conn: any ByteConn) async {
        defer { conn.close() }
        var buffer = Data()
        // Requests are read serially (HTTP framing on one socket is inherently ordered), but each is
        // *handled* on its own task so a long-running call — most importantly a `nucleic_subagent`
        // spawn that blocks until its worker finishes — doesn't stall later requests pipelined on the
        // same keep-alive connection. That is what lets an Orchestra supervisor's parallel subagent
        // calls actually run in parallel instead of one-at-a-time. Responses must still leave in
        // request order (HTTP/1.1 has no response IDs), so each handler awaits the previous one's
        // send before writing its own; `previous` retains the in-flight chain for draining on close.
        var previous: Task<Void, Never>? = nil
        // Ids of every handler task spawned on this connection. Finished tasks removed themselves
        // from `handlerTasks`, so cancelling by id at teardown only reaches the still-running ones.
        var spawned: [UUID] = []
        while !Task.isCancelled {
            guard let request = await nextRequest(on: conn, buffer: &buffer) else { break }
            let close = request.headers["connection"]?.lowercased() == "close"
            let prior = previous
            let taskID = UUID()
            let token = Self.bearerToken(of: request)
            // A gated `tools/call` from an SSE-capable client is answered as a keepalive'd event
            // stream (``respondStreamingToolCall``) so a handler that blocks for minutes never goes
            // byte-silent long enough for the client to abort the request. Everything else keeps the
            // buffered single-response path. Decided here on the actor (cheap: header-gated before any
            // parse) so the streaming branch inherits the same per-request task registration, ordering
            // (`await prior?.value`), and cancellation as the buffered one.
            let streaming = streamableToolCall(from: request)
            let task = Task {
                if streaming {
                    await prior?.value
                    await self.respondStreamingToolCall(request, on: conn)
                } else {
                    let response = await self.handle(request)
                    await prior?.value
                    try? await self.sendResponse(response, on: conn)
                }
                await self.handlerTaskFinished(taskID, token: token)
            }
            previous = task
            spawned.append(taskID)
            // No suspension since the Task was created (this actor still holds `serve`), so the
            // task can't have reached `handlerTaskFinished` yet — registration never races removal.
            registerHandlerTask(task, id: taskID, token: token)
            if close { break }
        }
        // The connection is dead (client hung up, `Connection: close`, or the server is stopping):
        // no response can be delivered anymore, so CANCEL the still-running handlers instead of
        // letting them keep working for a peer that's gone — this is what unwinds an in-flight
        // `nucleic_subagent` spawn when its supervisor is killed. Cancellation is cooperative;
        // handlers that finish anyway just flush into the closed socket harmlessly.
        for id in spawned { handlerTasks[id]?.cancel() }
        // Let outstanding handlers unwind and flush (in order) before `defer` closes the socket.
        await previous?.value
    }

    /// The request's bearer token (empty when absent/malformed) — the key handler tasks are
    /// indexed under so `unregister(token:)` can cancel a dead session's in-flight calls.
    private static func bearerToken(of request: HTTPRequest) -> String {
        let authorization = request.headers["authorization"] ?? ""
        return authorization.hasPrefix("Bearer ") ? String(authorization.dropFirst(7)) : ""
    }

    private func registerHandlerTask(_ task: Task<Void, Never>, id: UUID, token: String) {
        handlerTasks[id] = task
        if !token.isEmpty { handlerTaskIDsByToken[token, default: []].insert(id) }
    }

    private func handlerTaskFinished(_ id: UUID, token: String) {
        handlerTasks.removeValue(forKey: id)
        if !token.isEmpty, var ids = handlerTaskIDsByToken[token] {
            ids.remove(id)
            handlerTaskIDsByToken[token] = ids.isEmpty ? nil : ids
        }
    }

    /// Cancel every in-flight handler task authenticated by `token` — the session's run has ended
    /// (teardown/shutdown unregisters its token), so its suspended calls must unwind now rather
    /// than survive their supervisor. Entries clean themselves up as the cancelled tasks finish.
    private func cancelHandlerTasks(token: String) {
        for id in handlerTaskIDsByToken[token] ?? [] { handlerTasks[id]?.cancel() }
    }

    private struct HTTPRequest: Sendable {
        let method: String
        let path: String
        let headers: [String: String]  // lowercased keys
        let body: Data
    }

    private struct HTTPResponse: Sendable {
        let status: Int
        let statusText: String
        let contentType: String?
        let body: Data
    }

    /// Hard ceiling on a single request's bytes (headers + body). The only clients are our own
    /// in-container shims/tracer over loopback/VM-gateway, but a compromised agent shares the
    /// per-session token, so cap the buffer to bound memory: a request that grows past this drops
    /// the connection rather than letting an attacker stream gigabytes into `Data`. Generous enough
    /// for a full command-event batch (capped at the source too) plus the largest MCP payload.
    static let maxRequestBytes = 4 * 1024 * 1024

    private func nextRequest(on conn: any ByteConn, buffer: inout Data) async -> HTTPRequest? {
        while true {
            if let request = Self.parseRequest(from: &buffer) { return request }
            // Bound memory: an over-long request (or a lying Content-Length) drops the connection.
            if buffer.count > Self.maxRequestBytes { return nil }
            do {
                guard let chunk = try await conn.receive(maxLength: 1 << 16) else { return nil }
                buffer.append(chunk)
            } catch {
                return nil
            }
        }
    }

    private static func parseRequest(from buffer: inout Data) -> HTTPRequest? {
        guard let headerEnd = buffer.range(of: Data("\r\n\r\n".utf8)) else { return nil }
        let headerData = buffer.subdata(in: buffer.startIndex..<headerEnd.lowerBound)
        guard let headerText = String(data: headerData, encoding: .utf8) else { return nil }
        let lines = headerText.components(separatedBy: "\r\n")
        guard let requestLine = lines.first else { return nil }
        let parts = requestLine.split(separator: " ")
        guard parts.count >= 2 else { return nil }

        var headers: [String: String] = [:]
        for line in lines.dropFirst() {
            guard let colon = line.firstIndex(of: ":") else { continue }
            let key = line[..<colon].trimmingCharacters(in: .whitespaces).lowercased()
            let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
            headers[key] = value
        }

        let contentLength = headers["content-length"].flatMap(Int.init) ?? 0
        let bodyStart = headerEnd.upperBound
        guard buffer.distance(from: bodyStart, to: buffer.endIndex) >= contentLength else {
            return nil
        }
        let body = buffer.subdata(in: bodyStart..<buffer.index(bodyStart, offsetBy: contentLength))
        buffer.removeSubrange(buffer.startIndex..<buffer.index(bodyStart, offsetBy: contentLength))

        return HTTPRequest(
            method: String(parts[0]), path: String(parts[1]), headers: headers, body: body)
    }

    private func sendResponse(_ response: HTTPResponse, on conn: any ByteConn) async throws {
        var head = "HTTP/1.1 \(response.status) \(response.statusText)\r\n"
        if let contentType = response.contentType {
            head += "Content-Type: \(contentType)\r\n"
        }
        head += "Content-Length: \(response.body.count)\r\nConnection: keep-alive\r\n\r\n"
        var payload = Data(head.utf8)
        payload.append(response.body)
        try await conn.send(payload)
    }

    // MARK: - SSE streaming for long-running tool calls

    /// Response head for an SSE-streamed `tools/call` (see ``respondStreamingToolCall(_:on:)``).
    /// No `Content-Length` — the body streams — and `Connection: close`, since the stream carries a
    /// single JSON-RPC result and ends the connection right after it.
    private static let sseResponseHead = Data(
        ("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"
            + "Cache-Control: no-cache\r\nConnection: close\r\n\r\n").utf8)
    /// One SSE keepalive frame — a `:`-prefixed comment the client ignores as an MCP message but
    /// which still puts bytes on the wire, resetting the client's body timeout and every relay's
    /// idle clock between here and the CLI.
    private static let sseKeepaliveFrame = Data(": keepalive\n\n".utf8)

    private enum StreamOutcome: Sendable {
        case handled(HTTPResponse)
        case keepaliveEnded
    }

    /// Whether `request` is a gated `tools/call` from an SSE-capable client — the calls that can
    /// block for minutes and so must be answered as a keepalive'd stream rather than a byte-silent
    /// buffered response. Cheap-gates on method + `Accept` before parsing the body, and requires a
    /// registered tool for the token so an unauthorized request falls to the buffered path (which
    /// returns the proper 401) instead of a 200 stream. A body that doesn't parse also falls back —
    /// the buffered path emits the correct `-32700`.
    private func streamableToolCall(from request: HTTPRequest) -> Bool {
        guard request.method == "POST" else { return false }
        guard (request.headers["accept"] ?? "").contains("text/event-stream") else { return false }
        guard hasRegisteredMCPTool(Self.bearerToken(of: request)) else { return false }
        guard let message = try? JSONValue(parsing: request.body) else { return false }
        return message["method"]?.stringValue == "tools/call"
    }

    /// Answer a `tools/call` as an MCP Streamable-HTTP SSE response: flush the head immediately (so
    /// the client's headers timeout is satisfied at once), emit a keepalive comment every
    /// ``sseKeepaliveInterval`` while the handler runs, then deliver the JSON-RPC result as a single
    /// `data:` event and close. Runs inside the caller's registered per-request task; the handler is
    /// awaited through a structured task group so cancellation (token unregister / connection close)
    /// still unwinds a parked spawn, and the keepalive child is cancelled and fully drained before
    /// the result is written so the two never interleave on the socket.
    private func respondStreamingToolCall(_ request: HTTPRequest, on conn: any ByteConn) async {
        try? await conn.send(Self.sseResponseHead)
        try? await conn.send(Self.sseKeepaliveFrame)

        let interval = sseKeepaliveInterval
        let response: HTTPResponse = await withTaskGroup(of: StreamOutcome.self) { group in
            group.addTask { .handled(await self.handle(request)) }
            group.addTask {
                while !Task.isCancelled {
                    do { try await Task.sleep(for: interval) } catch { break }  // cancelled → stop
                    if Task.isCancelled { break }
                    try? await conn.send(Self.sseKeepaliveFrame)
                }
                return .keepaliveEnded
            }
            var result: HTTPResponse?
            for await outcome in group {
                if case .handled(let r) = outcome {
                    result = r
                    group.cancelAll()  // stop keepalives; keep draining so the child fully returns
                }
            }
            // Unreachable in practice (`handle` always returns), but keep the stream well-formed.
            return result
                ?? HTTPResponse(
                    status: 200, statusText: "OK", contentType: "application/json",
                    body: Data("{}".utf8))
        }

        var event = Data("data: ".utf8)
        event.append(response.body)  // compact single-line JSON-RPC — one `data:` line is valid SSE
        event.append(Data("\n\n".utf8))
        try? await conn.send(event)
        conn.close()  // single-response stream: close so the connection/thread frees immediately
    }

    // MARK: - MCP / JSON-RPC dispatch

    /// Whether `token` has any agent-callable MCP tool registered (ignoring the passive git/gh/
    /// command report routes, which aren't tools). Gates the `/mcp` endpoint: Claude registers
    /// `approve`; Codex/Grok register `check_conflict` (and the capability tools) but not `approve`,
    /// so authorizing on `approve` alone would lock them out. Each tool is still individually gated
    /// on its own handler in `tools/list` + `tools/call`, so a token only sees what it registered.
    private func hasRegisteredMCPTool(_ token: String) -> Bool {
        handlers[token] != nil || conflictHandlers[token] != nil || hostExecHandlers[token] != nil
            || macVMExecHandlers[token] != nil || macVMComputerHandlers[token] != nil
            || macVMClearNotificationsHandlers[token] != nil
            || macVMOperatorHandlers[token] != nil || linuxVMExecHandlers[token] != nil
            || linuxVMComputerHandlers[token] != nil || linuxContainerHandlers[token] != nil
            || orchestraSubagentHandlers[token] != nil
            || orchestraSuperviseHandlers[token] != nil
            || orchestraReplyToWorkerHandlers[token] != nil
            || orchestraAskSupervisorHandlers[token] != nil
            || macVMControlHandlers[token] != nil
            || linuxVMControlHandlers[token] != nil
    }

    private func handle(_ request: HTTPRequest) async -> HTTPResponse {
        guard request.method == "POST" else {
            // Streamable-HTTP clients may probe GET (server-push channel) — we
            // don't offer one, 405 is the spec-sanctioned answer.
            return HTTPResponse(
                status: 405, statusText: "Method Not Allowed", contentType: nil, body: Data())
        }

        // The `git` / `gh` interceptor shims post here (not JSON-RPC). Route before MCP dispatch.
        if request.path == Self.gitEventPath {
            return handleGitEvent(request)
        }
        if request.path == Self.ghEventPath {
            return handleGhEvent(request)
        }
        // The non-git command shims + bash tracer post here (not JSON-RPC).
        if request.path == Self.commandEventPath {
            return handleCommandEvent(request)
        }

        let authorization = request.headers["authorization"] ?? ""
        let token = authorization.hasPrefix("Bearer ") ? String(authorization.dropFirst(7)) : ""
        guard hasRegisteredMCPTool(token) else {
            return HTTPResponse(
                status: 401, statusText: "Unauthorized", contentType: "application/json",
                body: Data(#"{"error":"invalid bearer token"}"#.utf8))
        }

        guard let message = try? JSONValue(parsing: request.body) else {
            return rpcError(id: .null, code: -32700, message: "Parse error")
        }

        let id = message["id"] ?? .null
        let method = message["method"]?.stringValue ?? ""

        // Notifications (no id) are acknowledged with 202 and no body.
        if message["id"] == nil {
            return HTTPResponse(status: 202, statusText: "Accepted", contentType: nil, body: Data())
        }

        switch method {
        case "initialize":
            let requested = message["params"]?["protocolVersion"]?.stringValue ?? "2025-06-18"
            return rpcResult(
                id: id,
                result: .object([
                    "protocolVersion": .string(requested),
                    "capabilities": .object(["tools": .object(["listChanged": .bool(false)])]),
                    "serverInfo": .object([
                        "name": .string("nucleic-approval"), "version": .string("0.1.0"),
                    ]),
                ]))

        case "ping":
            return rpcResult(id: id, result: .object([:]))

        case "tools/list":
            var tools: [JSONValue] = []
            // `approve` — only for tokens whose backend drives approvals through us (Claude). Codex
            // and Grok use their own native approvals and never register this handler, so it stays
            // hidden from them rather than advertising a tool they can't use.
            if handlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.toolName),
                        "description": .string(
                            "Ask the Nucleic user to approve or deny a gated tool call."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "tool_name": .object(["type": .string("string")]),
                                "input": .object(["type": .string("object")]),
                                "tool_use_id": .object(["type": .string("string")]),
                            ]),
                            "required": .array([.string("tool_name"), .string("input")]),
                        ]),
                    ]))
            }
            // `check_conflict` — any backend that registered the conflict handler (Claude, Codex,
            // Grok), so every agent can proactively avoid colliding with another active session.
            if conflictHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.conflictToolName),
                        "description": .string(
                            "Before starting a distinct task that edits files, check whether it "
                                + "conflicts with another currently-active Nucleic agent. Pass a "
                                + "one-line task description and the repo-relative files/areas you "
                                + "expect to change. If the result says the task was deferred or "
                                + "cancelled, STOP and do not edit; if it says proceed (or there is "
                                + "no conflict), continue."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "task": .object(["type": .string("string")]),
                                "files": .object([
                                    "type": .string("array"),
                                    "items": .object(["type": .string("string")]),
                                ]),
                            ]),
                            "required": .array([.string("task")]),
                        ]),
                    ]))
            }
            // Only advertise host_exec when this session opted into host build/run.
            if hostExecHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.hostExecToolName),
                        "description": .string(
                            "Run a command on the HOST machine (macOS), OUTSIDE this Linux sandbox "
                                + "— a LAST-RESORT escape hatch, NOT a general-purpose tool. It exists "
                                + "solely for work that genuinely cannot run inside the container: "
                                + "compiling or running a macOS-only target (a Swift package, a "
                                + "SwiftUI/AppKit app, an xcodebuild/codesign/xcrun step). Before "
                                + "calling it you must have confirmed the task is impossible in the "
                                + "container — which already builds and tests JavaScript, Python, and "
                                + "C/C++ and handles all ordinary shell, file, and search work. Do NOT "
                                + "use it for convenience, for anything that would run in the "
                                + "container, to install software, to fetch from the network, or to "
                                + "run git/gh (host git/gh is blocked and bypasses the shared-trunk "
                                + "version control — run git inside the container). Pass a single shell "
                                + "`command`; it runs in this session's worktree on the host (combine "
                                + "build + run into one command, e.g. \"swift build && swift run "
                                + "MyTool\"). Also pass `reason`: a specific justification for why "
                                + "this cannot run in the container (a container-runnable command is "
                                + "rejected, and an empty/vague reason is rejected). Returns "
                                + "{exit_code, stdout, stderr}. Every call needs explicit user "
                                + "approval and is NEVER auto-approved, so call it only when host "
                                + "execution is genuinely unavoidable."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "command": .object(["type": .string("string")]),
                                "reason": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Why this command cannot run inside the sandbox container. "
                                            + "If the command names an executable that also exists on "
                                            + "Linux, do not just restate the command — the host need "
                                            + "is not self-evident, so explain what specifically makes "
                                            + "THIS invocation require macOS and why the container "
                                            + "cannot do it (e.g. it links an Xcode-only framework, or "
                                            + "it is a codesign/notarization step). Required; empty or "
                                            + "vague reasons are rejected."),
                                ]),
                            ]),
                            "required": .array([.string("command"), .string("reason")]),
                        ]),
                    ]))
            }
            // Only advertise mac_vm_exec when this session opted into the macOS VM.
            if macVMExecHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.macVMExecToolName),
                        "description": .string(
                            "Run a command inside this session's isolated macOS VM (Apple "
                                + "Virtualization) — a real, disposable Mac separate from both this Linux "
                                + "sandbox AND the shared host. Use it for macOS-only work that needs a "
                                + "full Mac: `xcodebuild`, `xcrun simctl` (booting/driving iOS/other "
                                + "simulators), running a built .app, `codesign`/notarization, or any "
                                + "true end-to-end test of a Mac/iOS build. PREFER this over `host_exec` "
                                + "for such work: each agent gets its OWN VM with its own Mac "
                                + "toolchain, so parallel Mac builds don't thrash the ONE shared Mac the "
                                + "way host_exec does (host_exec escapes onto that single shared host). Do "
                                + "NOT use it for work the Linux container already does (JavaScript, "
                                + "Python, C/C++, ordinary shell/file/git) — that belongs in the "
                                + "container. The command runs over SSH in the VM; the session's repo is "
                                + "shared into the VM under \"/Volumes/My Shared Files/\". Pass a single "
                                + "shell `command` (combine build + run, e.g. \"xcodebuild -scheme App "
                                + "test\"), plus `reason`: why this needs the macOS VM specifically. "
                                + "Returns {exit_code, stdout, stderr}. Every call needs explicit user "
                                + "approval and is NEVER auto-approved."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "command": .object(["type": .string("string")]),
                                "reason": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Why this command needs the macOS VM (a Mac-only toolchain: "
                                            + "Xcode, the simulators, codesign) rather than the Linux "
                                            + "container. Required; empty or vague reasons are rejected."),
                                ]),
                            ]),
                            "required": .array([.string("command"), .string("reason")]),
                        ]),
                    ]))
            }
            // Only advertise mac_vm_clear_notifications when this session opted into VM computer-use.
            if macVMClearNotificationsHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.macVMClearNotificationsToolName),
                        "description": .string(
                            "Dismiss the macOS VM's on-screen notifications when a banner or alert is "
                                + "obstructing part of the screen (e.g. it's covering a control you need to "
                                + "click, or hiding what you're trying to read in a `mac_vm_computer` "
                                + "screenshot). Kills the guest's NotificationCenter — the on-screen "
                                + "notifications clear immediately and it relaunches clean. Takes no "
                                + "arguments. Acts only on your own disposable VM, so it needs NO approval. "
                                + "Returns {exit_code, stdout, stderr}. After calling it, take a fresh "
                                + "`mac_vm_computer` screenshot to confirm the view is clear."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([:]),
                        ]),
                    ]))
            }
            // Only advertise mac_vm_computer when this session opted into VM computer-use.
            if macVMComputerHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.macVMComputerToolName),
                        "description": .string(
                            "Drive the GUI of this session's isolated macOS VM like your own Mac — a "
                                + "computer-use loop for a real, disposable Mac. Use it to SEE and "
                                + "operate the desktop when a command isn't enough: visually debug a "
                                + "macOS/iOS app you built (launch it, look at its window, click through "
                                + "it), drive Xcode or the Simulator UI, or verify how something looks. "
                                + "Each call performs ONE `action` and returns a fresh screenshot of the "
                                + "VM screen, so work in a loop: screenshot → decide → act → screenshot. "
                                + "The screenshot is the full screen at its native pixels, so target "
                                + "`x`,`y` exactly as you see them. Pixel actions: `screenshot` (just "
                                + "look); `left_click`/`right_click`/`double_click` at `x`,`y`; "
                                + "`mouse_move` to `x`,`y`; `left_click_drag` to `x`,`y` (from the "
                                + "current cursor); `type` the literal `text`; `key` a chord in `text` "
                                + "(e.g. \"cmd+s\", \"return\", \"tab\", \"cmd+shift+4\"); `scroll` with "
                                + "`scroll_direction`+`scroll_amount`; `launch_app` the app named in "
                                + "`text` (e.g. \"Safari\", \"Xcode\"); `open_browser` a browser named "
                                + "in `text` (\"chrome\", \"firefox\", \"safari\", \"edge\"; default "
                                + "safari) — a predictable shortcut that finds and opens it, then waits "
                                + "for its window; `cursor_position`; `wait` "
                                + "`duration_ms` (let a window open). SEMANTIC actions (preferred when "
                                + "available — they act on controls by identity, not coordinates, and "
                                + "keep working even when screenshots come back blank): `ax_dump` "
                                + "returns the frontmost app's accessibility tree (every control's "
                                + "role/title/value/frame/actions, each with a `ref`); `ax_press` a "
                                + "`ref` (optionally a specific AX action name in `text`); "
                                + "`ax_set_value` writes `value` into a `ref`'d field; `ax_focus` a "
                                + "`ref`; `ax_element_at` resolves the element under `x`,`y`. Convention: "
                                + "ax_dump → act on a ref → ax_dump again (refs go stale after the UI "
                                + "changes). The ax_* actions need the VM's native agent; if the reply "
                                + "says it's unavailable, use screenshots + pixel actions. If screenshots "
                                + "come back blank or unavailable, rely on `ax_dump` — it is "
                                + "framebuffer-independent. This runs in the VM sandbox, so actions are "
                                + "NOT individually approval-gated. Prefer `mac_vm_exec` for headless "
                                + "build/test commands; use this when you need to look at or operate the "
                                + "screen."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "action": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "One of: screenshot, left_click, right_click, double_click, "
                                            + "mouse_move, left_click_drag, type, key, scroll, "
                                            + "cursor_position, launch_app, open_browser, wait, "
                                            + "ax_dump, ax_element_at, ax_press, ax_set_value, "
                                            + "ax_focus."),
                                ]),
                                "x": .object(["type": .string("integer")]),
                                "y": .object(["type": .string("integer")]),
                                "text": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Text to type, a key/chord for `key`, an app name for "
                                            + "`launch_app`, a browser name for `open_browser` "
                                            + "(chrome/firefox/safari/edge), or an AX action name for "
                                            + "`ax_press` (default AXPress)."),
                                ]),
                                "ref": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Element handle from the last ax_dump/ax_element_at (for "
                                            + "ax_press/ax_set_value/ax_focus)."),
                                ]),
                                "value": .object([
                                    "type": .string("string"),
                                    "description": .string("The value to write, for ax_set_value."),
                                ]),
                                "scroll_direction": .object(["type": .string("string")]),
                                "scroll_amount": .object(["type": .string("integer")]),
                                "duration_ms": .object(["type": .string("integer")]),
                            ]),
                            "required": .array([.string("action")]),
                        ]),
                    ]))
            }
            // Only advertise mac_vm_request_operator when this session opted into VM computer-use.
            if macVMOperatorHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.macVMOperatorToolName),
                        "description": .string(
                            "Ask the Nucleic USER to take the wheel and operate this session's macOS VM "
                                + "by hand — a LAST-RESORT hand-off for the rare step you cannot do "
                                + "yourself with `mac_vm_computer`, because it genuinely requires a human: "
                                + "solving a CAPTCHA, completing a login / two-factor prompt, accepting a "
                                + "one-time interactive OS dialog. Do NOT use it for ordinary GUI work you "
                                + "can drive yourself (clicking, typing, launching apps) — that is what "
                                + "`mac_vm_computer` is for; use this ONLY when a real person is required. "
                                + "When you call it, Nucleic shows the user a request card, and if they "
                                + "accept, opens an interactive viewer of the VM they can click and type "
                                + "into, with your `instructions` shown alongside. The call BLOCKS until "
                                + "the user finishes or declines. Pass `instructions`: exactly what the "
                                + "user should do in the VM, specific and self-contained (name the window "
                                + "/ page and the concrete action). Pass `reason`: why a human is required "
                                + "rather than you doing it. Returns {completed, note}: `completed` is "
                                + "whether the user says they did it, `note` is any message they left — "
                                + "read both, then continue (re-screenshot the VM to confirm state). Every "
                                + "call needs explicit user consent and is NEVER auto-approved."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "instructions": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "What the user should do in the VM, concretely and "
                                            + "self-contained (e.g. \"solve the CAPTCHA in the Safari "
                                            + "window, then click Continue\"). Required."),
                                ]),
                                "reason": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Why this step needs a human rather than you driving the VM "
                                            + "yourself. Required; empty or vague reasons are rejected."),
                                ]),
                            ]),
                            "required": .array([.string("instructions"), .string("reason")]),
                        ]),
                    ]))
            }
            // Only advertise linux_vm_exec when this session opted into the Linux VM.
            if linuxVMExecHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.linuxVMExecToolName),
                        "description": .string(
                            "Run a command inside this session's isolated Linux VM (Apple "
                                + "Virtualization) — a real, disposable Linux machine with its own kernel, "
                                + "separate from both this Linux container AND any `linux_container` you "
                                + "create. Use it ONLY for Linux dev work a container CANNOT do: things that "
                                + "need a real kernel (custom kernel modules, systemd, nested "
                                + "virtualization, low-level networking) or a full desktop/GUI. For ordinary "
                                + "build/test/scripting, stay in this container or a `linux_container` — the "
                                + "VM is heavier. Prefer this over a macOS VM whenever the choice is open "
                                + "(it is lighter and boots faster). The command runs over the VM's vsock "
                                + "agent; the session's repo is shared into the VM (the tool mounts it and "
                                + "runs there by default). Pass a single shell `command`, plus `reason`: why "
                                + "a container can't do this and it needs the Linux VM. Returns {exit_code, "
                                + "stdout, stderr}. Every call needs explicit user approval and is NEVER "
                                + "auto-approved."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "command": .object(["type": .string("string")]),
                                "reason": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Why this needs the Linux VM (a real kernel, systemd, or a "
                                            + "desktop/GUI) rather than the container. Required; empty or "
                                            + "vague reasons are rejected."),
                                ]),
                            ]),
                            "required": .array([.string("command"), .string("reason")]),
                        ]),
                    ]))
            }
            // Only advertise linux_vm_computer when this session opted into Linux VM computer-use.
            if linuxVMComputerHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.linuxVMComputerToolName),
                        "description": .string(
                            "Drive the GUI of this session's isolated Linux VM like your own Linux "
                                + "desktop — a computer-use loop for a real, disposable machine. Use it to "
                                + "SEE and operate a Linux desktop app or GUI you can't test headlessly. "
                                + "Each call performs ONE `action` and returns a fresh screenshot, so work "
                                + "in a loop: screenshot → decide → act → screenshot. The screenshot is the "
                                + "full screen at native pixels, so target `x`,`y` exactly as you see them. "
                                + "Actions: `screenshot`; `left_click`/`right_click`/`double_click` at "
                                + "`x`,`y`; `mouse_move` to `x`,`y`; `left_click_drag` to `x`,`y`; `type` "
                                + "the literal `text`; `key` a chord in `text` (e.g. \"ctrl+s\", \"return\", "
                                + "\"tab\"); `scroll` with `scroll_direction`+`scroll_amount`; `launch_app` "
                                + "the binary named in `text`; `open_browser` a browser named in `text` "
                                + "(\"firefox\" or \"chrome\"; default firefox — Firefox ships in the "
                                + "base) — a predictable shortcut that finds and opens it in the desktop "
                                + "session, then waits for its window; `cursor_position`; `wait` "
                                + "`duration_ms`. The "
                                + "semantic `ax_*` actions are macOS-only and unavailable here — use pixel "
                                + "actions. This runs in the VM sandbox, so actions are NOT individually "
                                + "approval-gated."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "action": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "One of: screenshot, left_click, right_click, double_click, "
                                            + "mouse_move, left_click_drag, type, key, scroll, "
                                            + "cursor_position, launch_app, open_browser, wait."),
                                ]),
                                "x": .object(["type": .string("integer")]),
                                "y": .object(["type": .string("integer")]),
                                "text": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Text to type, a key/chord for `key`, a binary name for "
                                            + "`launch_app`, or a browser name for `open_browser` "
                                            + "(firefox/chrome)."),
                                ]),
                                "scroll_direction": .object(["type": .string("string")]),
                                "scroll_amount": .object(["type": .string("integer")]),
                                "duration_ms": .object(["type": .string("integer")]),
                            ]),
                            "required": .array([.string("action")]),
                        ]),
                    ]))
            }
            // Only advertise linux_container when the agent may create its own containers.
            if linuxContainerHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.linuxContainerToolName),
                        "description": .string(
                            "Spin up and manage your OWN throwaway Linux containers — the LIGHTEST "
                                + "isolation available, far cheaper than any VM. Reach for it for "
                                + "lightweight work you want kept separate from your main sandbox: trying a "
                                + "risky install, testing a build in a fresh checkout, or running something "
                                + "you don't want touching your working tree. PREFER a container over a "
                                + "Linux VM for anything that doesn't need a real kernel, systemd, or a GUI "
                                + "— it covers almost all ordinary build/test/scripting. Managed lifecycle "
                                + "via `op`: `create` starts a container (optional `image`, defaults to your "
                                + "sandbox image; optional `name` label) and returns its `name`; `exec` runs "
                                + "a `command` (optional `workdir`) in the named container; `stop` and "
                                + "`remove` tear it down; `list` returns the containers you created. "
                                + "`create`/`exec`/`stop`/`remove` need user approval (pass `reason`); `list` "
                                + "is a free query. Returns {ok, name, names, message} or, for `exec`, "
                                + "{exit_code, stdout, stderr}."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "op": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "One of: create, exec, stop, remove, list."),
                                ]),
                                "name": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "The container to act on (exec/stop/remove), or an optional "
                                            + "label for create."),
                                ]),
                                "image": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "For create: the OCI image; omit for your own sandbox image."),
                                ]),
                                "command": .object([
                                    "type": .string("string"),
                                    "description": .string("For exec: the shell command to run."),
                                ]),
                                "workdir": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "For exec: the working directory inside the container."),
                                ]),
                                "reason": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Why you need this container op. Required for "
                                            + "create/exec/stop/remove; empty or vague reasons are "
                                            + "rejected."),
                                ]),
                            ]),
                            "required": .array([.string("op")]),
                        ]),
                    ]))
            }
            // Only advertise nucleic_subagent when Orchestra is active for this session.
            if orchestraSubagentHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.orchestraSubagentToolName),
                        "description": .string(
                            "Spawn a Nucleic-managed worker subagent for Orchestra. Use this instead "
                                + "of native Task/Agent tools: Nucleic creates an ordinary observed "
                                + "session for the worker, applies the user's configured worker model, "
                                + "and routes it through Nucleic Control/sandboxing, tracking its "
                                + "transcript and approvals. NON-BLOCKING: it returns as soon as the "
                                + "worker starts, with a `worker_id` to track it — it does NOT wait "
                                + "for the worker to finish. Pass `task`: a short label, and `prompt`: "
                                + "the complete self-contained instructions the worker should execute. "
                                + "For independent subtasks, issue multiple calls in one message to fan "
                                + "out (bounded by the user's worker cap). After dispatching, call "
                                + "`nucleic_supervise` to receive worker questions and results, and "
                                + "`nucleic_reply_to_worker` to answer questions. Returns "
                                + "{ok, worker_id, status:\"running\", title, model} or "
                                + "{denied:true, message}."),
                        // Claude Code executes an MCP tool call concurrently with its siblings only
                        // when the tool advertises `readOnlyHint` (its MCP adapter maps
                        // isConcurrencySafe directly to that annotation; there is no separate
                        // concurrency hint). Without it, several nucleic_subagent calls in one
                        // assistant block run strictly one-at-a-time — serializing the whole
                        // fan-out. Spawning is not literally read-only, but the hint is safe here:
                        // the tool is pre-allowed (--allowedTools), so it never rides the
                        // permission path this hint could otherwise relax, and real concurrency
                        // is bounded app-side by the Settings > Agents worker cap
                        // (`defaultOrchestraMaxConcurrentWorkers`).
                        "annotations": .object(["readOnlyHint": .bool(true)]),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "task": .object([
                                    "type": .string("string"),
                                    "description": .string("Short label for the worker session."),
                                ]),
                                "prompt": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "Complete, self-contained instructions for the worker."),
                                ]),
                            ]),
                            "required": .array([.string("task"), .string("prompt")]),
                        ]),
                    ]))
            }
            // Supervisor drive loop — advertised alongside nucleic_subagent. No readOnlyHint: this is
            // the single serializing wait the supervisor blocks on, not a concurrent sibling call.
            if orchestraSuperviseHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.orchestraSuperviseToolName),
                        "description": .string(
                            "Drive your dispatched Orchestra workers. BLOCKS until at least one worker "
                                + "reports an event, then returns the batch: {events:[…], "
                                + "remaining_running}. Each event has a `kind`: \"question\" "
                                + "({worker_id, task, question}) — a worker is paused awaiting your "
                                + "answer, reply with `nucleic_reply_to_worker`; \"completed\" "
                                + "({worker_id, task, model, output}) — the worker's final result; "
                                + "\"failed\" ({worker_id, task, message}). Call this in a loop after "
                                + "dispatching workers, handling events until `remaining_running` is 0 "
                                + "and every worker has reported completed/failed. Takes no arguments."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([:]),
                        ]),
                    ]))
            }
            // Supervisor answers a worker's nucleic_ask_supervisor. No readOnlyHint (mutates channel state).
            if orchestraReplyToWorkerHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.orchestraReplyToWorkerToolName),
                        "description": .string(
                            "Answer a worker that is paused in `nucleic_ask_supervisor` (surfaced as a "
                                + "\"question\" event from `nucleic_supervise`). Pass `worker_id` (from "
                                + "the question event) and `reply` (your answer/decision — relay the "
                                + "user's choice here if you escalated via AskUserQuestion). The worker "
                                + "resumes with your reply. Returns {ok:true} or {ok:false, message} if "
                                + "no worker with that id is currently waiting."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "worker_id": .object([
                                    "type": .string("string"),
                                    "description": .string("The waiting worker's id."),
                                ]),
                                "reply": .object([
                                    "type": .string("string"),
                                    "description": .string("Your answer to the worker's question."),
                                ]),
                            ]),
                            "required": .array([.string("worker_id"), .string("reply")]),
                        ]),
                    ]))
            }
            // Worker-only: ask the supervisor. Advertised only for machine-spawned worker sessions.
            if orchestraAskSupervisorHandlers[token] != nil {
                tools.append(
                    .object([
                        "name": .string(Self.orchestraAskSupervisorToolName),
                        "description": .string(
                            "Ask your supervisor for a decision, missing context, or clarification, or "
                                + "flag a blocker or a discovery that may change the plan. BLOCKS until "
                                + "the supervisor replies (they may relay to the human), then returns "
                                + "{ok:true, answer}. Use this instead of guessing on anything that "
                                + "would meaningfully change your output; do NOT use AskUserQuestion — "
                                + "you cannot reach the user directly. If the supervisor's run has "
                                + "ended, returns {ok:false, supervisor_unavailable:true, answer} — "
                                + "proceed autonomously on your best judgment. Pass `question`."),
                        "inputSchema": .object([
                            "type": .string("object"),
                            "properties": .object([
                                "question": .object([
                                    "type": .string("string"),
                                    "description": .string(
                                        "What you need from the supervisor."),
                                ]),
                            ]),
                            "required": .array([.string("question")]),
                        ]),
                    ]))
            }
            // Only advertise mac_vm_control when this session can use the macOS VM (exec or computer).
            if macVMControlHandlers[token] != nil {
                tools.append(Self.vmControlToolSchema(
                    name: Self.macVMControlToolName, osLabel: "macOS",
                    sibling: Self.macVMExecToolName))
            }
            // Only advertise linux_vm_control when this session can use the Linux VM.
            if linuxVMControlHandlers[token] != nil {
                tools.append(Self.vmControlToolSchema(
                    name: Self.linuxVMControlToolName, osLabel: "Linux",
                    sibling: Self.linuxVMExecToolName))
            }
            return rpcResult(id: id, result: .object(["tools": .array(tools)]))

        case "tools/call":
            let params = message["params"]
            let toolName = params?["name"]?.stringValue
            let arguments = params?["arguments"]
            switch toolName {
            case Self.toolName:
                // Only reachable for tokens that registered the approve handler (Claude); a backend
                // with native approvals never advertises this tool, but fail safe if one calls it.
                guard let handler = handlers[token] else {
                    return toolResult(
                        id: id,
                        text: Reply.deny(message: "Approvals are handled natively for this agent.")
                            .wireJSON())
                }
                let call = ApprovalCall(
                    toolName: arguments?["tool_name"]?.stringValue ?? "unknown",
                    input: arguments?["input"] ?? .object([:]),
                    toolUseID: arguments?["tool_use_id"]?.stringValue)
                // This await is the bridge: it suspends the HTTP response until the
                // human answers (ApprovalCoordinator), then returns the mapped reply.
                let reply = await handler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.conflictToolName:
                let files = (arguments?["files"]?.arrayValue ?? []).compactMap { $0.stringValue }
                let call = ConflictCall(
                    task: arguments?["task"]?.stringValue ?? "", files: files)
                // No handler registered (shouldn't happen) → fail open: no conflict.
                guard let conflictHandler = conflictHandlers[token] else {
                    return toolResult(id: id, text: ConflictReply(resolution: .noConflict).wireJSON())
                }
                let reply = await conflictHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.hostExecToolName:
                let call = HostExecCall(
                    command: arguments?["command"]?.stringValue ?? "",
                    reason: arguments?["reason"]?.stringValue ?? "")
                // No handler (tool shouldn't be visible) → refuse rather than run anything.
                guard let hostExecHandler = hostExecHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: HostExecReply.denied(message: "Host execution is not enabled.")
                            .wireJSON())
                }
                // Suspends until the user approves and the host command finishes (HOST_EXEC).
                let reply = await hostExecHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.macVMExecToolName:
                let call = MacVMExecCall(
                    command: arguments?["command"]?.stringValue ?? "",
                    reason: arguments?["reason"]?.stringValue ?? "")
                guard let macVMExecHandler = macVMExecHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: MacVMExecReply.denied(message: "The macOS VM is not enabled.")
                            .wireJSON())
                }
                // Suspends until the user approves and the in-VM command finishes.
                let reply = await macVMExecHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.macVMClearNotificationsToolName:
                guard let macVMClearNotificationsHandler = macVMClearNotificationsHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: MacVMExecReply.denied(message: "The macOS VM is not enabled.")
                            .wireJSON())
                }
                let clearReply = await macVMClearNotificationsHandler(MacVMClearNotificationsCall())
                return toolResult(id: id, text: clearReply.wireJSON())

            case Self.macVMComputerToolName:
                let call = MacVMComputerCall(
                    action: arguments?["action"]?.stringValue ?? "screenshot",
                    x: arguments?["x"]?.intValue,
                    y: arguments?["y"]?.intValue,
                    text: arguments?["text"]?.stringValue,
                    ref: arguments?["ref"]?.stringValue,
                    value: arguments?["value"]?.stringValue,
                    scrollDirection: arguments?["scroll_direction"]?.stringValue,
                    scrollAmount: arguments?["scroll_amount"]?.intValue,
                    durationMs: arguments?["duration_ms"]?.intValue)
                guard let macVMComputerHandler = macVMComputerHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: MacVMComputerReply.denied(message: "VM computer-use is not enabled.")
                            .deniedJSON())
                }
                // Runs the action in the VM and returns the post-action screenshot as image content.
                switch await macVMComputerHandler(call) {
                case .denied(let message):
                    return toolResult(
                        id: id, text: MacVMComputerReply.denied(message: message).deniedJSON())
                case .ok(let text, let image):
                    if let image {
                        return toolResult(id: id, text: text, imageBase64: image)
                    }
                    return toolResult(id: id, text: text)
                }

            case Self.macVMOperatorToolName:
                let call = MacVMOperatorCall(
                    reason: arguments?["reason"]?.stringValue ?? "",
                    instructions: arguments?["instructions"]?.stringValue ?? "")
                guard let macVMOperatorHandler = macVMOperatorHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: MacVMOperatorReply.denied(message: "The macOS VM is not enabled.")
                            .wireJSON())
                }
                // Suspends until the user finishes operating the VM (or declines).
                let reply = await macVMOperatorHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.linuxVMExecToolName:
                let call = MacVMExecCall(
                    command: arguments?["command"]?.stringValue ?? "",
                    reason: arguments?["reason"]?.stringValue ?? "")
                guard let linuxVMExecHandler = linuxVMExecHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: MacVMExecReply.denied(message: "The Linux VM is not enabled.")
                            .wireJSON())
                }
                let reply = await linuxVMExecHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.linuxVMComputerToolName:
                let call = MacVMComputerCall(
                    action: arguments?["action"]?.stringValue ?? "screenshot",
                    x: arguments?["x"]?.intValue,
                    y: arguments?["y"]?.intValue,
                    text: arguments?["text"]?.stringValue,
                    ref: arguments?["ref"]?.stringValue,
                    value: arguments?["value"]?.stringValue,
                    scrollDirection: arguments?["scroll_direction"]?.stringValue,
                    scrollAmount: arguments?["scroll_amount"]?.intValue,
                    durationMs: arguments?["duration_ms"]?.intValue)
                guard let linuxVMComputerHandler = linuxVMComputerHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: MacVMComputerReply.denied(message: "VM computer-use is not enabled.")
                            .deniedJSON())
                }
                switch await linuxVMComputerHandler(call) {
                case .denied(let message):
                    return toolResult(
                        id: id, text: MacVMComputerReply.denied(message: message).deniedJSON())
                case .ok(let text, let image):
                    if let image {
                        return toolResult(id: id, text: text, imageBase64: image)
                    }
                    return toolResult(id: id, text: text)
                }

            case Self.linuxContainerToolName:
                let call = ContainerToolCall(
                    op: arguments?["op"]?.stringValue ?? "",
                    name: arguments?["name"]?.stringValue,
                    image: arguments?["image"]?.stringValue,
                    command: arguments?["command"]?.stringValue,
                    workdir: arguments?["workdir"]?.stringValue,
                    reason: arguments?["reason"]?.stringValue ?? "")
                guard let linuxContainerHandler = linuxContainerHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: ContainerToolReply.denied(
                            message: "Agent-managed containers are not enabled.").wireJSON())
                }
                let reply = await linuxContainerHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.orchestraSubagentToolName:
                let call = OrchestraSubagentCall(
                    task: arguments?["task"]?.stringValue ?? "",
                    prompt: arguments?["prompt"]?.stringValue ?? "")
                guard let orchestraSubagentHandler = orchestraSubagentHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: OrchestraSubagentResult.denied(
                            message: "Nucleic-managed Orchestra subagents are not enabled.")
                            .wireJSON())
                }
                let reply = await orchestraSubagentHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.orchestraSuperviseToolName:
                guard let superviseHandler = orchestraSuperviseHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: OrchestraSuperviseResult(events: [], remainingRunning: 0).wireJSON())
                }
                // Suspends (like `approve`) until the supervisor's workers report events; the
                // handler task is cancelled by `unregister` if the supervisor's run ends first.
                let reply = await superviseHandler()
                return toolResult(id: id, text: reply.wireJSON())

            case Self.orchestraReplyToWorkerToolName:
                let call = OrchestraReplyToWorkerCall(
                    workerID: arguments?["worker_id"]?.stringValue ?? "",
                    reply: arguments?["reply"]?.stringValue ?? "")
                guard let replyHandler = orchestraReplyToWorkerHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: OrchestraReplyResult.unknown(
                            message: "Orchestra supervision is not enabled for this session.")
                            .wireJSON())
                }
                let reply = await replyHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.orchestraAskSupervisorToolName:
                let call = OrchestraAskSupervisorCall(
                    question: arguments?["question"]?.stringValue ?? "")
                guard let askHandler = orchestraAskSupervisorHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: OrchestraAskSupervisorResult.unavailable(
                            message: "No supervisor is available; proceed autonomously.")
                            .wireJSON())
                }
                // Suspends until the supervisor replies via `nucleic_reply_to_worker`, or this
                // worker's own run ends (its token is unregistered → this handler task cancelled →
                // the AppStore side resumes it with an `.unavailable` answer).
                let reply = await askHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.macVMControlToolName:
                let call = VMControlCall(op: arguments?["op"]?.stringValue ?? "")
                guard let macVMControlHandler = macVMControlHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: VMControlReply.denied(message: "The macOS VM is not enabled.")
                            .wireJSON())
                }
                let reply = await macVMControlHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            case Self.linuxVMControlToolName:
                let call = VMControlCall(op: arguments?["op"]?.stringValue ?? "")
                guard let linuxVMControlHandler = linuxVMControlHandlers[token] else {
                    return toolResult(
                        id: id,
                        text: VMControlReply.denied(message: "The Linux VM is not enabled.")
                            .wireJSON())
                }
                let reply = await linuxVMControlHandler(call)
                return toolResult(id: id, text: reply.wireJSON())

            default:
                return rpcError(id: id, code: -32602, message: "Unknown tool")
            }

        default:
            return rpcError(id: id, code: -32601, message: "Method not found: \(method)")
        }
    }

    /// Handle a `POST /git-event` from the in-container `git` interceptor shim: bearer-token
    /// gated like the MCP route, but a plain JSON body `{argv, cwd, exitCode, subcommand,
    /// sessionId}`. Fire-and-forget — the registered handler returns immediately (it offloads
    /// any real work), so a report never blocks the agent's git call. Always 202s a known
    /// token (even on a malformed body) so the shim never retries or stalls; 401s an unknown one.
    private func handleGitEvent(_ request: HTTPRequest) -> HTTPResponse {
        let authorization = request.headers["authorization"] ?? ""
        let token = authorization.hasPrefix("Bearer ") ? String(authorization.dropFirst(7)) : ""
        guard let handler = gitReportHandlers[token] else {
            return HTTPResponse(
                status: 401, statusText: "Unauthorized", contentType: "application/json",
                body: Data(#"{"error":"invalid bearer token"}"#.utf8))
        }
        if let message = try? JSONValue(parsing: request.body) {
            let argv = (message["argv"]?.arrayValue ?? []).compactMap { $0.stringValue }
            handler(GitReportCall(
                argv: argv,
                cwd: message["cwd"]?.stringValue ?? "",
                exitCode: message["exitCode"]?.intValue ?? 0,
                subcommand: message["subcommand"]?.stringValue,
                sessionID: message["sessionId"]?.stringValue))
        }
        return HTTPResponse(status: 202, statusText: "Accepted", contentType: nil, body: Data())
    }

    /// Handle a `POST /gh-event` from the in-container `gh` interceptor shim — the exact twin of
    /// `handleGitEvent`: bearer-token gated, plain JSON `{argv, cwd, exitCode, subcommand,
    /// sessionId}`, fire-and-forget (202 on any known-token body, 401 on an unknown token).
    private func handleGhEvent(_ request: HTTPRequest) -> HTTPResponse {
        let authorization = request.headers["authorization"] ?? ""
        let token = authorization.hasPrefix("Bearer ") ? String(authorization.dropFirst(7)) : ""
        guard let handler = ghReportHandlers[token] else {
            return HTTPResponse(
                status: 401, statusText: "Unauthorized", contentType: "application/json",
                body: Data(#"{"error":"invalid bearer token"}"#.utf8))
        }
        if let message = try? JSONValue(parsing: request.body) {
            let argv = (message["argv"]?.arrayValue ?? []).compactMap { $0.stringValue }
            handler(GhReportCall(
                argv: argv,
                cwd: message["cwd"]?.stringValue ?? "",
                exitCode: message["exitCode"]?.intValue ?? 0,
                subcommand: message["subcommand"]?.stringValue,
                sessionID: message["sessionId"]?.stringValue))
        }
        return HTTPResponse(status: 202, statusText: "Accepted", contentType: nil, body: Data())
    }

    /// Handle a `POST /command-event` from the non-git command interceptor: bearer-token gated
    /// like `/git-event`. Two body shapes, both fanned out to one `CommandReportCall` per command:
    ///
    ///   * shim — `{type:"command", command, argv, cwd, exitCode, durationMs, stdout, stderr,
    ///     truncated, sessionId}` — one rich, output-carrying report.
    ///   * tracer — `{type:"command-batch", sessionId, events:[{line, cwd, exitCode, durationMs}]}`
    ///     — a batch of metadata-only reports for a whole Bash tool call.
    ///
    /// Fire-and-forget: handlers return immediately. Always 202s a known token (even on a malformed
    /// body) so the shim/tracer never retry or stall; 401s an unknown one.
    private func handleCommandEvent(_ request: HTTPRequest) -> HTTPResponse {
        let authorization = request.headers["authorization"] ?? ""
        let token = authorization.hasPrefix("Bearer ") ? String(authorization.dropFirst(7)) : ""
        guard let handler = commandReportHandlers[token] else {
            return HTTPResponse(
                status: 401, statusText: "Unauthorized", contentType: "application/json",
                body: Data(#"{"error":"invalid bearer token"}"#.utf8))
        }
        if let message = try? JSONValue(parsing: request.body) {
            for call in Self.parseCommandReports(message) { handler(call) }
        }
        return HTTPResponse(status: 202, statusText: "Accepted", contentType: nil, body: Data())
    }

    /// Decode a `/command-event` body into zero or more `CommandReportCall`s. A `command-batch`
    /// (tracer) yields one per `events[]` entry; anything else is treated as a single shim report.
    static func parseCommandReports(_ message: JSONValue) -> [CommandReportCall] {
        let sessionID = message["sessionId"]?.stringValue
        if message["type"]?.stringValue == "command-batch" {
            return (message["events"]?.arrayValue ?? []).map { event in
                CommandReportCall(
                    command: nil, argv: [], commandLine: event["line"]?.stringValue ?? "",
                    cwd: event["cwd"]?.stringValue ?? "",
                    exitCode: event["exitCode"]?.intValue ?? 0,
                    durationMs: event["durationMs"]?.intValue,
                    stdout: "", stderr: "", truncated: false, source: .tracer, sessionID: sessionID)
            }
        }
        let argv = (message["argv"]?.arrayValue ?? []).compactMap { $0.stringValue }
        return [CommandReportCall(
            command: message["command"]?.stringValue, argv: argv,
            commandLine: message["commandLine"]?.stringValue,
            cwd: message["cwd"]?.stringValue ?? "",
            exitCode: message["exitCode"]?.intValue ?? 0,
            durationMs: message["durationMs"]?.intValue,
            stdout: message["stdout"]?.stringValue ?? "",
            stderr: message["stderr"]?.stringValue ?? "",
            truncated: message["truncated"]?.boolValue ?? false,
            source: .shim, sessionID: sessionID)]
    }

    /// A successful `tools/call` result wrapping `text` in a single MCP text content block.
    private func toolResult(id: JSONValue, text: String) -> HTTPResponse {
        rpcResult(
            id: id,
            result: .object([
                "content": .array([
                    .object(["type": .string("text"), "text": .string(text)])
                ]),
                "isError": .bool(false),
            ]))
    }

    /// As ``toolResult(id:text:)`` but also attaches an image content block, so a tool can return a
    /// **screenshot the model actually sees** (standard MCP image content; the Claude CLI forwards an
    /// image tool result into the model's context). Used by `mac_vm_computer` to close the see→act loop.
    /// `mimeType` is the base64 payload's type (e.g. `image/jpeg`).
    private func toolResult(
        id: JSONValue, text: String, imageBase64: String, mimeType: String = "image/jpeg"
    ) -> HTTPResponse {
        rpcResult(
            id: id,
            result: .object([
                "content": .array([
                    .object(["type": .string("text"), "text": .string(text)]),
                    .object([
                        "type": .string("image"),
                        "data": .string(imageBase64),
                        "mimeType": .string(mimeType),
                    ]),
                ]),
                "isError": .bool(false),
            ]))
    }

    private func rpcResult(id: JSONValue, result: JSONValue) -> HTTPResponse {
        let body = JSONValue.object(["jsonrpc": .string("2.0"), "id": id, "result": result])
        return HTTPResponse(
            status: 200, statusText: "OK", contentType: "application/json",
            body: (try? body.encodedData()) ?? Data())
    }

    private func rpcError(id: JSONValue, code: Int, message: String) -> HTTPResponse {
        let body = JSONValue.object([
            "jsonrpc": .string("2.0"), "id": id,
            "error": .object(["code": .number(Double(code)), "message": .string(message)]),
        ])
        return HTTPResponse(
            status: 200, statusText: "OK", contentType: "application/json",
            body: (try? body.encodedData()) ?? Data())
    }
}

// MARK: - Transport abstraction

/// A bidirectional byte stream the HTTP/JSON-RPC serve loop drives, so the same dispatch runs over
/// either a Network.framework TCP connection (host loopback) or a raw unix-domain socket (the
/// vsock-relayed control plane). `receive` returns nil at EOF; `close` is idempotent.
private protocol ByteConn: Sendable {
    func receive(maxLength: Int) async throws -> Data?
    func send(_ data: Data) async throws
    func close()
}

#if canImport(Network)
/// ``ByteConn`` over a Network.framework connection (the TCP transport). Started on creation so the
/// serve loop can receive immediately.
private final class NWByteConn: ByteConn, @unchecked Sendable {
    private let connection: NWConnection
    init(_ connection: NWConnection) {
        self.connection = connection
        connection.start(queue: .global(qos: .userInitiated))
    }
    func receive(maxLength: Int) async throws -> Data? {
        try await withCheckedThrowingContinuation { cont in
            connection.receive(minimumIncompleteLength: 1, maximumLength: maxLength) {
                data, _, isComplete, error in
                if let error {
                    cont.resume(throwing: error)
                } else if let data, !data.isEmpty {
                    cont.resume(returning: data)
                } else if isComplete {
                    cont.resume(returning: nil)
                } else {
                    cont.resume(returning: Data())
                }
            }
        }
    }
    func send(_ data: Data) async throws {
        try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
            connection.send(
                content: data,
                completion: .contentProcessed { error in
                    if let error { cont.resume(throwing: error) } else { cont.resume() }
                })
        }
    }
    func close() { connection.cancel() }
}
#endif

/// ``ByteConn`` over an accepted `AF_UNIX` stream socket (the vsock-relayed transport). Reads/writes
/// are blocking POSIX calls offloaded to a background queue, so the actor never blocks and a turn
/// suspended on an approval holds no thread (no read is in flight between request and response). The
/// control plane's live connection count is small (one MCP connection plus short-lived interceptor
/// posts per container), so a thread parked on `read` per live connection is acceptable.
private final class UnixSocketByteConn: ByteConn, @unchecked Sendable {
    private let fd: Int32
    private let lock = NSLock()
    private var closed = false
    init(fd: Int32) {
        self.fd = fd
        // A client that dies mid-call (a killed supervisor's CLI) closes its end while a response
        // may still be in flight; without this, that write raises SIGPIPE and kills the WHOLE app
        // rather than surfacing as a plain EPIPE from `write` (handled in `send`). Linux has no
        // SO_NOSIGPIPE; there `writeNoSigpipe` passes MSG_NOSIGNAL on every send instead.
        #if canImport(Darwin)
        var one: Int32 = 1
        setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, socklen_t(MemoryLayout<Int32>.size))
        #endif
    }

    func receive(maxLength: Int) async throws -> Data? {
        let fd = self.fd
        return try await withCheckedThrowingContinuation { cont in
            DispatchQueue.global(qos: .userInitiated).async {
                var buffer = [UInt8](repeating: 0, count: maxLength)
                while true {
                    let n = buffer.withUnsafeMutableBytes { read(fd, $0.baseAddress, maxLength) }
                    if n > 0 {
                        cont.resume(returning: Data(buffer[0..<n]))
                    } else if n == 0 {
                        cont.resume(returning: nil)
                    } else if errno == EINTR {
                        continue
                    } else {
                        cont.resume(throwing: POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO))
                    }
                    return
                }
            }
        }
    }

    func send(_ data: Data) async throws {
        let fd = self.fd
        try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
            DispatchQueue.global(qos: .userInitiated).async {
                let result: Result<Void, Error> = data.withUnsafeBytes { raw in
                    guard let base = raw.baseAddress else { return .success(()) }
                    var offset = 0
                    while offset < raw.count {
                        let n = writeNoSigpipe(fd, base + offset, raw.count - offset)
                        if n > 0 {
                            offset += n
                        } else if n < 0 && errno == EINTR {
                            continue
                        } else {
                            return .failure(POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO))
                        }
                    }
                    return .success(())
                }
                cont.resume(with: result)
            }
        }
    }

    func close() {
        lock.lock()
        defer { lock.unlock() }
        guard !closed else { return }
        closed = true
        shutdown(fd, Int32(SHUT_RDWR))  // Glibc spells the constant as Int; Int32 on both platforms
        posixCloseFD(fd)
    }
}

/// Failure binding/listening the control-plane unix socket.
private struct UnixSocketError: Error, CustomStringConvertible {
    let description: String
    init(_ description: String) { self.description = description }
}

#if canImport(Network)
/// Resume-once guard for NWListener state callbacks (ready may be followed by
/// failed; the continuation must fire exactly once).
private final class OnceBox: @unchecked Sendable {
    private let lock = NSLock()
    private var claimed = false

    func claim() -> Bool {
        lock.lock()
        defer { lock.unlock() }
        if claimed { return false }
        claimed = true
        return true
    }
}
#endif
