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

# frozen_string_literal: true

require "json"

module EzAgent
  module API
    WIRE_INT64_MIN = -(2**63)
    WIRE_INT64_MAX = (2**63) - 1
    # The supported Ruby runtime targets the same native word width as its Go
    # peer. Keep Go-int projections within that wire width rather than Ruby's
    # unbounded Integer range.
    GO_INT_BITS = [0].pack("j").bytesize * 8
    GO_INT_MIN = -(2**(GO_INT_BITS - 1))
    GO_INT_MAX = (2**(GO_INT_BITS - 1)) - 1
    ATTACHMENT_CHUNK_MAX_BYTES = 98_304
    # Immutable base for typed operation results. Known fields have accessors;
    # unknown extension fields remain available through #[] and #to_h.
    class Value
      attr_reader :type

      class << self
        def fields(*names)
          names.each { |name| define_method(name) { @frame[name.to_s] } }
        end
      end

      def initialize(frame, expected_type: nil)
        unless frame.is_a?(Hash)
          raise DecodeError, "#{expected_type || self.class.name} response must be an object"
        end
        @frame = Immutable.copy(frame)
        if expected_type && @frame["type"] != expected_type
          raise DecodeError.new("expected #{expected_type}, got #{@frame["type"].inspect}",
                                frame_type: @frame["type"])
        end
        @type = @frame["type"]&.to_sym
        validate_itr!
      end

      def request_id
        @frame["request_id"]
      end

      def itr
        @frame["itr"]
      end

      def [](key)
        @frame[key.to_s]
      end

      def key?(key)
        @frame.key?(key.to_s)
      end

      def to_h
        @frame
      end

      private

      def finish!
        freeze
      end

      def require_field(name, klass)
        value = @frame[name.to_s]
        return value if value.is_a?(klass)

        malformed!("#{name} must be #{klass}")
      end

      def require_number(name)
        value = @frame[name.to_s]
        return value if value.is_a?(Numeric)

        malformed!("#{name} must be numeric")
      end

      def require_go_int(name, nonnegative: false)
        value = @frame[name.to_s]
        unless API.go_int?(value) && (!nonnegative || value >= 0)
          malformed!("#{name} must be#{nonnegative ? " a nonnegative" : ""} Go int")
        end
        value
      end

      def optional_go_int(name, nonnegative: false)
        return nil unless @frame.key?(name.to_s)

        require_go_int(name, nonnegative: nonnegative)
      end

      def require_int64(name, nonnegative: false)
        value = @frame[name.to_s]
        unless API.int64?(value) && (!nonnegative || value >= 0)
          malformed!("#{name} must be#{nonnegative ? " a nonnegative" : ""} signed 64-bit integer")
        end
        value
      end

      def optional_int64(name, nonnegative: false)
        return nil unless @frame.key?(name.to_s)

        require_int64(name, nonnegative: nonnegative)
      end

      def optional_field(name, klass)
        value = @frame[name.to_s]
        return nil if value.nil?
        return value if value.is_a?(klass)

        malformed!("#{name} must be #{klass} when present")
      end

      def require_array(name)
        require_field(name, Array)
      end

      def require_boolean(name)
        value = @frame[name.to_s]
        return value if value == true || value == false

        malformed!("#{name} must be boolean")
      end

      def optional_boolean(name)
        return nil unless @frame.key?(name.to_s)

        require_boolean(name)
      end

      def validate_itr!
        return unless @frame.key?("itr")

        malformed!("itr must be a signed 64-bit integer") unless API.int64?(@frame["itr"])
      end

      def validate_request_id!
        require_field(:request_id, String)
      end

      def malformed!(message)
        raise DecodeError.new("malformed #{@frame["type"] || self.class.name}: #{message}",
                              frame_type: @frame["type"])
      end
    end

    class VersionResult < Value
      fields :version, :stability, :build_date, :git_commit

      def initialize(frame)
        super(frame, expected_type: "version_result")
        %i[version stability build_date git_commit].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class CreatedLeaf < Value
      fields :root_id, :leaf_id, :model, :is_temp

      def initialize(frame)
        super(frame, expected_type: "leaf_created")
        %i[root_id leaf_id model].each { |field| require_field(field, String) }
        optional_boolean(:is_temp)
        validate_request_id!
        finish!
      end
    end

    class LeafInfo < Value
      # cwd is read-only, inherited from the leaf's root. has_children reports
      # whether another persistent leaf names this one in parent_leaf. Older services omit both.
      fields :id, :root_id, :cwd, :name, :turn_id, :model, :status, :updated_at,
             :is_temp, :has_children, :metadata

      def initialize(frame)
        super(frame)
        %i[id root_id name turn_id model status updated_at].each do |field|
          require_field(field, String)
        end
        optional_field(:cwd, String)
        optional_boolean(:is_temp)
        optional_boolean(:has_children)
        metadata = optional_field(:metadata, Hash)
        if metadata && !metadata.all? { |key, value| key.is_a?(String) && value.is_a?(String) }
          malformed!("metadata must contain string keys and values")
        end
        finish!
      end
    end

    # One leaf_list reply. Sync fields are nil on plain lists and on replies
    # from a service without sync support.
    class LeafList < Value
      fields :sync_id, :revision, :offset, :total

      def initialize(frame)
        super(frame)
        leaves = require_array(:leaves)
        @leaves = leaves.map { |leaf| LeafInfo.new(leaf) }.freeze
        optional_field(:sync_id, String)
        %i[revision offset total].each do |field|
          require_int64(field, nonnegative: true) if @frame.key?(field.to_s)
        end
        removed = optional_field(:removed, Array) || []
        malformed!("removed must contain strings") unless removed.all? { |id| id.is_a?(String) }
        @removed = removed.freeze
        finish!
      end

      attr_reader :leaves, :removed
    end

    class CwdInfo < Value
      fields :cwd, :leaf_count, :active_leaf_count, :last_activity_at

      def initialize(frame)
        super(frame)
        require_field(:cwd, String)
        require_go_int(:leaf_count, nonnegative: true)
        require_go_int(:active_leaf_count, nonnegative: true)
        optional_field(:last_activity_at, String)
        finish!
      end
    end

    class RootInfo < Value
      fields :id, :cwd, :root_turn_id, :created_at, :updated_at, :config

      def initialize(frame)
        super(frame)
        %i[id cwd root_turn_id created_at updated_at].each do |field|
          require_field(field, String)
        end
        optional_field(:config, String)
        finish!
      end
    end

    class AgentOutcome < Value
      fields :reason, :message

      def initialize(frame)
        super(frame)
        require_field(:reason, String)
        optional_field(:message, String)
        finish!
      end
    end

    class ActiveToolCall < Value
      fields :tool_call_id, :name, :turn_id

      def initialize(frame)
        super(frame)
        %i[tool_call_id name turn_id].each { |field| require_field(field, String) }
        finish!
      end
    end

    class AgentRuntime < Value
      attr_reader :outcome, :active_tool_calls

      def initialize(frame)
        super(frame)
        raw_outcome = @frame["outcome"]
        @outcome = raw_outcome.nil? ? nil : AgentOutcome.new(raw_outcome)
        raw_calls = @frame.fetch("active_tool_calls", [])
        malformed!("active_tool_calls must be Array") unless raw_calls.is_a?(Array)
        @active_tool_calls = raw_calls.map { |call| ActiveToolCall.new(call) }.freeze
        finish!
      end
    end

    class ProgressItem < Value
      fields :update_id, :title, :lines, :visualizer_macro, :visualizer_type

      def initialize(frame)
        super(frame)
        %i[update_id title].each { |field| require_field(field, String) }
        raw_lines = @frame.fetch("lines", [])
        malformed!("lines must be an array of strings") unless raw_lines.is_a?(Array) &&
                                                              raw_lines.all? { |line| line.is_a?(String) }
        macro_name = optional_field(:visualizer_macro, String)
        type = optional_field(:visualizer_type, String)
        unless (macro_name.nil? && type.nil?) ||
               (macro_name.is_a?(String) && !macro_name.empty? && type.is_a?(String) && !type.empty?)
          malformed!("visualizer_macro and visualizer_type must both be nonempty strings when present")
        end
        finish!
      end
    end

    class ProgressSnapshot < Value
      fields :turn_id
      attr_reader :items

      def initialize(frame)
        super(frame)
        require_field(:turn_id, String)
        @items = require_array(:items).map { |item| ProgressItem.new(item) }.freeze
        finish!
      end
    end

    # Persistent counters and point-in-time loaded-Agent projections.
    class LeafStatistics < Value
      fields :leaf_id, :name, :state, :active_turn_id, :tip_turn_id, :model,
             :thinking_level, :is_temp, :turn_count, :context_tokens,
             :input_tokens, :output_tokens, :estimated_cost, :queue_count,
             :root_cwd, :access_source
      attr_reader :runtime, :progress

      def initialize(frame)
        super(frame, expected_type: "leaf_stats_response")
        %i[leaf_id state tip_turn_id model thinking_level].each do |field|
          require_field(field, String)
        end
        optional_field(:active_turn_id, String)
        optional_field(:name, String)
        optional_field(:root_cwd, String)
        optional_boolean(:is_temp)
        %i[turn_count context_tokens input_tokens output_tokens queue_count].each do |field|
          require_go_int(field, nonnegative: true)
        end
        require_number(:estimated_cost)
        begin
          @runtime = @frame["runtime"].nil? ? nil : AgentRuntime.new(@frame["runtime"])
          @progress = @frame["progress"].nil? ? nil : ProgressSnapshot.new(@frame["progress"])
        rescue DecodeError => cause
          raise DecodeError.new("malformed leaf_stats_response projection: #{cause.message}",
                                frame_type: "leaf_stats_response", cause: cause)
        end
        validate_request_id!
        finish!
      end
    end

    class TurnSummary < Value
      fields :id, :kind, :state, :seq

      def initialize(frame)
        super(frame)
        %i[id kind state].each { |field| require_field(field, String) }
        require_go_int(:seq, nonnegative: true)
        finish!
      end
    end

    # Complete response to one list_history request. The tip identifies the
    # stable history cut and may name a draft omitted from the visible turns.
    class HistorySnapshot < Value
      include Enumerable

      fields :leaf_id, :tip_turn_id
      attr_reader :turns
      alias summaries turns

      def initialize(frame)
        super(frame, expected_type: "history_list")
        %i[leaf_id tip_turn_id].each { |field| require_field(field, String) }
        @turns = require_array(:turns).map { |turn| TurnSummary.new(turn) }.freeze
        validate_request_id!
        finish!
      end

      def each(&block)
        return @turns.each unless block

        @turns.each(&block)
      end

      def [](index, length = nil)
        if length.nil? && (index.is_a?(String) || index.is_a?(Symbol))
          return @frame[index.to_s]
        end
        return @turns[index] if length.nil?

        @turns[index, length]
      end

      def fetch(...)
        @turns.fetch(...)
      end

      def empty?
        @turns.empty?
      end

      def length
        @turns.length
      end
      alias size length

      def to_a
        @turns.dup
      end

      # Enumerable#to_h would interpret summaries as key/value pairs. Keep the
      # Value contract instead so response metadata and extensions survive.
      def to_h
        @frame
      end
    end

    class TurnTreeNode < Value
      fields :id, :parent_id, :kind, :state, :seq, :timestamp, :model,
             :provider, :stop_reason, :tool_name

      def initialize(frame)
        super(frame)
        %i[id kind state timestamp].each { |field| require_field(field, String) }
        optional_field(:parent_id, String)
        %i[model provider stop_reason tool_name].each { |field| optional_field(field, String) }
        require_go_int(:seq, nonnegative: true)
        finish!
      end
    end

    class StoredTurn < Value
      fields :leaf_id, :id, :root_id, :parent_id, :kind, :content_type,
             :content, :meta_files, :thinking, :model, :provider, :stop_reason,
             :usage, :tool_call_id, :tool_name, :other_meta, :timestamp, :state,
             :seq
      attr_reader :exit_message, :exit_classification

      def initialize(frame)
        super(frame, expected_type: "turn_content")
        %i[id root_id kind content_type content timestamp state].each do |field|
          require_field(field, String)
        end
        optional_field(:leaf_id, String)
        optional_field(:parent_id, String)
        %i[meta_files thinking model provider stop_reason usage tool_call_id tool_name other_meta].each do |field|
          optional_field(field, String)
        end
        require_go_int(:seq, nonnegative: true)
        validate_request_id!
        parse_exit_message!
        finish!
      end

      private

      def parse_exit_message!
        unless @frame.key?("other_meta")
          @exit_message = nil
          @exit_classification = :continue
          return
        end

        raw = @frame["other_meta"]
        malformed!("other_meta must be a nonempty JSON object") unless raw.is_a?(String)
        malformed!("other_meta must be a nonempty JSON object") if raw.empty? || !raw.valid_encoding?
        metadata = JSON.parse(raw)
        malformed!("other_meta must be a JSON object") unless metadata.is_a?(Hash)
        unless metadata.key?("exit_message")
          @exit_message = nil
          @exit_classification = :continue
          return
        end
        unless @frame["kind"] == "assistant" && @frame["state"] == "sent"
          malformed!("exit_message belongs only to sent assistant turns")
        end

        message = metadata["exit_message"]
        unless message.nil? || message.is_a?(String)
          malformed!("exit_message must be null or a string")
        end
        if message.is_a?(String)
          malformed!("exit_message must be nonempty valid text") if message.empty? || !message.valid_encoding? ||
                                                                     message.each_codepoint.any? { |codepoint| codepoint < 0x20 || codepoint == 0x7f || codepoint.between?(0x80, 0x9f) }
        end

        @exit_message = message&.dup&.freeze
        @exit_classification = if message.nil?
                                 :continue
                               elsif message == "SUCCESS"
                                 :success
                               else
                                 :error
                               end
      rescue JSON::ParserError, EncodingError
        malformed!("other_meta must be a JSON object")
      end
    end

    # One bounded attachment read. #data is the decoded binary string; #data_b64
    # and unknown extension fields retain the immutable wire representation.
    class AttachmentChunk < Value
      fields :turn_id, :attachment_index, :offset, :length, :size, :data_b64, :eof
      attr_reader :data

      def initialize(frame)
        super(frame, expected_type: "attachment_chunk")
        require_field(:turn_id, String)
        require_go_int(:attachment_index, nonnegative: true)
        require_int64(:offset, nonnegative: true)
        require_go_int(:length, nonnegative: true)
        require_int64(:size, nonnegative: true)
        require_field(:data_b64, String)
        require_boolean(:eof)
        validate_request_id!
        unless length <= ATTACHMENT_CHUNK_MAX_BYTES && offset <= size && length <= size - offset
          malformed!("chunk range exceeds attachment size or chunk limit")
        end
        unless eof == (offset + length == size) && (length.positive? || eof)
          malformed!("eof must match the chunk range and empty chunks must be at EOF")
        end
        unless data_b64.bytesize == ((length + 2) / 3) * 4
          malformed!("data_b64 must be padded standard base64 matching length")
        end
        begin
          @data = data_b64.unpack1("m0").freeze
        rescue ArgumentError
          malformed!("data_b64 must be padded standard base64")
        end
        unless @data.bytesize == length && [@data].pack("m0") == data_b64
          malformed!("data_b64 must be canonical padded standard base64 matching length")
        end
        finish!
      end
    end

    # Typed semantic turn accepted by prompt, steer, and virtual-root creation.
    class PendingTurn
      KNOWN_ADVANCED_FIELDS = %w[thinking other_meta stop_reason usage model provider].freeze
      KNOWN_FIELDS = %w[kind steer content_type content tool_call_id tool_name advanced attachment_blob fill_content_from_turn_id].freeze

      attr_reader :kind, :content_type, :content, :tool_call_id, :tool_name,
                  :advanced, :attachment_blob, :fill_content_from_turn_id, :steer

      def self.text(content, kind: "user", content_type: "text", steer: nil)
        new(kind: kind, content_type: content_type, content: content, steer: steer)
      end

      # Projects a decoded protocol object without discarding extension keys.
      def self.from_h(frame)
        raise ArgumentError, "pending turn must be a hash" unless frame.is_a?(Hash)

        raw = Immutable.copy(frame)
        values = KNOWN_FIELDS.each_with_object({}) { |key, result| result[key] = raw[key] }
        extensions = raw.reject { |key, _value| KNOWN_FIELDS.include?(key) }
        new(**values.transform_keys(&:to_sym), **extensions)
      end

      def initialize(kind:, content_type: nil, content: nil, tool_call_id: nil,
                     tool_name: nil, advanced: nil, attachment_blob: nil,
                     fill_content_from_turn_id: nil, steer: nil, **extensions)
        @kind = API.required_string(kind, :kind)
        unless steer.nil? || steer.equal?(true) || steer.equal?(false)
          raise ArgumentError, "steer must be a boolean"
        end
        @steer = steer
        @content_type = API.optional_string(content_type, :content_type)
        @content = API.optional_string(content, :content)
        @tool_call_id = API.optional_string(tool_call_id, :tool_call_id)
        @tool_name = API.optional_string(tool_name, :tool_name)
        @advanced = validate_advanced(advanced)
        @attachment_blob = validate_attachment_blob(attachment_blob)
        @fill_content_from_turn_id = API.optional_string(fill_content_from_turn_id,
                                                          :fill_content_from_turn_id)
        result = extensions.each_with_object({}) { |(key, value), memo| memo[key.to_s] = value }
        result["kind"] = @kind
        {
          "steer" => @steer, "content_type" => @content_type, "content" => @content,
          "tool_call_id" => @tool_call_id, "tool_name" => @tool_name,
          "advanced" => @advanced, "attachment_blob" => @attachment_blob,
          "fill_content_from_turn_id" => @fill_content_from_turn_id
        }.each { |key, value| result[key] = value unless value.nil? }
        @frame = Immutable.copy(result)
        freeze
      end

      def [](key)
        @frame[key.to_s]
      end

      def key?(key)
        @frame.key?(key.to_s)
      end

      def to_h
        @frame
      end

      private

      def validate_advanced(value)
        return nil if value.nil?
        raise ArgumentError, "advanced must be a hash" unless value.is_a?(Hash)

        advanced = Immutable.copy(value)
        KNOWN_ADVANCED_FIELDS.each do |field|
          next unless advanced.key?(field)
          raise ArgumentError, "advanced.#{field} must be a string" unless advanced[field].is_a?(String)
        end
        advanced
      end

      def validate_attachment_blob(value)
        return nil if value.nil?
        raise ArgumentError, "attachment_blob must be a hash" unless value.is_a?(Hash)

        attachment = Immutable.copy(value)
        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, "attachment_blob file_array and meta_files must be nonempty arrays of equal length"
        end

        files.each_with_index do |file, index|
          validate_file_element(file, index)
          validate_file_meta(metadata[index], index)
          expected = %w[filename mime_type size]
          unless expected.all? { |key| file[key] == metadata[index][key] }
            raise ArgumentError, "attachment_blob file_array[#{index}] must match meta_files[#{index}]"
          end
        end
        attachment
      end

      def validate_file_element(file, index)
        raise ArgumentError, "attachment_blob file_array[#{index}] must be a hash" unless file.is_a?(Hash)
        %w[filename mime_type encoding payload].each do |field|
          unless file[field].is_a?(String)
            raise ArgumentError, "attachment_blob file_array[#{index}].#{field} must be a string"
          end
        end
        API.required_int64(file["size"], "attachment_blob file_array[#{index}].size", nonnegative: true)
      end

      def validate_file_meta(meta, index)
        raise ArgumentError, "attachment_blob meta_files[#{index}] must be a hash" unless meta.is_a?(Hash)
        %w[filename mime_type].each do |field|
          unless meta[field].is_a?(String)
            raise ArgumentError, "attachment_blob meta_files[#{index}].#{field} must be a string"
          end
        end
        API.required_int64(meta["size"], "attachment_blob meta_files[#{index}].size", nonnegative: true)
      end
    end

    class PromptAcceptance < Value
      fields :root_id, :leaf_id, :turn_ids, :tip_turn_id

      def initialize(frame)
        super(frame, expected_type: "prompt_accepted")
        %i[root_id leaf_id tip_turn_id].each { |field| require_field(field, String) }
        ids = require_array(:turn_ids)
        malformed!("turn_ids must contain strings") unless ids.all? { |id| id.is_a?(String) }
        validate_request_id!
        finish!
      end
    end

    class SteerAcceptance < Value
      fields :leaf_id, :turn_ids, :tip_turn_id

      def initialize(frame)
        super(frame, expected_type: "steer_accepted")
        %i[leaf_id tip_turn_id].each { |field| require_field(field, String) }
        ids = require_array(:turn_ids)
        malformed!("turn_ids must contain strings") unless ids.all? { |id| id.is_a?(String) }
        validate_request_id!
        finish!
      end
    end

    class AbortAcknowledgement < Value
      fields :leaf_id

      def initialize(frame)
        super(frame, expected_type: "abort_received")
        require_field(:leaf_id, String)
        validate_request_id!
        finish!
      end
    end

    class RewoundLeaf < Value
      fields :leaf_id, :old_tip_turn_id, :new_tip_turn_id, :replay

      def initialize(frame)
        super(frame, expected_type: "leaf_rewound")
        %i[leaf_id old_tip_turn_id new_tip_turn_id].each do |field|
          require_field(field, String)
        end
        require_boolean(:replay)
        validate_request_id!
        finish!
      end
    end

    class QuestionReplyAcknowledgement < Value
      fields :leaf_id, :kind, :revision, :reply

      def initialize(frame)
        super(frame, expected_type: "question_reply_ack")
        %i[leaf_id kind revision reply].each { |field| require_field(field, String) }
        malformed!("kind must be project_config_trust") unless kind == "project_config_trust"
        malformed!("revision must not be empty") if revision.empty?
        malformed!("reply must be trust or reject") unless %w[trust reject].include?(reply)
        validate_request_id!
        finish!
      end
    end

    class LeafMetaUpdated < Value
      fields :leaf_id, :name_changed, :new_name, :set_config_keys, :deleted_keys

      def initialize(frame)
        super(frame, expected_type: "leaf_meta_updated")
        require_field(:leaf_id, String)
        optional_boolean(:name_changed)
        optional_field(:new_name, String)
        %i[set_config_keys deleted_keys].each do |field|
          values = @frame.fetch(field.to_s, [])
          malformed!("#{field} must contain strings") unless values.is_a?(Array) &&
                                                            values.all? { |value| value.is_a?(String) }
        end
        validate_request_id!
        finish!
      end
    end

    class LeafFileDescriptor < Value
      fields :file_id, :key, :path

      def initialize(frame)
        super(frame)
        %i[file_id key path].each do |field|
          value = require_field(field, String)
          malformed!("#{field} must not be empty") if value.empty?
        end
        finish!
      end
    end

    class LeafConfigValue < Value
      fields :leaf_id, :key, :value

      def initialize(frame, expected_type: "leaf_config_value")
        super(frame, expected_type: expected_type)
        %i[leaf_id key value].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class LeafConfigSet < LeafConfigValue
      def initialize(frame)
        super(frame, expected_type: "leaf_config_set")
      end
    end

    class LeafConfigDeleted < Value
      fields :leaf_id, :key

      def initialize(frame)
        super(frame, expected_type: "leaf_config_deleted")
        %i[leaf_id key].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class LeafConfigEntry < Value
      fields :key, :value

      def initialize(frame)
        super(frame)
        %i[key value].each { |field| require_field(field, String) }
        finish!
      end
    end

    class EffectiveConfiguration < Value
      fields :cwd, :config, :layers, :config_error

      def initialize(frame)
        super(frame, expected_type: "effective_config")
        %i[cwd config].each { |field| require_field(field, String) }
        layers = require_array(:layers)
        malformed!("layers must contain strings") unless layers.all? { |layer| layer.is_a?(String) }
        optional_field(:config_error, String)
        validate_request_id!
        finish!
      end
    end

    class ModelEntry < Value
      fields :ref, :name, :type, :max_context, :max_tokens, :flags,
             :thinking_levels, :zdr_supported

      def initialize(frame)
        super(frame)
        require_field(:ref, String)
        %i[name type].each { |field| optional_field(field, String) }
        %i[max_context max_tokens].each do |field|
          optional_go_int(field, nonnegative: true)
        end
        %i[flags thinking_levels].each do |field|
          values = @frame.fetch(field.to_s, [])
          malformed!("#{field} must contain strings") unless values.is_a?(Array) &&
                                                            values.all? { |value| value.is_a?(String) }
        end
        optional_boolean(:zdr_supported)
        finish!
      end
    end

    class ResolvedModels < Value
      fields :main, :small, :audit

      def initialize(frame)
        super(frame, expected_type: "resolved_models")
        %i[main small audit].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class ModelSet < Value
      fields :leaf_id, :model, :thinking_level

      def initialize(frame)
        super(frame, expected_type: "model_set")
        %i[leaf_id model].each { |field| require_field(field, String) }
        optional_field(:thinking_level, String)
        validate_request_id!
        finish!
      end
    end

    class ThinkingLevelSet < Value
      fields :leaf_id, :level

      def initialize(frame)
        super(frame, expected_type: "thinking_level_set")
        %i[leaf_id level].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class VirtualRootCreated < Value
      fields :root_id, :leaf_id, :model

      def initialize(frame)
        super(frame, expected_type: "virtual_root_created")
        %i[root_id leaf_id model].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class MacroInfo < Value
      fields :name, :description, :timeout, :max_timeout, :priority, :version,
             :triggers

      def internal
        @frame.fetch("internal", false)
      end

      def initialize(frame)
        super(frame)
        require_field(:name, String)
        optional_boolean(:internal)
        %i[description timeout max_timeout version].each { |field| optional_field(field, String) }
        priority = @frame["priority"]
        malformed!("priority must be Go-width Integer when present") unless priority.nil? || API.go_int?(priority)
        triggers = @frame.fetch("triggers", [])
        malformed!("triggers must contain strings") unless triggers.is_a?(Array) &&
                                                          triggers.all? { |value| value.is_a?(String) }
        finish!
      end
    end

    class MacroResult < Value
      fields :macro_call_id, :macro_name, :result, :is_error

      def initialize(frame)
        super(frame, expected_type: "macro_result")
        %i[macro_name result].each { |field| require_field(field, String) }
        optional_field(:macro_call_id, String)
        require_boolean(:is_error)
        validate_request_id!
        finish!
      end
    end

    class CwdUpdate < Value
      fields :cwd, :leaf_id

      def initialize(frame)
        super(frame, expected_type: "cwd_updated")
        require_field(:cwd, String)
        optional_field(:leaf_id, String)
        validate_request_id!
        finish!
      end
    end

    class LeafSubscription < Value
      fields :leaf_id

      def initialize(frame)
        super(frame, expected_type: "leaf_switched")
        require_field(:leaf_id, String)
        validate_request_id!
        finish!
      end
    end

    class DroppedFeed < Value
      fields :leaf_id

      def initialize(frame)
        super(frame, expected_type: "feed_dropped")
        require_field(:leaf_id, String)
        validate_request_id!
        finish!
      end
    end

    class RenamedLeaf < Value
      fields :leaf_id, :name

      def initialize(frame)
        super(frame, expected_type: "leaf_renamed")
        %i[leaf_id name].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class DeletedLeaf < Value
      fields :leaf_id, :turn_id

      def initialize(frame)
        super(frame, expected_type: "leaf_deleted")
        %i[leaf_id turn_id].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class QueuedMessage < Value
      fields :turn_id, :parent_turn_id, :request_id, :timestamp
      attr_reader :turn

      def initialize(frame)
        super(frame)
        %i[turn_id request_id timestamp].each { |field| require_field(field, String) }
        optional_field(:parent_turn_id, String)
        raw_turn = require_field(:turn, Hash)
        @turn = PendingTurn.from_h(raw_turn)
        finish!
      rescue ArgumentError => cause
        malformed!("turn is invalid: #{cause.message}")
      end
    end

    class VacuumResult < Value
      fields :roots_pruned, :turns_pruned

      def initialize(frame)
        super(frame, expected_type: "vacuum_result")
        %i[roots_pruned turns_pruned].each { |field| require_go_int(field, nonnegative: true) }
        validate_request_id!
        finish!
      end
    end

    class ToolMutation < Value
      fields :leaf_id, :tool_name

      def initialize(frame, expected_type:)
        super(frame, expected_type: expected_type)
        %i[leaf_id tool_name].each { |field| require_field(field, String) }
        validate_request_id!
        finish!
      end
    end

    class ToolInfo < Value
      fields :name, :description, :parameters, :timeout, :max_timeout, :tool_hint

      def initialize(frame)
        super(frame)
        require_field(:name, String)
        %i[description timeout max_timeout tool_hint].each do |field|
          optional_field(field, String)
        end
        optional_field(:parameters, Hash)
        finish!
      end
    end

    class ProviderModelInfo < Value
      fields :name, :max_context, :max_tokens, :thinking_levels, :zdr_supported

      def initialize(frame)
        super(frame)
        require_field(:name, String)
        %i[max_context max_tokens].each do |field|
          optional_go_int(field, nonnegative: true)
        end
        thinking = @frame.fetch("thinking_levels", [])
        malformed!("thinking_levels must contain strings") unless
          thinking.is_a?(Array) && thinking.all? { |level| level.is_a?(String) }
        optional_boolean(:zdr_supported)
        finish!
      end
    end

    class ProviderInfo < Value
      fields :name, :type, :base_url
      attr_reader :models

      def initialize(frame)
        super(frame)
        %i[name type base_url].each { |field| require_field(field, String) }
        raw_models = @frame.fetch("models", [])
        malformed!("models must be an array") unless raw_models.is_a?(Array)
        @models = raw_models.map { |model| ProviderModelInfo.new(model) }.freeze
        finish!
      end
    end

    class ConnectionInfo < Value
      fields :id, :name, :leaf_id
      attr_reader :tools, :plugins, :macros

      def initialize(frame)
        super(frame)
        %i[id name].each { |field| require_field(field, String) }
        optional_field(:leaf_id, String)
        %i[tools plugins macros].each do |field|
          values = optional_field(field, Array) || []
          malformed!("#{field} must contain strings") unless
            values.all? { |value| value.is_a?(String) }
          instance_variable_set("@#{field}", values.freeze)
        end
        finish!
      end
    end

    module_function

    def int64?(value)
      value.is_a?(Integer) && value.between?(WIRE_INT64_MIN, WIRE_INT64_MAX)
    end

    def go_int?(value)
      value.is_a?(Integer) && value.between?(GO_INT_MIN, GO_INT_MAX)
    end

    def required_int64(value, name, nonnegative: false)
      unless int64?(value) && (!nonnegative || value >= 0)
        raise ArgumentError, "#{name} must be#{nonnegative ? " a nonnegative" : ""} signed 64-bit Integer"
      end
      value
    end

    def required_go_int(value, name, nonnegative: false)
      unless go_int?(value) && (!nonnegative || value >= 0)
        raise ArgumentError, "#{name} must be#{nonnegative ? " a nonnegative" : ""} Go-width Integer"
      end
      value
    end

    def required_string(value, name, symbols: false)
      return value.dup.freeze if value.is_a?(String)
      return value.to_s.freeze if symbols && value.is_a?(Symbol)

      raise ArgumentError, "#{name} must be a string#{symbols ? " or symbol" : ""}"
    end

    def optional_string(value, name, symbols: false)
      return nil if value.nil?

      required_string(value, name, symbols: symbols)
    end
  end
end

module EzAgent
  module API
    class BackgroundTaskAddition < Value
      fields :leaf_id, :task_id

      def initialize(frame)
        super(frame, expected_type: "background_task_add_ack")
        require_field(:leaf_id, String)
        require_field(:task_id, String)
        validate_request_id!
        finish!
      end
    end

    class BackgroundTaskRemoval < Value
      fields :leaf_id, :task_id

      def initialize(frame)
        super(frame, expected_type: "background_task_remove_ack")
        require_field(:leaf_id, String)
        require_field(:task_id, String)
        validate_request_id!
        finish!
      end
    end
  end
end