# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-v1-0-agent-card-whose-declared-capabilities-streaming-and-defaultinputmodes-diverge-from-the-task-payl.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-v1-0-agent-card-whose-declared-capabilities-streaming-and-defaultinputmodes-diverge-from-the-task-payl.warrant.json
# Markdown SHA-256:   c4b94e0000f9f0cffcf4a8a7a56e30489f748f870b29d18c3b45e7e8b96e71f3
# Code AST SHA-256:   a25afd05f0cdc7dc22580d419a6fd11ef4af44f4cd619cbf9ca1af018fc6af7f
# Verified Classes:   CardHandlerDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CardHandlerDivergence(RuntimeError):
    """Raised when a task was constructed from a card snapshot that no longer
    matches the remote handler's enforced contract. This is NOT a transport
    error and NOT a malformed-request error; it is a remote-contract-drift
    signal that must not trigger task retry for side-effecting skills."""
    pass


def dispatch_task(card_snapshot: dict, task_payload: dict, skill_id: str,
                  side_effecting: bool, card_age_seconds: float,
                  card_ttl_seconds: float) -> dict:
    # Precondition: the card we are about to trust must still be within its
    # declared freshness window. A2A v1.0 gives us no digest binding, so TTL
    # is the only proxy we have for "handler and card are the same build."
    if card_age_seconds > card_ttl_seconds:
        raise CardHandlerDivergence(
            f"card snapshot for skill={skill_id!r} is {card_age_seconds:.0f}s old, "
            f"exceeds ttl={card_ttl_seconds:.0f}s; refusing dispatch because "
            f"handler may have redeployed without regenerating the card"
        )

    # Precondition: payload media type must be in the skill's declared input
    # modes AND the card must declare streaming if we intend to use it.
    part_modes = {p.get("mediaType") for p in task_payload.get("parts", [])}
    declared = set(card_snapshot.get("skills", [{}])[0].get("inputModes", []))
    if not part_modes.issubset(declared):
        raise CardHandlerDivergence(
            f"payload media types {part_modes} not subset of declared "
            f"{declared} for skill={skill_id!r}; card may be stale"
        )

    if side_effecting and not card_snapshot.get("capabilities", {}).get("streaming"):
        # Non-idempotent skill without streaming means we cannot observe
        # partial progress; a stream-EOF-before-terminal would be
        # indistinguishable from success. Refuse rather than risk duplicate.
        raise CardHandlerDivergence(
            f"side-effecting skill={skill_id!r} requires streaming for "
            f"progress observability; card declares streaming=false"
        )

    # ... actual dispatch, with the card snapshot persisted alongside task id ...
    return {"task_id": "t-...", "state": "submitted",
            "card_snapshot_digest": hash(frozenset(card_snapshot.items()))}
