ez-agent-ruby/lib/ez_agent/api/client.rb

# frozen_string_literal: true

require "json"
require "securerandom"
require "socket"

module EzAgent
  module API
    PROTOCOL_VERSION = 1
    DEFAULT_CONNECTION_NAME = "ruby-api".freeze
    READ_POLL_SECONDS = 2.0
    DEFAULT_STARTUP_TIMEOUT = 2.0
    DEFAULT_REQUEST_TIMEOUT = 5.0
    # Omitted timeouts renew on matching RPC heartbeats. Numeric arguments are
    # explicit absolute caller limits, including the legacy public constants.
    RenewableTimeout = Struct.new(:seconds)
    RENEWABLE_REQUEST_TIMEOUT = RenewableTimeout.new(5.0).freeze
    RENEWABLE_LONG_REQUEST_TIMEOUT = RenewableTimeout.new(10.0).freeze
    MAX_WIRE_ITR = (2**63) - 1

    # Resolved local AF_UNIX service endpoint.
    class Endpoint
      attr_reader :runtime_dir, :socket_path

      def self.resolve(socket_path: nil, env: ENV)
        if socket_path
          path = String(socket_path)
          raise EndpointError, "socket_path must not be empty" if path.empty?

          return new(File.dirname(path), path)
        end

        runtime_base = env["XDG_RUNTIME_DIR"]
        if runtime_base.nil? || runtime_base.empty?
          raise EndpointError, "XDG_RUNTIME_DIR is not set; a valid runtime directory is required"
        end

        runtime_dir = File.join(runtime_base, "ez-agent")
        new(runtime_dir, File.join(runtime_dir, "ez-agent.sock"))
      end

      def initialize(runtime_dir, socket_path)
        @runtime_dir = runtime_dir.dup.freeze
        @socket_path = socket_path.dup.freeze
        freeze
      end
    end

    # Immutable validated startup acknowledgement.
    class HelloAck
      attr_reader :itr, :server_id, :node_id, :state_dir, :connection_id, :config_error

      def initialize(frame)
        @itr = frame["itr"]
        unless @itr.nil? || API.int64?(@itr)
          raise DecodeError.new("malformed hello_ack: itr must be a signed 64-bit integer", frame_type: "hello_ack")
        end
        @server_id = frame.fetch("server_id").dup.freeze
        node_id = frame["node_id"]
        unless node_id.nil? || node_id.is_a?(String)
          raise DecodeError.new("malformed hello_ack: node_id must be a string", frame_type: "hello_ack")
        end
        @node_id = node_id&.dup&.freeze
        @state_dir = frame.fetch("state_dir").dup.freeze
        connection_id = frame["connection_id"]
        unless connection_id.nil? || connection_id.is_a?(String)
          raise DecodeError.new("malformed hello_ack: connection_id must be a string", frame_type: "hello_ack")
        end
        @connection_id = connection_id&.dup&.freeze
        @config_error = frame["config_error"]&.dup&.freeze
        freeze
      end
    end

    # Stream-backed initiating protocol-1 connection. It has one reader/reactor, an ordered
    # mutex-protected writer, and a callback dispatcher owned by #events.
    class Connection
      RESPONSE_ONLY_TYPES = %w[
        history_list turn_tree_list leaf_stats_response leaf_config_value
        leaf_config_list leaf_renamed leaf_meta_updated leaf_config_set
        leaf_config_deleted leaf_files_result attachment_chunk model_list resolved_models virtual_root_created
        model_set tool_info leaf_list root_list cwd_list cwd_updated vacuum_result macro_list
        macro_result tool_list plugin_list provider_list tool_added tool_removed
        thinking_level_set supported_filetypes_response connection_list queued_list
        feed_dropped leaf_switched leaf_rewound question_reply_ack
        background_task_add_ack background_task_remove_ack tool_invoke_result
      ].freeze

      DUAL_ROLE_TYPES = %w[
        abort_received leaf_created leaf_deleted prompt_accepted steer_accepted
      ].freeze

      attr_reader :endpoint, :name, :events, :hello_ack, :sessions,
                  :leaves, :roots, :turns, :config, :leaf_files, :metadata, :models,
                  :runs, :subscriptions, :macros, :daemon, :capabilities,
                  :tools, :plugins, :providers, :connections, :filetypes,
                  :maintenance, :notifications, :progress, :questions, :background_tasks

      class << self
        # Opens an initiating client connection over caller-supplied streams.
        # The reader must be pollable and support #read_nonblock; the writer is
        # reserved exclusively for complete protocol JSONL frames. Streams stay
        # caller-owned unless a once-only cleanup callback is supplied with #close.
        def open(reader:, writer:, close: nil, name: DEFAULT_CONNECTION_NAME,
                 cwd: Dir.pwd, leaf_id: nil, startup_timeout: DEFAULT_STARTUP_TIMEOUT,
                 provider_workers: DEFAULT_PROVIDER_WORKERS,
                 provider_heartbeat_interval: DEFAULT_PROVIDER_HEARTBEAT_INTERVAL)
          connection = new(reader: reader, writer: writer, transport_cleanup: close,
                           name: name, cwd: cwd, leaf_id: leaf_id,
                           provider_workers: provider_workers,
                           provider_heartbeat_interval: provider_heartbeat_interval)
          yield connection if block_given?
          connection.__send__(:start, startup_timeout)
          connection
        rescue Exception => error
          Incidents.record(:open, error)
          begin
            if connection
              connection.__send__(:cleanup_failed_startup, error)
            else
              close&.call
            end
          rescue Exception => cleanup_error
            Incidents.record(:open_cleanup, cleanup_error)
          end
          raise
        end

        # Compatibility adapter for the former Client.connect API. The AF_UNIX
        # construction itself lives in API.connect so every transport shares #open.
        def connect(**options, &block)
          API.connect(**options, &block)
        end
      end

      def initialize(reader:, writer:, transport_cleanup:, name:, cwd:, leaf_id:,
                     provider_workers: DEFAULT_PROVIDER_WORKERS,
                     provider_heartbeat_interval: DEFAULT_PROVIDER_HEARTBEAT_INTERVAL)
        @reader = reader
        @writer = writer
        @transport_cleanup = transport_cleanup
        @transport_cleanup_ran = false
        @endpoint = nil
        @name = String(name).dup.freeze
        raise ArgumentError, "name must not be empty" if @name.empty?
        @cwd = cwd.nil? ? nil : String(cwd).freeze
        @leaf_id = leaf_id.nil? ? nil : String(leaf_id).freeze
        provider_workers = Integer(provider_workers)
        provider_heartbeat_interval = Float(provider_heartbeat_interval)
        raise ArgumentError, "provider_workers must be positive" unless provider_workers.positive?
        unless provider_heartbeat_interval.positive?
          raise ArgumentError, "provider_heartbeat_interval must be positive"
        end
        @pending = PendingRequests.new
        @tool_invocations = ToolInvocations.new
        @writer_mutex = Mutex.new
        @next_itr = 1
        @terminal_mutex = Mutex.new
        @terminal_error = nil
        @locally_closed = false
        @cleanup_error = nil
        @events = Events.new(fatal_hook: method(:worker_failed))
        @reader_thread = nil
        @buffer = +""
        @sessions = Sessions.new(self)
        @leaves = @sessions
        @roots = Roots.new(self)
        @turns = Turns.new(self)
        @config = LeafConfig.new(self)
        @leaf_files = LeafFiles.new(self)
        @metadata = Metadata.new(self)
        @models = Models.new(self)
        @runs = RunControl.new(self)
        @subscriptions = Subscriptions.new(self)
        @capabilities = Capabilities.new(
          self, worker_count: provider_workers,
          heartbeat_interval: provider_heartbeat_interval
        )
        @tools = Tools.new(self)
        @plugins = Plugins.new(self)
        @providers = Providers.new(self)
        @connections = Connections.new(self)
        @filetypes = Filetypes.new(self)
        @maintenance = Maintenance.new(self)
        @notifications = Notifications.new(self)
        @progress = Progress.new(self)
        @questions = Questions.new(self)
        @background_tasks = BackgroundTasks.new(self)
        @macros = Macros.new(self)
        @daemon = Daemon.new(self)
      end

      def closed?
        @terminal_mutex.synchronize { !@terminal_error.nil? }
      end

      def terminal_error
        @terminal_mutex.synchronize { @terminal_error }
      end

      # Initiates local client shutdown only. It never sends the daemon-wide
      # shutdown frame. Use #join to wait for reader and callback completion.
      def close
        transition_terminal(
          ConnectionClosedError.new("connection closed locally"), locally_closed: true
        )
        self
      end

      # Joins all connection-owned threads. Unexpected terminal errors are
      # raised by default; a clean local close is not.
      def join(timeout: nil, raise_on_error: true)
        started = monotonic
        budget = timeout && Float(timeout)
        deadline = budget && started + budget
        join_thread(@reader_thread, deadline, "reader") if @reader_thread
        remaining = deadline && [deadline - monotonic, 0].max
        @capabilities.join(timeout: remaining)
        remaining = deadline && [deadline - monotonic, 0].max
        @events.join(timeout: remaining)
        error, locally_closed = @terminal_mutex.synchronize do
          [@terminal_error, @locally_closed]
        end
        raise error if error && !error.is_a?(StandardError)
        raise error if raise_on_error && error && !locally_closed

        self
      rescue TimeoutError => error
        Incidents.record(:connection_join, error, data: Incidents.timing(started, budget))
        raise
      end

      private

      def start(startup_timeout)
        timeout = Float(startup_timeout)
        raise ArgumentError, "startup_timeout must be positive" unless timeout.positive?

        hello = {"type" => "hello", "protocol" => PROTOCOL_VERSION, "name" => @name}
        hello["cwd"] = @cwd if @cwd && !@cwd.empty?
        hello["leaf_id"] = @leaf_id if @leaf_id && !@leaf_id.empty?
        write_frame(hello, startup: true)
        frame = read_startup_frame(timeout)
        validate_hello_ack(frame)
        @hello_ack = HelloAck.new(frame)
        @reader_thread = Thread.new do
          Thread.current.report_on_exception = false
          read_loop
        end
        @reader_thread.name = "ez-agent-api-reader" if @reader_thread.respond_to?(:name=)
        self
      rescue TransportError => cause
        raise HandshakeError.new("hello exchange failed: #{cause.message}", cause: cause)
      end

      def cleanup_failed_startup(error)
        begin
          transition_terminal(error, preserve_primary: true)
        rescue Exception => cleanup_error
          retain_cleanup_error(cleanup_error, boundary: :startup_cleanup)
        end
        # Attempt both joins even if one has a fatal secondary failure.
        [[@capabilities, :startup_provider_join], [@events, :startup_callback_join]].each do |owner, boundary|
          owner.join
        rescue Exception => cleanup_error
          retain_cleanup_error(cleanup_error, boundary: boundary)
        end
      end

      # AF_UNIX endpoint metadata is attached only by the convenience adapter;
      # direct stream connections do not require endpoint metadata.
      def set_endpoint(endpoint)
        @endpoint = endpoint
      end

      def read_startup_frame(timeout)
        deadline = monotonic + timeout
        loop do
          if (newline = @buffer.index("\n"))
            line = @buffer.slice!(0, newline + 1)
            return decode_frame(line, handshake: true)
          end

          remaining = deadline - monotonic
          if remaining <= 0
            raise HandshakeError.new("timed out waiting for hello_ack after #{timeout}s")
          end

          wait = [remaining, READ_POLL_SECONDS].min
          next unless IO.select([@reader], nil, nil, wait)

          begin
            chunk = @reader.read_nonblock(16_384)
          rescue IO::WaitReadable
            next
          end
          @buffer << chunk
        end
      rescue EOFError
        unless @buffer.empty?
          error = IncompleteFrameError.new(observed_bytes: @buffer.bytesize)
          raise HandshakeError.new("malformed hello response", cause: error)
        end
        raise HandshakeError.new("connection closed before hello_ack")
      rescue IOError, SystemCallError => cause
        raise TransportError.new("reading hello_ack: #{cause.message}", cause: cause)
      end

      def validate_hello_ack(frame)
        if frame["type"] == "error"
          code = frame["code"].is_a?(String) ? frame["code"] : nil
          message = frame["message"].is_a?(String) ? frame["message"] : "service rejected hello"
          raise HandshakeError.new(message, code: code)
        end
        unless frame["type"] == "hello_ack"
          raise HandshakeError, "expected hello_ack, got #{frame["type"].inspect}"
        end
        unless frame["protocol"].is_a?(Integer) && frame["protocol"] == PROTOCOL_VERSION
          raise HandshakeError, "unsupported protocol #{frame["protocol"].inspect}"
        end
        unless frame["server_id"].is_a?(String) && frame["state_dir"].is_a?(String) &&
               (frame["node_id"].nil? || frame["node_id"].is_a?(String)) &&
               (frame["connection_id"].nil? || frame["connection_id"].is_a?(String)) &&
               (frame["config_error"].nil? || frame["config_error"].is_a?(String))
          raise HandshakeError, "malformed hello_ack fields"
        end
      end

      def read_loop
        loop do
          drain_inbound_frames
          break if closed?

          ready = IO.select([@reader], nil, nil, READ_POLL_SECONDS)
          if ready.nil?
            break if closed?
            next
          end

          begin
            chunk = @reader.read_nonblock(16_384)
          rescue IO::WaitReadable
            next
          end
          @buffer << chunk
        end
      rescue EOFError => cause
        begin
          drain_inbound_frames
        rescue DecodeError => error
          Incidents.record(:reader, error)
          @events.__send__(:report_diagnostic, error)
          transition_terminal(error, preserve_primary: true)
          return
        rescue Exception => error
          Incidents.record(:reader, error)
          transition_terminal(error, preserve_primary: true)
          raise
        end
        error = eof_error(cause)
        Incidents.record(:reader, error) unless closed?
        @events.__send__(:report_diagnostic, error) if error.is_a?(DecodeError)
        transition_terminal(error, preserve_primary: true)
      rescue DecodeError => cause
        Incidents.record(:reader, cause)
        @events.__send__(:report_diagnostic, cause)
        transition_terminal(cause, preserve_primary: true)
      rescue IOError, SystemCallError => cause
        error = TransportError.new("reading service connection: #{cause.message}", cause: cause)
        Incidents.record(:reader, error) unless closed?
        transition_terminal(error, preserve_primary: true)
      rescue Exception => cause # Keep every unexpected reactor failure visible and terminal.
        Incidents.record(:reader, cause)
        unless cause.is_a?(StandardError)
          transition_terminal(cause, preserve_primary: true)
          raise
        end
        transition_terminal(TransportError.new("reader reactor failed: #{cause.message}", cause: cause), preserve_primary: true)
      ensure
        @events.close(connection_closed_error)
      end

      def decode_frame(line, handshake: false)
        frame, malformed_json = parse_json(line)
        if malformed_json
          error = DecodeError.new("malformed JSONL frame", reason: :malformed_json)
          if handshake
            raise HandshakeError.new("malformed hello response", cause: error), cause: nil
          end

          raise error, cause: nil
        end
        unless frame.is_a?(Hash)
          error = DecodeError.new("JSONL frame must be an object", reason: :invalid_envelope)
          raise HandshakeError.new("malformed hello response", cause: error) if handshake
          raise error
        end
        type = frame["type"]
        unless type.is_a?(String) && !type.empty?
          error = DecodeError.new("JSONL frame must have a nonempty string type",
                                  reason: :invalid_envelope)
          raise HandshakeError.new("malformed hello response", cause: error) if handshake
          raise error
        end
        if frame.key?("itr") && !API.int64?(frame["itr"])
          error = DecodeError.new("JSONL frame itr must be a signed 64-bit integer", reason: :invalid_envelope)
          raise HandshakeError.new("malformed hello response", cause: error) if handshake
          raise error
        end
        frame
      end

      # JSON::ParserError messages can contain peer-controlled input. Consume
      # that exception entirely inside this helper and return only a fixed
      # failure signal; no public SDK error retains it in either cause chain.
      def parse_json(line)
        [JSON.parse(line), false]
      rescue JSON::ParserError
        [nil, true]
      end

      # The canonical JSONL transport treats every malformed envelope or JSON
      # payload as terminal. Complete frames are routed in order; an exception
      # escapes to #read_loop, which releases all connection-owned waiters.
      def drain_inbound_frames
        loop do
          newline = @buffer.index("\n")
          return unless newline

          line = @buffer.slice!(0, newline + 1)
          route_frame(decode_frame(line))
        end
      end

      def eof_error(cause)
        if @buffer.empty?
          TransportError.new("connection closed by peer", cause: cause)
        else
          IncompleteFrameError.new(observed_bytes: @buffer.bytesize, cause: cause)
        end
      end

      # Correlation and event waiters are resolved before callbacks are queued.
      def route_frame(frame)
        if frame["type"] == "tool_invoke_done"
          @tool_invocations.route(frame)
          return
        end
        if frame["type"] == "heartbeat"
          @pending.heartbeat(frame)
          return
        end
        matched = @pending.resolve(frame)
        return if matched && !DUAL_ROLE_TYPES.include?(frame["type"])
        return if @capabilities.route(frame)

        if frame["type"] == "turn_content" &&
           frame["request_id"].is_a?(String) && !frame["request_id"].empty?
          # The unsolicited event form has an empty request ID. Once its RPC
          # waiter is gone, a solicited response must not become live content.
          return
        end

        if RESPONSE_ONLY_TYPES.include?(frame["type"])
          # Late or manually supplied acknowledgements are never broadcasts.
          return
        end

        event = API.event_from_frame(frame)
        if event
          @events.publish(event)
        else
          publish_unsupported(frame)
        end
      end

      def publish_unsupported(frame)
        frozen_frame = Immutable.copy(frame)
        error = UnsupportedMessageError.new(message_type: frame["type"], frame: frozen_frame)
        @events.publish_unsupported(frozen_frame, error)
      end

      # Foundation primitive used by later typed operation services. Deliberately
      # private: callers do not receive a public raw-frame transport escape hatch.
      def tool_invocations
        @tool_invocations
      end

      def request(type, response_types:, timeout: RENEWABLE_REQUEST_TIMEOUT, fields: {})
        started = monotonic
        renewable = timeout.is_a?(RenewableTimeout)
        duration = Float(renewable ? timeout.seconds : timeout)
        raise ArgumentError, "timeout must be positive" unless duration.positive?
        raise connection_closed_error if closed?

        request_id = "rpc_#{SecureRandom.hex(16)}"
        Incidents.breadcrumb(:request, event: :started,
                            data: {request_id: request_id}.merge(Incidents.timing(started, duration)))
        entry = @pending.register(request_id, response_types: response_types)
        frame = stringify_keys(fields).merge("type" => type.to_s, "request_id" => request_id)
        write_frame(frame)
        result = nil
        loop do
          result = entry.wait(timeout: duration, renewable: renewable)
          break unless result == :timeout

          @pending.timeout(entry, duration, request_type: type.to_s,
                           response_types: response_types, leaf_id: frame["leaf_id"], renewable: renewable)
        end
        data = {request_id: request_id}.merge(Incidents.timing(started, duration))
        Incidents.breadcrumb(:request, event: :completed, outcome: :success, data: data)
        if monotonic - started >= duration
          Incidents.record(:request, TimeoutError.new, event: :completed, outcome: :success, data: data)
        end
        result
      rescue Exception => error
        data = {request_id: request_id}.merge(Incidents.timing(started, duration))
        local_cancel = local_cancellation?(error)
        Incidents.breadcrumb(:request, event: :completed,
                            outcome: local_cancel ? :cancel : :fail, data: data)
        Incidents.record(:request, error, data: data) unless local_cancel
        raise
      ensure
        @pending.cancel(entry) if entry
      end

      # Foundation primitive for typed one-way operation services. Like
      # #request, this remains private and is never a raw public transport API.
      def send_command(type, fields: {})
        raise connection_closed_error if closed?

        write_frame(stringify_keys(fields).merge("type" => type.to_s))
        nil
      end

      # Private typed path for capability results that were recursively frozen
      # and encoded before their call claimed terminal delivery. The exact
      # validated bytes are written; this path never re-encodes the frame.
      def send_prepared_capability_frame(prepared)
        unless prepared.is_a?(PreparedCapabilityFrame) && prepared.frozen? &&
               prepared.jsonl.is_a?(String) && prepared.jsonl.frozen?
          raise ArgumentError, "prepared capability frame required"
        end
        raise connection_closed_error if closed?

        write_encoded_frame(prepared.jsonl)
        nil
      end

      # Private typed heartbeat path. The call-state predicate is rechecked
      # while holding the writer mutex, so a heartbeat cannot be serialized
      # after a result has claimed terminal delivery.
      def send_provider_heartbeat(state, kind, call_id)
        frame = {"type" => "heartbeat", "kind" => kind.to_s, "call_id" => call_id.to_s}
        data = JSON.generate(frame) << "\n"
        write_encoded_frame(data, guard: -> { state.__heartbeat_allowed? })
      rescue JSON::GeneratorError => cause
        raise EncodeError.new("encoding provider heartbeat: #{cause.message}", cause: cause)
      end

      def write_frame(frame, startup: false)
        raise ArgumentError, "connection-owned itr must not be supplied" if frame.key?("itr")

        data = begin
          JSON.generate(frame) << "\n"
        rescue JSON::GeneratorError => cause
          error = EncodeError.new("encoding protocol frame: #{cause.message}", cause: cause)
          Incidents.record(:write_frame, error)
          raise error
        end
        write_encoded_frame(data, startup: startup)
      end

      # Adds connection-local iteration at the final serialized write point.
      # Prepared capability payloads are parsed only to validate their object
      # envelope; their semantic JSON bytes are otherwise retained verbatim.
      def write_encoded_frame(data, startup: false, guard: nil)
        @writer_mutex.synchronize do
          raise connection_closed_error if !startup && closed?
          return false if guard && !guard.call
          raise EncodeError, "outbound iteration exhausted" if @next_itr > MAX_WIRE_ITR

          encoded = insert_itr(data, @next_itr)
          offset = 0
          while offset < encoded.bytesize
            written = @writer.write(encoded.byteslice(offset, encoded.bytesize - offset))
            raise IOError, "short write" unless written&.positive?

            offset += written
          end
          # Caller-supplied streams may buffer writes (notably stdio and
          # IO.pipe with sync disabled). Flush each complete JSONL frame while
          # the writer remains serialized, before making its iteration visible.
          @writer.flush
          @next_itr += 1
          true
        end
      rescue ConnectionClosedError, EncodeError => error
        Incidents.record(:write_encode, error) if error.is_a?(EncodeError)
        raise
      rescue IOError, SystemCallError => cause
        error = TransportError.new("writing service connection: #{cause.message}", cause: cause)
        won_terminal = transition_terminal(error, preserve_primary: true) unless startup
        # Terminal cleanup may close the stream after the write but before its
        # flush. A losing writer must return the published pending error, not a
        # second terminal cause. Clean local cancellation stays incident-free.
        closed_error = connection_closed_error
        raise closed_error if !startup && local_cancellation?(closed_error)

        Incidents.record(:write, error)
        raise closed_error if !startup && !won_terminal

        raise error
      rescue Exception => error
        Incidents.record(:write_unexpected, error)
        transition_terminal(error, preserve_primary: true) unless startup
        raise
      end

      def insert_itr(data, itr)
        unless data.is_a?(String) && data.end_with?("\n")
          raise EncodeError, "encoded protocol frame must be one JSONL object"
        end
        object = JSON.parse(data)
        unless object.is_a?(Hash)
          raise EncodeError, "encoded protocol frame must be a JSON object"
        end
        if object.key?("itr")
          raise EncodeError, "connection-owned itr must not be supplied"
        end
        unless data.start_with?("{") && data.end_with?("}\n")
          raise EncodeError, "encoded protocol frame must be a compact JSON object"
        end

        body = data.byteslice(1, data.bytesize - 3)
        body.empty? ? "{\"itr\":#{itr}}\n" : "{\"itr\":#{itr},#{body}}\n"
      rescue JSON::ParserError => cause
        raise EncodeError.new("encoded protocol frame is invalid JSON: #{cause.message}", cause: cause)
      end

      def stringify_keys(hash)
        hash.each_with_object({}) { |(key, value), result| result[key.to_s] = value }
      end

      def transition_terminal(error, locally_closed: false, preserve_primary: false)
        closed_error = nil
        run_cleanup = @terminal_mutex.synchronize do
          next false if @terminal_error

          @terminal_error = error
          @locally_closed = locally_closed
          closed_error = ConnectionClosedError.new(
            "connection closed while request was pending", cause: error
          )
          @pending_closed_error = closed_error
          unless @transport_cleanup_ran || @transport_cleanup.nil?
            @transport_cleanup_ran = true
            next true
          end
          false
        end
        changed = !closed_error.nil?
        if changed
          @tool_invocations.close(closed_error)
          @pending.fail_all(closed_error)
          @capabilities.close(closed_error)
          @events.close(closed_error)
          run_transport_cleanup(preserve_primary: preserve_primary) if run_cleanup
        end
        changed
      end

      # Connection-owned workers publish fatal state before rethrowing. Cleanup
      # must not replace the worker's original exception, even if it also fails.
      def worker_failed(error)
        transition_terminal(error)
      rescue Exception
        nil
      end

      def local_cancellation?(error)
        @terminal_mutex.synchronize do
          @locally_closed && @cleanup_error.nil? && error.equal?(@pending_closed_error)
        end
      end

      def connection_closed_error
        @terminal_mutex.synchronize do
          @pending_closed_error || ConnectionClosedError.new("connection is closed", cause: @terminal_error)
        end
      end

      # Runs after terminal waiters and notifications have been released. The
      # once-only claim is made under @terminal_mutex, while callback execution
      # remains outside it so re-entrant cleanup cannot deadlock shutdown.
      def run_transport_cleanup(preserve_primary: false)
        return if @transport_cleanup.nil?

        @transport_cleanup.call
      rescue Exception => error
        retain_cleanup_error(error)
        raise unless preserve_primary || error.is_a?(StandardError)
      end

      def retain_cleanup_error(error, boundary: :cleanup)
        @terminal_mutex.synchronize { @cleanup_error ||= error } if @terminal_mutex
        Incidents.record(boundary, error)
      end

      def monotonic
        Process.clock_gettime(Process::CLOCK_MONOTONIC)
      end

      def join_thread(thread, deadline, label)
        return thread.join unless deadline

        remaining = deadline - monotonic
        if remaining <= 0 || !thread.join(remaining)
          raise TimeoutError, "#{label} join timed out"
        end
      end
    end

    # Backward-compatible name for the stream-backed client connection.
    Client = Connection
  end
end