# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-pin-the-a2a-agent-card-signature-jwk-kid-before-delegating-a-task-across-vendors.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-pin-the-a2a-agent-card-signature-jwk-kid-before-delegating-a-task-across-vendors.warrant.json
# Markdown SHA-256:   a85376eef820fbe7a09806636444463f8f2919353321937f274bbc5259a14290
# Code AST SHA-256:   14b9bc1a83016d603e29dd60abbea32d32334e96d73c9d20bd9dcb9dbb7c9bbd
# Verified Classes:   AgentCardBindingError, VerifiedCard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AgentCardBindingError(RuntimeError):
    """Raised when the card signer is not bound to the task endpoint operator."""
    pass


@dataclass(frozen=True)
class VerifiedCard:
    kid: str
    issuer: str
    endpoint_url: str
    endpoint_tls_san: str


def assert_signer_bound_to_endpoint(card: VerifiedCard) -> None:
    # The invariant: the kid that signed the card must be attributable to the
    # host that will actually execute tasks/send. We approximate the binding by
    # requiring the issuer identity to appear in the endpoint's TLS SAN.
    issuer_host = card.issuer.split("://")[-1].split("/")[0].lower()
    san = card.endpoint_tls_san.lower()
    if not issuer_host or issuer_host not in san:
        raise AgentCardBindingError(
            f"kid={card.kid!r} signed by issuer {card.issuer!r} is not bound to "
            f"endpoint {card.endpoint_url!r} (SAN={card.endpoint_tls_san!r}); "
            "refusing cross-vendor delegation to avoid silent capability downgrade"
        )


def delegate_task(card: VerifiedCard, payload: dict) -> str:
    assert_signer_bound_to_endpoint(card)
    # Only reached when signer and endpoint operator are the same principal.
    digest = hashlib.sha256(repr(sorted(payload.items())).encode()).hexdigest()
    return f"task-{digest[:16]}"


if __name__ == "__main__":
    good = VerifiedCard(
        kid="a-prod-2026-11",
        issuer="https://agent.vendor-a.example",
        endpoint_url="https://agent.vendor-a.example/a2a",
        endpoint_tls_san="agent.vendor-a.example",
    )
    print(delegate_task(good, {"skill": "summarize"}))

    bad = VerifiedCard(
        kid="a-prod-2026-11",
        issuer="https://agent.vendor-a.example",
        endpoint_url="https://gateway.vendor-b.example/a2a",
        endpoint_tls_san="gateway.vendor-b.example",
    )
    try:
        delegate_task(bad, {"skill": "summarize"})
    except AgentCardBindingError as exc:
        print(f"blocked: {exc}")
