Skip to content

The agent that grows with you

fix(agent): only the first attempt of a user turn carries user attribution (billing parity)

Teknium70d31a5a5da7
diff --git a/agent/agent_init.py b/agent/agent_init.py
index e311afa1407..f6328ce054d 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2179,7 +2179,7 @@ def _init_usage_state(agent):
# Per-session usage accounting.
_USAGE_STATE: dict[str, Any] = {
"_user_turn_count": 0,
- "_is_user_initiated_turn": False, "_user_initiated_api_call": None, # request_headers turn attribution
+ "_is_user_initiated_turn": False, # first API call of a user turn (provider request_headers attribution)
# Usage anchors (agent/usage_anchor.py): last response's exact usage + transcript
# snapshot; invalidated on compaction/session switch so stale anchors never suppress compression.
"_usage_anchor": None,
diff --git a/agent/turn_api_request.py b/agent/turn_api_request.py
index 26fa1f79998..f7ae756e7e2 100644
--- a/agent/turn_api_request.py
+++ b/agent/turn_api_request.py
@@ -40,16 +40,15 @@ def _set_extra_header(api_kwargs: Any, key: str, value: str) -> None:
api_kwargs["extra_headers"] = _xh
-def _apply_user_turn_request_headers(agent: Any, api_kwargs: Any, api_call_count: Any) -> None:
- """Provider per-request headers (turn attribution). The first API call of a user turn consumes the
- turn flag exactly once, whatever the route answers (or if its hook fails), and claims its
- ``api_call_count``: every attempt of that call (retry, fallback activation) rebuilds the payload with
- the same count and keeps the attribution; tool-loop follow-ups get the route's default."""
- if getattr(agent, "_is_user_initiated_turn", False):
- agent._is_user_initiated_turn = False
- agent._user_initiated_api_call = api_call_count
- if getattr(agent, "_user_initiated_api_call", None) != api_call_count:
+def _apply_user_turn_request_headers(agent: Any, api_kwargs: Any) -> None:
+ """Provider per-request headers (turn attribution). Only the first payload built in a user turn (the
+ first attempt of its first API call) is user-initiated, and it consumes the turn flag exactly once,
+ whatever the route answers (or if its hook fails). Every later build of the turn (a 429/5xx retry, a
+ fallback activation, a tool-loop follow-up) gets the route's default: the historical billing
+ behaviour, kept on purpose."""
+ if not getattr(agent, "_is_user_initiated_turn", False):
return
+ agent._is_user_initiated_turn = False
from agent.provider_route_hooks import route_answer
_request_headers = route_answer(
"request_headers", provider=agent.provider or "", base_url=agent.base_url or "",
@@ -152,7 +151,7 @@ def build_request_payload(
# retry must bypass the cache.
if agent._empty_content_retries > 0 and agent._is_openrouter_url():
_set_extra_header(api_kwargs, "X-OpenRouter-Cache", "false")
- _apply_user_turn_request_headers(agent, api_kwargs, api_call_count)
+ _apply_user_turn_request_headers(agent, api_kwargs)
try:
from hermes_cli.middleware import apply_llm_request_middleware
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 10952e4678b..83d29da847d 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -1127,7 +1127,6 @@ def build_turn_context(
# Turn-initiator state for per-request provider headers: the first API call of this
# user turn is user-initiated; tool-loop follow-ups are agent-initiated.
agent._is_user_initiated_turn = True
- agent._user_initiated_api_call = None
# Preserve the original user message (no nudge injection).
original_user_message = persist_user_message if persist_user_message is not None else user_message
diff --git a/providers/base.py b/providers/base.py
index 48e0418db21..4f8abd00463 100644
--- a/providers/base.py
+++ b/providers/base.py
@@ -462,7 +462,7 @@ class ProviderProfile:
def request_headers(self, *, base_url: str, model: str = "", user_initiated: bool = False) -> dict[str, str]:
"""Per-request headers (``extra_headers``) for *base_url*; ``user_initiated`` is True only on the
- first API call of a user turn, every attempt of it (attribution). Pure: core memoizes the answer per argument set."""
+ first attempt of a user turn's first API call (attribution). Pure: core memoizes the answer per argument set."""
return {}
def max_tokens_param(self, *, base_url: str, model: str = "") -> str | None:
diff --git a/run_agent.py b/run_agent.py
index 643cf274455..c6b2267fd4e 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -406,8 +406,8 @@ class AIAgent(
self._compaction_prompt_drift_logged = False
# Who wrote the current turn. build_turn_context() sets it at the start of every turn.
self._turn_author = None
- # First API call of a user turn (provider request_headers) and the api_call_count that claimed it.
- self._is_user_initiated_turn, self._user_initiated_api_call = False, None
+ # True for the first API call of a user turn, False for tool-loop follow-ups (provider request_headers).
+ self._is_user_initiated_turn = False
self._transition_context_engine_session(
old_session_id=old_session_id, new_session_id=getattr(self, "session_id", None),
diff --git a/tests/agent/test_provider_wire_seams.py b/tests/agent/test_provider_wire_seams.py
index 26f164009b8..e428de49816 100644
--- a/tests/agent/test_provider_wire_seams.py
+++ b/tests/agent/test_provider_wire_seams.py
@@ -130,15 +130,14 @@ def test_user_turn_attribution_is_consumed_by_the_first_call_only(wire_profile):
assert "X-Attr" not in (_payload(agent, api_call_count=2).get("extra_headers") or {}) # tool-loop follow-up
-def test_every_attempt_of_the_first_call_keeps_user_turn_attribution(wire_profile):
- # A 429/5xx retry (or a fallback activation) rebuilds the payload for the SAME API call: still the user's.
+def test_only_the_first_attempt_of_a_user_turn_carries_user_attribution(wire_profile):
+ # A 429/5xx retry (or a fallback activation) rebuilds the payload for the same API call; like Hermes
+ # always has, it goes out with the route's default attribution (billing parity), not the user's.
agent = _agent("wirefake", HOST)
agent._is_user_initiated_turn = True
assert _payload(agent, api_call_count=1).get("extra_headers") == {"X-Attr": "user"}
- assert _payload(agent, api_call_count=1).get("extra_headers") == {"X-Attr": "user"} # retried attempt
+ assert "X-Attr" not in (_payload(agent, api_call_count=1).get("extra_headers") or {}) # retried attempt
assert "X-Attr" not in (_payload(agent, api_call_count=2).get("extra_headers") or {})
- agent.reset_session_state()
- assert "X-Attr" not in (_payload(agent, api_call_count=1).get("extra_headers") or {})
def test_route_without_attribution_still_consumes_the_turn_flag(wire_profile):