# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-cross-vendor-delegation-and-why-does-schema-negotiation-silently-succeed-against-a-depr.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-cross-vendor-delegation-and-why-does-schema-negotiation-silently-succeed-against-a-depr.warrant.json
# Markdown SHA-256:   5806f38ea1c7b5a06c0422258b492686489d1d39c8ce2790963dc2c39d88a834
# Code AST SHA-256:   90c861d4f60310efc70950e3d310cbcb9cea9b4a03f8282cb33d412a241a420a
# Verified Classes:   StaleCardDelegationError, AgentCard, TaskResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleCardDelegationError(RuntimeError):
    """Raised when a delegation proceeds on a card whose validity window has lapsed
    or when the response artifact's outputMode is not bound to the caller's accepted set."""


@dataclass
class AgentCard:
    skill_id: str
    output_modes: frozenset[str]
    ttl_seconds: Optional[int]
    fetched_at: float


@dataclass
class TaskResponse:
    returned_skill: str
    artifact_output_mode: str


def delegate(
    card: AgentCard,
    accepted_output_modes: frozenset[str],
    now: float,
    response: TaskResponse,
) -> None:
    # Boundary 1: card validity window. Absent TTL means valid for this turn only;
    # any cross-turn planning phase invalidates the cache.
    if card.ttl_seconds is None:
        raise StaleCardDelegationError(
            f"card for skill {card.skill_id!r} has no ttl; cross-turn delegation "
            f"requires refetch at send time (fetched_at={card.fetched_at}, now={now})"
        )
    if now - card.fetched_at > card.ttl_seconds:
        raise StaleCardDelegationError(
            f"card for skill {card.skill_id!r} expired: "
            f"age={now - card.fetched_at:.1f}s > ttl={card.ttl_seconds}s"
        )

    # Boundary 2: capability substitution via deprecated alias.
    if response.returned_skill != card.skill_id:
        raise StaleCardDelegationError(
            f"capability substitution: sent {card.skill_id!r}, "
            f"remote executed {response.returned_skill!r}"
        )

    # Boundary 3: output-mode binding. The response mode must be in the set the
    # caller declared; a silent downgrade is a failure, not a degradation.
    if response.artifact_output_mode not in accepted_output_modes:
        raise StaleCardDelegationError(
            f"output-mode downgrade: remote returned "
            f"{response.artifact_output_mode!r}, caller accepted "
            f"{sorted(accepted_output_modes)!r}"
        )
