# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capability-from-a-cached-agent-card-that-has-silently-drifted-from-the-live-a2a-endpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capability-from-a-cached-agent-card-that-has-silently-drifted-from-the-live-a2a-endpoint.warrant.json
# Markdown SHA-256:   fdd5429540891cc2aa3b0e20fe2cd7b985866e56bfee6fcfe892384d137693ca
# Code AST SHA-256:   61eb7b29722678a8a7b00e7ce6dc6431e6b6ab0c76be00e2c8411a9df5076fca
# Verified Classes:   CardEndpointDivergence, AgentCard, TaskResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class CardEndpointDivergence(RuntimeError):
    """Raised when a dispatched task's parameters exceed the peer's actual
    accepted domain despite validating against the peer's Agent Card."""
    pass


@dataclass
class AgentCard:
    skill_id: str
    declared_max_tokens: int | None  # None means card declares unbounded integer


@dataclass
class TaskResult:
    state: str            # "completed" | "failed" | "rejected"
    error_signal: str | None  # machine-readable hint, if any


CONSERVATIVE_DEFAULT_MAX_TOKENS = 4096


def negotiate_max_tokens(card: AgentCard, local_limit: int) -> int:
    """Clamp to the card's declared bound; never derive from local limit alone."""
    if card.declared_max_tokens is None:
        # Card is type-permissive; we must NOT send local_limit. Use conservative default.
        return min(CONSERVATIVE_DEFAULT_MAX_TOKENS, local_limit)
    return min(card.declared_max_tokens, local_limit)


def dispatch_with_renegotiation(
    card: AgentCard,
    local_limit: int,
    send_fn,
    refetch_card_fn,
) -> TaskResult:
    max_tokens = negotiate_max_tokens(card, local_limit)
    result = send_fn(card.skill_id, max_tokens)

    if result.state == "failed" and result.error_signal in (
        "PARAM_OUT_OF_RANGE",
        "MAX_TOKENS_EXCEEDED",
    ):
        # Deterministic parameter rejection: refetch, re-clamp, retry once.
        fresh = refetch_card_fn(card.skill_id)
        retry_max = negotiate_max_tokens(fresh, local_limit)
        if retry_max >= max_tokens:
            # Card still declares permissive; clamp did not shrink. Escalate.
            raise CardEndpointDivergence(
                f"skill={card.skill_id} rejected maxTokens={max_tokens} "
                f"but refetched card declares no tighter bound; "
                f"card-vs-endpoint divergence is unresolvable by renegotiation"
            )
        result = send_fn(card.skill_id, retry_max)

    if result.state == "failed" and result.error_signal is None:
        # No machine-readable signal: do NOT classify as transient by default.
        raise CardEndpointDivergence(
            f"skill={card.skill_id} failed without error_signal; "
            f"cannot distinguish transient from parameter rejection"
        )

    return result
