# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-capability-attestation-during-a2a-v1-0-cross-runtime-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-capability-attestation-during-a2a-v1-0-cross-runtime-delegation.warrant.json
# Markdown SHA-256:   f646a1453c8c15edc85de9f57af61cefaf9cd67b30995f2d989496082469daab
# Code AST SHA-256:   a8760b2fc7ec01ac090747e253bdb90ba4d119b7cb1242f0406275cf1ab53f3c
# Verified Classes:   StaleAgentCardError, AgentCard, Envelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleAgentCardError(RuntimeError):
    """Raised when a delegation envelope would be built from an unbound or stale Agent Card."""


@dataclass
class AgentCard:
    last_modified: Optional[float]   # epoch seconds; None means unbounded/unknown
    etag: Optional[str]
    streaming: bool
    output_modes: list[str]
    skill_version: Optional[str]


@dataclass
class Envelope:
    streaming: bool
    accepted_output_modes: list[str]
    skill_version_echo: Optional[str]


def build_envelope(
    card: AgentCard,
    client_parseable: list[str],
    max_card_age_s: float,
    now: Optional[float] = None,
) -> Envelope:
    now = time.time() if now is None else now

    # Invariant 1: no envelope from an unattested card.
    if card.last_modified is None:
        raise StaleAgentCardError(
            "Agent Card has no lastModified/etag binding; cannot bound attestation age. "
            "Re-fetch required before delegation."
        )

    age = now - card.last_modified
    if age > max_card_age_s:
        raise StaleAgentCardError(
            f"Agent Card age {age:.1f}s exceeds max_card_age {max_card_age_s:.1f}s; "
            "capability attestation may have drifted."
        )

    # Invariant 2: explicit streaming preference, never inherited from card default.
    streaming = bool(card.streaming and age < 300.0)

    # Invariant 3: accepted modes are an intersection, not a subset assumption.
    accepted = [m for m in client_parseable if m in card.output_modes]
    if not accepted:
        raise StaleAgentCardError(
            f"Empty output-mode intersection: client={client_parseable} "
            f"card={card.output_modes}. Refusing to delegate."
        )

    return Envelope(
        streaming=streaming,
        accepted_output_modes=accepted,
        skill_version_echo=card.skill_version,
    )


def validate_result(envelope: Envelope, returned_part_types: list[str]) -> None:
    # Invariant 4: server emitting outside acceptedOutputModes is a violation.
    for t in returned_part_types:
        if t not in envelope.accepted_output_modes:
            raise StaleAgentCardError(
                f"Server returned part type {t!r} outside acceptedOutputModes "
                f"{envelope.accepted_output_modes}; card is stale or handler drifted."
            )
