# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-is-schema-compatible-but-capability-incompatible-at-delegation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-is-schema-compatible-but-capability-incompatible-at-delegation-time.warrant.json
# Markdown SHA-256:   ec0cc587e4b4b06d71064f6081f0e020f9dfe99995bf1de683941c3fbfa5e165
# Code AST SHA-256:   bedb9e03a5226debe3d0df96ba303323bae2ac8ffabe3cef21fbfde9f9f287d3
# Verified Classes:   CapabilityIncompatibilityError, AgentCard, Envelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal


class CapabilityIncompatibilityError(RuntimeError):
    """Raised when a card is schema-valid but the bound envelope is outside the enforced contract."""
    pass


@dataclass(frozen=True)
class AgentCard:
    version: str
    input_modes: frozenset[str]
    output_modes: frozenset[str]
    streaming: bool
    skill_ids: frozenset[str]


@dataclass(frozen=True)
class Envelope:
    skill_id: str | None
    parts_modes: frozenset[str]
    expects_stream: bool


def bind_envelope(card: AgentCard, env: Envelope, probe_passed: bool) -> Literal["delegate", "probe", "refuse"]:
    # Structural pass is assumed: caller has already validated the card schema.
    if not env.parts_modes <= card.input_modes:
        raise CapabilityIncompatibilityError(
            f"envelope modes {env.parts_modes} not subset of declared {card.input_modes}"
        )
    if env.skill_id is None and len(card.skill_ids) > 1:
        # Ambiguous skill -> remote classifier may re-route; must probe.
        return "probe"
    if env.skill_id is not None and env.skill_id not in card.skill_ids:
        raise CapabilityIncompatibilityError(
            f"pinned skill {env.skill_id!r} absent from card skills {card.skill_ids}"
        )
    if env.expects_stream and not card.streaming:
        raise CapabilityIncompatibilityError(
            "envelope requests stream but card advertises streaming:false"
        )
    if env.expects_stream and not probe_passed:
        # Streaming contract unverified: first-event window must be asserted.
        return "probe"
    if not probe_passed:
        return "probe"
    return "delegate"


def delegate(card: AgentCard, env: Envelope, probe_passed: bool) -> str:
    action = bind_envelope(card, env, probe_passed)
    if action == "refuse":
        raise CapabilityIncompatibilityError("delegation refused at bind time")
    if action == "probe":
        # Caller must run a narrowing probe before re-binding.
        raise CapabilityIncompatibilityError(
            "probe required before delegation: capability not yet narrowed"
        )
    return f"delegated skill={env.skill_id} version={card.version}"
