# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-task-because-the-remote-agent-card-s-declared-defaultinputmodes-defaultoutputmodes-are-satisfied-only-by-a-mi.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-task-because-the-remote-agent-card-s-declared-defaultinputmodes-defaultoutputmodes-are-satisfied-only-by-a-mi.warrant.json
# Markdown SHA-256:   9a5afd16bd10ce0de75394f309cd1fb74a21897d92042e6e7e51e12dfd58d1c1
# Code AST SHA-256:   af3f704fa7f0035868a509f06c483733bc98fe5471061d665534fb47d3641cbd
# Verified Classes:   EmissionModeViolation, UnboundedEmissionSet, AgentCard, DelegationGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class EmissionModeViolation(RuntimeError):
    """Remote emitted an artifact mimeType outside the caller's acceptedOutputModes."""
    pass


class UnboundedEmissionSet(RuntimeError):
    """Card's defaultOutputModes exceeds local consumable set and conformance is unverified."""
    pass


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


@dataclass
class DelegationGuard:
    local_consumable_mimes: FrozenSet[str]
    remote_conformance_verified: bool = False

    def validate_preflight(self, card: AgentCard) -> FrozenSet[str]:
        """Return the set of acceptedOutputModes to pin, or raise if unbounded."""
        unbounded = card.default_output_modes - self.local_consumable_mimes
        if not unbounded:
            # Caller can render anything the remote might emit.
            return card.default_output_modes
        if not self.remote_conformance_verified:
            raise UnboundedEmissionSet(
                f"card.defaultOutputModes contains {sorted(unbounded)} "
                f"outside local consumable set {sorted(self.local_consumable_mimes)}; "
                f"remote conformance on acceptedOutputModes narrowing is unverified. "
                f"Refusing delegation."
            )
        # Weak path: pin to a single consumable mode; post-hoc assertion required.
        pinned = card.default_output_modes & self.local_consumable_mimes
        if not pinned:
            raise UnboundedEmissionSet(
                f"no overlap between card.defaultOutputModes "
                f"{sorted(card.default_output_modes)} and local consumable "
                f"{sorted(self.local_consumable_mimes)}"
            )
        return frozenset({sorted(pinned)[0]})

    def assert_artifact(self, artifact_mime: str, accepted: FrozenSet[str]) -> None:
        """Post-return guard: fire before handing artifact to consumer."""
        if artifact_mime not in accepted:
            raise EmissionModeViolation(
                f"remote emitted {artifact_mime!r} outside acceptedOutputModes "
                f"{sorted(accepted)}; task is terminal and artifact unconsumable. "
                f"Cancel contextId and re-delegate with pinned single mode."
            )


# Observed failure reproduction:
card = AgentCard(
    default_input_modes=frozenset({"text/plain", "application/json"}),
    default_output_modes=frozenset({"text/plain", "application/json", "application/pdf"}),
)
guard = DelegationGuard(
    local_consumable_mimes=frozenset({"text/plain", "application/json"}),
    remote_conformance_verified=False,
)
# Naive intersection check passes (unsound); guard raises:
try:
    accepted = guard.validate_preflight(card)
except UnboundedEmissionSet as e:
    accepted = frozenset({"application/json"})  # fallback pin under verified-conformance assumption
    # ... remote returns application/pdf ...
try:
    guard.assert_artifact("application/pdf", accepted)
except EmissionModeViolation as e:
    print(f"caught: {e}")
