# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-negotiate-sse-to-post-upgrade-after-a-streamable-session-resume-and-why-does-the-naive-replay-silently-duplicate-tool-side-e.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-negotiate-sse-to-post-upgrade-after-a-streamable-session-resume-and-why-does-the-naive-replay-silently-duplicate-tool-side-e.warrant.json
# Markdown SHA-256:   28d965a432449d29b50ac1084bfccfe7c6eea39a000f686b0e55802c01e1c9f5
# Code AST SHA-256:   b3b7a26a8c8d30abf581e0439e16a7defd81c7ac63318f32c81347caf53bb1d0
# Verified Classes:   ResumeReplayAmbiguity
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ResumeReplayAmbiguity(RuntimeError):
    """Raised when a stream resume cannot prove whether an in-flight
    mutating tools/call was already executed server-side."""
    pass


NON_IDEMPOTENT_TOOLS = frozenset({"write_file", "exec", "send_email", "delete"})


def safe_resume_retry(
    tool_name: str,
    jsonrpc_id: str,
    last_event_id: int,
    server_caps: dict,
    outstanding: bool,
) -> str:
    """Decide whether re-POSTing an in-flight call after a stream resume is safe.

    Returns the action to take: 'retry', 'probe', or 'escalate'.
    Raises ResumeReplayAmbiguity when the call is mutating, outstanding,
    and the server has not advertised id-keyed dedup.
    """
    if not outstanding:
        return "retry"

    idempotent = tool_name not in NON_IDEMPOTENT_TOOLS
    dedup = bool(server_caps.get("tools", {}).get("idempotentRetry", False))

    if idempotent:
        return "retry"

    if dedup:
        # Server keys execution on (session_id, jsonrpc_id); replay is safe.
        return "retry"

    # Mutating, outstanding, no dedup guarantee: we cannot know if the
    # server already committed the side effect before the stream died.
    # last_event_id only bounds the *stream*, not the *execution*.
    raise ResumeReplayAmbiguity(
        f"tool={tool_name!r} id={jsonrpc_id!r} last_event_id={last_event_id} "
        f"is outstanding across a stream resume with no id-keyed dedup; "
        f"re-POST risks duplicate side effect. Probe outcome before retrying."
    )


def resume_session(
    tool_name: str,
    jsonrpc_id: str,
    last_event_id: int,
    server_caps: dict,
    outstanding: bool,
) -> str:
    try:
        return safe_resume_retry(
            tool_name, jsonrpc_id, last_event_id, server_caps, outstanding
        )
    except ResumeReplayAmbiguity as exc:
        # Downgrade to probe: read the affected resource, do not re-POST.
        return f"probe: {exc}"
