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

# frozen_string_literal: true

require "json"
require "thread"

module EzAgent
  module API
    DEFAULT_PROVIDER_WORKERS = 4
    DEFAULT_PROVIDER_HEARTBEAT_INTERVAL = 1.0
    # Deprecated compatibility default. announce is one-way; this never creates
    # a remote registration barrier or changes capability visibility.
    DEFAULT_REGISTRATION_TIMEOUT = 5.0

    # Immutable metadata for one Ruby-provided capability.
    class CapabilityDefinition
      attr_reader :kind, :name, :handler

      def initialize(kind:, name:, handler:)
        @kind = kind.to_sym
        @name = API.required_string(name, :name)
        raise ArgumentError, "name must not be empty" if @name.empty?
        raise ArgumentError, "provider callback block required" unless handler

        @handler = handler
      end

      def [](key)
        to_h[key.to_s]
      end
    end

    class ToolDefinition < CapabilityDefinition
      attr_reader :description, :parameters, :timeout, :max_timeout, :tool_hint

      def initialize(name:, description: nil, parameters: nil, timeout: nil,
                     max_timeout: nil, tool_hint: nil, handler:)
        super(kind: :tool, name: name, handler: handler)
        @description = API.optional_string(description, :description)
        unless parameters.nil? || parameters.is_a?(Hash)
          raise ArgumentError, "parameters must be a hash"
        end
        @parameters = parameters.nil? ? nil : Immutable.copy(parameters)
        @timeout = API.optional_string(timeout, :timeout)
        @max_timeout = API.optional_string(max_timeout, :max_timeout)
        @tool_hint = API.optional_string(tool_hint, :tool_hint)
        freeze
      end

      def to_h
        compact_metadata(
          "name" => name, "description" => description, "parameters" => parameters,
          "timeout" => timeout, "max_timeout" => max_timeout, "tool_hint" => tool_hint
        )
      end

      private

      def compact_metadata(values)
        Immutable.copy(values.reject { |_key, value| value.nil? })
      end
    end

    class PluginDefinition < CapabilityDefinition
      attr_reader :description, :priority

      def initialize(name:, description: nil, priority: nil, handler:)
        super(kind: :plugin, name: name, handler: handler)
        @description = API.optional_string(description, :description)
        @priority = priority.nil? ? nil : API.required_go_int(priority, :priority)
        freeze
      end

      def to_h
        values = {"name" => name}
        values["description"] = description unless description.nil?
        values["priority"] = priority unless priority.nil?
        Immutable.copy(values)
      end
    end

    class MacroDefinition < CapabilityDefinition
      attr_reader :description, :timeout, :max_timeout, :priority, :version,
                  :triggers, :internal

      def initialize(name:, description: nil, timeout: nil, max_timeout: nil,
                     priority: nil, version: nil, triggers: nil, internal: false, handler:)
        super(kind: :macro, name: name, handler: handler)
        unless internal.equal?(true) || internal.equal?(false)
          raise ArgumentError, "internal must be true or false"
        end
        @internal = internal
        @description = API.optional_string(description, :description)
        @timeout = API.optional_string(timeout, :timeout)
        @max_timeout = API.optional_string(max_timeout, :max_timeout)
        @priority = priority.nil? ? nil : API.required_go_int(priority, :priority)
        @version = version.nil? ? nil : API.required_string(version, :version)
        raise ArgumentError, "version must not be empty" if @version == ""
        unless triggers.nil? || (triggers.is_a?(Array) && triggers.all? { |value| value.is_a?(String) })
          raise ArgumentError, "triggers must be nil or an array of strings"
        end
        # Preserve nil versus an explicit empty array and keep trigger strings open.
        @triggers = triggers.nil? ? nil : triggers.map { |value| value.dup.freeze }.freeze
        freeze
      end

      def to_h
        values = {"name" => name}
        values["version"] = version unless version.nil?
        values["description"] = description unless description.nil?
        values["timeout"] = timeout unless timeout.nil?
        values["max_timeout"] = max_timeout unless max_timeout.nil?
        values["priority"] = priority unless priority.nil?
        values["triggers"] = triggers unless triggers.nil?
        values["internal"] = true if internal
        Immutable.copy(values)
      end
    end

    # Exact recursively immutable capability envelope and its pre-encoded JSONL
    # bytes. Construction is the terminal-delivery validation barrier.
    class PreparedCapabilityFrame
      attr_reader :frame, :jsonl

      def initialize(frame)
        @frame = Immutable.copy(frame)
        @jsonl = (JSON.generate(@frame) << "\n").freeze
        freeze
      rescue JSON::GeneratorError => cause
        raise EncodeError.new("capability result is not JSON-encodable", cause: cause)
      end
    end

    # Typed terminal values returned by provider callbacks.
    class ToolCallResult
      attr_reader :turn

      def initialize(turn)
        raise ArgumentError, "turn must be PendingTurn" unless turn.is_a?(PendingTurn)

        @turn = turn
        freeze
      end
    end

    class PluginCallResult
      attr_reader :pending_turns, :is_error

      def initialize(pending_turns, is_error: false)
        unless pending_turns.is_a?(Array) && pending_turns.all? { |turn| turn.is_a?(PendingTurn) }
          raise ArgumentError, "pending_turns must contain PendingTurn values"
        end
        unless is_error.equal?(true) || is_error.equal?(false)
          raise ArgumentError, "is_error must be true or false"
        end

        @pending_turns = pending_turns.dup.freeze
        @is_error = is_error
        freeze
      end
    end

    class MacroCallResult
      attr_reader :result, :is_error

      def initialize(result = "", is_error: false)
        @result = String(result).dup.freeze
        unless is_error.equal?(true) || is_error.equal?(false)
          raise ArgumentError, "is_error must be true or false"
        end
        @is_error = is_error
        freeze
      end
    end

    # Minimal identity and cooperative cancellation state published by the
    # socket reader before raw call projection reaches a provider worker.
    class ProviderCallState
      attr_reader :call_id, :name, :leaf_id, :kind

      def initialize(kind:, call_id:, name:, leaf_id:)
        @kind = kind.to_sym
        @call_id = API.required_string(call_id, :call_id)
        @name = API.required_string(name, :name)
        @leaf_id = API.required_string(leaf_id, :leaf_id)
        @mutex = Mutex.new
        @condition = ConditionVariable.new
        @cancelled = false
        @terminal = false
      end

      def cancelled?
        @mutex.synchronize { @cancelled }
      end
      alias canceled? cancelled?

      def wait_for_cancellation(timeout: nil)
        deadline = timeout && monotonic + Float(timeout)
        @mutex.synchronize do
          until @cancelled
            if deadline
              remaining = deadline - monotonic
              return nil unless remaining.positive?
              @condition.wait(@mutex, remaining)
            else
              @condition.wait(@mutex)
            end
          end
          true
        end
      end

      def heartbeat_allowed?
        @mutex.synchronize { !@cancelled && !@terminal }
      end
      alias __heartbeat_allowed? heartbeat_allowed?

      def cancel!
        @mutex.synchronize do
          return false if @cancelled || @terminal

          @cancelled = true
          @condition.broadcast
          true
        end
      end

      def claim_terminal!
        @mutex.synchronize do
          return false if @cancelled || @terminal

          @terminal = true
          true
        end
      end

      alias __cancel! cancel!
      alias __claim_terminal! claim_terminal!

      private

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

    # Typed callback view over reader-published call state.
    class CapabilityCall
      attr_reader :call_id, :name, :leaf_id, :kind

      def initialize(provider, kind: nil, call_id: nil, name: nil, leaf_id: nil,
                     state: nil)
        @provider = provider
        @state = state || ProviderCallState.new(
          kind: kind, call_id: call_id, name: name, leaf_id: leaf_id
        )
        @kind = @state.kind
        @call_id = @state.call_id
        @name = @state.name
        @leaf_id = @state.leaf_id
      end

      def cancelled?
        @state.cancelled?
      end
      alias canceled? cancelled?

      # Waits for a tool_abort notification or provider shutdown. nil means no
      # cancellation arrived before timeout; true means cancellation arrived.
      def wait_for_cancellation(timeout: nil)
        @state.wait_for_cancellation(timeout: timeout)
      end
      alias wait_for_cancel wait_for_cancellation

      # Refreshes only the daemon's idle watchdog. It cannot extend max_timeout.
      def heartbeat!
        @provider.__send__(:send_heartbeat, self)
        self
      end

      def __cancel!
        @state.cancel!
      end

      def __claim_terminal!
        @state.claim_terminal!
      end

      def __state
        @state
      end
    end

    # A top-level-frozen decoded envelope transferred exclusively from the
    # reader to workers. Nested projection/deep copying is intentionally deferred.
    RawProviderCall = Struct.new(:state, :frame) do
      def initialize(state, frame)
        super(state, frame.dup.freeze)
        freeze
      end

      def kind = state.kind
      def call_id = state.call_id
      def name = state.name
      def leaf_id = state.leaf_id
      def cancelled? = state.cancelled?
      def __cancel! = state.cancel!
      def __claim_terminal! = state.claim_terminal!
    end

    class ToolProviderCall < CapabilityCall
      attr_reader :arguments, :turn_id, :root_id, :cwd

      def initialize(provider, frame, state: nil)
        super(provider, state: state, kind: :tool,
              call_id: provider.__send__(:required_frame_string, frame, "tool_call_id"),
              name: provider.__send__(:required_frame_string, frame, "name"),
              leaf_id: provider.__send__(:required_frame_string, frame, "leaf_id"))
        arguments = frame["arguments"]
        raise DecodeError.new("malformed tool_call: arguments must be an object", frame_type: "tool_call") unless arguments.is_a?(Hash)

        @arguments = Immutable.copy(arguments)
        @turn_id = provider.__send__(:required_frame_string, frame, "turn_id").freeze
        @root_id = provider.__send__(:required_frame_string, frame, "root_id").freeze
        @cwd = provider.__send__(:required_frame_string, frame, "cwd").freeze
      end

      # Optional early scheduler acknowledgement. It never replaces the result.
      def acknowledge(parallel: false)
        @provider.__send__(:acknowledge_tool, self, parallel)
        self
      end

      def parallel!
        acknowledge(parallel: true)
      end

      def success(content = "", friendly_call: nil)
        ToolCallResult.new(text_turn(content, false, friendly_call))
      end

      def error(message, friendly_call: nil)
        ToolCallResult.new(text_turn(message, true, friendly_call))
      end

      def result(turn)
        ToolCallResult.new(turn)
      end

      private

      def text_turn(content, is_error, friendly_call)
        metadata = {"is_error" => is_error}
        metadata["friendly_call"] = String(friendly_call) unless friendly_call.nil?
        PendingTurn.new(
          kind: "tool_result", content_type: "text", content: String(content),
          tool_call_id: call_id, tool_name: name,
          advanced: {"other_meta" => JSON.generate(metadata)}
        )
      end
    end

    class PluginProviderCall < CapabilityCall
      attr_reader :root_id, :cwd, :role, :pending_turns, :config

      def initialize(provider, frame, state: nil)
        super(provider, state: state, kind: :plugin,
              call_id: provider.__send__(:required_frame_string, frame, "plugin_call_id"),
              name: provider.__send__(:required_frame_string, frame, "name"),
              leaf_id: provider.__send__(:required_frame_string, frame, "leaf_id"))
        @root_id = provider.__send__(:required_frame_string, frame, "root_id").freeze
        @cwd = provider.__send__(:required_frame_string, frame, "cwd").freeze
        @role = provider.__send__(:required_frame_string, frame, "role").freeze
        turns = frame["pending_turns"]
        unless turns.is_a?(Array)
          raise DecodeError.new("malformed plugin_call: pending_turns must be an array", frame_type: "plugin_call")
        end
        @pending_turns = turns.map { |turn| provider.__send__(:pending_turn_from_frame, turn) }.freeze
        config = frame.fetch("config", {})
        unless config.is_a?(Hash) && config.all? { |key, value| key.is_a?(String) && value.is_a?(String) }
          raise DecodeError.new("malformed plugin_call: config must contain string values", frame_type: "plugin_call")
        end
        @config = Immutable.copy(config)
      end

      def success(turns = pending_turns)
        PluginCallResult.new(turns)
      end

      def error(turns = pending_turns)
        PluginCallResult.new(turns, is_error: true)
      end
    end

    class MacroProviderCall < CapabilityCall
      attr_reader :param_string

      def initialize(provider, frame, state: nil)
        super(provider, state: state, kind: :macro,
              call_id: provider.__send__(:required_frame_string, frame, "macro_call_id"),
              name: provider.__send__(:required_frame_string, frame, "macro_name"),
              leaf_id: provider.__send__(:required_frame_string, frame, "leaf_id"))
        @param_string = provider.__send__(:required_frame_string, frame, "param_string").freeze
      end

      def success(result = "")
        MacroCallResult.new(result)
      end

      def error(message)
        MacroCallResult.new(message, is_error: true)
      end
    end

    # Reusable provider runtime. Control traffic and a fixed-size worker pool are
    # independent of Events callbacks and any future Workflow Run admission.
    class Capabilities
      CONTROL_STOP = Object.new.freeze
      WORK_STOP = Object.new.freeze
      PROVIDER_FRAME_TYPES = %w[
        tool_call tool_abort tool_info_request plugin_call plugin_info_request
        macro_call_ipc macro_info_request
      ].freeze

      attr_reader :worker_count, :heartbeat_interval

      def initialize(client, worker_count: DEFAULT_PROVIDER_WORKERS,
                     heartbeat_interval: DEFAULT_PROVIDER_HEARTBEAT_INTERVAL)
        @client = client
        @worker_count = Integer(worker_count)
        raise ArgumentError, "provider_workers must be positive" unless @worker_count.positive?
        @heartbeat_interval = Float(heartbeat_interval)
        raise ArgumentError, "provider_heartbeat_interval must be positive" unless @heartbeat_interval.positive?

        @mutex = Mutex.new
        @condition = ConditionVariable.new
        @registration_mutex = Mutex.new
        @batch_owner = nil
        @batch_snapshot = nil
        @definitions = {tool: {}, plugin: {}, macro: {}}
        @calls = {}
        @active_heartbeats = {}
        @rpc_heartbeats = {}
        @tool_acks = {}
        @closed_error = nil
        @control_queue = Queue.new
        @work_queue = Queue.new
        @control_thread = Thread.new do
          Thread.current.report_on_exception = false
          control_loop
        end
        @control_thread.name = "ez-agent-api-provider-control" if @control_thread.respond_to?(:name=)
        @workers = Array.new(@worker_count) do |index|
          Thread.new do
            Thread.current.report_on_exception = false
            worker_loop
          end.tap do |thread|
            thread.name = "ez-agent-api-provider-#{index + 1}" if thread.respond_to?(:name=)
          end
        end
        @heartbeat_thread = Thread.new do
          Thread.current.report_on_exception = false
          heartbeat_loop
        end
        @heartbeat_thread.name = "ez-agent-api-provider-heartbeats" if @heartbeat_thread.respond_to?(:name=)
      end

      def provide_tool(name, description: nil, parameters: nil, timeout: nil,
                       max_timeout: nil, tool_hint: nil,
                       registration_timeout: DEFAULT_REGISTRATION_TIMEOUT, &handler)
        warn_registration_timeout(registration_timeout)
        install(ToolDefinition.new(name: name, description: description,
                                   parameters: parameters, timeout: timeout,
                                   max_timeout: max_timeout, tool_hint: tool_hint,
                                   handler: handler))
      end
      alias tool provide_tool

      def provide_plugin(name, description: nil, priority: nil,
                         registration_timeout: DEFAULT_REGISTRATION_TIMEOUT, &handler)
        warn_registration_timeout(registration_timeout)
        install(PluginDefinition.new(name: name, description: description,
                                     priority: priority, handler: handler))
      end
      alias plugin provide_plugin

      def provide_macro(name, description: nil, timeout: nil, max_timeout: nil,
                        priority: nil, version: nil, triggers: nil, internal: false,
                        registration_timeout: DEFAULT_REGISTRATION_TIMEOUT, &handler)
        warn_registration_timeout(registration_timeout)
        install(MacroDefinition.new(name: name, description: description,
                                    timeout: timeout, max_timeout: max_timeout,
                                    priority: priority, version: version,
                                    triggers: triggers, internal: internal, handler: handler))
      end
      alias macro provide_macro

      # Announce carries a complete cumulative capability snapshot for the whole
      # connection. It is a connection-level projection, not a per-capability
      # event, and is not meant to be emitted frequently. Registrations made
      # inside this block are installed locally and published with exactly one
      # announce for the resulting snapshot.
      def batch
        raise ArgumentError, "batch requires a block" unless block_given?
        # Nested batches join the outer one so the whole tree still announces once.
        return yield if @batch_owner.equal?(Thread.current)

        @registration_mutex.synchronize do
          @batch_owner = Thread.current
          @batch_snapshot = nil
          begin
            result =
              begin
                yield
              rescue Exception => error
                Incidents.record(:provider_batch, error)
                # Definitions already installed locally must still reach the peer,
                # otherwise this client would answer calls the daemon never routes.
                flush_batch_announce(quiet: true)
                raise
              end
            flush_batch_announce
            result
          ensure
            @batch_owner = nil
            @batch_snapshot = nil
          end
        end
      end

      def queued_calls
        @work_queue.length
      end

      def active_calls
        @mutex.synchronize { @calls.values.dup.freeze }
      end

      def closed?
        @mutex.synchronize { !@closed_error.nil? }
      end

      # Internal reader route. It performs only validation/state publication and
      # nonblocking enqueueing; callbacks and writes happen on provider threads.
      def route(frame)
        return false unless PROVIDER_FRAME_TYPES.include?(frame["type"])

        case frame["type"]
        when "tool_info_request"
          enqueue_info(:tool, frame)
        when "plugin_info_request"
          enqueue_info(:plugin, frame)
        when "macro_info_request"
          enqueue_info(:macro, frame)
        when "tool_call"
          enqueue_raw_call(:tool, frame)
        when "plugin_call"
          enqueue_raw_call(:plugin, frame)
        when "macro_call_ipc"
          enqueue_raw_call(:macro, frame)
        when "tool_abort"
          route_tool_abort(frame)
        end
        true
      rescue DecodeError => error
        Incidents.record(:provider_route, error)
        @client.events.__send__(:report_provider_error, error)
        true
      end

      def close(error = ConnectionClosedError.new("provider connection closed"))
        calls = nil
        changed = @mutex.synchronize do
          next false if @closed_error

          @closed_error = error
          calls = @calls.values.dup
          @active_heartbeats.clear
          @rpc_heartbeats.clear
          @condition.broadcast
          true
        end
        return self unless changed

        calls.each(&:__cancel!)
        @control_queue << CONTROL_STOP
        @worker_count.times { @work_queue << WORK_STOP }
        self
      end

      def join(timeout: nil)
        started = monotonic
        budget = timeout && Float(timeout)
        deadline = budget && started + budget
        [@control_thread, @heartbeat_thread, *@workers].each do |thread|
          next if Thread.current.equal?(thread)

          if deadline
            remaining = deadline - monotonic
            if remaining <= 0 || !thread.join(remaining)
              raise TimeoutError, "provider worker join timed out"
            end
          else
            thread.join
          end
        end
        self
      rescue TimeoutError => error
        Incidents.record(:provider_join, error, data: Incidents.timing(started, budget))
        raise
      end

      private

      # Compatibility-only keyword: announce is one-way and cannot observe a
      # remote registration barrier. Nondefault values are ignored deliberately.
      def warn_registration_timeout(value)
        return if value == DEFAULT_REGISTRATION_TIMEOUT

        warn("EzAgent::API capability registration_timeout is deprecated and ignored; announce is one-way")
      end

      # Registration is local and fire-and-forget. This mutex preserves both
      # monotonic complete snapshots and their write order across callers.
      def install(definition)
        if @batch_owner.equal?(Thread.current)
          @batch_snapshot = install_locally(definition)
          return definition
        end

        @registration_mutex.synchronize do
          send_command("announce", install_locally(definition))
        end
        definition
      end

      def install_locally(definition)
        @mutex.synchronize do
          raise @closed_error if @closed_error
          if @definitions.fetch(definition.kind).key?(definition.name)
            raise RegistrationCollisionError.new(
              "#{definition.kind} #{definition.name.inspect} is already registered by this client",
              kind: definition.kind, name: definition.name
            )
          end

          @definitions.fetch(definition.kind)[definition.name] = definition
          {
            "tools" => @definitions[:tool].keys.dup,
            "plugins" => @definitions[:plugin].keys.dup,
            "macros" => @definitions[:macro].keys.dup
          }
        end
      end

      def flush_batch_announce(quiet: false)
        snapshot = @batch_snapshot
        return if snapshot.nil?

        @batch_snapshot = nil
        begin
          send_command("announce", snapshot)
        rescue StandardError
          raise unless quiet
        end
      end

      def plural_key(kind)
        {tool: "tools", plugin: "plugins", macro: "macros"}.fetch(kind)
      end

      def enqueue_info(kind, frame)
        names = frame["names"]
        request_id = frame["request_id"]
        unless names.is_a?(Array) && names.all? { |value| value.is_a?(String) } && request_id.is_a?(String)
          raise DecodeError.new("malformed #{kind}_info_request", frame_type: "#{kind}_info_request")
        end
        state = ProviderCallState.new(kind: :rpc, call_id: request_id, name: "metadata", leaf_id: "metadata")
        @mutex.synchronize { @rpc_heartbeats[request_id] = state }
        @control_queue << [:info, kind, names.dup.freeze, request_id.dup.freeze]
      end

      def enqueue_raw_call(kind, frame)
        id_key = {tool: "tool_call_id", plugin: "plugin_call_id", macro: "macro_call_id"}.fetch(kind)
        name_key = kind == :macro ? "macro_name" : "name"
        state = ProviderCallState.new(
          kind: kind,
          call_id: required_frame_string(frame, id_key),
          name: required_frame_string(frame, name_key),
          leaf_id: required_frame_string(frame, "leaf_id")
        )
        raw = RawProviderCall.new(state, frame)
        status = @mutex.synchronize do
          next :closed if @closed_error
          next :duplicate if @calls.key?(raw.call_id)

          @calls[raw.call_id] = state
          @active_heartbeats[raw.call_id] = state
          @definitions.fetch(kind).key?(raw.name) ? :accepted : :unhandled
        end
        case status
        when :accepted
          @work_queue << [:call, raw]
        when :unhandled
          # Missing local dispatch is still admitted, visible, heartbeated, and
          # eventually receives a typed provider error on the bounded pool.
          @work_queue << [:unhandled, raw]
        when :duplicate
          @client.events.__send__(:report_provider_error, DecodeError.new(
            "duplicate #{kind} call id #{raw.call_id.inspect}",
            frame_type: frame.fetch("type")
          ))
        end
      end

      def route_tool_abort(frame)
        call_id = required_frame_string(frame, "tool_call_id")
        call = @mutex.synchronize { @calls[call_id] }
        call.__cancel! if call
        @control_queue << [:abort_ack, call_id]
      end

      def control_loop
        loop do
          work = @control_queue.pop
          break if work.equal?(CONTROL_STOP)
          next if closed?

          case work.fetch(0)
          when :info
            handle_info(*work.drop(1))
          when :abort_ack
            send_command("tool_abort_ack", "tool_call_id" => work.fetch(1))
          end
        rescue ConnectionClosedError, TransportError
          break
        rescue Exception => error
          Incidents.record(:provider_control, error)
          unless error.is_a?(StandardError)
            @client.__send__(:worker_failed, error)
            raise
          end
          @client.events.__send__(:report_provider_error, error)
        end
      end

      def handle_info(kind, names, request_id)
        definitions = @mutex.synchronize do
          names.filter_map { |name| @definitions.fetch(kind)[name] }
        end
        key = plural_key(kind)
        state = @mutex.synchronize { @rpc_heartbeats[request_id] }
        state&.claim_terminal!
        send_command("#{kind}_info_response", key => definitions.map(&:to_h),
                     "request_id" => request_id)
      ensure
        @mutex.synchronize { @rpc_heartbeats.delete(request_id) }
      end

      def worker_loop
        loop do
          work = @work_queue.pop
          break if work.equal?(WORK_STOP)
          if closed?
            discard_work(work)
            next
          end

          case work.fetch(0)
          when :call
            execute_call(work.fetch(1))
          when :unhandled
            deliver_unhandled(work.fetch(1))
          when :cancel_callback
            work.fetch(1).call
          end
        rescue ConnectionClosedError, TransportError
          break
        rescue Exception => error
          Incidents.record(:provider, error)
          unless error.is_a?(StandardError)
            @client.__send__(:worker_failed, error)
            raise
          end
          @client.events.__send__(:report_provider_error, error)
        end
      end

      def execute_call(raw)
        return finish_call(raw) if raw.cancelled?

        begin
          call = project_call(raw)
        rescue DecodeError => error
          Incidents.record(:provider_call, error)
          @client.events.__send__(:report_provider_error, error)
          prepared = prepare_raw_error_frame(raw, "Ruby provider rejected malformed call")
          send_prepared_frame(prepared) if raw.__claim_terminal!
          return
        end

        definition = @mutex.synchronize { @definitions.fetch(call.kind)[call.name] }
        unless definition
          deliver_unhandled(raw)
          return
        end

        begin
          value = definition.handler.call(call)
          result = normalize_result(call, value)
          validate_provider_result!(call, result)
          prepared = prepare_result_frame(call, result)
        rescue Exception => cause
          unless cause.is_a?(StandardError)
            Incidents.record(:provider_call, cause)
            raise
          end
          report_callback_failure(call, cause)
          prepared = prepare_safe_error_frame(call)
        end

        send_prepared_frame(prepared) if call.__claim_terminal!
      ensure
        finish_call(raw)
      end

      def project_call(raw)
        case raw.kind
        when :tool
          ToolProviderCall.new(self, raw.frame, state: raw.state)
        when :plugin
          PluginProviderCall.new(self, raw.frame, state: raw.state)
        when :macro
          MacroProviderCall.new(self, raw.frame, state: raw.state)
        end
      rescue DecodeError
        raise
      rescue ArgumentError, TypeError => cause
        raise DecodeError.new(
          "malformed #{raw.frame["type"]} projection: #{cause.message}",
          frame_type: raw.frame["type"], cause: cause
        )
      end

      def deliver_unhandled(raw)
        return if raw.cancelled?

        prepared = prepare_raw_error_frame(raw, "unhandled Ruby #{raw.kind} #{raw.name}")
        send_prepared_frame(prepared) if raw.__claim_terminal!
      ensure
        finish_call(raw)
      end

      def prepare_raw_error_frame(raw, message)
        frame = case raw.kind
                when :tool
                  turn = safe_tool_error_turn(raw, message)
                  {"type" => "tool_result", "tool_call_id" => raw.call_id,
                   "turn" => turn.to_h}
                when :plugin
                  {"type" => "plugin_result", "plugin_call_id" => raw.call_id,
                   "pending_turns" => [], "is_error" => true}
                when :macro
                  {"type" => "macro_result_ipc", "macro_call_id" => raw.call_id,
                   "result" => message, "is_error" => true}
                end
        PreparedCapabilityFrame.new(frame)
      end

      def safe_tool_error_turn(call, message)
        PendingTurn.new(
          kind: "tool_result", content_type: "text", content: String(message),
          tool_call_id: call.call_id, tool_name: call.name,
          advanced: {"other_meta" => JSON.generate("is_error" => true)}
        )
      end

      def normalize_result(call, value)
        case call.kind
        when :tool
          return value if value.is_a?(ToolCallResult)
          return ToolCallResult.new(value) if value.is_a?(PendingTurn)
          return call.success(value) if value.is_a?(String) || value.nil?
        when :plugin
          return value if value.is_a?(PluginCallResult)
          return call.success(value) if value.is_a?(Array)
          return call.success if value.nil?
        when :macro
          return value if value.is_a?(MacroCallResult)
          return call.success(value) if value.is_a?(String) || value.nil?
          if value.is_a?(Hash)
            result = value.key?(:result) ? value[:result] : value["result"]
            is_error = value.key?(:is_error) ? value[:is_error] : value.fetch("is_error", false)
            return MacroCallResult.new(result || "", is_error: is_error)
          end
        end
        raise ArgumentError, "invalid #{call.kind} provider result #{value.class}"
      end

      def validate_provider_result!(call, result)
        return unless call.kind == :tool

        turn = result.turn
        raise ArgumentError, "tool result kind must be exactly tool_result" unless turn.kind == "tool_result"
        unless turn.content_type.nil? || turn.content_type.empty? || turn.content_type == "text"
          raise ArgumentError, "tool result content_type must be text"
        end
        unless turn.fill_content_from_turn_id.nil? || turn.fill_content_from_turn_id.empty?
          raise ArgumentError, "tool result must not contain a synthetic content reference"
        end
        validate_tool_advanced!(turn.advanced)
        validate_tool_attachment!(turn.attachment_blob)
      end

      def validate_tool_advanced!(advanced)
        return if advanced.nil?

        %w[thinking stop_reason usage model provider].each do |key|
          value = advanced[key]
          unless value.nil? || value == ""
            raise ArgumentError, "tool result must not contain assistant metadata"
          end
        end
        other_meta = advanced["other_meta"]
        return if other_meta.nil? || other_meta == ""
        raise ArgumentError, "tool result advanced.other_meta must be a string" unless other_meta.is_a?(String)

        object = JSON.parse(other_meta)
        raise ArgumentError, "tool result advanced.other_meta must be a JSON object" unless object.is_a?(Hash)
      rescue JSON::ParserError => cause
        raise ArgumentError, "tool result advanced.other_meta must be a JSON object: #{cause.message}"
      end

      # Mirrors the feasible structural/size checks needed before Ruby emits an
      # attachment-bearing tool result. The daemon remains canonical authority.
      def validate_tool_attachment!(attachment)
        return if attachment.nil?

        files = attachment["file_array"]
        metadata = attachment["meta_files"]
        unless files.is_a?(Array) && !files.empty? && metadata.is_a?(Array) &&
               files.length == metadata.length
          raise ArgumentError, "tool result attachment arrays must be nonempty and equal length"
        end
        binary_total = 0
        files.each_with_index do |file, index|
          meta = metadata[index]
          unless file.is_a?(Hash) && meta.is_a?(Hash)
            raise ArgumentError, "tool result attachment #{index} must contain objects"
          end
          filename = file["filename"]
          mime_type = file["mime_type"]
          size = file["size"]
          encoding = file["encoding"]
          payload = file["payload"]
          unless filename.is_a?(String) && !filename.empty? && mime_type.is_a?(String) &&
                 !mime_type.empty? && size.is_a?(Integer) && size >= 0 && payload.is_a?(String)
            raise ArgumentError, "tool result attachment #{index} has invalid fields"
          end
          actual = case encoding
                   when "utf8"
                     payload.bytesize
                   when "b64"
                     decoded = payload.unpack1("m0")
                     binary_total += decoded.bytesize
                     if decoded.bytesize > 32 * 1024 * 1024 || binary_total > 32 * 1024 * 1024
                       raise ArgumentError, "tool result binary attachments exceed 32 MiB"
                     end
                     decoded.bytesize
                   else
                     raise ArgumentError, "tool result attachment #{index} has unsupported encoding"
                   end
          raise ArgumentError, "tool result attachment #{index} size mismatch" unless size == actual
          expected = {"filename" => filename, "mime_type" => mime_type, "size" => size}
          unless expected.all? { |key, value| meta[key] == value }
            raise ArgumentError, "tool result attachment #{index} metadata mismatch"
          end
        rescue ArgumentError => cause
          raise cause
        end
      end

      def report_callback_failure(call, cause)
        error = CallbackError.new(
          "provider callback or result preparation failed for #{call.kind} #{call.name.inspect}",
          event: call, cause: cause
        )
        Incidents.record(:provider_callback, error)
        @client.events.__send__(:report_provider_error, error)
      end

      def prepare_result_frame(call, result)
        frame = case call.kind
                when :tool
                  turn = normalize_tool_turn(call, result.turn)
                  {"type" => "tool_result", "tool_call_id" => call.call_id,
                   "turn" => turn.to_h}
                when :plugin
                  {"type" => "plugin_result", "plugin_call_id" => call.call_id,
                   "pending_turns" => result.pending_turns.map(&:to_h),
                   "is_error" => result.is_error}
                when :macro
                  {"type" => "macro_result_ipc", "macro_call_id" => call.call_id,
                   "result" => result.result, "is_error" => result.is_error}
                end
        PreparedCapabilityFrame.new(frame)
      end

      # Known ASCII-only fallback. Preparation happens before terminal claim as
      # well, so even the recovery path cannot orphan a watchdog on encode.
      def prepare_safe_error_frame(call)
        prepare_raw_error_frame(call, "Ruby capability callback returned an invalid result")
      end

      def send_prepared_frame(prepared)
        @client.__send__(:send_prepared_capability_frame, prepared)
      end

      def normalize_tool_turn(call, turn)
        values = turn.to_h.dup
        values["tool_call_id"] = call.call_id
        values["tool_name"] = call.name
        PendingTurn.from_h(values)
      end

      def finish_call(call)
        @mutex.synchronize do
          @calls.delete(call.call_id)
          @active_heartbeats.delete(call.call_id)
          @tool_acks.delete(call.call_id)
        end
      end

      def discard_work(work)
        call = work[1]
        finish_call(call) if call.respond_to?(:call_id)
      end

      def acknowledge_tool(call, parallel)
        unless parallel.equal?(true) || parallel.equal?(false)
          raise ArgumentError, "parallel must be true or false"
        end
        send = @mutex.synchronize do
          next false if @closed_error || call.cancelled? || @tool_acks[call.call_id]

          @tool_acks[call.call_id] = true
          true
        end
        send_command("tool_ack", "tool_call_id" => call.call_id, "parallel" => parallel) if send
        send
      end

      def send_heartbeat(call)
        return false if closed?

        state = call.respond_to?(:__state) ? call.__state : call
        @client.__send__(:send_provider_heartbeat, state,
                         call.kind.to_s, call.call_id)
      end

      def heartbeat_loop
        loop do
          closed = @mutex.synchronize do
            @condition.wait(@mutex, @heartbeat_interval) unless @closed_error
            !@closed_error.nil?
          end
          break if closed

          calls = @mutex.synchronize { @active_heartbeats.values.dup }
          calls.each { |call| send_heartbeat(call) }
          rpcs = @mutex.synchronize { @rpc_heartbeats.values.dup }
          rpcs.each { |state| @client.__send__(:send_provider_heartbeat, state, "rpc", state.call_id) }
        rescue ConnectionClosedError, TransportError
          break
        rescue Exception => error
          Incidents.record(:heartbeat, error)
          unless error.is_a?(StandardError)
            @client.__send__(:worker_failed, error)
            raise
          end
          @client.events.__send__(:report_provider_error, error)
        end
      end

      def provider_request(type, response_type, timeout, fields = {})
        @client.__send__(:request, type, response_types: [response_type],
                        timeout: timeout, fields: fields)
      end

      def send_command(type, fields)
        @client.__send__(:send_command, type, fields: fields)
      end

      def required_frame_string(frame, key)
        value = frame[key]
        unless value.is_a?(String)
          raise DecodeError.new("malformed #{frame["type"]}: #{key} must be a string",
                                frame_type: frame["type"])
        end
        value.dup
      end

      def pending_turn_from_frame(frame)
        unless frame.is_a?(Hash) && frame["kind"].is_a?(String)
          raise DecodeError.new("malformed plugin_call pending turn", frame_type: "plugin_call")
        end
        advanced = frame["advanced"]
        attachment = frame["attachment_blob"]
        unless advanced.nil? || advanced.is_a?(Hash)
          raise DecodeError.new(
            "malformed plugin_call: pending turn advanced must be an object",
            frame_type: "plugin_call"
          )
        end
        unless attachment.nil? || attachment.is_a?(Hash)
          raise DecodeError.new(
            "malformed plugin_call: pending turn attachment_blob must be an object",
            frame_type: "plugin_call"
          )
        end
        PendingTurn.from_h(frame)
      rescue DecodeError
        raise
      rescue ArgumentError, TypeError => cause
        raise DecodeError.new(
          "malformed plugin_call pending turn: #{cause.message}",
          frame_type: "plugin_call", cause: cause
        )
      end

      def optional_frame_string(frame, key)
        value = frame[key]
        unless value.nil? || value.is_a?(String)
          raise DecodeError.new("malformed plugin_call: #{key} must be a string",
                                frame_type: "plugin_call")
        end
        value
      end

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