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

# frozen_string_literal: true

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

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,
                  :extra_api_support

      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
        @extra_api_support = frame.fetch("extra_api_support", false)
        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 tool_approval_result
        extra_response version_result provider_usage_list_result provider_usage_result provider_usage_set_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, :tool_approvals

      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,
                 extras: [],
                 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,
                           extras: extras,
                           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:,
                     extras: [],
                     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
        @local_extras = ExtraDiscovery.snapshot(extras)
        @remote_extras = {}.freeze
        @discovery_mutex = Mutex.new
        @extra_discovery = :not_requested
        @discovery_checks = {}
        @api_version = nil
        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
        @tool_approval_waiters = ToolApprovalWaiters.new
        @writer_mutex = Mutex.new
        @next_itr = 1
        @write_incomplete = false
        @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)
        @tool_approvals = ToolApprovals.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)
        @outbound = OutboundWork.new(fatal_hook: method(:worker_failed))
      end

      # Waits without an implicit deadline. A timeout abandons only this wait.
      def remote_supports(name, *bounds, timeout: nil)
        check = remote_supports_async(name, *bounds)
        check.wait(timeout: timeout)
      ensure
        check&.cancel unless check&.done?
      end

      def remote_supports_if_known(name, *bounds)
        check = remote_supports_async(name, *bounds)
        raise CapabilityUnknownError, "extra discovery is pending" unless check.done?
        check.wait
      ensure
        check&.cancel unless check&.done?
      end

      def extra_discovery
        @discovery_mutex.synchronize { @extra_discovery }
      end

      def remote_extras
        @discovery_mutex.synchronize { @remote_extras }
      end

      def remote_supports_async(name, *bounds)
        unless name.is_a?(String) && !name.empty?
          raise ArgumentError, "name must be a nonempty string"
        end
        unless bounds.empty? || bounds.length == 2
          raise ArgumentError, "expected no version bounds or both min and max"
        end
        min, max = bounds.empty? ? [WIRE_INT32_MIN, WIRE_INT32_MAX] : bounds
        valid_bounds = [min, max].all? do |bound|
          bound.is_a?(Integer) && bound.between?(WIRE_INT32_MIN, WIRE_INT32_MAX)
        end
        unless valid_bounds && min <= max
          raise ArgumentError, "version bounds must be ordered signed 32-bit integers"
        end
        check = CapabilityCheck.new(@events) do |cancelled|
          @discovery_mutex.synchronize { @discovery_checks.delete(cancelled) }
        end
        # Caller thread cancellation must not leave the shared request marked
        # requested without its writer. No I/O or user code runs in this section.
        Thread.handle_interrupt(Exception => :never) do
          register_discovery_check(check, name, min, max)
        end
        handed_off = true
        check
      ensure
        # Deferred interruption or Thread#kill can unwind registration before
        # the caller receives its handle. Detach even when rescue is skipped.
        unless handed_off
          Thread.handle_interrupt(Exception => :never) { check&.cancel }
        end
      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
        @outbound.join(timeout: remaining)
        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 register_discovery_check(check, name, min, max)
        request_id = nil
        @discovery_mutex.synchronize do
          raise connection_closed_error if closed?
          raise HandshakeError, "connection is not ready" unless @hello_ack
          if @extra_discovery == :not_requested
            @extra_discovery = :requested
            @discovery_request_id = request_id = "extra_#{SecureRandom.hex(16)}"
          end
          if [:received, :unavailable].include?(@extra_discovery)
            resolve_capability(check, name, min, max)
          else
            @discovery_checks[check] = [name.dup.freeze, min, max]
          end
          if request_id
            @outbound.submit do
              write_frame({"type" => "extra", "request_id" => request_id})
            end
          end
        end
        check
      end

      def resolve_capability(check, name, min, max)
        version = ExtraDiscovery.supported_version(
          @remote_extras, name, api_version: @api_version,
          extra_api_support: @extra_discovery == :received, min: min, max: max
        )
        # Unavailable discovery never implies native future.* support.
        version = EXTRA_UNSUPPORTED unless @extra_discovery == :received
        check.__resolve(value: version)
      end

      def settle_discovery(frame)
        return false unless %w[extra_response error].include?(frame["type"])
        @discovery_mutex.synchronize do
          return false unless @extra_discovery == :requested &&
                              frame["request_id"] == @discovery_request_id
          @extra_discovery = :unavailable
          if frame["type"] == "extra_response"
            begin
              extras = ExtraDiscovery.snapshot(frame["extras"], error_class: DecodeError)
              @remote_extras = extras.to_h { |entry| [entry["name"], entry["version"]] }.freeze
              @extra_discovery = :received
            rescue DecodeError
              # Invalid inventories disable discovery, not the connection.
            end
          end
          @discovery_checks.each do |check, args|
            resolve_capability(check, *args)
          end
          @discovery_checks.clear
          true
        end
      end

      # One admission gate for every extra-dependent operation. Explicit
      # numeric timeouts cover discovery and execution; defaults retain the
      # existing renewable RPC timeout only after admission.
      def extra_operation(name, bounds, capability_wait:, timeout:)
        unless [:wait, :if_known].include?(capability_wait)
          raise ArgumentError, "capability_wait must be :wait or :if_known"
        end
        explicit = !timeout.is_a?(RenewableTimeout)
        duration = explicit && Float(timeout)
        raise ArgumentError, "timeout must be positive" if explicit && !duration.positive?
        deadline = explicit && monotonic + duration
        version = if capability_wait == :if_known
                    remote_supports_if_known(name, *bounds)
                  else
                    remote_supports(name, *bounds, timeout: explicit ? duration : nil)
                  end
        raise UnsupportedExtraError, name if version == EXTRA_UNSUPPORTED
        remaining = deadline && deadline - monotonic
        raise TimeoutError, "operation timed out before admission" if remaining && remaining <= 0
        yield(remaining || timeout, deadline)
      end

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

        hello = {"type" => "hello", "protocol" => PROTOCOL_VERSION, "name" => @name,
                 "extra_api_support" => true}
        hello["cwd"] = @cwd if @cwd && !@cwd.empty?
        hello["leaf_id"] = @leaf_id if @leaf_id && !@leaf_id.empty?
        write_frame(hello, startup: true, deadline: deadline)
        frame = read_startup_frame([deadline - monotonic, 0].max)
        validate_hello_ack(frame)
        @api_version = frame.fetch("protocol")
        @hello_ack = HelloAck.new(frame)
        @extra_discovery_enabled = frame["ready"] != false &&
                                   ExtraDiscovery.enabled?(@api_version, @hello_ack.extra_api_support)
        @discovery_mutex.synchronize do
          @extra_discovery = :unavailable unless @extra_discovery_enabled
        end
        @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 every join even if one has a fatal secondary failure.
        [[@reader_thread, :startup_reader_join], [@outbound, :startup_reader_join],
         [@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.key?("extra_api_support") || [true, false].include?(frame["extra_api_support"])) &&
               (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)
        return if settle_discovery(frame)
        if frame["type"] == "extra" && @extra_discovery_enabled
          request_id = frame["request_id"]
          unless request_id.is_a?(String) && !request_id.empty?
            raise DecodeError.new("extra requires a nonempty request_id", frame_type: "extra")
          end
          extras = ExtraDiscovery.advertised(@local_extras, @api_version)
          @outbound.submit do
            write_frame({"type" => "extra_response", "request_id" => request_id, "extras" => extras})
          end
          return
        end
        if frame["type"] == "tool_invoke_done"
          @tool_invocations.route(frame)
          return
        end
        if frame["type"] == "tool_approval_done"
          @tool_approval_waiters.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 tool_approval_waiters
        @tool_approval_waiters
      end

      def request(type, response_types:, timeout: RENEWABLE_REQUEST_TIMEOUT, fields: {}, deadline: nil)
        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, deadline: deadline)
        result = nil
        loop do
          wait_duration = deadline ? [deadline - monotonic, 0].max : duration
          result = entry.wait(timeout: wait_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, deadline: nil)
        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, deadline: deadline)
      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, deadline: nil)
        write_started = false
        write_completed = false
        write_error = nil
        with_writer_lock(deadline) do
          raise connection_closed_error if !startup && closed?
          return false if guard && !guard.call
          # A killed writer unlocks before its outer ensure publishes terminal
          # state. Reject reuse in that gap rather than append to a partial frame.
          raise TransportError, "previous protocol write was interrupted" if @write_incomplete
          raise EncodeError, "outbound iteration exhausted" if @next_itr > MAX_WIRE_ITR

          encoded = insert_itr(data, @next_itr)
          offset = 0
          while offset < encoded.bytesize
            write_started = true
            @write_incomplete = true
            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
          Thread.handle_interrupt(Exception => :never) do
            @next_itr += 1
            @write_incomplete = false
            write_completed = true
          end
          true
        end
      rescue ConnectionClosedError, EncodeError => error
        write_error = 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)
        write_error = error
        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
        write_error = error
        # Deadline or caller interruption before admission emits no bytes.
        # Once writing starts, interruption may leave a partial JSONL frame.
        if write_started && !write_completed
          Incidents.record(:write_unexpected, error)
          transition_terminal(error, preserve_primary: true) unless startup
        end
        raise
      ensure
        # Thread#kill bypasses rescue, but still unwinds this ensure. A frame
        # interrupted before flush and iteration commit makes reuse unsafe.
        Thread.handle_interrupt(Exception => :never) do
          if write_started && !write_completed && !closed?
            failure = write_error || TransportError.new("protocol write interrupted before completion")
            transition_terminal(failure, preserve_primary: true)
          end
        end
      end

      # Startup and explicit whole-operation deadlines include mutex acquisition
      # and flush. Timeout unwinds the writer lock before cleanup; the caller
      # tracks whether a write began to distinguish safe admission expiry from
      # potentially partial writes.
      def with_writer_lock(deadline)
        return @writer_mutex.synchronize { yield } unless deadline

        remaining = deadline - monotonic
        raise TimeoutError, "write deadline exceeded" unless remaining.positive?

        ::Timeout.timeout(remaining, TimeoutError, "write deadline exceeded") do
          @writer_mutex.synchronize { yield }
        end
      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
          @outbound&.close
          @discovery_mutex.synchronize do
            @discovery_checks.each_key { |check| check.__resolve(error: closed_error) }
            @discovery_checks.clear
          end
          @tool_invocations.close(closed_error)
          @tool_approval_waiters.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