# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-agent-card-whose-capabilities-streaming-is-true-but-whose-defaultinputmodes-excludes-application-json-the-discove.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-an-a2a-agent-card-whose-capabilities-streaming-is-true-but-whose-defaultinputmodes-excludes-application-json-the-discove.warrant.json
# Markdown SHA-256:   13487cf988db023f165bb280624daca29f23ae8a194f923ea4901aa56f82d121
# Code AST SHA-256:   e29291ab65c4c6bd652c6bea69a8fdf4c828496f5cf6b9bc556aba2ab9629be7
# Verified Classes:   ModalityClosureError, AgentCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ModalityClosureError(RuntimeError):
    """Raised when a peer Agent Card's declared modalities do not cover the
    exact Message parts a client intends to send. This is a discovery-time
    refusal, not a runtime retry condition."""


@dataclass(frozen=True)
class AgentCard:
    streaming: bool
    default_input_modes: FrozenSet[str]
    default_output_modes: FrozenSet[str]


def resolve_modes(card: AgentCard) -> tuple[FrozenSet[str], FrozenSet[str]]:
    # A2A v1.0: omitted defaultInputModes/defaultOutputModes default to text/plain.
    in_modes = card.default_input_modes or frozenset({"text/plain"})
    out_modes = card.default_output_modes or frozenset({"text/plain"})
    return in_modes, out_modes


def assert_modality_closure(
    card: AgentCard,
    outbound_part_types: FrozenSet[str],
    request_streaming: bool,
) -> None:
    """Enforce the discovery-time modality closure invariant.

    Must be called after card resolution and BEFORE message/send. The
    outbound_part_types argument must be derived from the planner's actual
    next Message, not from static config, because planners are
    non-deterministic about attaching DataParts.
    """
    if not outbound_part_types:
        raise ModalityClosureError(
            "refusing delegation: outbound_part_types is empty; "
            "cannot prove modality closure against peer card"
        )

    peer_in, peer_out = resolve_modes(card)

    missing_in = outbound_part_types - peer_in
    if missing_in:
        # Do NOT silently downgrade: dropping a DataPart changes task
        # semantics and yields plausible-but-wrong output on the peer.
        raise ModalityClosureError(
            f"peer card defaultInputModes={sorted(peer_in)} does not cover "
            f"outbound part types {sorted(missing_in)}; refusing message/send"
        )

    if request_streaming:
        if not card.streaming:
            raise ModalityClosureError(
                "client requested streaming but peer card "
                "capabilities.streaming is false"
            )
        # Streaming output must be serializable by the peer's encoder.
        missing_out = outbound_part_types - peer_out
        if missing_out:
            raise ModalityClosureError(
                f"peer card defaultOutputModes={sorted(peer_out)} does not "
                f"cover streamed part types {sorted(missing_out)}; "
                f"refusing streaming request (fall back to non-streaming "
                f"message/send, which surfaces a terminal TaskState.failed)"
            )


def delegate(
    card: AgentCard,
    outbound_part_types: FrozenSet[str],
    request_streaming: bool = True,
) -> None:
    # Pre-flight: fail at discovery, not after a 300s TaskState.working timeout.
    assert_modality_closure(card, outbound_part_types, request_streaming)
    # ... only now issue message/send ...


if __name__ == "__main__":
    # The observed card: streaming=true, input=text/plain only.
    observed_card = AgentCard(
        streaming=True,
        default_input_modes=frozenset({"text/plain"}),
        default_output_modes=frozenset({"text/plain"}),
    )
    # Planner intends to attach a DataPart (application/json) + TextPart.
    try:
        delegate(
            observed_card,
            outbound_part_types=frozenset({"text/plain", "application/json"}),
            request_streaming=True,
        )
    except ModalityClosureError as exc:
        print(f"REFUSED AT DISCOVERY: {exc}")
