# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-resumable-sse-stream-as-dead-rather-than-resumable-the-last-event-id-elicitation-pending-boundary-in-mcp-streamable-http.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-resumable-sse-stream-as-dead-rather-than-resumable-the-last-event-id-elicitation-pending-boundary-in-mcp-streamable-http.warrant.json
# Markdown SHA-256:   d202ee97261e22167d94db3c4bcffb8b7f64166dd7d4862a3a76e305e3f2fe36
# Code AST SHA-256:   3afafc903a5dd75abed04fbc5cf6f128732704d2a8958f3d518fc56ef1784a08
# Verified Classes:   StaleElicitationError, UnknownPendingRequestError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleElicitationError(RuntimeError):
    """Raised when a replayed elicitation request is no longer live server-side."""


class UnknownPendingRequestError(RuntimeError):
    """Server rejected a submitted elicitation result because the request no longer exists."""


def resume_stream_and_reconcile(replayed_events, submit_response, now, submission_deadline):
    """
    Reconcile replayed SSE events after a reconnect.

    replayed_events: iterable of dicts with keys 'type', 'request_id', 'has_liveness_assertion'
    submit_response: callable(request_id, payload) -> raises UnknownPendingRequestError or returns ack
    """
    live_requests = []
    for ev in replayed_events:
        if ev["type"] != "elicitation/create":
            continue
        rid = ev["request_id"]
        if ev.get("has_liveness_assertion"):
            live_requests.append(rid)
            continue
        if now > submission_deadline:
            # Transport-resumable but session-dead: do not re-present.
            raise StaleElicitationError(
                f"replayed elicitation {rid} has no liveness assertion and is past deadline; "
                "treating stream as dead rather than resumable"
            )
        live_requests.append(rid)

    for rid in live_requests:
        try:
            submit_response(rid, {"confirm": True})
        except UnknownPendingRequestError as exc:
            # Terminal: do NOT re-resume to retry the elicitation.
            raise StaleElicitationError(
                f"elicitation {rid} rejected as unknown pending request; aborting interaction"
            ) from exc
    return live_requests
