# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-delegated-authority-after-a-per-tool-scope-downgrade-in-a2a-oauth-2-1-token-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-delegated-authority-after-a-per-tool-scope-downgrade-in-a2a-oauth-2-1-token-exchange.warrant.json
# Markdown SHA-256:   4cbd4d7532b236a63e5f863255caf743d2911efd231d11c60661072c29288212
# Code AST SHA-256:   4ab23197158d9e145e5a186e92dbe642c21aec6556e00b7b4f67cb2b62f4357b
# Verified Classes:   AuthorityReducedError, DelegatedToken, ScopeAwareTokenCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Dict, Optional, Tuple


class AuthorityReducedError(RuntimeError):
    """Raised when a tool is dispatched with a token whose grant no longer
    covers the tool's required scope. Terminal for this tool under the
    current token; caller must re-derive the executable plan subset."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    subject: str
    audience: str
    scope: FrozenSet[str]
    raw: str = field(repr=False)

    def covers(self, required: FrozenSet[str]) -> bool:
        return required.issubset(self.scope)


class ScopeAwareTokenCache:
    """Cache keyed on (task, agent, scope) so a narrowed token from a
    mid-task exchange cannot be silently reused for a broader tool call."""

    def __init__(self) -> None:
        self._store: Dict[Tuple[str, str, FrozenSet[str]], DelegatedToken] = {}

    def put(self, task_id: str, agent_id: str, tok: DelegatedToken) -> None:
        self._store[(task_id, agent_id, tok.scope)] = tok

    def lookup_covering(
        self, task_id: str, agent_id: str, required: FrozenSet[str]
    ) -> Optional[DelegatedToken]:
        for (t, a, scope), tok in self._store.items():
            if t == task_id and a == agent_id and required.issubset(scope):
                return tok
        return None


def dispatch_tool(
    cache: ScopeAwareTokenCache,
    task_id: str,
    agent_id: str,
    tool: str,
    required_scope: FrozenSet[str],
) -> str:
    tok = cache.lookup_covering(task_id, agent_id, required_scope)
    if tok is None:
        # Distinguish "never had it" from "had it, then it was downgraded".
        any_token = any(
            t == task_id and a == agent_id
            for (t, a, _s) in cache._store
        )
        if any_token:
            raise AuthorityReducedError(
                f"tool={tool} requires={sorted(required_scope)} but no cached "
                f"token for ({task_id},{agent_id}) covers it; a mid-task "
                f"exchange narrowed the grant. Re-derive plan subset."
            )
        raise AuthorityReducedError(
            f"no delegated token for ({task_id},{agent_id}); cannot call {tool}"
        )
    # ... perform the actual tool call with tok.raw ...
    return f"dispatched {tool} with scope={sorted(tok.scope)}"


def exchange_and_cache(
    cache: ScopeAwareTokenCache,
    task_id: str,
    agent_id: str,
    requested: FrozenSet[str],
    granted: FrozenSet[str],
    raw: str,
) -> DelegatedToken:
    if not granted.issubset(requested):
        # AS granted more than requested: protocol violation, refuse.
        raise AuthorityReducedError(
            f"exchange granted {sorted(granted)} not subset of requested "
            f"{sorted(requested)}; refusing to cache"
        )
    tok = DelegatedToken(subject=agent_id, audience="downstream",
                         scope=granted, raw=raw)
    cache.put(task_id, agent_id, tok)
    return tok
