# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-v1-0-agent-card-whose-capability-advertisement-diverges-from-the-delegated-task-s-declared-modality-a.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-v1-0-agent-card-whose-capability-advertisement-diverges-from-the-delegated-task-s-declared-modality-a.warrant.json
# Markdown SHA-256:   8ea1d62f786c2806bd0e4a619d6a9fdce617532d8d28a176fce212406e617d7f
# Code AST SHA-256:   12c912b9b272f2519ee1c0bc6cbe69cb8769ef25655b2f36f62ee0cf2feae996
# Verified Classes:   CapabilityEchoMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityEchoMismatch(RuntimeError):
    """Raised when a peer's working event does not echo the delegated modalities."""
    pass


def dispatch_delegated_task(client, peer_card, task):
    # Card is a hint, not a guarantee. Check eligibility only.
    if not set(task.input_modes).issubset(set(peer_card.default_input_modes)):
        raise CapabilityEchoMismatch(
            f"task modalities {task.input_modes} not advertised by {peer_card.url}"
        )

    # Send a probe (metadata-only) before streaming the payload.
    probe = client.tasks_send(peer_card, task, probe_only=True)
    working = probe.first_status_event(state="working")

    if working is None:
        raise CapabilityEchoMismatch(
            f"peer {peer_card.url} did not emit a working event for probe"
        )

    echoed = set(working.get("acceptedInputModes", []))
    if not set(task.input_modes).issubset(echoed):
        # Peer accepted optimistically but did not confirm modalities.
        # Fail closed: evict card, mark peer degraded, do not stream payload.
        client.cache.evict(peer_card.url)
        client.peers.mark_degraded(peer_card.url, reason="modality-echo-mismatch")
        raise CapabilityEchoMismatch(
            f"peer {peer_card.url} working event echoed {echoed or '<none>'}, "
            f"expected superset of {task.input_modes}"
        )

    # Only now is the delegation conformance-proven. Stream the payload.
    return client.tasks_send(peer_card, task, probe_only=False)
