# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-a2a-task-because-the-remote-agent-card-s-declared-capabilities-are-structurally-satisfiable-but.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-a2a-task-because-the-remote-agent-card-s-declared-capabilities-are-structurally-satisfiable-but.warrant.json
# Markdown SHA-256:   da6317a66ab535f4524ee1065d1666e6af28b0f79a7d7da78d276384fa3516d7
# Code AST SHA-256:   f1fa8e713a7714b5781698b6d1e7d79a37cfc69affb37714da390b1475639368
# Verified Classes:   StaleCapabilityAssertion
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleCapabilityAssertion(RuntimeError):
    """Raised when a remote Agent Card asserts a capability boolean that the
    executing instance has not confirmed for the current task, and the
    workload is long enough that mid-stream failure would strand state."""
    pass


def preflight_delegation(
    resolved_card: dict,
    acceptance_response: dict,
    expected_tokens: int,
    unrecoverable_token_threshold: int = 2000,
) -> None:
    """Enforce the capability-probe invariant before committing a long task.

    resolved_card: the Agent Card fetched from /.well-known/agent.json
    acceptance_response: the Task / first TaskStatusUpdateEvent returned by
        the remote after opening the stream.
    """
    caps = resolved_card.get("capabilities", {})
    depends_on_history = bool(caps.get("stateTransitionHistory"))
    long_task = expected_tokens >= unrecoverable_token_threshold

    if not (depends_on_history and long_task):
        return  # short task or no history dependency: card check is adequate

    # Binding check: does the executor echo the card version it is running?
    executor_card_etag = acceptance_response.get("metadata", {}).get("cardEtag")
    resolved_card_etag = resolved_card.get("etag")

    if executor_card_etag is None:
        # No binding. Caller cannot prove the executor matches the card.
        # For a long task that relies on history, this is a hard stop.
        raise StaleCapabilityAssertion(
            "Remote accepted a long task requiring stateTransitionHistory "
            "but did not echo a card etag; capability boolean is unbound to "
            "the executing instance and may be stale. Refusing to spend "
            f"{expected_tokens} tokens on an unconfirmed recovery path. "
            "Issue a probe task or downgrade to message/send with an "
            "explicit checkpoint contract."
        )

    if executor_card_etag != resolved_card_etag:
        raise StaleCapabilityAssertion(
            "Executor card etag "
            f"{executor_card_etag!r} != resolved card etag "
            f"{resolved_card_etag!r}; the well-known card is a stale "
            "artifact and its capability booleans do not describe the "
            "executor that will run this task."
        )


def delegate(remote, task_payload: dict, expected_tokens: int):
    card = remote.resolve_card()  # may be CDN-cached; treat as claim
    stream = remote.open_stream(task_payload)
    acceptance = stream.first_event()
    preflight_delegation(card, acceptance, expected_tokens)
    return stream.drain()
