The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(providers): expose plugin account usage hook
KoNit-K400b6c41cd43
diff --git a/agent/account_usage.py b/agent/account_usage.pyindex e8c31a92004..f94d410f881 100644--- a/agent/account_usage.py+++ b/agent/account_usage.py@@ -640,6 +640,11 @@ def fetch_account_usage() -> Optional[AccountUsageSnapshot]:fetcher = _USAGE_FETCHERS.get(str(provider or "").strip().lower())try:- return fetcher(base_url, api_key) if fetcher else None+ if fetcher:+ return fetcher(base_url, api_key)+ from providers import get_provider_profile++ profile = get_provider_profile(str(provider or "").strip().lower())+ return profile.fetch_account_usage(base_url=base_url, api_key=api_key) if profile else Noneexcept Exception:return Nonediff --git a/providers/base.py b/providers/base.pyindex 9a275fc0dee..91859963f22 100644--- a/providers/base.py+++ b/providers/base.py@@ -13,6 +13,10 @@ from __future__ import annotationsimport loggingfrom dataclasses import dataclass, field+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from agent.account_usage import AccountUsageSnapshotfrom typing import Any, Callablelogger = logging.getLogger(__name__)@@ -125,6 +129,18 @@ class ProviderProfile:# ── Hooks (override in subclass for complex providers) ───+ def fetch_account_usage(+ self, *, base_url: str | None = None, api_key: str | None = None+ ) -> AccountUsageSnapshot | None:+ """Return an account-usage snapshot for this provider, if available.++ The ``/usage`` command invokes this only when no built-in account+ usage fetcher owns the provider. Implementations may make their+ provider-specific request and must return an ``AccountUsageSnapshot``+ or ``None``; exceptions fail open at the dispatch boundary.+ """+ return None+def resolve_aux_model(self, *, vision: bool = False) -> str:"""Return a LIVE cheap-model id for auxiliary tasks, or "".diff --git a/tests/agent/test_account_usage_fetch.py b/tests/agent/test_account_usage_fetch.pyindex 072dc21c6f2..9debb8469b8 100644--- a/tests/agent/test_account_usage_fetch.py+++ b/tests/agent/test_account_usage_fetch.py@@ -6,6 +6,21 @@ from agent.account_usage import (fetch_account_usage,render_account_usage_lines,)+from providers.base import ProviderProfile+++class _UsageProfile(ProviderProfile):+ def __init__(self, snapshot=None, error=None):+ super().__init__(name="plugin-usage")+ self.snapshot = snapshot+ self.error = error+ self.calls = 0++ def fetch_account_usage(self, *, base_url=None, api_key=None):+ self.calls += 1+ if self.error:+ raise self.error+ return self.snapshotclass _Response:@@ -95,6 +110,38 @@ def test_fetch_account_usage_codex(monkeypatch):assert "Credits balance: $12.50" in snapshot.details+def test_fetch_account_usage_uses_provider_profile_hook(monkeypatch):+ snapshot = AccountUsageSnapshot(+ provider="plugin-usage", source="plugin", fetched_at=datetime.now(timezone.utc),+ details=("Credit: 10/100",),+ )+ profile = _UsageProfile(snapshot)+ monkeypatch.setattr("providers.get_provider_profile", lambda name: profile)++ assert fetch_account_usage("plugin-usage", base_url="https://plugin.test", api_key="key") is snapshot+ assert profile.calls == 1+++def test_fetch_account_usage_profile_hook_fails_open(monkeypatch):+ monkeypatch.setattr("providers.get_provider_profile", lambda name: _UsageProfile(error=RuntimeError("nope")))++ assert fetch_account_usage("plugin-usage") is None+++def test_fetch_account_usage_prefers_builtin_fetcher_over_profile(monkeypatch):+ builtin = AccountUsageSnapshot(+ provider="openrouter", source="builtin", fetched_at=datetime.now(timezone.utc),+ )+ profile = _UsageProfile(+ AccountUsageSnapshot(provider="openrouter", source="plugin", fetched_at=datetime.now(timezone.utc))+ )+ monkeypatch.setattr("agent.account_usage._USAGE_FETCHERS", {"openrouter": lambda base_url, api_key: builtin})+ monkeypatch.setattr("providers.get_provider_profile", lambda name: profile)++ assert fetch_account_usage("openrouter") is builtin+ assert profile.calls == 0++def test_render_account_usage_lines_includes_reset_and_provider():snapshot = AccountUsageSnapshot(provider="openai-codex",diff --git a/website/docs/developer-guide/model-provider-plugin.md b/website/docs/developer-guide/model-provider-plugin.mdindex 5c2507d3920..04e626c88f7 100644--- a/website/docs/developer-guide/model-provider-plugin.md+++ b/website/docs/developer-guide/model-provider-plugin.md@@ -146,6 +146,14 @@ class AcmeProfile(ProviderProfile):(Bedrock → None), or public/unauthenticated catalogs (OpenRouter)."""return super().fetch_models(api_key=api_key, base_url=base_url, timeout=timeout)+ def fetch_account_usage(self, *, api_key=None, base_url=None):+ """Return AccountUsageSnapshot for /usage, or None when unavailable.++ The hook runs only when the provider has no built-in usage fetcher.+ It may raise: core catches failures and keeps /usage empty for that turn.+ """+ return None+def create_client(self, **client_kwargs):"""Supply your own client object instead of the shared openai.OpenAI.Default returns None (= use the standard client). Override when the@@ -157,6 +165,30 @@ class AcmeProfile(ProviderProfile):return None```+## Account usage++Model-provider plugins can provide account or plan usage to `/usage` by+overriding `ProviderProfile.fetch_account_usage`. Import and return the shared+`agent.account_usage.AccountUsageSnapshot` (with any `AccountUsageWindow`+entries); do not format output in the plugin. Returning `None`, or raising an+exception, leaves `/usage` empty just as it does for providers without usage+data. Built-in usage fetchers always take precedence, so this hook cannot+replace the account-usage behavior for a built-in provider.++```python+from datetime import datetime, timezone++from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow++def fetch_account_usage(self, *, api_key=None, base_url=None):+ return AccountUsageSnapshot(+ provider=self.name,+ source="my_provider_api",+ fetched_at=datetime.now(timezone.utc),+ windows=(AccountUsageWindow(label="Monthly", used_percent=25),),+ )+```+## External-process (ACP) providersAn agent CLI driven over stdio is not an HTTP endpoint. Set `auth_type="external_process"`, describe how to launch the binary, and supply the client with `create_client`. No core edits are needed — `hermes -m <name>`, `/model`, credential resolution, runtime resolution and the auxiliary client (compression, vision) all key on `auth_type`, not on the provider name. `plugins/model-providers/copilot-acp/` is the in-tree example.