# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-elicitation-response-loss-when-an-mcp-server-pushes-a-mid-task-prompt-and-the-client-reconnects-on-a-different-http-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-elicitation-response-loss-when-an-mcp-server-pushes-a-mid-task-prompt-and-the-client-reconnects-on-a-different-http-session.warrant.json
# Markdown SHA-256:   385097f90dc2d349ac1be430551e10ce2c0095ca48dbc99bdd38e9c396d9d051
# Code AST SHA-256:   f27adb901f6c3e2f03ef8dca9dd0ce94134ff66f59048284b1f73af824d0ce65
# Verified Classes:   ElicitationAttributionError, PendingElicitation, ElicitationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ElicitationAttributionError(RuntimeError):
    """Raised when an elicitation response cannot be bound to a pending,
    call-scoped prompt. This is a protocol-integrity failure, not a user
    decline: the response must not be applied to any tool call."""


class PendingElicitation:
    __slots__ = ("request_id", "tool_call_token")

    def __init__(self, request_id: str, tool_call_token: str) -> None:
        self.request_id = request_id
        self.tool_call_token = tool_call_token


class ElicitationLedger:
    """Client-side ledger: the only authority on which elicitation responses
    are valid. Keyed by the tool-call token the agent itself minted, so a
    server that re-mints request ids on reconnect cannot misroute answers."""

    def __init__(self) -> None:
        self._pending: dict[tuple[str, str], PendingElicitation] = {}

    def register(self, request_id: str, tool_call_token: str) -> None:
        self._pending[(tool_call_token, request_id)] = PendingElicitation(
            request_id, tool_call_token
        )

    def resolve(self, request_id: str, tool_call_token: str, answer: object) -> object:
        key = (tool_call_token, request_id)
        if key not in self._pending:
            # Server re-minted an id, routed by arrival order, or the
            # elicitation was already cancelled. Refuse to guess.
            raise ElicitationAttributionError(
                f"no pending elicitation for request_id={request_id!r} "
                f"tool_call_token={tool_call_token!r}; "
                f"pending={sorted(self._pending)}"
            )
        del self._pending[key]
        return answer

    def cancel(self, request_id: str, tool_call_token: str) -> None:
        self._pending.pop((tool_call_token, request_id), None)


def apply_elicitation_response(
    ledger: ElicitationLedger,
    request_id: str,
    tool_call_token: str,
    answer: object,
    *,
    server_replayed: bool,
) -> object:
    if server_replayed and answer is None:
        # Replay with no answer is a transport artifact, not a decision.
        # Do not collapse it into 'declined'.
        raise ElicitationAttributionError(
            "replayed elicitation arrived without an answer; "
            "treat as transport fault, not user decline"
        )
    return ledger.resolve(request_id, tool_call_token, answer)
