# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-agent-silently-exceed-its-capability-scope-when-a-token-exchange-refreshes-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-agent-silently-exceed-its-capability-scope-when-a-token-exchange-refreshes-mid-task.warrant.json
# Markdown SHA-256:   ec61efa209f73ab32224d5e02128d2110d4cd66de08556113414b168fccdbcda
# Code AST SHA-256:   35dadb584b4a8cfbdd293a45a819f7865c29a2761183ffc0d1e85710f04f1725
# Verified Classes:   ScopeWideningOnRefresh, CapabilityHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class ScopeWideningOnRefresh(RuntimeError):
    """Raised when a refreshed capability token exceeds the scope it was minted with."""
    pass

@dataclass
class CapabilityHandle:
    name: str
    granted_scope: FrozenSet[str]          # authoritative base for refresh
    token: str = ""
    issued_at: float = 0.0

    def accept_refresh(self, new_token: str, new_scope: FrozenSet[str], now: float) -> None:
        # Invariant: refresh must never widen the capability envelope.
        if not new_scope.issubset(self.granted_scope):
            extra = new_scope - self.granted_scope
            raise ScopeWideningOnRefresh(
                f"capability {self.name!r} refreshed with scope {sorted(new_scope)} "
                f"which exceeds minted scope {sorted(self.granted_scope)}; "
                f"unexpected privileges: {sorted(extra)}. "
                f"Aborting step: planner authorization model is stale."
            )
        self.token = new_token
        self.issued_at = now

def guarded_tool_call(handle: CapabilityHandle, required: FrozenSet[str], call) -> object:
    # Pre-flight: the agent may only invoke tools inside its *minted* scope,
    # regardless of what the live token happens to permit.
    if not required.issubset(handle.granted_scope):
        raise ScopeWideningOnRefresh(
            f"tool requires {sorted(required)} but capability {handle.name!r} "
            f"was minted for {sorted(handle.granted_scope)}"
        )
    return call(handle.token)
