Skip to content

The agent that grows with you

agent: forward first stream chunk timestamp to post_api_request hook

overtonebluee17276c7b402
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 3ca66656a50..50f7e5a9732 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -5516,6 +5516,14 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
# responsive. See the canonical comment block above ``_stale_streak()``.
if result["response"] is not None:
_reset_stale_streak(agent)
+ # Surface first-chunk timing for observability (forwarded to the
+ # ``post_api_request`` plugin hook by the conversation loop). The
+ # per-attempt stream diagnostic dict already records ``first_chunk_at``
+ # on the first received chunk; propagate the latest value onto the agent
+ # so the loop can read it without threading the diag through returns.
+ _diag_last = request_client_holder.get("diag")
+ if isinstance(_diag_last, dict) and _diag_last.get("first_chunk_at"):
+ agent._last_api_first_chunk_at = float(_diag_last["first_chunk_at"])
return result["response"]
# ── Provider fallback ──────────────────────────────────────────────────
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 2b7a336c806..b0946d276bd 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -3153,6 +3153,10 @@ def run_conversation(
try:
agent._reset_stream_delivery_tracking()
+ # Per-attempt first-chunk timestamp, refreshed each attempt so
+ # a stale value from a previous API call can never leak into
+ # the post_api_request hook (set again on stream success).
+ agent._last_api_first_chunk_at = None
# api_messages is built once, before this retry loop, while the
# primary provider is active. A mid-conversation fallback can
# switch to a require-side provider (DeepSeek / Kimi / MiMo) that
@@ -7120,6 +7124,14 @@ def run_conversation(
api_duration=api_duration,
started_at=api_start_time,
ended_at=_api_ended_at,
+ # First received stream chunk timestamp (epoch seconds), set by
+ # interruptible_streaming_api_call from its per-attempt
+ # stream diagnostics; None when the response was not
+ # streamed or no chunk arrived. TTFB =
+ # first_chunk_at - started_at.
+ first_chunk_at=getattr(
+ agent, "_last_api_first_chunk_at", None
+ ),
finish_reason=finish_reason,
message_count=len(api_messages),
response_model=getattr(response, "model", None),
diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.py
index 549ce0e68c4..aaff4f73b2e 100644
--- a/hermes_cli/hooks.py
+++ b/hermes_cli/hooks.py
@@ -205,6 +205,9 @@ _DEFAULT_PAYLOADS = {
"api_mode": "anthropic_messages",
"api_call_count": 1,
"api_duration": 1.234,
+ "started_at": 1756000000.0,
+ "ended_at": 1756000001.234,
+ "first_chunk_at": 1756000000.512,
"finish_reason": "stop",
"message_count": 4,
"response_model": "claude-sonnet-4-6",