# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-tool-session-when-an-mcp-http-native-streamable-transport-upgrades-sse-to-a-resumable-stream-mid-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-tool-session-when-an-mcp-http-native-streamable-transport-upgrades-sse-to-a-resumable-stream-mid-negotiation.warrant.json
# Markdown SHA-256:   4f6620f921accc1638e2fa376797ba4487720b23c0936ac10f047c5e911ea936
# Code AST SHA-256:   9e3ea47895ad51fd1e6fc246af4f629d376310cc708e5f7ac6eb6f9b243df1bf
# Verified Classes:   CapabilityEpochMismatch, UnknownStreamEventType
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityEpochMismatch(RuntimeError):
    """Raised when a resumable MCP stream reconnect carries a Last-Event-ID
    whose capability epoch does not match the session's bound epoch."""
    pass


class UnknownStreamEventType(RuntimeError):
    """Raised when an SSE event type is not in the negotiated allowlist,
    which during an upgrade window indicates a dropped upgrade marker."""
    pass


# Allowlist of SSE event types the client understands. Anything outside this
# set during a reconnect window is a dropped signal, not noise.
KNOWN_EVENT_TYPES = frozenset({"message", "ping", "upgrade", "capabilities"})


def resume_stream(
    session_id: str,
    last_event_id: int,
    request_capability_epoch: int,
    session_bound_epoch: int,
    first_event_after_resume: dict,
) -> dict:
    """Validate a resumable-stream upgrade before consuming any replayed event.

    Returns the authoritative capability set to use for the resumed stream.
    Raises if the epoch is inconsistent or the upgrade marker was dropped.
    """
    if request_capability_epoch != session_bound_epoch:
        raise CapabilityEpochMismatch(
            f"session {session_id}: reconnect at Last-Event-ID={last_event_id} "
            f"carries capability_epoch={request_capability_epoch} but session "
            f"is bound to epoch={session_bound_epoch}; refusing resume to avoid "
            f"silent capability regression"
        )

    event_type = first_event_after_resume.get("event", "message")
    if event_type not in KNOWN_EVENT_TYPES:
        raise UnknownStreamEventType(
            f"session {session_id}: first event after resume has unknown type "
            f"{event_type!r}; upgrade marker likely dropped, refusing to replay "
            f"to avoid duplicate side-effecting tool calls"
        )

    if event_type == "capabilities":
        # Server re-emitted capabilities at the resume point: authoritative.
        return first_event_after_resume["data"]

    # No capabilities event: fall back to conservative default set and
    # require the caller to re-issue initialize if non-default caps are needed.
    return {"tools": {"listChanged": False}, "streamed_tool_results": False}
