Skip to content

The agent that grows with you

refactor(agent/context_references,billing_*): unify path/binary checks and _parse_* helpers (1492->1118 LOC)

Teknium315e29160937
diff --git a/agent/billing_links.py b/agent/billing_links.py
index d38cbc4bdd7..3e98efd376f 100644
--- a/agent/billing_links.py
+++ b/agent/billing_links.py
@@ -1,10 +1,8 @@
-"""Provider-agnostic billing/credit recovery links.
+"""Provider-agnostic billing/credit recovery links for billing-classified failures.
-Maps a billing-classified failure onto a recovery link + label. *Detection* is
-:mod:`agent.error_classifier` (``FailoverReason.billing``), the single source of
-truth for "credit wall vs. rate limit / auth / transport". The :class:`BillingBlock`
-rides the turn result and the gateway ``message.complete`` event so every surface
-renders one structured signal instead of re-parsing error text.
+Detection lives in :mod:`agent.error_classifier` (``FailoverReason.billing``); the
+:class:`BillingBlock` rides the turn result and the gateway ``message.complete`` event
+so every surface renders one structured signal instead of re-parsing error text.
"""
from __future__ import annotations
@@ -17,12 +15,9 @@ from utils import base_url_host_matches
@dataclass
class BillingBlock:
- """Structured billing-wall descriptor shared across every surface.
-
- ``is_nous`` is the routing bit: Nous has an in-app billing surface (desktop
- Settings → Billing, TUI/CLI ``/topup``) preferred over ``billing_url``;
- third-party providers have none, so ``billing_url`` is the deep link needed.
- """
+ """Structured billing-wall descriptor shared across every surface. ``is_nous`` is the routing bit:
+ Nous has an in-app billing surface (Settings → Billing, ``/topup``) preferred over ``billing_url``;
+ third-party providers have none, so ``billing_url`` is the deep link needed."""
provider: str
provider_label: str
@@ -43,10 +38,9 @@ class _Provider:
hosts: tuple[str, ...] = ()
-# Single source of truth: slug(s) + base_url host(s) → curated "add credits"
-# page (not marketing homes). Hosts back the OpenAI-compatible fallback where the
-# slug is a generic bucket but base_url reveals the real upstream. Unknown
-# providers degrade to a readable label with no invented URL.
+# Single source of truth: slug(s) + base_url host(s) → curated "add credits" page.
+# Hosts back the OpenAI-compatible fallback where the slug is a generic bucket but
+# base_url reveals the real upstream. Unknown providers get a readable label, no URL.
_PROVIDERS: tuple[_Provider, ...] = (
_Provider("OpenAI", "https://platform.openai.com/settings/organization/billing", ("openai",), ("api.openai.com",)),
_Provider("Anthropic", "https://console.anthropic.com/settings/billing", ("anthropic",), ("api.anthropic.com",)),
@@ -69,9 +63,7 @@ _BY_SLUG: dict[str, _Provider] = {slug: p for p in _PROVIDERS for slug in p.slug
def is_nous_inference_route(provider: str, base_url: str) -> bool:
"""True when the failing route is the Nous-managed inference gateway."""
- return (provider or "").strip().lower() == "nous" or base_url_host_matches(
- str(base_url or ""), "inference-api.nousresearch.com"
- )
+ return (provider or "").strip().lower() == "nous" or base_url_host_matches(str(base_url or ""), "inference-api.nousresearch.com")
def _nous_billing_url() -> Optional[str]:
@@ -85,23 +77,17 @@ def _nous_billing_url() -> Optional[str]:
def _resolve_provider_link(slug: str, base_url: str) -> tuple[str, Optional[str]]:
"""Resolve ``(label, url)``: exact slug → base_url host → readable-label fallback."""
- hit = _BY_SLUG.get(slug)
+ base = str(base_url or "")
+ hit = _BY_SLUG.get(slug) or next(
+ (p for p in _PROVIDERS if any(base_url_host_matches(base, host) for host in p.hosts)), None
+ )
if hit:
return hit.label, hit.url
- base = str(base_url or "")
- for p in _PROVIDERS:
- if any(base_url_host_matches(base, host) for host in p.hosts):
- return p.label, p.url
return slug.replace("_", " ").replace("-", " ").strip().title() or "your provider", None
def build_billing_block(*, provider: str, base_url: str, model: str, message: str = "") -> BillingBlock:
- """Build the billing descriptor for a billing-classified failure.
-
- ``message`` is the guidance already assembled by the agent loop
- (:func:`agent.conversation_loop._billing_or_entitlement_message`), carried
- through unchanged so every surface shows identical copy.
- """
+ """Billing descriptor for a billing-classified failure; ``message`` (agent-loop guidance) passes through unchanged."""
slug = (provider or "").strip().lower()
model = (model or "").strip()
if is_nous_inference_route(slug, base_url):
diff --git a/agent/billing_usage.py b/agent/billing_usage.py
index 2722429fc2d..1a9f9f5a257 100644
--- a/agent/billing_usage.py
+++ b/agent/billing_usage.py
@@ -1,18 +1,11 @@
"""Shared dollar-denominated usage model for the ``/usage`` and ``/subscription`` bars.
-Terminal surfaces show **dollars**, never "credits"; the monthly subscription
-allowance and separately-purchased top-up dollars must stay distinctly visible.
-
-Data source: ``NousPortalAccountInfo.paid_service_access_info`` (USD floats despite
-the legacy ``*_credits`` names): ``subscription_credits_remaining`` (plan $ left),
-``purchased_credits_remaining`` (top-up $, rolls over), ``total_usable_credits``;
-plus ``subscription.monthly_credits`` (plan bar denominator) and ``current_period_end``.
-
-Design: two SEPARATE bars rather than one three-segment bar — at terminal widths
-three same-glyph density segments are unreadable. Plan bar = spent vs allowance
-(carries % used); top-up bar = purchased money that doesn't expire. Fail-open:
-missing/non-finite fields degrade to fewer bars; logged-out / unreachable portal
-yields ``available=False`` and the surface shows nothing.
+Terminal surfaces show **dollars**, never "credits"; the plan allowance and top-up
+dollars stay distinctly visible as two SEPARATE bars (a three-segment bar is
+unreadable at terminal widths). Source: ``NousPortalAccountInfo.paid_service_access_info``
+(USD floats despite the legacy ``*_credits`` names) plus ``subscription.monthly_credits``
+(plan bar denominator) and ``current_period_end``. Fail-open: missing/non-finite fields
+degrade to fewer bars; logged-out / unreachable portal yields ``available=False``.
"""
from __future__ import annotations
@@ -31,11 +24,7 @@ LOW_BALANCE_THRESHOLD_USD = 5.0
def _finite(value: Any) -> Optional[float]:
- """Return value as a float iff it's a real finite number (not bool/NaN/Inf).
-
- NaN/Infinity slip past isinstance (json.loads parses bare NaN by default) and
- would otherwise render as ``$nan`` with a falsely-confident gauge.
- """
+ """Float iff a real finite number (not bool/NaN/Inf); json.loads admits bare NaN, which would render ``$nan``."""
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
f = float(value)
@@ -51,7 +40,6 @@ def nous_logged_in() -> bool:
"""Cheap local auth-state check: a Nous access token is present. Fail-closed."""
try:
from hermes_cli.auth import get_provider_auth_state
-
tok = (get_provider_auth_state("nous") or {}).get("access_token")
return isinstance(tok, str) and bool(tok.strip())
except Exception:
@@ -61,20 +49,15 @@ def nous_logged_in() -> bool:
def fetch_nous_account(timeout: float):
"""Wall-clock-bounded fresh portal account fetch. Raises on failure/timeout."""
import concurrent.futures
-
from hermes_cli.nous_account import get_nous_portal_account_info
-
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
return pool.submit(get_nous_portal_account_info, force_fresh=True).result(timeout=timeout)
def format_renews(value: Optional[str]) -> Optional[str]:
"""ISO date/timestamp -> ``Jul 24, 2026``; unparseable input is returned unchanged."""
- if not value:
- return None
from datetime import datetime
-
- text = str(value).strip()
+ text = str(value or "").strip()
if not text:
return None
iso = text[:-1] + "+00:00" if text.endswith("Z") else text
@@ -91,11 +74,8 @@ def format_renews(value: Optional[str]) -> Optional[str]:
@dataclass(frozen=True)
class UsageBar:
- """One full-resolution bar: ``spent`` of ``total``, plus a remaining figure.
-
- ``kind`` is ``"plan"`` (monthly allowance, shows % used) or ``"topup"`` (no
- denominator — ``spent`` is 0 and ``total == remaining`` so it renders full).
- """
+ """One bar: ``spent`` of ``total`` plus remaining. ``plan`` shows % used; ``topup`` has no
+ denominator (``spent`` is 0 and ``total == remaining`` so it renders full)."""
kind: str # "plan" | "topup"
remaining_usd: float
@@ -111,18 +91,13 @@ class UsageBar:
@property
def fill_fraction(self) -> float:
"""Fraction of the bar that should read as 'remaining' (filled)."""
- if self.total_usd <= 0:
- return 0.0
- return max(0.0, min(1.0, self.remaining_usd / self.total_usd))
+ return max(0.0, min(1.0, self.remaining_usd / self.total_usd)) if self.total_usd > 0 else 0.0
@dataclass(frozen=True)
class UsageModel:
- """Surface-agnostic dollar usage model shared by /usage and /subscription.
-
- ``status``: ``free`` (no paid access / no plan), ``low`` (paid, spendable < $5,
- ALERT), ``healthy`` (paid, spendable >= $5), ``depleted`` (paid access lost).
- """
+ """Dollar usage model shared by /usage and /subscription. ``status``: ``free`` (no plan / no
+ paid access), ``low`` (spendable < $5, ALERT), ``healthy`` (>= $5), ``depleted`` (paid access lost)."""
available: bool
status: str = "free"
@@ -145,29 +120,21 @@ def usage_model_from_account(account_info: Any) -> UsageModel:
try:
if account_info is None or not getattr(account_info, "logged_in", False):
return UsageModel(available=False)
-
+ # Sub-structs are dataclasses or None; getattr(None, ..., None) is None, so no guards needed.
access = getattr(account_info, "paid_service_access_info", None)
sub = getattr(account_info, "subscription", None)
paid = getattr(account_info, "paid_service_access", None)
-
- sub_remaining = _finite(getattr(access, "subscription_credits_remaining", None)) if access else None
- topup_remaining = _finite(getattr(access, "purchased_credits_remaining", None)) if access else None
- total_usable = _finite(getattr(access, "total_usable_credits", None)) if access else None
-
- plan_name = getattr(sub, "plan", None) if sub is not None else None
- renews_at = getattr(sub, "current_period_end", None) if sub is not None else None
- monthly = _finite(getattr(sub, "monthly_credits", None)) if sub is not None else None
-
+ sub_remaining = _finite(getattr(access, "subscription_credits_remaining", None))
+ topup_remaining = _finite(getattr(access, "purchased_credits_remaining", None))
+ total_usable = _finite(getattr(access, "total_usable_credits", None))
+ plan_name = getattr(sub, "plan", None)
+ renews_at = getattr(sub, "current_period_end", None)
+ monthly = _finite(getattr(sub, "monthly_credits", None))
has_subscription = bool(plan_name) or (monthly is not None and monthly > 0)
has_topup = bool(topup_remaining and topup_remaining > 0)
-
# Prefer the server's total; else sum the parts we have.
- if total_usable is not None:
- total_spendable = total_usable
- else:
- parts = [v for v in (sub_remaining, topup_remaining) if v is not None]
- total_spendable = sum(parts) if parts else None
-
+ parts = [v for v in (sub_remaining, topup_remaining) if v is not None]
+ total_spendable = total_usable if total_usable is not None else (sum(parts) if parts else None)
if paid is False:
status = "depleted"
elif not has_subscription and not has_topup:
@@ -176,34 +143,20 @@ def usage_model_from_account(account_info: Any) -> UsageModel:
status = "low"
else:
status = "healthy"
-
# Plan bar needs a positive allowance AND a remaining to place on it; spent is
# clamped so a debt/over-cap balance reads fully spent, not negative.
- plan_bar: Optional[UsageBar] = None
+ plan_bar = topup_bar = None
if monthly is not None and monthly > 0 and sub_remaining is not None:
- plan_bar = UsageBar(
- kind="plan",
- remaining_usd=max(0.0, min(monthly, sub_remaining)),
- total_usd=monthly,
- spent_usd=max(0.0, monthly - sub_remaining),
- )
-
+ plan_bar = UsageBar(kind="plan", remaining_usd=max(0.0, min(monthly, sub_remaining)), total_usd=monthly,
+ spent_usd=max(0.0, monthly - sub_remaining))
# Top-up has no monthly cap, so the bar renders full = balance.
- topup_bar: Optional[UsageBar] = None
if topup_remaining is not None and topup_remaining > 0:
topup_bar = UsageBar(kind="topup", remaining_usd=topup_remaining, total_usd=topup_remaining, spent_usd=0.0)
-
return UsageModel(
- available=True,
- status=status,
- plan_name=plan_name,
- renews_at=renews_at,
- renews_display=format_renews(renews_at),
- subscription_remaining_usd=sub_remaining,
- topup_remaining_usd=topup_remaining,
- total_spendable_usd=total_spendable,
- plan_bar=plan_bar,
- topup_bar=topup_bar,
+ available=True, status=status, plan_name=plan_name, renews_at=renews_at,
+ renews_display=format_renews(renews_at), subscription_remaining_usd=sub_remaining,
+ topup_remaining_usd=topup_remaining, total_spendable_usd=total_spendable,
+ plan_bar=plan_bar, topup_bar=topup_bar,
)
except Exception:
logger.debug("usage ▸ model build failed (fail-open)", exc_info=True)
@@ -211,11 +164,7 @@ def usage_model_from_account(account_info: Any) -> UsageModel:
def build_usage_model(*, timeout: float = 10.0) -> UsageModel:
- """Fetch account-info and build the shared usage model. Fail-open.
-
- ``HERMES_DEV_CREDITS_FIXTURE`` short-circuits to a fixture so every usage state
- is testable without a live account.
- """
+ """Fetch account-info and build the usage model; fail-open. ``HERMES_DEV_CREDITS_FIXTURE`` short-circuits to a fixture."""
fixture = _dev_fixture_usage_model()
if fixture is not None:
return fixture
@@ -228,8 +177,6 @@ def build_usage_model(*, timeout: float = 10.0) -> UsageModel:
return UsageModel(available=False)
-# ── Dev fixtures (throwaway scaffolding — env-var driven, no live portal) ────
-
def _plan_bar(remaining: float, spent: float) -> UsageBar:
return UsageBar(kind="plan", remaining_usd=remaining, total_usd=20.0, spent_usd=spent)
@@ -241,23 +188,14 @@ def _dev_fixture_usage_model() -> Optional[UsageModel]:
plus = dict(available=True, plan_name="Plus", renews_at="2026-07-01")
specs: dict[str, dict] = {
"free": dict(available=True, status="free", plan_name=None),
- "healthy": dict(
- **plus, status="healthy", subscription_remaining_usd=14.0, total_spendable_usd=14.0,
- plan_bar=_plan_bar(14.0, 6.0),
- ),
+ "healthy": dict(**plus, status="healthy", subscription_remaining_usd=14.0, total_spendable_usd=14.0, plan_bar=_plan_bar(14.0, 6.0)),
"topup": dict(
**plus, status="healthy", subscription_remaining_usd=14.0, topup_remaining_usd=12.0,
total_spendable_usd=26.0, plan_bar=_plan_bar(14.0, 6.0),
topup_bar=UsageBar(kind="topup", remaining_usd=12.0, total_usd=12.0, spent_usd=0.0),
),
- "low": dict(
- **plus, status="low", subscription_remaining_usd=3.4, total_spendable_usd=3.4,
- plan_bar=_plan_bar(3.4, 16.6),
- ),
- "depleted": dict(
- **plus, status="depleted", subscription_remaining_usd=0.0, total_spendable_usd=0.0,
- plan_bar=_plan_bar(0.0, 20.0),
- ),
+ "low": dict(**plus, status="low", subscription_remaining_usd=3.4, total_spendable_usd=3.4, plan_bar=_plan_bar(3.4, 16.6)),
+ "depleted": dict(**plus, status="depleted", subscription_remaining_usd=0.0, total_spendable_usd=0.0, plan_bar=_plan_bar(0.0, 20.0)),
}
spec = specs.get(name)
return UsageModel(**spec) if spec else None
diff --git a/agent/billing_view.py b/agent/billing_view.py
index f2c0ef0fdfa..ee603cc56e7 100644
--- a/agent/billing_view.py
+++ b/agent/billing_view.py
@@ -1,10 +1,8 @@
-"""Surface-agnostic core for the Remote Spending screens.
+"""Surface-agnostic core for the Remote Spending screens (CLI ``_show_billing``, TUI JSON-RPC).
-One fetch/parse per concern, consumed identically by the CLI handler
-(``cli.py::_show_billing``), the TUI JSON-RPC methods (``tui_gateway/server.py``),
-and any other surface. Parse the server payload into a frozen dataclass and
-**fail open**: when not logged in or the portal is unreachable, return a struct
-with ``logged_in=False`` and let the surface degrade gracefully (never crash).
+One fetch/parse per concern; the server payload is parsed into frozen dataclasses.
+**Fail open**: when not logged in or the portal is unreachable, return a struct with
+``logged_in=False`` and let the surface degrade gracefully (never crash).
Money discipline: the server emits decimal STRINGS (``"142.5"``, not fixed 2dp).
We keep them as :class:`decimal.Decimal` end-to-end and only format for display.
@@ -22,16 +20,11 @@ from typing import Any, Callable, Optional
logger = logging.getLogger(__name__)
-# ── Decimal money helpers ────────────────────────────────────────────────────
-
-
def parse_money(value: Any) -> Optional[Decimal]:
"""Server money value (decimal string; defensively int/float) -> Decimal, or None. Never raises."""
- if value is None:
- return None
try:
# Decimal(str(...)) avoids binary-float artifacts if a float ever sneaks in.
- return Decimal(str(value).strip())
+ return Decimal(str(value).strip()) if value is not None else None
except (InvalidOperation, ValueError, TypeError):
return None
@@ -39,9 +32,8 @@ def parse_money(value: Any) -> Optional[Decimal]:
def format_money(value: Optional[Decimal], *, grouped: bool = False) -> str:
"""``$X`` for whole dollars, ``$X.YY`` (exactly 2dp) otherwise; ``None`` -> ``—``.
- ``grouped=True`` adds thousands separators (``$1,234.50``) to mirror the TUI's
- ``toLocaleString('en-US')`` on plan-catalog rows; the default is intentionally
- ungrouped and asserted so across the other surfaces.
+ ``grouped=True`` adds thousands separators (mirrors the TUI's ``toLocaleString('en-US')``
+ on plan-catalog rows); the default is intentionally ungrouped across the other surfaces.
"""
if value is None:
return "—"
@@ -57,7 +49,9 @@ def _optional_str(raw: dict, key: str) -> Optional[str]:
return value if isinstance(value, str) else None
-# ── Parsed sub-structures ────────────────────────────────────────────────────
+def _dict_parser(fn: Callable[[dict], Any]) -> Callable[[Any], Any]:
+ """Sub-structure parsers accept anything and return None unless the payload is a dict."""
+ return lambda raw: fn(raw) if isinstance(raw, dict) else None
# resolvedVia (server card-on-file ladder rung) → "why THIS card?". Unknown/absent
@@ -78,16 +72,12 @@ class CardInfo:
@property
def masked(self) -> str:
# A Link payment method has no card number (last4 = "") — brand alone, not "Link ····".
- if not self.last4:
- return self.brand
- return f"{self.brand} ····{self.last4}"
+ return f"{self.brand} ····{self.last4}" if self.last4 else self.brand
@property
def provenance(self) -> Optional[str]:
"""Human label for why this card was picked, or None (unknown rung / old server)."""
- if self.resolved_via is None:
- return None
- return _CARD_PROVENANCE_LABELS.get(self.resolved_via)
+ return _CARD_PROVENANCE_LABELS.get(self.resolved_via) if self.resolved_via is not None else None
@property
def display(self) -> str:
@@ -98,9 +88,8 @@ class CardInfo:
@dataclass(frozen=True)
class PaymentMethodInfo:
- """Payment method on file. ``kind`` is "card", "link", or "unknown" — anything
- else is normalised to "unknown" at parse time so consumers only see fields
- that belong to the kind they are looking at."""
+ """Payment method on file. ``kind`` is "card" | "link" | "unknown" (settled at parse time
+ so consumers only see fields that belong to the kind they are looking at)."""
kind: str
brand: Optional[str] = None
@@ -142,22 +131,18 @@ class OrgRoleCapability:
@property
def is_admin(self) -> bool:
- """Deprecated/display only — legacy OWNER/ADMIN check, NOT a capability check
- (use :attr:`can_change_plan` to gate plan-change actions)."""
+ """Display only — legacy OWNER/ADMIN check; gate plan-change actions on :attr:`can_change_plan`."""
return (self.role or "").upper() in ("OWNER", "ADMIN")
@property
def can_change_plan(self) -> bool:
"""Server capability when supplied; otherwise the legacy role fallback."""
- if self.can_change_plan_raw is not None:
- return self.can_change_plan_raw
- return self.is_admin
+ return self.can_change_plan_raw if self.can_change_plan_raw is not None else self.is_admin
@dataclass(frozen=True)
class BillingState(OrgRoleCapability):
- """Parsed ``GET /api/billing/state``. Fail-open: ``logged_in=False`` (empty
- fields) when not logged in or the portal is unreachable."""
+ """Parsed ``GET /api/billing/state``; fail-open ``logged_in=False`` (empty fields) when unavailable."""
logged_in: bool
org_id: Optional[str] = None
@@ -179,94 +164,67 @@ class BillingState(OrgRoleCapability):
@property
def can_charge(self) -> bool:
- """Offer charge/auto-reload actions: server-granted ``can_change_plan`` (so
- e.g. FINANCE_ADMIN can be granted via ``canChangePlan``) AND the per-org
- kill-switch. Display gating only — the server still enforces."""
+ """Offer charge/auto-reload actions: ``can_change_plan`` (server-grantable, e.g. FINANCE_ADMIN)
+ AND the per-org kill-switch. Display gating only — the server still enforces."""
return self.can_change_plan and self.cli_billing_enabled
-def _parse_card(raw: Any) -> Optional[CardInfo]:
- if not isinstance(raw, dict):
- return None
- brand = raw.get("brand")
- last4 = raw.get("last4")
+@_dict_parser
+def _parse_card(raw: dict) -> Optional[CardInfo]:
+ brand, last4 = raw.get("brand"), raw.get("last4")
if not (isinstance(brand, str) and isinstance(last4, str)):
return None
return CardInfo(brand=brand, last4=last4, resolved_via=_optional_str(raw, "resolvedVia"))
-def _parse_payment_method(raw: Any) -> Optional[PaymentMethodInfo]:
- if not isinstance(raw, dict):
- return None
- kind = raw.get("kind")
- if not isinstance(kind, str):
+@_dict_parser
+def _parse_payment_method(raw: dict) -> Optional[PaymentMethodInfo]:
+ if not isinstance(kind := raw.get("kind"), str):
return None
resolved_via = _optional_str(raw, "resolvedVia")
brand = _optional_str(raw, "brand")
last4 = _optional_str(raw, "last4")
# Settle the kind here (like _parse_card) so nothing downstream re-checks fields.
if kind == "card" and brand and last4:
- return PaymentMethodInfo(
- kind="card", brand=brand, last4=last4, wallet=_optional_str(raw, "wallet"), resolved_via=resolved_via
- )
+ return PaymentMethodInfo(kind="card", brand=brand, last4=last4, wallet=_optional_str(raw, "wallet"), resolved_via=resolved_via)
if kind == "link":
return PaymentMethodInfo(kind="link", email=_optional_str(raw, "email"), resolved_via=resolved_via)
return PaymentMethodInfo(kind="unknown", raw_kind=kind, resolved_via=resolved_via)
-def _parse_monthly_cap(raw: Any) -> Optional[MonthlyCap]:
- if not isinstance(raw, dict):
- return None
- return MonthlyCap(
- limit_usd=parse_money(raw.get("limitUsd")),
- spent_this_month_usd=parse_money(raw.get("spentThisMonthUsd")),
- is_default_ceiling=bool(raw.get("isDefaultCeiling")),
- )
+@_dict_parser
+def _parse_monthly_cap(raw: dict) -> MonthlyCap:
+ return MonthlyCap(limit_usd=parse_money(raw.get("limitUsd")), spent_this_month_usd=parse_money(raw.get("spentThisMonthUsd")),
+ is_default_ceiling=bool(raw.get("isDefaultCeiling")))
-def _parse_auto_reload(raw: Any) -> Optional[AutoReload]:
- if not isinstance(raw, dict):
- return None
- return AutoReload(
- enabled=bool(raw.get("enabled")),
- threshold_usd=parse_money(raw.get("thresholdUsd")),
- reload_to_usd=parse_money(raw.get("reloadToUsd")),
- card=_parse_auto_reload_card(raw.get("card")),
- )
+@_dict_parser
+def _parse_auto_reload(raw: dict) -> AutoReload:
+ return AutoReload(enabled=bool(raw.get("enabled")), threshold_usd=parse_money(raw.get("thresholdUsd")),
+ reload_to_usd=parse_money(raw.get("reloadToUsd")), card=_parse_auto_reload_card(raw.get("card")))
-def _parse_auto_reload_card(raw: Any) -> Optional[AutoReloadCard]:
- if not isinstance(raw, dict):
- return None
- kind = raw.get("kind")
- if kind not in ("canonical", "distinct", "none"):
+@_dict_parser
+def _parse_auto_reload_card(raw: dict) -> Optional[AutoReloadCard]:
+ if (kind := raw.get("kind")) not in ("canonical", "distinct", "none"):
return None
- if kind in ("canonical", "none"):
+ if kind != "distinct":
return AutoReloadCard(kind=kind)
- return AutoReloadCard(
- kind=kind,
- payment_method_id=_optional_str(raw, "paymentMethodId"),
- brand=_optional_str(raw, "brand"),
- last4=_optional_str(raw, "last4"),
- )
+ return AutoReloadCard(kind=kind, payment_method_id=_optional_str(raw, "paymentMethodId"),
+ brand=_optional_str(raw, "brand"), last4=_optional_str(raw, "last4"))
def parse_org_fields(payload: dict[str, Any]) -> tuple[dict[str, Any], Optional[bool]]:
"""``(org dict or {}, canChangePlan if bool else None)`` — shared by both state parsers."""
- raw_org = payload.get("org")
- ccp = payload.get("canChangePlan")
+ raw_org, ccp = payload.get("org"), payload.get("canChangePlan")
return (raw_org if isinstance(raw_org, dict) else {}), (ccp if isinstance(ccp, bool) else None)
-def billing_state_from_payload(
- payload: dict[str, Any], *, portal_url: Optional[str] = None
-) -> BillingState:
+def billing_state_from_payload(payload: dict[str, Any], *, portal_url: Optional[str] = None) -> BillingState:
"""Map a raw ``/api/billing/state`` JSON dict into :class:`BillingState`."""
org, can_change_plan_raw = parse_org_fields(payload)
- raw_bounds = payload.get("bounds")
- bounds: dict[str, Any] = raw_bounds if isinstance(raw_bounds, dict) else {}
+ bounds: dict[str, Any] = payload.get("bounds") if isinstance(payload.get("bounds"), dict) else {}
presets = [p for p in map(parse_money, payload.get("chargePresets") or ()) if p is not None]
-
return BillingState(
logged_in=True,
org_id=org.get("id"),
@@ -287,31 +245,20 @@ def billing_state_from_payload(
)
-# ── Fail-open builders (the surface front doors) ─────────────────────────────
-
-
def fetch_portal_state(
- endpoint: str,
- label: str,
- *,
- failed: Callable[..., Any],
- parse: Callable[[dict, Optional[str]], Any],
- portal_fallback: Callable[[str], str],
- timeout: float,
- log: logging.Logger,
+ endpoint: str, label: str, *, failed: Callable[..., Any], parse: Callable[[dict, Optional[str]], Any],
+ portal_fallback: Callable[[str], str], timeout: float, log: logging.Logger,
):
"""Shared fail-open fetch+parse for the billing/subscription overview builders.
- ``failed(**kw)`` builds the ``logged_in=False`` struct: bare on auth failure,
- with ``error`` set on a portal/HTTP failure so the surface can show a clear
- message. Prefers a server-supplied ``portalUrl`` (absolutized); else
+ ``failed(**kw)`` builds the ``logged_in=False`` struct: bare on auth failure, with ``error``
+ set on a portal/HTTP failure. Portal URL: server ``portalUrl`` (absolutized), else
``portal_fallback(portal_base_url)``.
"""
try:
import hermes_cli.nous_billing as nb
except Exception:
return failed(error="billing client unavailable")
-
try:
payload = getattr(nb, endpoint)(timeout=timeout)
except nb.BillingAuthError:
@@ -322,7 +269,6 @@ def fetch_portal_state(
except Exception:
log.debug("%s ▸ /state unexpected error (fail-open)", label, exc_info=True)
return failed(error=f"could not load {label} state")
-
raw_portal = payload.get("portalUrl") if isinstance(payload, dict) else None
portal_url = nb._absolutize_portal_url(raw_portal) if raw_portal else None
if not portal_url:
@@ -334,72 +280,51 @@ def fetch_portal_state(
def build_billing_state(*, timeout: float = 15.0) -> BillingState:
- """Fetch + parse ``/api/billing/state``. Fail-open (see :func:`fetch_portal_state`).
-
- ``HERMES_DEV_BILLING_FIXTURE`` short-circuits to a fixture so card-on-file /
- admin / scope states are testable offline.
- """
+ """Fetch + parse ``/api/billing/state``; fail-open. ``HERMES_DEV_BILLING_FIXTURE`` short-circuits to a fixture."""
fixture = _dev_fixture_billing_state()
if fixture is not None:
return fixture
return fetch_portal_state(
- "get_billing_state",
- "billing",
+ "get_billing_state", "billing", timeout=timeout, log=logger,
failed=lambda **kw: BillingState(logged_in=False, **kw),
parse=lambda payload, portal_url: billing_state_from_payload(payload, portal_url=portal_url),
portal_fallback=lambda base: f"{base.rstrip('/')}/billing?topup=open",
- timeout=timeout,
- log=logger,
)
-# ── Dev fixtures (throwaway scaffolding — env-var driven, no live portal) ────
+# ── Dev fixtures (env-var driven, no live portal) ────────────────────────────
+
+_FIXTURE_ALIASES = {
+ "logged_out": "logged-out", "loggedout": "logged-out", "card_sub": "card-sub", "card_autoreload": "card-autoreload",
+ "autoreload": "card-autoreload", "not-admin": "notadmin", "member": "notadmin", "billing_off": "billing-off", "off": "billing-off",
+}
def _dev_fixture_billing_state() -> Optional[BillingState]:
"""``HERMES_DEV_BILLING_FIXTURE`` -> :class:`BillingState` for offline UX; None when unset.
- nocard · card · card-sub (provenance label) · card-autoreload · notadmin (MEMBER)
- · billing-off (per-org kill-switch) · logged-out. Unknown name → logged-out with
- ``error`` so the misconfiguration is visible. Pair with ``HERMES_DEV_CREDITS_FIXTURE``
- for the usage bar.
+ Names: nocard · card · card-sub · card-autoreload · notadmin · billing-off · logged-out; an
+ unknown name yields logged-out with ``error`` so the misconfiguration is visible.
"""
name = (os.getenv("HERMES_DEV_BILLING_FIXTURE") or "").strip().lower()
if not name:
return None
- aliases = {
- "logged_out": "logged-out", "loggedout": "logged-out",
- "card_sub": "card-sub",
- "card_autoreload": "card-autoreload", "autoreload": "card-autoreload",
- "not-admin": "notadmin", "member": "notadmin",
- "billing_off": "billing-off", "off": "billing-off",
- }
- name = aliases.get(name, name)
+ name = _FIXTURE_ALIASES.get(name, name)
if name == "logged-out":
return BillingState(logged_in=False)
# Prod portal host (matches subscription_view._DEV_FIXTURE_PORTAL) + the /topup deep-link suffix.
common: dict[str, Any] = dict(
- logged_in=True,
- org_id="org_acme",
- org_slug="acme",
- org_name="Acme Inc",
- role="OWNER",
- balance_usd=Decimal("3.40"),
- cli_billing_enabled=True,
- charge_presets=(Decimal("10"), Decimal("25"), Decimal("50")),
- min_usd=Decimal("5"),
- max_usd=Decimal("500"),
- portal_url="https://portal.nousresearch.com/billing?topup=open",
+ logged_in=True, org_id="org_acme", org_slug="acme", org_name="Acme Inc", role="OWNER",
+ balance_usd=Decimal("3.40"), cli_billing_enabled=True, min_usd=Decimal("5"), max_usd=Decimal("500"),
+ charge_presets=(Decimal("10"), Decimal("25"), Decimal("50")), portal_url="https://portal.nousresearch.com/billing?topup=open",
)
card = CardInfo(brand="Visa", last4="4242")
overrides: dict[str, dict[str, Any]] = {
"nocard": dict(card=None),
"card": dict(card=card),
"card-sub": dict(card=CardInfo(brand="Visa", last4="4242", resolved_via="subPin")),
- "card-autoreload": dict(
- card=card, auto_reload=AutoReload(enabled=True, threshold_usd=Decimal("5"), reload_to_usd=Decimal("25"))
- ),
+ "card-autoreload": dict(card=card, auto_reload=AutoReload(enabled=True, threshold_usd=Decimal("5"), reload_to_usd=Decimal("25"))),
"notadmin": dict(card=card, role="MEMBER"),
"billing-off": dict(card=None, cli_billing_enabled=False),
}
@@ -408,19 +333,12 @@ def _dev_fixture_billing_state() -> Optional[BillingState]:
return BillingState(**{**common, **overrides[name]})
-# ── Idempotency ──────────────────────────────────────────────────────────────
-
-
def new_idempotency_key() -> str:
- """Fresh UUID for a user-confirmed purchase. ``Idempotency-Key`` is mandatory on
- ``POST /charge``: reuse the key across retries of the SAME buy so a double-submit
- collapses to one charge; never reuse across amounts (server 409 idempotency_conflict)."""
+ """Fresh ``Idempotency-Key`` for ``POST /charge``: reuse across retries of the SAME buy so a
+ double-submit collapses to one charge; never across amounts (server 409 idempotency_conflict)."""
return str(uuid.uuid4())
-# ── Amount validation (custom charge input) ──────────────────────────────────
-
-
@dataclass(frozen=True)
class AmountValidation:
ok: bool
@@ -428,20 +346,19 @@ class AmountValidation:
error: Optional[str] = None
-def validate_charge_amount(
- raw: str, *, min_usd: Optional[Decimal], max_usd: Optional[Decimal]
-) -> AmountValidation:
- """Mirror the server's accept/reject (bounds + multipleOf 0.01) for instant UI
- feedback; the server is still authoritative."""
+def validate_charge_amount(raw: str, *, min_usd: Optional[Decimal], max_usd: Optional[Decimal]) -> AmountValidation:
+ """Mirror the server's accept/reject (bounds + multipleOf 0.01) for instant UI feedback; server is authoritative."""
amount = parse_money((raw or "").strip().lstrip("$").strip())
if amount is None:
- return AmountValidation(ok=False, error="Enter a dollar amount, e.g. 100")
- if amount <= 0:
- return AmountValidation(ok=False, error="Amount must be greater than $0")
- if amount != amount.quantize(Decimal("0.01")):
- return AmountValidation(ok=False, error="Amount can't be smaller than a cent")
- if min_usd is not None and amount < min_usd:
- return AmountValidation(ok=False, error=f"Minimum is {format_money(min_usd)}")
- if max_usd is not None and amount > max_usd:
- return AmountValidation(ok=False, error=f"Maximum is {format_money(max_usd)}")
- return AmountValidation(ok=True, amount=amount)
+ error = "Enter a dollar amount, e.g. 100"
+ elif amount <= 0:
+ error = "Amount must be greater than $0"
+ elif amount != amount.quantize(Decimal("0.01")):
+ error = "Amount can't be smaller than a cent"
+ elif min_usd is not None and amount < min_usd:
+ error = f"Minimum is {format_money(min_usd)}"
+ elif max_usd is not None and amount > max_usd:
+ error = f"Maximum is {format_money(max_usd)}"
+ else:
+ return AmountValidation(ok=True, amount=amount)
+ return AmountValidation(ok=False, error=error)
diff --git a/agent/context_references.py b/agent/context_references.py
index b8ce46d6706..5b12083b9c4 100644
--- a/agent/context_references.py
+++ b/agent/context_references.py
@@ -15,17 +15,10 @@ from pathlib import Path
from typing import Awaitable, Callable
from agent.model_metadata import estimate_tokens_rough
-from hermes_cli._subprocess_compat import (
- IS_WINDOWS,
- harden_git_argv,
- noninteractive_git_env,
- windows_hide_flags,
-)
+from hermes_cli._subprocess_compat import IS_WINDOWS, harden_git_argv, noninteractive_git_env, windows_hide_flags
from hermes_cli.sizefmt import format_bytes
-# ---------------------------------------------------------------------------
-# Plugin context-reference provider API
-# ---------------------------------------------------------------------------
+# ── Plugin context-reference provider API ────────────────────────────────────
BUILTIN_PREFIXES = frozenset({"diff", "staged", "file", "folder", "git", "url"})
@@ -52,12 +45,10 @@ class ContextReferenceProvider(ABC):
@abstractmethod
async def autocomplete(self, query: str, *, limit: int = 10) -> list[ContextCompletionItem]:
"""Return autocomplete items for the given query string."""
- ...
@abstractmethod
async def expand(self, target: str) -> str | None:
"""Expand *target* to prompt content. Return ``None`` to skip."""
- ...
def register_context_reference_provider(provider: ContextReferenceProvider) -> None:
@@ -87,26 +78,25 @@ REFERENCE_PATTERN = re.compile(
_PLUGIN_REFERENCE_PATTERN = re.compile(
rf"(?<![\w/])@(?P<kind>[a-zA-Z][a-zA-Z0-9_-]*):(?P<value>{_QUOTED_REFERENCE_VALUE}(?::\d+(?:-\d+)?)?|\S+)"
)
+# ``@file:`` value: quoted path or bare path, each with an optional ``:start[-end]`` range.
+_FILE_VALUE_PATTERN = re.compile(
+ r'^(?:(?P<quote>`|"|\')(?P<qpath>.+?)(?P=quote)|(?P<path>.+?))(?::(?P<start>\d+)(?:-(?P<end>\d+))?)?$'
+)
TRAILING_PUNCTUATION = ",.;!?"
+_OPENERS = {")": "(", "]": "[", "}": "{"}
_NEEDS_QUOTING = re.compile(r"""[\s()\[\]{}<>"'`]""")
_SENSITIVE_HOME_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".docker", ".azure", ".config/gh")
_SENSITIVE_HERMES_DIRS = (Path("skills") / ".hub",)
-_SENSITIVE_HOME_FILES = (
- Path(".ssh") / "authorized_keys",
- Path(".ssh") / "id_rsa",
- Path(".ssh") / "id_ed25519",
- Path(".ssh") / "config",
- Path(".bashrc"),
- Path(".zshrc"),
- Path(".profile"),
- Path(".bash_profile"),
- Path(".zprofile"),
- Path(".netrc"),
- Path(".pgpass"),
- Path(".npmrc"),
- Path(".pypirc"),
-)
+_SENSITIVE_HOME_FILES = tuple(Path(p) for p in (
+ ".ssh/authorized_keys", ".ssh/id_rsa", ".ssh/id_ed25519", ".ssh/config", ".bashrc", ".zshrc",
+ ".profile", ".bash_profile", ".zprofile", ".netrc", ".pgpass", ".npmrc", ".pypirc",
+))
+_TEXT_EXTENSIONS = (".py", ".md", ".txt", ".json", ".yaml", ".yml", ".toml", ".js", ".ts")
+_FENCE_LANGUAGES = {
+ ".py": "python", ".js": "javascript", ".ts": "typescript", ".tsx": "tsx", ".jsx": "jsx",
+ ".json": "json", ".md": "markdown", ".sh": "bash", ".yml": "yaml", ".yaml": "yaml", ".toml": "toml",
+}
@dataclass(frozen=True)
@@ -131,12 +121,13 @@ class ContextReferenceResult:
blocked: bool = False
-def format_reference_value(value: str) -> str:
- """Quote a reference value so ``REFERENCE_PATTERN`` reads it back whole.
+UrlFetcher = Callable[[str], str | Awaitable[str]] | None
+Expansion = tuple[str | None, str | None] # (warning, block) — exactly one side is set
+
- The unquoted alternative is ``\\S+``, so a path with a space would parse as a
- truncated ref. Mirrors ``formatRefValue`` in the desktop's directive-text.tsx.
- """
+def format_reference_value(value: str) -> str:
+ """Quote a value so ``REFERENCE_PATTERN`` (bare alternative ``\\S+``) reads it back whole.
+ Mirrors ``formatRefValue`` in the desktop's directive-text.tsx."""
if not _NEEDS_QUOTING.search(value):
return value
for quote in ("`", '"', "'"):
@@ -149,130 +140,76 @@ def parse_context_references(message: str) -> list[ContextReference]:
refs: list[ContextReference] = []
if not message:
return refs
-
for match in REFERENCE_PATTERN.finditer(message):
- simple = match.group("simple")
- if simple:
- refs.append(ContextReference(raw=match.group(0), kind=simple, target="", start=match.start(), end=match.end()))
- continue
- kind = match.group("kind")
+ kind = match.group("simple") or match.group("kind")
value = _strip_trailing_punctuation(match.group("value") or "")
- if kind == "file":
+ if match.group("simple"):
+ target, line_start, line_end = "", None, None
+ elif kind == "file":
target, line_start, line_end = _parse_file_reference_value(value)
else:
target, line_start, line_end = _strip_reference_wrappers(value), None, None
- refs.append(
- ContextReference(
- raw=match.group(0),
- kind=kind,
- target=target,
- start=match.start(),
- end=match.end(),
- line_start=line_start,
- line_end=line_end,
- )
- )
+ refs.append(ContextReference(match.group(0), kind, target, match.start(), match.end(), line_start, line_end))
# Second pass: plugin-registered prefixes the built-in pattern missed.
- if _context_reference_providers:
- for match in _PLUGIN_REFERENCE_PATTERN.finditer(message):
- kind = match.group("kind")
- if kind in BUILTIN_PREFIXES or kind not in _context_reference_providers:
- continue
- if any(r.kind == kind and r.start == match.start() for r in refs):
- continue
- value = _strip_trailing_punctuation(match.group("value") or "")
- refs.append(
- ContextReference(
- raw=match.group(0),
- kind=kind,
- target=_strip_reference_wrappers(value),
- start=match.start(),
- end=match.end(),
- )
- )
-
+ for match in _PLUGIN_REFERENCE_PATTERN.finditer(message) if _context_reference_providers else ():
+ kind = match.group("kind")
+ if kind in BUILTIN_PREFIXES or kind not in _context_reference_providers:
+ continue
+ if any(r.kind == kind and r.start == match.start() for r in refs):
+ continue
+ target = _strip_reference_wrappers(_strip_trailing_punctuation(match.group("value") or ""))
+ refs.append(ContextReference(match.group(0), kind, target, match.start(), match.end()))
return refs
def preprocess_context_references(
- message: str,
- *,
- cwd: str | Path,
- context_length: int,
- url_fetcher: Callable[[str], str | Awaitable[str]] | None = None,
+ message: str, *, cwd: str | Path, context_length: int, url_fetcher: UrlFetcher = None,
allowed_root: str | Path | None = None,
) -> ContextReferenceResult:
"""Sync wrapper; safe both without a loop (CLI) and inside a running loop (gateway)."""
coro = preprocess_context_references_async(
- message,
- cwd=cwd,
- context_length=context_length,
- url_fetcher=url_fetcher,
- allowed_root=allowed_root,
+ message, cwd=cwd, context_length=context_length, url_fetcher=url_fetcher, allowed_root=allowed_root
)
try:
- loop = asyncio.get_running_loop()
+ asyncio.get_running_loop()
except RuntimeError:
- loop = None
- if loop and loop.is_running():
- import concurrent.futures
- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
- return pool.submit(asyncio.run, coro).result()
- return asyncio.run(coro)
+ return asyncio.run(coro)
+ import concurrent.futures
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
+ return pool.submit(asyncio.run, coro).result()
async def preprocess_context_references_async(
- message: str,
- *,
- cwd: str | Path,
- context_length: int,
- url_fetcher: Callable[[str], str | Awaitable[str]] | None = None,
+ message: str, *, cwd: str | Path, context_length: int, url_fetcher: UrlFetcher = None,
allowed_root: str | Path | None = None,
) -> ContextReferenceResult:
refs = parse_context_references(message)
if not refs:
return ContextReferenceResult(message=message, original_message=message)
-
cwd_path = Path(cwd).expanduser().resolve()
# Default root = cwd so @ references cannot escape the workspace unless a caller widens it.
allowed_root_path = Path(allowed_root).expanduser().resolve() if allowed_root is not None else cwd_path
- warnings: list[str] = []
- blocks: list[str] = []
- injected_tokens = 0
-
# Expand concurrently (each ref is independent; several @url: refs would otherwise
# serialize web_extract round-trips). gather preserves order, so warnings/blocks
# are assembled in ref order; the token-budget check runs once afterwards.
- expanded = await asyncio.gather(
- *(_expand_reference(ref, cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path) for ref in refs)
+ tasks = (_expand_reference(ref, cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path) for ref in refs)
+ expanded = await asyncio.gather(*tasks)
+ warnings = [warning for warning, _ in expanded if warning]
+ blocks = [block for _, block in expanded if block]
+ injected_tokens = sum(estimate_tokens_rough(block) for block in blocks)
+ result = ContextReferenceResult(
+ message=message, original_message=message, references=refs, warnings=warnings, injected_tokens=injected_tokens
)
- for warning, block in expanded:
- if warning:
- warnings.append(warning)
- if block:
- blocks.append(block)
- injected_tokens += estimate_tokens_rough(block)
hard_limit = max(1, int(context_length * 0.50))
soft_limit = max(1, int(context_length * 0.25))
if injected_tokens > hard_limit:
- warnings.append(
- f"@ context injection refused: {injected_tokens} tokens exceeds the 50% hard limit ({hard_limit})."
- )
- return ContextReferenceResult(
- message=message,
- original_message=message,
- references=refs,
- warnings=warnings,
- injected_tokens=injected_tokens,
- expanded=False,
- blocked=True,
- )
+ warnings.append(f"@ context injection refused: {injected_tokens} tokens exceeds the 50% hard limit ({hard_limit}).")
+ result.blocked = True
+ return result
if injected_tokens > soft_limit:
- warnings.append(
- f"@ context injection warning: {injected_tokens} tokens exceeds the 25% soft limit ({soft_limit})."
- )
+ warnings.append(f"@ context injection warning: {injected_tokens} tokens exceeds the 25% soft limit ({soft_limit}).")
# The `@file:`/`@folder:` tokens stay where the user typed them: the token IS the
# reference (clients render it as an inline chip); stripping it left a hole in the
@@ -282,44 +219,25 @@ async def preprocess_context_references_async(
final = f"{final}\n\n--- Context Warnings ---\n" + "\n".join(f"- {warning}" for warning in warnings)
if blocks:
final = f"{final}\n\n--- Attached Context ---\n\n" + "\n\n".join(blocks)
-
- return ContextReferenceResult(
- message=final.strip(),
- original_message=message,
- references=refs,
- warnings=warnings,
- injected_tokens=injected_tokens,
- expanded=bool(blocks or warnings),
- blocked=False,
- )
-
-
-def _git_log_args(ref: ContextReference) -> list[str]:
- count = max(1, min(int(ref.target or "1"), 10))
- return ["log", f"-{count}", "-p"]
+ result.message = final.strip()
+ result.expanded = bool(blocks or warnings)
+ return result
# Git-backed reference kinds -> f(ref) -> git argv (the label is "git " + argv).
_GIT_REFERENCE_ARGS: dict[str, Callable[[ContextReference], list[str]]] = {
"diff": lambda ref: ["diff"],
"staged": lambda ref: ["diff", "--staged"],
- "git": _git_log_args,
+ "git": lambda ref: ["log", f"-{max(1, min(int(ref.target or '1'), 10))}", "-p"],
}
async def _expand_reference(
- ref: ContextReference,
- cwd: Path,
- *,
- url_fetcher: Callable[[str], str | Awaitable[str]] | None = None,
- allowed_root: Path | None = None,
-) -> tuple[str | None, str | None]:
- """Return ``(warning, block)`` for one reference; exactly one side is set."""
+ ref: ContextReference, cwd: Path, *, url_fetcher: UrlFetcher = None, allowed_root: Path | None = None
+) -> Expansion:
try:
- if ref.kind == "file":
- return _expand_file_reference(ref, cwd, allowed_root=allowed_root)
- if ref.kind == "folder":
- return _expand_folder_reference(ref, cwd, allowed_root=allowed_root)
+ if ref.kind in ("file", "folder"):
+ return _expand_path_reference(ref, cwd, allowed_root=allowed_root)
if ref.kind in _GIT_REFERENCE_ARGS:
git_args = _GIT_REFERENCE_ARGS[ref.kind](ref)
return _expand_git_reference(ref, cwd, git_args, "git " + " ".join(git_args))
@@ -330,7 +248,6 @@ async def _expand_reference(
return None, f"🌐 {ref.raw} ({estimate_tokens_rough(content)} tokens)\n{content}"
except Exception as exc:
return f"{ref.raw}: {exc}", None
-
provider = _context_reference_providers.get(ref.kind)
if provider is not None:
try:
@@ -339,99 +256,53 @@ async def _expand_reference(
return None, f"📌 {ref.raw} ({estimate_tokens_rough(plugin_content)} tokens)\n{plugin_content}"
except Exception as exc:
return f"{ref.raw}: plugin expansion error: {exc}", None
-
return f"{ref.raw}: unsupported reference type", None
-def _expand_file_reference(
- ref: ContextReference,
- cwd: Path,
- *,
- allowed_root: Path | None = None,
-) -> tuple[str | None, str | None]:
+def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Path | None = None) -> Expansion:
+ """``@file:`` / ``@folder:``: resolve, allow-check, then inline text / binary stub / listing."""
+ is_folder = ref.kind == "folder"
path = _resolve_path(cwd, ref.target, allowed_root=allowed_root)
_ensure_reference_path_allowed(path)
if not path.exists():
- return f"{ref.raw}: file not found", None
- if not path.is_file():
- return f"{ref.raw}: path is not a file", None
+ return f"{ref.raw}: {ref.kind} not found", None
+ if not (path.is_dir() if is_folder else path.is_file()):
+ return f"{ref.raw}: path is not a {ref.kind}", None
+ if is_folder:
+ listing = _build_folder_listing(path, cwd)
+ return None, f"📁 {ref.raw} ({estimate_tokens_rough(listing)} tokens)\n{listing}"
if _is_binary_file(path):
# A bare "not supported" warning was a dead end (the model gave up); the file IS
# on disk where the agent's tools run, so hand it an actionable block instead.
return None, _binary_reference_block(ref, path)
-
text = path.read_text(encoding="utf-8")
if ref.line_start is not None:
- lines = text.splitlines()
- start_idx = max(ref.line_start - 1, 0)
- end_idx = min(ref.line_end or ref.line_start, len(lines))
- text = "\n".join(lines[start_idx:end_idx])
-
- lang = _code_fence_language(path)
+ text = "\n".join(text.splitlines()[max(ref.line_start - 1, 0):ref.line_end or ref.line_start])
+ lang = _FENCE_LANGUAGES.get(path.suffix.lower(), "")
return None, f"📄 {ref.raw} ({estimate_tokens_rough(text)} tokens)\n```{lang}\n{text}\n```"
-def _expand_folder_reference(
- ref: ContextReference,
- cwd: Path,
- *,
- allowed_root: Path | None = None,
-) -> tuple[str | None, str | None]:
- path = _resolve_path(cwd, ref.target, allowed_root=allowed_root)
- _ensure_reference_path_allowed(path)
- if not path.exists():
- return f"{ref.raw}: folder not found", None
- if not path.is_dir():
- return f"{ref.raw}: path is not a folder", None
- listing = _build_folder_listing(path, cwd)
- return None, f"📁 {ref.raw} ({estimate_tokens_rough(listing)} tokens)\n{listing}"
-
-
-def _run_quiet(
- cmd: list[str], cwd: Path, timeout: int, env: dict | None = None
-) -> subprocess.CompletedProcess:
+def _run_quiet(cmd: list[str], cwd: Path, timeout: int, env: dict | None = None) -> subprocess.CompletedProcess:
"""subprocess.run with captured text output, no stdin, and no console flash on Windows."""
popen_kwargs: dict = {"creationflags": windows_hide_flags()} if IS_WINDOWS else {}
- if env is not None:
- popen_kwargs["env"] = env
- return subprocess.run(
- cmd,
- cwd=cwd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=timeout,
- stdin=subprocess.DEVNULL,
- **popen_kwargs,
- )
+ return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, encoding='utf-8', errors='replace',
+ timeout=timeout, stdin=subprocess.DEVNULL, **popen_kwargs, **({} if env is None else {"env": env}))
-def _expand_git_reference(
- ref: ContextReference,
- cwd: Path,
- args: list[str],
- label: str,
-) -> tuple[str | None, str | None]:
+def _expand_git_reference(ref: ContextReference, cwd: Path, args: list[str], label: str) -> Expansion:
try:
# Repo-supplied config/attributes must never execute code (GHSA-7x36-8jrh-v4pw).
- result = _run_quiet(
- ["git", *harden_git_argv(args)], cwd, 30, env=noninteractive_git_env()
- )
+ result = _run_quiet(["git", *harden_git_argv(args)], cwd, 30, env=noninteractive_git_env())
except subprocess.TimeoutExpired:
return f"{ref.raw}: git command timed out (30s)", None
if result.returncode != 0:
- stderr = (result.stderr or "").strip() or "git command failed"
- return f"{ref.raw}: {stderr}", None
+ return f"{ref.raw}: {(result.stderr or '').strip() or 'git command failed'}", None
content = result.stdout.strip() or "(no output)"
return None, f"🧾 {label} ({estimate_tokens_rough(content)} tokens)\n```diff\n{content}\n```"
-async def _fetch_url_content(
- url: str,
- *,
- url_fetcher: Callable[[str], str | Awaitable[str]] | None = None,
-) -> str:
- fetcher = url_fetcher or _default_url_fetcher
- content = fetcher(url)
+async def _fetch_url_content(url: str, *, url_fetcher: UrlFetcher = None) -> str:
+ content = (url_fetcher or _default_url_fetcher)(url)
if inspect.isawaitable(content):
content = await content
return str(content or "").strip()
@@ -439,120 +310,76 @@ async def _fetch_url_content(
async def _default_url_fetcher(url: str) -> str:
from tools.web_tools import web_extract_tool
+ docs = json.loads(await web_extract_tool([url], format="markdown")).get("results", [])
+ return str(docs[0].get("content") or docs[0].get("raw_content") or "").strip() if docs else ""
- raw = await web_extract_tool([url], format="markdown")
- docs = json.loads(raw).get("results", [])
- if not docs:
- return ""
- doc = docs[0]
- return str(doc.get("content") or doc.get("raw_content") or "").strip()
+
+def _is_under(path: Path, root: Path) -> bool:
+ try:
+ path.relative_to(root)
+ except ValueError:
+ return False
+ return True
def _resolve_path(cwd: Path, target: str, *, allowed_root: Path | None = None) -> Path:
- path = Path(os.path.expanduser(target))
- if not path.is_absolute():
- path = cwd / path
- resolved = path.resolve()
- if allowed_root is not None:
- try:
- resolved.relative_to(allowed_root)
- except ValueError as exc:
- raise ValueError("path is outside the allowed workspace") from exc
+ resolved = (cwd / Path(os.path.expanduser(target))).resolve() # `/` keeps an absolute target as-is
+ if allowed_root is not None and not _is_under(resolved, allowed_root):
+ raise ValueError("path is outside the allowed workspace")
return resolved
def _ensure_reference_path_allowed(path: Path) -> None:
"""Refuse credential/internal paths. Fails CLOSED: the gateway feeds untrusted remote text here."""
from hermes_constants import get_hermes_home
- home = Path(os.path.expanduser("~")).resolve()
- hermes_home = get_hermes_home().resolve()
-
- blocked_exact = {home / rel for rel in _SENSITIVE_HOME_FILES}
- blocked_exact.add(hermes_home / ".env")
- blocked_dirs = [home / rel for rel in _SENSITIVE_HOME_DIRS]
- blocked_dirs.extend(hermes_home / rel for rel in _SENSITIVE_HERMES_DIRS)
-
+ home, hermes_home = Path(os.path.expanduser("~")).resolve(), get_hermes_home().resolve()
+ blocked_exact = {home / rel for rel in _SENSITIVE_HOME_FILES} | {hermes_home / ".env"}
+ blocked_dirs = [home / rel for rel in _SENSITIVE_HOME_DIRS] + [hermes_home / rel for rel in _SENSITIVE_HERMES_DIRS]
if path in blocked_exact:
raise ValueError("path is a sensitive credential file and cannot be attached")
- for blocked_dir in blocked_dirs:
- try:
- path.relative_to(blocked_dir)
- except ValueError:
- continue
+ if any(_is_under(path, blocked_dir) for blocked_dir in blocked_dirs):
raise ValueError("path is a sensitive credential or internal Hermes path and cannot be attached")
-
# Anchor to the canonical read deny-list (agent/file_safety.get_read_block_error): the
# narrow list above never caught auth.json, .anthropic_oauth.json, mcp-tokens/, webhook
# secrets or project .env files, and it grows automatically with that deny-list.
try:
from agent.file_safety import get_read_block_error
-
- if get_read_block_error(str(path)) is not None:
- raise ValueError(
- "path is a sensitive credential or internal Hermes path and cannot be attached"
- )
+ blocked = get_read_block_error(str(path)) is not None
except ValueError:
raise
except Exception:
# If the canonical lookup fails, falling through would re-open the exact hole this
# guard closes; a spurious block is recoverable, a leaked credential is not.
- raise ValueError(
- "path could not be verified against the credential deny-list and cannot be attached"
- )
+ raise ValueError("path could not be verified against the credential deny-list and cannot be attached")
+ if blocked:
+ raise ValueError("path is a sensitive credential or internal Hermes path and cannot be attached")
def _strip_trailing_punctuation(value: str) -> str:
stripped = value.rstrip(TRAILING_PUNCTUATION)
- while stripped.endswith((")", "]", "}")):
- closer = stripped[-1]
- opener = {")": "(", "]": "[", "}": "{"}[closer]
- if stripped.count(closer) > stripped.count(opener):
- stripped = stripped[:-1]
- continue
- break
+ # Drop unbalanced closers so "(see @file:x.py)" does not swallow the ")".
+ while stripped.endswith((")", "]", "}")) and stripped.count(stripped[-1]) > stripped.count(_OPENERS[stripped[-1]]):
+ stripped = stripped[:-1]
return stripped
def _strip_reference_wrappers(value: str) -> str:
- if len(value) >= 2 and value[0] == value[-1] and value[0] in "`\"'":
- return value[1:-1]
- return value
+ return value[1:-1] if len(value) >= 2 and value[0] == value[-1] and value[0] in "`\"'" else value
def _parse_file_reference_value(value: str) -> tuple[str, int | None, int | None]:
- quoted_match = re.match(
- r'^(?P<quote>`|"|\')(?P<path>.+?)(?P=quote)(?::(?P<start>\d+)(?:-(?P<end>\d+))?)?$',
- value,
- )
- if quoted_match:
- line_start = quoted_match.group("start")
- line_end = quoted_match.group("end")
- return (
- quoted_match.group("path"),
- int(line_start) if line_start is not None else None,
- int(line_end or line_start) if line_start is not None else None,
- )
-
- range_match = re.match(r"^(?P<path>.+?):(?P<start>\d+)(?:-(?P<end>\d+))?$", value)
- if range_match:
- line_start = int(range_match.group("start"))
- return (
- range_match.group("path"),
- line_start,
- int(range_match.group("end") or range_match.group("start")),
- )
-
- return _strip_reference_wrappers(value), None, None
-
-
-_TEXT_EXTENSIONS = (".py", ".md", ".txt", ".json", ".yaml", ".yml", ".toml", ".js", ".ts")
+ m = _FILE_VALUE_PATTERN.match(value)
+ start = m and m.group("start")
+ if not start: # no line range: the whole value is the (possibly quoted) path
+ return _strip_reference_wrappers(value), None, None
+ return m.group("qpath") or m.group("path"), int(start), int(m.group("end") or start)
def _is_binary_file(path: Path) -> bool:
- mime, _ = mimetypes.guess_type(path.name)
- if mime and not mime.startswith("text/") and not path.name.endswith(_TEXT_EXTENSIONS):
- return True
- return b"\x00" in path.read_bytes()[:4096]
+ mime = mimetypes.guess_type(path.name)[0]
+ return bool(mime and not mime.startswith("text/") and not path.name.endswith(_TEXT_EXTENSIONS)) or (
+ b"\x00" in path.read_bytes()[:4096]
+ )
def _build_folder_listing(path: Path, cwd: Path, limit: int = 200) -> str:
@@ -561,22 +388,23 @@ def _build_folder_listing(path: Path, cwd: Path, limit: int = 200) -> str:
base_depth = len(path.relative_to(cwd).parts)
for entry in entries:
indent = " " * max(len(entry.relative_to(cwd).parts) - base_depth - 1, 0)
- if entry.is_dir():
- lines.append(f"{indent}- {entry.name}/")
- else:
- lines.append(f"{indent}- {entry.name} ({_file_metadata(entry)})")
+ lines.append(f"{indent}- {entry.name}/" if entry.is_dir() else f"{indent}- {entry.name} ({_file_metadata(entry)})")
if len(entries) >= limit:
lines.append("- ...")
return "\n".join(lines)
def _iter_visible_entries(path: Path, cwd: Path, limit: int) -> list[Path]:
- rg_entries = _rg_files(path, cwd, limit=limit)
- if rg_entries is not None:
+ """Files under ``path`` via ``rg --files`` (honours ignore files), else an os.walk fallback."""
+ try:
+ rg = _run_quiet(["rg", "--files", str(path.relative_to(cwd))], cwd, 10)
+ except (FileNotFoundError, OSError, subprocess.TimeoutExpired):
+ rg = None
+ if rg is not None and rg.returncode == 0:
output: list[Path] = []
seen_dirs: set[Path] = set()
- for rel in rg_entries:
- full = cwd / rel
+ for line in [ln.strip() for ln in rg.stdout.splitlines() if ln.strip()][:limit]:
+ full = cwd / Path(line)
for parent in full.parents:
if parent == cwd or parent in seen_dirs or path not in {parent, *parent.parents}:
continue
@@ -584,89 +412,46 @@ def _iter_visible_entries(path: Path, cwd: Path, limit: int) -> list[Path]:
output.append(parent)
output.append(full)
return sorted({p for p in output if p.exists()}, key=lambda p: (not p.is_dir(), str(p)))
-
output = []
for root, dirs, files in os.walk(path):
dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d != "__pycache__")
files = sorted(f for f in files if not f.startswith("."))
- root_path = Path(root)
for name in dirs + files:
- output.append(root_path / name)
+ output.append(Path(root) / name)
if len(output) >= limit:
return output
return output
-def _rg_files(path: Path, cwd: Path, limit: int) -> list[Path] | None:
+def _binary_reference_block(ref: ContextReference, path: Path) -> str:
+ mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
try:
- result = _run_quiet(["rg", "--files", str(path.relative_to(cwd))], cwd, 10)
- except (FileNotFoundError, OSError, subprocess.TimeoutExpired):
- return None
- if result.returncode != 0:
- return None
- files = [Path(line.strip()) for line in result.stdout.splitlines() if line.strip()]
- return files[:limit]
-
-
-def _agent_visible_path(path: Path) -> str:
- """Map a host path to what the agent's tools can read in the active backend.
-
- Under a container backend the host path dangles inside the sandbox; files staged
- into an auto-mounted cache dir are translated via ``tools.credential_files``.
- Falls back to the host path when the backend is local or translation fails.
- """
+ size = format_bytes(path.stat().st_size)
+ except OSError:
+ size = "unknown size"
+ # Under a container backend the host path dangles inside the sandbox: translate staged
+ # files to their auto-mounted cache path; fall back to the host path (local backend /
+ # translation failure). Run the idempotent TERMINAL_ENV bridge first so in-process
+ # gateways that never bridged terminal.* config still see the active backend.
try:
- # In-process gateways may not have bridged terminal.* config into TERMINAL_ENV
- # yet; run the idempotent bridge so the translation gate sees the active backend.
from tools.terminal_tool import _ensure_terminal_env_bridged
-
_ensure_terminal_env_bridged()
from tools.credential_files import to_agent_visible_cache_path
-
- return to_agent_visible_cache_path(str(path))
+ visible = to_agent_visible_cache_path(str(path))
except Exception:
- return str(path)
-
-
-def _binary_reference_block(ref: ContextReference, path: Path) -> str:
- mime, _ = mimetypes.guess_type(path.name)
- mime = mime or "application/octet-stream"
- try:
- size = format_bytes(path.stat().st_size)
- except OSError:
- size = "unknown size"
+ visible = str(path)
return (
f"📎 {ref.raw} ({mime}, {size}) — binary file, not inlined as text. "
- f"It is available on disk at `{_agent_visible_path(path)}`. Use your tools to work with it "
+ f"It is available on disk at `{visible}`. Use your tools to work with it "
f"(read or convert it, extract its text, or view/render it as needed); "
f"do not tell the user the file type is unsupported."
)
def _file_metadata(path: Path) -> str:
- if _is_binary_file(path):
- return f"{path.stat().st_size} bytes"
- try:
- line_count = path.read_text(encoding="utf-8").count("\n") + 1
- except Exception:
- return f"{path.stat().st_size} bytes"
- return f"{line_count} lines"
-
-
-_FENCE_LANGUAGES = {
- ".py": "python",
- ".js": "javascript",
- ".ts": "typescript",
- ".tsx": "tsx",
- ".jsx": "jsx",
- ".json": "json",
- ".md": "markdown",
- ".sh": "bash",
- ".yml": "yaml",
- ".yaml": "yaml",
- ".toml": "toml",
-}
-
-
-def _code_fence_language(path: Path) -> str:
- return _FENCE_LANGUAGES.get(path.suffix.lower(), "")
+ if not _is_binary_file(path):
+ try:
+ return f"{path.read_text(encoding='utf-8').count(chr(10)) + 1} lines"
+ except Exception:
+ pass
+ return f"{path.stat().st_size} bytes"