The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(usage-window): carry the plan gauge on the canonical usage feed
Teknium655926daba2e
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 59ed430b2dd..19bbc924e30 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -605,8 +605,16 @@ export interface Usage {dev_credits_spent_micros?: number | nullcost_usd?: number | nullcost_status?: string | null+ plan_gauge?: PlanGauge | null[key: string]: unknown}+/** ``gateway/session_usage.py::plan_gauge``: a window plan's allowance for the status bar. */+export interface PlanGauge {+ id: string+ label: string+ used_bp: number+ resets_at_ms?: number | null+}export interface McpServerStatus {name?: stringstatus?: string | null@@ -3510,6 +3518,7 @@ export interface SessionUsageResult {dev_credits_spent_micros?: number | nullcost_usd?: number | nullcost_status?: string | null+ plan_gauge?: PlanGauge | nullcredits_lines?: string[] | nullcredits_usage_window?: boolean | null[key: string]: unknown@@ -4711,6 +4720,7 @@ export interface SessionStats {model: stringprovider: stringfallback_model?: string | null+ plan_gauge?: PlanGauge | null}export interface RollbackSessionDiffParams {session_id: string@@ -5755,6 +5765,7 @@ export interface SessionUsagePayload {model?: string | nullprovider?: string | nullfallback_model?: string | null+ plan_gauge?: PlanGauge | null}/** ``prompt_turn._invoke_agent`` ``_on_session_title`` hook. */export interface SessionTitlePayload {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 534f4e64162..96b343ba04d 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -27255,6 +27255,43 @@"title": "PingResult","type": "object"},+ "PlanGauge": {+ "additionalProperties": false,+ "description": "``gateway/session_usage.py::plan_gauge``: a window plan's allowance for the status bar.",+ "properties": {+ "id": {+ "title": "Id",+ "type": "string"+ },+ "label": {+ "title": "Label",+ "type": "string"+ },+ "used_bp": {+ "title": "Used Bp",+ "type": "integer"+ },+ "resets_at_ms": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Resets At Ms"+ }+ },+ "required": [+ "id",+ "label",+ "used_bp"+ ],+ "title": "PlanGauge",+ "type": "object"+ },"PlanUsage": {"additionalProperties": false,"description": "``hermes_cli/model_picker_usage.py::PickerUsage.to_payload`` \u2014 usage-window plan chrome.",@@ -38736,6 +38773,17 @@],"default": null,"title": "Fallback Model"+ },+ "plan_gauge": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/PlanGauge"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"required": [@@ -39277,6 +39325,17 @@],"default": null,"title": "Fallback Model"+ },+ "plan_gauge": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/PlanGauge"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"title": "SessionUsagePayload",@@ -39505,6 +39564,17 @@"default": null,"title": "Cost Status"},+ "plan_gauge": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/PlanGauge"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },"credits_lines": {"anyOf": [{@@ -45147,6 +45217,17 @@],"default": null,"title": "Cost Status"+ },+ "plan_gauge": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/PlanGauge"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"title": "Usage",diff --git a/gateway/session_usage.py b/gateway/session_usage.pyindex 68c3102c62c..225d31cc2e8 100644--- a/gateway/session_usage.py+++ b/gateway/session_usage.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport contextlibimport dataclasses+import time_COUNTERS = (("input_tokens", "session_input_tokens"), ("output_tokens", "session_output_tokens"),("cache_read_tokens", "session_cache_read_tokens"),@@ -57,6 +58,23 @@ def _rate_limit(agent):return None+def plan_gauge(agent) -> dict | None:+ """Window plans only: the allowance the status bar shows at a glance (today's, else the one that binds),+ from the reply headers the agent already tracks — no extra round trip, None for everyone else."""+ with contextlib.suppress(Exception):+ state = getattr(agent, "_credits_state", None)+ if getattr(state, "is_usage_window", False) is True: # `is True`: a Mock agent's attribute is not a plan+ binding = state.binding_gauge+ day = next((g for g in state.gauges if g.id == "day" and g.scope == "all"), None)+ # A full allowance is what blocks, so it wins over today's; a passed reset is no longer current.+ gauge = binding if binding is not None and binding.full else (day or binding)+ reset = getattr(gauge, "resets_at_ms", None)+ if gauge is not None and not (isinstance(reset, int) and 0 < reset <= int(time.time() * 1000)):+ return {"id": gauge.id, "label": gauge.label, "used_bp": int(gauge.used_bp),+ "resets_at_ms": gauge.resets_at_ms}+ return None++def usage_stats(agent) -> dict:"""The frozen ``session.usage`` / ``session.stats`` dict; zeros before the first turn built an agent."""stats: dict = {key: int(getattr(agent, attr, 0) or 0) for key, attr in _COUNTERS}@@ -80,6 +98,8 @@ def usage_stats(agent) -> dict:model=str(getattr(agent, "model", "") or ""), provider=str(getattr(agent, "provider", "") or ""),fallback_model=(str(getattr(agent, "model", "") or "") or None)if getattr(agent, "_fallback_activated", False) is True else None)+ if (gauge := plan_gauge(agent)) is not None: # absent off a window plan, as on the embedded path+ stats["plan_gauge"] = gaugereturn stats@@ -134,6 +154,8 @@ def tui_usage(stats: dict) -> dict:usage[key] = round(float(stats[source_key]), 1)if isinstance(stats.get("active_subagents"), int):usage["active_subagents"] = stats["active_subagents"]+ if isinstance(stats.get("plan_gauge"), dict):+ usage["plan_gauge"] = stats["plan_gauge"]return usagediff --git a/tests/gateway/test_local_viewer_usage.py b/tests/gateway/test_local_viewer_usage.pyindex 44cd5bfba79..09d1fb78820 100644--- a/tests/gateway/test_local_viewer_usage.py+++ b/tests/gateway/test_local_viewer_usage.py@@ -175,6 +175,28 @@ def test_published_usage_view_matches_the_embedded_ticker(agent):assert frame['usage'] == _get_usage(agent)+def test_a_window_plans_gauge_rides_the_canonical_usage_feed():+ """The Desktop status bar's plan allowance reads ``usage.plan_gauge``; a normal local session's+ ticks and turn-end usage come from the gateway (``usage_frame`` / ``tui_usage``), not ``_get_usage``."""+ from agent.credits_tracker import CreditsState+ from agent.usage_gauges import WindowGauge+ from gateway.session_usage import publish_usage, tui_usage, usage_stats+ from tui_gateway.contracts.registry import CANONICAL_METHODS, EVENTS+ from tui_gateway.server import _get_usage++ day = WindowGauge(id='day', scope='all', label='today', used_bp=4_200, resets_at_ms=4_000_000_000_000)+ agent = _agent()+ agent._credits_state = CreditsState(denominator_kind='usage_window', gauges=(day,))+ published = []+ publish_usage(_turn(Platform.LOCAL, published, agent), agent)+ frame = published[-1][1]+ expected = {'id': 'day', 'label': 'today', 'used_bp': 4_200, 'resets_at_ms': 4_000_000_000_000}+ assert frame['usage']['plan_gauge'] == expected == _get_usage(agent)['plan_gauge']+ assert tui_usage(usage_stats(agent))['plan_gauge'] == expected # message.complete.usage+ EVENTS['session.usage'].payload.model_validate(frame)+ CANONICAL_METHODS['session.stats'].result.model_validate(usage_stats(agent))++def test_turn_end_publishes_the_agents_banner_info():"""Main re-emitted ``session.info`` at every turn end; the first turn's carries the built agent's``system_prompt`` (the banner's ``▸ System Prompt — N chars`` row, FINDINGS row 2) and tools."""diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.pyindex d71c449a32d..3a9dd88a19d 100644--- a/tui_gateway/contracts/canonical.py+++ b/tui_gateway/contracts/canonical.py@@ -12,7 +12,7 @@ from __future__ import annotationsfrom typing import Literalfrom .base import JsonValue, Params, Result-from .common import McpServerStatus, OpenModel, ProjectRef+from .common import McpServerStatus, OpenModel, PlanGauge, ProjectReffrom .events import SkinPayloadfrom .groups_bot_relay import RoomParams, RoomTaskReceiptfrom .prompt_voice import ClarifyLockParams, ClarifyLockResult@@ -237,6 +237,7 @@ class SessionStats(Result):model: strprovider: strfallback_model: str | None = None+ plan_gauge: PlanGauge | None = Nonecanonical_method("session.stats", params=SessionStatsParams, result=SessionStats,diff --git a/tui_gateway/contracts/common.py b/tui_gateway/contracts/common.pyindex 241c316bfd5..2f6702df5f7 100644--- a/tui_gateway/contracts/common.py+++ b/tui_gateway/contracts/common.py@@ -16,6 +16,15 @@ class OpenModel(Result):model_config = Result.model_config | {"extra": "allow"}+class PlanGauge(Result):+ """``gateway/session_usage.py::plan_gauge``: a window plan's allowance for the status bar."""++ id: str+ label: str+ used_bp: int+ resets_at_ms: int | None = None++class Usage(OpenModel):"""``tui_gateway/server.py::_get_usage`` + ``agent/context_breakdown.py::context_usage_fields``."""@@ -42,6 +51,7 @@ class Usage(OpenModel):dev_credits_spent_micros: int | None = Nonecost_usd: float | None = Nonecost_status: str | None = None+ plan_gauge: PlanGauge | None = Noneclass ProjectRef(Result):diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 1d9603953cf..d782b3e6eec 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -18,7 +18,7 @@ from __future__ import annotationsfrom pydantic import Fieldfrom .base import JsonValue, Payload, WireEnum-from .common import MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usage+from .common import MessageReaction, PlanGauge, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usagefrom .config_free_tier_control import FreeTierChallengePayload, SessionControlSnapshotfrom .registry import event@@ -336,6 +336,7 @@ class SessionUsagePayload(Payload):model: str | None = Noneprovider: str | None = Nonefallback_model: str | None = None+ plan_gauge: PlanGauge | None = Noneevent("session.usage", SessionUsagePayload, doc="Mid-turn usage tick; message.complete carries the authoritative final usage.")diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 446567f2a35..b9ab08d4b48 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1421,19 +1421,10 @@ def _get_usage(agent) -> dict:for _key, _val in (("avg_latency_s", _total_lat / _n), ("avg_tps", _avg_vel)):if _val is not None and _val == _val and 0 < _val < 1e6: # guard NaN/negative/absurd provider timingsusage[_key] = round(float(_val), 1)- # Window plans only: the allowance the desktop status bar shows at a glance (today's, else the one that- # binds), from the reply headers the agent already tracks — no extra round trip, absent for everyone else.- with contextlib.suppress(Exception):- state = getattr(agent, "_credits_state", None)- if getattr(state, "is_usage_window", False) is True: # `is True`: a Mock agent's attribute is not a plan- binding = state.binding_gauge- day = next((g for g in state.gauges if g.id == "day" and g.scope == "all"), None)- # A full allowance is what blocks, so it wins over today's; a passed reset is no longer current.- gauge = binding if binding is not None and binding.full else (day or binding)- reset = getattr(gauge, "resets_at_ms", None)- if gauge is not None and not (isinstance(reset, int) and 0 < reset <= int(time.time() * 1000)):- usage["plan_gauge"] = {"id": gauge.id, "label": gauge.label, "used_bp": int(gauge.used_bp),- "resets_at_ms": gauge.resets_at_ms}+ # Window plans only: the desktop status bar's allowance (the canonical feed carries the same one).+ from gateway.session_usage import plan_gauge+ if (gauge := plan_gauge(agent)) is not None:+ usage["plan_gauge"] = gauge# Live count of background/async subagents (CLI status bar ⛓ parity, same async_delegation registry).with contextlib.suppress(Exception):from tools.async_delegation import active_count as _async_active_count