# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-remote-agent-card-s-declared-defaultinputmodes-defaultoutputmodes-as-non-binding-and-how-does-silent-ca.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-remote-agent-card-s-declared-defaultinputmodes-defaultoutputmodes-as-non-binding-and-how-does-silent-ca.warrant.json
# Markdown SHA-256:   6df2a62b7ea88c86eba8618eba9fa0812ae671223dae7e66df7f4585fc598895
# Code AST SHA-256:   77feb240b3df0ab296e986b6073fdf06b8b945cf84eba1f784bb3e8b8262633d
# Verified Classes:   CapabilityNarrowingError, TaskState, AgentCard, TaskStatus
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class CapabilityNarrowingError(RuntimeError):
    """Raised when a remote agent's input-required payload does not conform
    to its card-declared inputModes, indicating runtime capability narrowing."""
    pass


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


@dataclass
class AgentCard:
    input_modes: list[str]
    output_modes: list[str]
    card_version: str = "unknown"


@dataclass
class TaskStatus:
    state: TaskState
    parts: list[dict[str, Any]] = field(default_factory=list)


def _part_mime(part: dict[str, Any]) -> str | None:
    if "text" in part:
        return "text/plain"
    if "data" in part:
        return "application/json"
    if "file" in part:
        return part["file"].get("mimeType")
    return None


def handle_input_required(
    card: AgentCard,
    status: TaskStatus,
    remote_task_id: str,
    cancel_fn,
    refresh_card_fn,
) -> TaskState:
    """Transition handler for input-required. Distinguishes negotiation
    continuation from capability narrowing. Returns the next local state."""
    if status.state is not TaskState.INPUT_REQUIRED:
        raise CapabilityNarrowingError(
            f"handle_input_required called in state {status.state}"
        )

    declared = set(card.input_modes)
    observed = {_part_mime(p) for p in status.parts}
    observed.discard(None)

    if observed and observed.issubset(declared):
        # Negotiation continuation: payload conforms to card.
        return TaskState.WORKING

    # Capability narrowing: the remote agent is asking for something the
    # card said was already acceptable, or asking in a mode the card did
    # not declare. Cancel the remote task before mutating local state.
    try:
        cancel_fn(remote_task_id)
    except Exception as exc:
        raise CapabilityNarrowingError(
            f"failed to cancel orphaned remote task {remote_task_id}: {exc}"
        ) from exc

    refreshed = refresh_card_fn()
    if refreshed.input_modes == card.input_modes:
        # Card did not change; the narrowing is runtime-only and the
        # delegating agent cannot adapt. Terminal failure is correct,
        # but only after remote cancellation.
        return TaskState.FAILED

    # Card changed: re-evaluate with the new capability surface.
    if observed and observed.issubset(set(refreshed.input_modes)):
        return TaskState.WORKING

    raise CapabilityNarrowingError(
        f"remote task {remote_task_id} narrowed to {sorted(observed)}; "
        f"card now declares {sorted(refreshed.input_modes)}; no viable path"
    )
