# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-renegotiate-an-a2a-v1-0-agent-card-mid-task-when-a-peer-s-advertised-defaultinputmodes-defaultoutputmodes-diver.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-renegotiate-an-a2a-v1-0-agent-card-mid-task-when-a-peer-s-advertised-defaultinputmodes-defaultoutputmodes-diver.warrant.json
# Markdown SHA-256:   966153e6dfa8019dda1cabb43e658176dcf23f93a2607fe8aacac072dd2c9dd8
# Code AST SHA-256:   fb6b9ea947c9237ac96a73edf912d2f95f8995b2dda5a43bc4614ea1af9ef6e5
# Verified Classes:   AgentCardDivergenceError, CachedCard, TaskNegotiation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class AgentCardDivergenceError(RuntimeError):
    """Raised when a received Part's media type falls outside both the
    negotiated acceptedOutputModes and the cached Agent Card's default modes,
    and the divergence cannot be resolved by a single card re-fetch."""


@dataclass
class CachedCard:
    default_input_modes: set[str]
    default_output_modes: set[str]
    version: str


@dataclass
class TaskNegotiation:
    accepted_output_modes: set[str]
    observed_modes: set[str] = field(default_factory=set)
    open_decode: bool = False
    refetched: bool = False


def handle_part(
    part: dict[str, Any],
    negotiation: TaskNegotiation,
    card: CachedCard,
    refetch_card,  # callable() -> CachedCard
) -> dict[str, Any]:
    """Decode a single Part from a TaskArtifactUpdateEvent.

    Invariant: the card bounds negotiation, not emission. Never drop a part
    silently; never abort a task for an in-spec emission.
    """
    mime = part.get("file", {}).get("mimeType") or part.get("metadata", {}).get("mimeType")
    ptype = part.get("type")

    if ptype not in {"text", "file", "data"}:
        raise AgentCardDivergenceError(f"unknown part type {ptype!r}")

    # In-mode or open-decode: accept and record.
    if mime is None or mime in negotiation.accepted_output_modes or mime in card.default_output_modes:
        if mime:
            negotiation.observed_modes.add(mime)
        return part

    # Out of both negotiated set and cached card. Card may be stale.
    if not negotiation.refetched:
        fresh = refetch_card()
        negotiation.refetched = True
        if mime in fresh.default_output_modes:
            negotiation.observed_modes.add(mime)
            return part

    # Divergence is real: runtime/tool drift. Degrade to open-decode for the
    # remainder of the task rather than cancel or drop.
    if not negotiation.open_decode:
        negotiation.open_decode = True
        negotiation.observed_modes.add(mime)
        return part

    # Already in open-decode and still unclassifiable -> hard stop with reason.
    raise AgentCardDivergenceError(
        f"part mimeType {mime!r} outside negotiated {sorted(negotiation.accepted_output_modes)} "
        f"and card {sorted(card.default_output_modes)} after re-fetch; "
        f"open-decode already active"
    )
