# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-task-in-a-foreign-agent-card-s-acceptedinputmodes-but-silently-drop-binary-payloads-at-the-first-message-send.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-task-in-a-foreign-agent-card-s-acceptedinputmodes-but-silently-drop-binary-payloads-at-the-first-message-send.warrant.json
# Markdown SHA-256:   7378708560fa21420e887004bf31bfe68d702755388022cbdbe449d6933ec05d
# Code AST SHA-256:   168daa71d74be8d5d85a4061e5e0120918754622fe2bb1431b06244e74902533
# Verified Classes:   ModalityAcceptanceError, TaskHandle
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ModalityAcceptanceError(RuntimeError):
    """Raised when a task envelope is accepted but the modality is not
    confirmed before the client releases its source payload."""
    pass


@dataclass
class TaskHandle:
    task_id: str
    card_input_modes: list[str]
    source_parts: list[dict] = field(default_factory=list)
    payload_released: bool = False
    modality_confirmed: bool = False


def send_task(client, remote_card: dict, parts: list[dict],
              deadline_s: float = 30.0) -> TaskHandle:
    declared = set(remote_card.get("defaultInputModes", []))
    for p in parts:
        mt = p.get("mimeType")
        if mt and mt not in declared:
            # Pre-flight: card does not even advertise it. Reject locally.
            raise ModalityAcceptanceError(
                f"mime {mt!r} not in card defaultInputModes {sorted(declared)}"
            )

    resp = client.rpc("tasks/send", {"message": {"parts": parts}})
    if "error" in resp.get("result", {}):
        # JSON-RPC error embedded in 200 body — the silent-413 case.
        raise ModalityAcceptanceError(
            f"envelope-level error: {resp['result']['error']}"
        )

    handle = TaskHandle(
        task_id=resp["result"]["id"],
        card_input_modes=sorted(declared),
        source_parts=parts,
    )

    # CRITICAL: do NOT release payload on envelope ack. Hold until we see
    # a status event that is not input-required naming a modality defect.
    t0 = time.monotonic()
    while time.monotonic() - t0 < deadline_s:
        ev = client.poll_status(handle.task_id)
        state = ev.get("state")
        if state == "working" or state == "completed":
            handle.modality_confirmed = True
            handle.payload_released = True  # safe now
            return handle
        if state == "input-required":
            msg = ev.get("message", "")
            if "mimeType" in msg or "part" in msg.lower():
                # Modality falsified post-envelope; card match was provisional.
                raise ModalityAcceptanceError(
                    f"task {handle.task_id} entered input-required for modality "
                    f"defect: {msg!r}; card advertised {handle.card_input_modes} "
                    f"but compound-part precondition unmet"
                )
            # Otherwise it's genuine user input; keep payload, escalate.
            return handle
        if state == "failed":
            raise ModalityAcceptanceError(
                f"task {handle.task_id} failed before modality confirmation"
            )
        time.sleep(0.5)

    if not handle.modality_confirmed and not handle.payload_released:
        raise ModalityAcceptanceError(
            f"task {handle.task_id} never confirmed modality within {deadline_s}s; "
            f"source payload still held — do not cache as compatible"
        )
    return handle
