# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a2a-v1-0-capability-from-a-stale-agent-card-the-input-required-auth-required-task-state-divergence-across-ven.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a2a-v1-0-capability-from-a-stale-agent-card-the-input-required-auth-required-task-state-divergence-across-ven.warrant.json
# Markdown SHA-256:   54af8644feb86d94b1fc58ab80062f7ea4d637ff0d41a95cfe00c2becc181ca7
# Code AST SHA-256:   e48201f75fa95991841035f8dfe89ee700262c5e5a0bd280fcf29e2abd7d9bf4
# Verified Classes:   CardStateDivergenceError, TaskState, AgentCard, TaskUpdate, Client
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional

class CardStateDivergenceError(RuntimeError):
    """Raised when a task update's control message contradicts the cached Agent Card
    in a way that cannot be resolved without re-fetching the card."""
    pass

class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    AUTH_REQUIRED = "auth-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"

# States that are non-terminal and resumable; must never be mapped to local failure.
RESUMABLE = {TaskState.INPUT_REQUIRED, TaskState.AUTH_REQUIRED}

# Control-plane part types that are exempt from the card's inputModes check.
CONTROL_PART_TYPES = {
    "application/vnd.a2a.auth-required+json",
    "application/vnd.a2a.input-required+json",
}

@dataclass
class AgentCard:
    version: str
    input_modes: set
    streaming: bool

@dataclass
class TaskUpdate:
    state: TaskState
    part_types: list
    auth_scheme: Optional[str] = None
    card_version_seen: Optional[str] = None

@dataclass
class Client:
    cached_card: AgentCard
    card_ttl_expired: bool = False

    def validate_update(self, update: TaskUpdate) -> None:
        # 1. Control-plane parts are exempt from inputModes conformance.
        payload_parts = [p for p in update.part_types if p not in CONTROL_PART_TYPES]
        for p in payload_parts:
            if p not in self.cached_card.input_modes:
                # Payload modality outside card: must re-fetch, cannot trust cache.
                raise CardStateDivergenceError(
                    f"payload part {p!r} not in cached inputModes "
                    f"{self.cached_card.input_modes!r} (card v{self.cached_card.version})"
                )
        # 2. Resumable states must not be treated as terminal failure.
        if update.state in RESUMABLE:
            if update.auth_scheme is None and not self.card_ttl_expired:
                # Unknown control part with no explicit scheme: re-fetch required.
                raise CardStateDivergenceError(
                    f"state {update.state.value} with no auth scheme and "
                    f"unexpired card v{self.cached_card.version}; re-fetch before proceeding"
                )
            return  # accept; route to credential-refresh / human handler
        # 3. Streaming capability must be honored, not silently degraded.
        if update.state == TaskState.WORKING and not self.cached_card.streaming:
            # If the client opened a stream against a non-streaming card, that is
            # a client-side error, not a server fault.
            raise CardStateDivergenceError(
                "streaming reader opened against card with capabilities.streaming=false"
            )

    def handle(self, update: TaskUpdate) -> str:
        self.validate_update(update)
        if update.state in RESUMABLE:
            return "resume:awaiting_control_input"
        if update.state == TaskState.COMPLETED:
            return "done"
        return "in_progress"
