# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-the-sse-resume-cursor-against-the-oauth-2-1-resource-metadata-resource-binding-when-an-mcp-server-migrates-a-session.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-the-sse-resume-cursor-against-the-oauth-2-1-resource-metadata-resource-binding-when-an-mcp-server-migrates-a-session.warrant.json
# Markdown SHA-256:   1241cd703fda9b53ea223f30858808ad29d38b97da48b27acdfff30a6218ff27
# Code AST SHA-256:   92630767ff765154209c0fc0c1841e8519d8af0eef0b52daca079650e07b2a46
# Verified Classes:   ForeignResumeCursorError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ForeignResumeCursorError(RuntimeError):
    """Raised when a Last-Event-ID cursor is presented to an endpoint
    whose OAuth 2.1 protected-resource `resource` identifier differs
    from the one under which the cursor was issued."""
    pass


def resume_stream(
    cursor_id: str,
    cursor_origin_resource: str,
    resume_endpoint_resource: str,
    token_audiences: list[str],
    client_checkpoint: dict,
) -> dict:
    """Decide whether to resume from server event log or cold-start.

    Returns a dict describing the resume plan. Raises
    ForeignResumeCursorError if the cursor crosses a resource boundary
    and the caller has not opted into a cold-start fallback.
    """
    if cursor_origin_resource != resume_endpoint_resource:
        # Cursor is foreign to this endpoint. Do NOT present it.
        if resume_endpoint_resource not in token_audiences:
            # Token also invalid for the new resource; caller must
            # re-authorize against the new AS before retrying.
            raise ForeignResumeCursorError(
                f"cursor {cursor_id!r} issued under {cursor_origin_resource!r} "
                f"cannot be resumed at {resume_endpoint_resource!r}; "
                f"token audiences {token_audiences!r} do not cover the new "
                f"resource — re-authorize against the endpoint's "
                f"authorization_servers before cold-starting"
            )
        # Token valid, cursor foreign: cold-start from client checkpoint.
        return {
            "action": "cold_start",
            "reason": "foreign_cursor",
            "from_checkpoint": client_checkpoint,
            "discarded_cursor": cursor_id,
        }

    # Same resource: cursor is replayable.
    return {
        "action": "resume",
        "last_event_id": cursor_id,
        "resource": resume_endpoint_resource,
    }
