# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-late-bound-agent-card-capability-that-is-only-valid-within-a-task-scoped-negotiation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-late-bound-agent-card-capability-that-is-only-valid-within-a-task-scoped-negotiation-window.warrant.json
# Markdown SHA-256:   e9c8477f570d59f3abb10b3b0141edd4615058791e04ee46b83a98947b391286
# Code AST SHA-256:   92334e2fc26bcc26b0c30692cb59e907d97a2842f0301cca5906317e56238ae9
# Verified Classes:   NegotiationWindowError, AgentCard, TaskRef
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class NegotiationWindowError(RuntimeError):
    """Raised when a card-advertised capability is used outside its valid negotiation window."""
    pass


@dataclass
class AgentCard:
    etag: str
    streaming: bool
    push_notifications: bool
    served_by_executor: bool  # True only if card server == executor process


@dataclass
class TaskRef:
    task_id: str
    card_etag_at_send: str
    opened_at: float


def negotiate_streaming(
    card: AgentCard,
    task: TaskRef,
    first_frame_deadline_s: float = 5.0,
    frame_clock=time.monotonic,
) -> bool:
    """
    Decide whether to commit to the streaming channel for `task`.

    Returns True only if the capability is positively confirmed by a first frame
    within the deadline, OR the card is served by the executor itself (monotonic).
    Raises NegotiationWindowError when the window has expired or the card is stale
    relative to the task, so the caller must reconcile via tasks/get instead of
    re-issuing tasks/send with a fresh taskId.
    """
    if not card.streaming:
        return False

    # Card must match the version negotiated at send time.
    if card.etag != task.card_etag_at_send:
        raise NegotiationWindowError(
            f"card etag {card.etag!r} != task-bound etag "
            f"{task.card_etag_at_send!r} for task {task.task_id!r}; "
            "re-fetch card only for NEW tasks, reconcile this task via tasks/get"
        )

    # Homogeneous runtime: card and executor share lifecycle -> trust the card.
    if card.served_by_executor:
        return True

    # Heterogeneous runtime: capability is advisory; require positive confirmation.
    start = frame_clock()
    while frame_clock() - start < first_frame_deadline_s:
        if _first_frame_received(task.task_id):
            return True
        time.sleep(0.05)

    raise NegotiationWindowError(
        f"no streaming frame for task {task.task_id!r} within "
        f"{first_frame_deadline_s}s; do NOT re-issue with a new taskId -- "
        "issue tasks/get to read terminality from the store"
    )


def _first_frame_received(task_id: str) -> bool:
    # Placeholder: real implementation polls the transport's frame buffer.
    return False
