# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-advertises-an-a2a-agent-card-capability-it-cannot-honor-under-delegated-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-advertises-an-a2a-agent-card-capability-it-cannot-honor-under-delegated-authority.warrant.json
# Markdown SHA-256:   ebfc445b4047fbe9a532dd7b9a26f4705886ff1124d2ba56a9f51476b0d36820
# Code AST SHA-256:   bd7df2a11d2e7da04c60f3491726e08e6853b942e36e1a4d27e3b3fbd2103f69
# Verified Classes:   AgentCardContractError, AgentCard, TaskEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class AgentCardContractError(RuntimeError):
    """Raised when a callee's Agent Card is not a complete delegation contract."""


@dataclass(frozen=True)
class AgentCard:
    agent_id: str
    skills: tuple[str, ...]
    declared_scopes: frozenset[str] | None  # None == card omits authorization envelope


@dataclass(frozen=True)
class TaskEnvelope:
    task_id: str
    skill: str
    delegated_scopes: frozenset[str]


def preflight_delegation(
    card: AgentCard,
    envelope: TaskEnvelope,
    downstream_scope_closure: dict[str, Iterable[str]],
) -> None:
    """Refuse to send a task whose delegated authority cannot satisfy the skill.

    Enforces the decision boundary: the authorization envelope must be
    published on the card and must cover the skill's downstream closure.
    Deferring this check to execution produces unresolvable `input-required`
    tasks in A2A v1.0.
    """
    if envelope.skill not in card.skills:
        raise AgentCardContractError(
            f"agent {card.agent_id!r} does not declare skill {envelope.skill!r}"
        )

    if card.declared_scopes is None:
        raise AgentCardContractError(
            f"agent {card.agent_id!r} publishes no authorization envelope; "
            f"delegation under a narrowed token is unsafe for skill "
            f"{envelope.skill!r} (task {envelope.task_id!r} not sent)"
        )

    required = frozenset(downstream_scope_closure.get(envelope.skill, ()))
    missing = required - envelope.delegated_scopes
    if missing:
        raise AgentCardContractError(
            f"task {envelope.task_id!r}: delegated scopes "
            f"{sorted(envelope.delegated_scopes)} cannot satisfy downstream "
            f"closure {sorted(required)} for skill {envelope.skill!r}; "
            f"missing {sorted(missing)}. Re-mint the token before tasks/send — "
            f"do not accept and stall in 'working'."
        )


def send_task(
    card: AgentCard,
    envelope: TaskEnvelope,
    downstream_scope_closure: dict[str, Iterable[str]],
) -> str:
    preflight_delegation(card, envelope, downstream_scope_closure)
    return envelope.task_id
