# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-capability-negotiation-when-the-requested-tool-grant-exceeds-the-delegating-agent-s-own-residual-authority-a.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-capability-negotiation-when-the-requested-tool-grant-exceeds-the-delegating-agent-s-own-residual-authority-a.warrant.json
# Markdown SHA-256:   e6be99ea496a1ffa8775d6c2abf70cad839552ec951670af5207bd38d5c74aa5
# Code AST SHA-256:   8d7c8b613553fe5e457baddf46879223a0102ec659e3619e4c7b01caefe70174
# Verified Classes:   CapabilityExhaustedError, GrantLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CapabilityExhaustedError(RuntimeError):
    """Raised when residual authority is insufficient for the requested amount.

    Distinct from a plain denial: the capability *is* the orchestrator's to
    grant, but prior outstanding grants have consumed the budget. Callers
    should escalate upward or accept the counter-offer, not retry unchanged.
    """


@dataclass
class GrantLedger:
    total_budget: int
    outstanding: dict = field(default_factory=dict)  # agent_id -> amount

    def residual(self) -> int:
        return self.total_budget - sum(self.outstanding.values())


def negotiate_grant(ledger: GrantLedger, agent_id: str, requested: int) -> int:
    """Return the amount actually granted, or raise if residual is zero.

    Enforces the residual invariant: sum(outstanding) + granted <= total_budget.
    Counter-offers the residual amount when the full request cannot be met.
    """
    if requested <= 0:
        raise ValueError("requested amount must be positive")

    remaining = ledger.residual()

    if remaining <= 0:
        # Capability is ours to give but fully delegated. Escalate, don't deny.
        raise CapabilityExhaustedError(
            f"capability exhausted: budget={ledger.total_budget} "
            f"outstanding={ledger.outstanding} residual=0; "
            f"agent {agent_id!r} must escalate to parent authority"
        )

    granted = min(requested, remaining)  # partial counter-offer
    ledger.outstanding[agent_id] = ledger.outstanding.get(agent_id, 0) + granted
    return granted


def release_grant(ledger: GrantLedger, agent_id: str, amount: int) -> None:
    held = ledger.outstanding.get(agent_id, 0)
    if amount > held:
        raise ValueError(f"release of {amount} exceeds held {held} for {agent_id!r}")
    if amount == held:
        del ledger.outstanding[agent_id]
    else:
        ledger.outstanding[agent_id] = held - amount
