# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-capability-claim-in-an-a2a-v1-0-agent-card-when-the-remote-task-lifecycle-has-already-advanced-past-the-advertised.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-capability-claim-in-an-a2a-v1-0-agent-card-when-the-remote-task-lifecycle-has-already-advanced-past-the-advertised.warrant.json
# Markdown SHA-256:   d79afafc05f54c4c7665cac8816fbb55eaf8f4334141571f2a01b3771c6634a7
# Code AST SHA-256:   e26040e04c219b5b62af382e3dc6f8299087f033ef79df6152633e95c1b8c97c
# Verified Classes:   StaleCapabilityWarrantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleCapabilityWarrantError(RuntimeError):
    """Raised when a delegator attempts to resume a task using a mode
    authorized only by a stale AgentCard, not by the task's history."""
    pass


TERMINAL_STATES = {"completed", "failed", "canceled", "rejected"}


def resume_task(agent_card: dict, task: dict, payload_mode: str) -> dict:
    """
    Guard a cross-vendor resume against stale card warranty.

    agent_card: the AgentCard as re-fetched at resume time (may be stale).
    task:       the Task object from tasks/get, including status and history.
    payload_mode: the input mode the delegator intends to send.
    """
    state = task["status"]["state"]

    if state in TERMINAL_STATES:
        raise StaleCapabilityWarrantError(
            f"task {task['id']} is terminal ({state}); resume is not a valid "
            f"transition. Card advertised skill "
            f"{agent_card.get('skills', [{}])[0].get('id')} but that warrants "
            f"creation only, not continuation of a terminal task."
        )

    # The authoritative mode set is what the task has actually accepted,
    # not what the card advertises.
    accepted_modes = {
        entry["inputMode"]
        for entry in task.get("history", [])
        if entry.get("role") == "user" and "inputMode" in entry
    }

    if accepted_modes and payload_mode not in accepted_modes:
        raise StaleCapabilityWarrantError(
            f"task {task['id']} has only accepted input modes "
            f"{sorted(accepted_modes)}; delegator is sending {payload_mode!r} "
            f"based on card inputModes "
            f"{agent_card.get('skills', [{}])[0].get('inputModes')}. "
            f"Card is stale for this task; re-fetch or match history."
        )

    if state == "input-required":
        requested = task["status"].get("message", {}).get("requestedMode")
        if requested and requested != payload_mode:
            raise StaleCapabilityWarrantError(
                f"task {task['id']} is input-required for mode {requested!r}, "
                f"delegator prepared {payload_mode!r}. Card cannot override "
                f"the task's own input-required branch."
            )

    # Card is now used only as a negative filter: protocol version must match.
    if agent_card.get("protocolVersion") != "1.0":
        raise StaleCapabilityWarrantError(
            f"card protocolVersion {agent_card.get('protocolVersion')!r} "
            f"is not speakable by this delegator; resume aborted."
        )

    return {"taskId": task["id"], "mode": payload_mode, "state": state}
