Skip to content

The agent that grows with you

Merge origin/main (562ee8ab76a): fold usage-less empty-response guard, unterminated tool-call strip, skills-first memory guidance into the simplified modules

Teknium3bff2a581dc0
diff --cc agent/agent_runtime_helpers.py
index 3101db3e43e,1880698e81b..5f3d0ede464
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@@ -46,18 -81,36 +46,29 @@@ _TOOL_CALL_BLOCK_PATTERNS = tuple
_NAMED_FUNCTION_BLOCK_PATTERN = re.compile(
r'(?:(?<=^)|(?<=[\n\r.!?:]))[ \t]*'
r'<function\b[^>]*\bname\s*=[^>]*>'
- r'(?:(?:(?!</function>).)*)</function>',
- re.DOTALL | re.IGNORECASE,
+ r'(?:(?:(?!</function>).)*)</function>', re.DOTALL | re.IGNORECASE,
)
-
_UNTERMINATED_REASONING_BLOCK_PATTERN = re.compile(
- rf'(?:^|\n)[ \t]*<(?:{"|".join(_REASONING_TAG_NAMES)})\b[^>]*>.*$',
- re.DOTALL | re.IGNORECASE,
+ rf'(?:^|\n)[ \t]*<(?:{"|".join(_REASONING_TAG_NAMES)})\b[^>]*>.*$', re.DOTALL | re.IGNORECASE
)
-
_ORPHAN_REASONING_TAG_PATTERN = re.compile(
- rf'</?(?:{"|".join(_REASONING_TAG_NAMES)})>\s*',
- re.IGNORECASE,
+ rf'</?(?:{"|".join(_REASONING_TAG_NAMES)})>\s*', re.IGNORECASE
)
-
_STRAY_TOOL_CALL_CLOSER_PATTERN = re.compile(
- rf'</(?:{"|".join(_TOOL_CALL_TAG_NAMES)}|function)>\s*',
- re.IGNORECASE,
+ rf'</(?:{"|".join(_TOOL_CALL_TAG_NAMES)}|function)>\s*', re.IGNORECASE
)
+ # A tool-call opener with no closer, or GLM-style argument markup
+ # (<arg_key>/<arg_value>) outside any closed block, means the stream was
+ # cut mid-serialization of a text-channel tool call (#101899). The call
+ # can't be recovered; strip from the block-boundary opener (or the line
+ # holding the first stray argument tag) to the end of the text.
+ _UNTERMINATED_TOOL_CALL_PATTERN = re.compile(
+ rf'(?:^|\n)[ \t]*<(?:{"|".join(_TOOL_CALL_TAG_NAMES)})\b[^>]*>.*$'
+ r'|(?:^|\n)[^\n<]*</?arg_(?:key|value)\b.*$',
+ re.DOTALL | re.IGNORECASE,
+ )
+
def _ra():
"""Lazy ``run_agent`` reference for test-patch routing."""
@@@ -541,47 -981,104 +552,47 @@@ def repair_message_sequence_with_cursor
return repairs
+def _flatten_content_text(content: Any) -> str:
+ """Flatten list/dict content (e.g. Anthropic-via-OpenRouter block lists) to text: a raw list
+ hitting ``re.sub`` raises TypeError and the loop retries forever. Thinking/reasoning blocks
+ are dropped outright; their text key varies per provider."""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "".join(
+ part if isinstance(part, str) else part.get("text")
+ for part in content
+ if isinstance(part, str) or (
+ isinstance(part, dict)
+ and str(part.get("type") or "").strip().lower() not in {"thinking", "reasoning", "redacted_thinking"}
+ and isinstance(part.get("text"), str) and part.get("text")
+ )
+ )
+ if isinstance(content, dict):
+ return str(content.get("text") or content.get("content") or "")
+ return str(content)
+
+
+# Order matters: closed pairs first (case-insensitive so mixed-case tags don't fall through to the
+# unterminated pass and eat trailing content), then tool-call XML blocks, the boundary+name-gated
+# <function> block, the unterminated reasoning block, stray orphan reasoning tags, and finally stray
+# tool-call CLOSERS only (bare/unterminated <function> is kept: a truncated streaming tail may still
+# be valuable, matching OpenClaw's asymmetry).
+_THINK_STRIP_PATTERNS = (
+ *_REASONING_BLOCK_PATTERNS, *_TOOL_CALL_BLOCK_PATTERNS, _NAMED_FUNCTION_BLOCK_PATTERN,
+ _UNTERMINATED_REASONING_BLOCK_PATTERN, _ORPHAN_REASONING_TAG_PATTERN,
- _STRAY_TOOL_CALL_CLOSER_PATTERN,
++ _STRAY_TOOL_CALL_CLOSER_PATTERN, _UNTERMINATED_TOOL_CALL_PATTERN,
+)
+
def strip_think_blocks(agent, content: str) -> str:
- """Remove reasoning/thinking blocks from content, returning only visible text.
-
- Handles four cases:
- 1. Closed tag pairs (`` <think>… ``) — the common path when
- the provider emits complete reasoning blocks.
- 2. Unterminated open tag at a block boundary (start of text or
- after a newline) — e.g. MiniMax M2.7 / NIM endpoints where the
- closing tag is dropped. Everything from the open tag to end
- of string is stripped. The block-boundary check mirrors
- ``gateway/stream_consumer.py``'s filter so models that mention
- `` <think>`` in prose aren't over-stripped.
- 3. Stray orphan open/close tags that slip through.
- 4. Tag variants: `` <think>``, ``<thinking>``, ``<reasoning>``,
- ``<REASONING_SCRATCHPAD>``, ``<thought>`` (Gemma 4), all
- case-insensitive.
-
- Additionally strips standalone tool-call XML blocks that some open
- models (notably Gemma variants on OpenRouter) emit inside assistant
- content instead of via the structured ``tool_calls`` field:
- * ``<tool_call>…</tool_call>``
- * ``<tool_calls>…</tool_calls>``
- * ``<tool_result>…</tool_result>``
- * ``<function_call>…</function_call>``
- * ``<function_calls>…</function_calls>``
- * ``<function name="…">…</function>`` (Gemma style)
- Ported from openclaw/openclaw#67318. The ``<function>`` variant is
- boundary-gated (only strips when the tag sits at start-of-line or
- after punctuation and carries a ``name="..."`` attribute) so prose
- mentions like "Use <function> in JavaScript" are preserved.
- """
- if not content:
- return ""
- # Coerce non-string content to text before any regex runs. Providers
- # that return assistant ``content`` as a list of blocks (Anthropic via
- # OpenRouter emits ``[{"type":"text",...}, {"type":"thinking",...}]``) or
- # as a dict flow into this shared helper from several callers — most
- # notably ``_interim_assistant_visible_text`` reading a *stored* history
- # message whose content was persisted as a list. A raw list/dict reaching
- # ``re.sub`` below raises ``TypeError: expected string or bytes-like
- # object, got 'list'``, which the outer conversation loop swallows and
- # retries forever (observed as an infinite "preparing terminal…" loop on
- # Anthropic models via OpenRouter). Flatten here so every caller is safe.
- if not isinstance(content, str):
- if isinstance(content, list):
- _parts: list[str] = []
- for _part in content:
- if isinstance(_part, str):
- _parts.append(_part)
- elif isinstance(_part, dict):
- _ptype = str(_part.get("type") or "").strip().lower()
- # Drop reasoning/thinking blocks outright — this function's
- # whole job is to strip them, and their text lives under
- # different keys ("thinking", "reasoning") per provider.
- if _ptype in {"thinking", "reasoning", "redacted_thinking"}:
- continue
- _text = _part.get("text")
- if isinstance(_text, str) and _text:
- _parts.append(_text)
- content = "".join(_parts)
- elif isinstance(content, dict):
- content = str(content.get("text") or content.get("content") or "")
- else:
- content = str(content)
- if not content:
- return ""
- # 1. Closed tag pairs — case-insensitive for all variants so
- # mixed-case tags (<THINK>, <Thinking>) don't slip through to
- # the unterminated-tag pass and take trailing content with them.
- for _pattern in _REASONING_BLOCK_PATTERNS:
- content = _pattern.sub('', content)
- # 1b. Tool-call XML blocks (openclaw/openclaw#67318). Handle the
- # generic tag names first — they have no attribute gating since
- # a literal <tool_call> in prose is already vanishingly rare.
- for _pattern in _TOOL_CALL_BLOCK_PATTERNS:
- content = _pattern.sub('', content)
- # 1c. <function name="...">...</function> — Gemma-style standalone
- # tool call. Only strip when the tag sits at a block boundary
- # (start of text, after a newline, or after sentence-ending
- # punctuation) AND carries a name="..." attribute. This keeps
- # prose mentions like "Use <function> to declare" safe.
- content = _NAMED_FUNCTION_BLOCK_PATTERN.sub('', content)
- # 2. Unterminated reasoning block — open tag at a block boundary
- # (start of text, or after a newline) with no matching close.
- # Strip from the tag to end of string. Fixes #8878 / #9568
- # (MiniMax M2.7 leaking raw reasoning into assistant content).
- content = _UNTERMINATED_REASONING_BLOCK_PATTERN.sub('', content)
- # 3. Stray orphan open/close tags that slipped through.
- content = _ORPHAN_REASONING_TAG_PATTERN.sub('', content)
- # 3b. Stray tool-call closers. (We do NOT strip bare <function> or
- # unterminated <function name="..."> because a truncated tail
- # during streaming may still be valuable to the user; matches
- # OpenClaw's intentional asymmetry.)
- content = _STRAY_TOOL_CALL_CLOSER_PATTERN.sub('', content)
- # 3c. Tool-call openers or argument markup surviving 1b belong to a
- # block that never closed — a mid-serialization stream cut (#101899).
- content = _UNTERMINATED_TOOL_CALL_PATTERN.sub('', content)
+ """Remove reasoning/thinking blocks from content, returning only visible text: closed tag
+ pairs, unterminated open tags at a block boundary (mirrors ``gateway/stream_consumer.py``),
+ stray orphan tags (all case-insensitive variants), and standalone tool-call XML blocks some
+ open models emit; ``<function>`` is boundary- and ``name=``-gated so prose mentions survive."""
+ content = _flatten_content_text(content) if content else ""
+ for pattern in _THINK_STRIP_PATTERNS if content else ():
+ content = pattern.sub('', content)
return content
diff --cc agent/empty_response_guard.py
index 7e7e66ab5ee,293d677bfdd..1d8a563db00
--- a/agent/empty_response_guard.py
+++ b/agent/empty_response_guard.py
@@@ -1,22 -1,45 +1,45 @@@
-"""Deterministic-empty detection and cost-aware retry budgets (NS-503).
+"""Deterministic-empty detection and cost-aware retry budgets.
-When a provider returns an empty completion, the agent loop retries up to
-3 times and then walks the fallback chain. Every attempt re-sends the full
-conversation input — at large context on paid routes this bills the user
-repeatedly for a turn that produces no text (the "charged ~$2.33 for an
-empty answer" incident class).
+On an empty completion the loop retries up to 3 times, then walks the fallback chain —
+each attempt re-bills the full input. Signaled refusals (``content_filter``, Anthropic
+``refusal``, Bedrock guardrails) are already terminal; this handles *unsignaled* empties
+(success, zero output tokens, generic finish reason — typical of portal-proxied refusals).
-Signaled refusals (``finish_reason="content_filter"``, Anthropic
-``stop_reason="refusal"``, Bedrock guardrails) are already terminal and
-never reach the empty-retry loop. This module addresses the *unsignaled*
-empties: the provider reports a successful completion with zero output
-tokens and a generic finish reason (portal-proxied refusals commonly look
-like this).
+Two independent guards, both failing OPEN to legacy behaviour:
-Two independent guards, both failing OPEN to today's behaviour:
+1. Deterministic-empty: two consecutive empties, both with usage present and
+ ``output_tokens == 0``, from the same (model, provider, finish_reason) → skip the
+ remaining retries and go straight to the fallback chain. Missing usage or
+ ``output_tokens > 0`` (think-block stripping, whitespace, flaky decoding) never classifies.
+2. Cost-aware budget: when one empty attempt's estimated input cost exceeds the threshold
+ (default $0.25), the retry budget drops from 3 to 1. Unknown pricing / missing usage /
+ included routes leave it untouched.
- Config ``agent.empty_response_guard.{enabled, cost_threshold_usd}`` is resolved once by
- ``agent_init`` and stashed on the agent so the hot loop never re-reads config (no env vars).
+ 1. **Deterministic-empty detection** — two consecutive empty attempts from
+ the same (model, provider, finish_reason) are treated as deterministic
+ when usage proves zero output, or when usage is absent and the assembled
+ responses contain neither content nor reasoning. Remaining retries are
+ skipped and the loop proceeds straight to the fallback chain (a different
+ model may behave differently). Mixed evidence or any generated tokens keep
+ the full retry budget.
+
+ 2. **Cost-aware retry budget** — when the estimated input cost of a
+ single empty attempt exceeds the configured threshold (default
+ $0.25), the empty-retry budget for this streak drops from 3 to 1.
+ Unknown pricing, missing usage, or included/subscription routes
+ leave the budget untouched.
+
+ Configured via the additive ``agent.empty_response_guard`` section in
+ ``config.yaml`` (resolved once at agent init by ``agent_init``)::
+
+ agent:
+ empty_response_guard:
+ enabled: true # false = legacy fixed 3-retry behaviour
+ cost_threshold_usd: 0.25 # per-attempt cost that halves the budget
+
+ Per project policy, no ``HERMES_*`` environment variables are involved —
+ ``.env`` is reserved for credentials; behavioural settings live in
+ ``config.yaml``.
"""
from __future__ import annotations
@@@ -146,11 -200,20 +170,17 @@@ def _zero_output(agent: Any, response:
return (True, (output + reasoning) == 0)
- def record_empty_attempt(agent: Any, *, finish_reason: str, response: Any) -> None:
+ def record_empty_attempt(
+ agent: Any,
+ *,
+ finish_reason: str,
+ response: Any,
+ observed_generation: bool = True,
+ ) -> None:
"""Record one empty completion in the current streak.
- Must be called before ``_empty_content_retries`` is incremented for
- this attempt: a counter of 0 marks the start of a new streak and
- clears prior history (this transparently follows every existing
- counter-reset site).
- """
+ Call BEFORE ``_empty_content_retries`` is incremented: a counter of 0 marks a new
+ streak and clears prior history."""
attempts = _attempts(agent)
if getattr(agent, "_empty_content_retries", 0) == 0:
attempts.clear()
diff --cc agent/prompt_builder.py
index e5fb6bbc99e,f1c5ab0890a..6fc87fee804
--- a/agent/prompt_builder.py
+++ b/agent/prompt_builder.py
@@@ -165,15 -275,26 +165,24 @@@ def build_memory_guidance(memory_enable
else:
frame = (
"You have a persistent user profile, carried across sessions and "
- "loaded into each new session's context; save durable facts "
- "about the user with the "
- "memory tool (target='user') — the built-in notes store is "
- "disabled, so never target='memory'. "
+ "loaded into each new session's context; save durable facts about the user with the "
+ "memory tool (target='user') — the built-in notes store is disabled, so never target='memory'. "
)
return frame + (
- "Save proactively — storage has a hard character budget, and when it fills, replace or consolidate stale "
- "entries in the same batch rather than skipping the save. Write entries as declarative facts, not instructions "
- "to yourself: 'User prefers concise responses' ✓ — 'Always respond concisely' ✗ (imperative phrasing gets "
- "re-read as a directive in later sessions and can override the user's current request). Route by longevity: a "
- "fact stale within a week belongs in session history; procedures and workflows belong in skills."
+ "Skills come first: when you learn something while doing a task — a "
+ "procedure, a pitfall, and the user's preferences and corrections "
+ "for that kind of work — record it in the skill you used or built "
+ "for the task (skill_manage), where it loads only when relevant. "
+ "Memory is the narrow exception for facts that apply to EVERY "
+ "session regardless of task (who the user is, environment facts, "
+ "standing conventions with no task home); it has a hard character "
+ "budget, so when it fills, replace or consolidate stale entries "
+ "rather than skipping the save. Write entries as declarative facts, "
+ "not instructions to yourself: 'User prefers concise responses' ✓ — "
+ "'Always respond concisely' ✗ (imperative phrasing gets re-read as "
+ "a directive in later sessions and can override the user's current "
+ "request). A fact stale within a week belongs in session history; "
+ "procedures and workflows belong in skills."
)
diff --cc agent/turn_empty_response.py
index 537b0735d68,00000000000..60c8ee91ded
mode 100644,000000..100644
--- a/agent/turn_empty_response.py
+++ b/agent/turn_empty_response.py
@@@ -1,286 -1,0 +1,289 @@@
+"""Empty / thinking-only final-response recovery ladder for the conversation turn loop.
+
+Runs when the model returned no visible text after ``<think>`` blocks. Ladder order is
+load-bearing: partial-stream recovery → reuse prior turn content (housekeeping tools only)
+→ one post-tool-call nudge → thinking-only prefill continuation (×2) → empty-response
+retries (budgeted, deterministic-empty short-circuit) → fallback provider → terminal
+``(empty)`` sentinel. Nothing here imports ``agent.conversation_loop`` at module level.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional
+
+from agent import empty_response_guard as _empty_guard
+from agent.message_metadata import append_message
+from agent.turn_recovery import interruptible_backoff_sleep
+
+logger = logging.getLogger("agent.conversation_loop")
+
+_INLINE_THINK_RE = re.compile(r'<think>|<thinking>|<reasoning>', re.IGNORECASE)
+
+
+@dataclass
+class EmptyResponseVerdict:
+ """Outcome of ``recover_empty_response``.
+
+ ``action``: ``"break"`` (turn is done — ``final_response`` is set), ``"continue"``
+ (re-enter the OUTER turn loop: a nudge/prefill row was appended, a retry wait
+ elapsed, or a fallback was activated and preflight must re-run), ``"return"``
+ (interrupted during a retry wait — return ``result``) or ``"fallthrough"``
+ (unreachable: every path exits; kept for the contract)."""
+
+ action: str
+ result: Optional[Dict[str, Any]]
+ final_response: Any
+ turn_exit_reason: Any
+ active_system_prompt: Any
+ preflight_compression_blocked: bool
+
+
+def _retry_empty(
+ agent: Any, response: Any, finish_reason: str, empty_candidate: bool, *, messages: Any,
- conversation_history: Any, api_call_count: int,
++ conversation_history: Any, api_call_count: int, observed_generation: bool = False,
+) -> tuple:
+ """Budgeted empty-response retry. Each empty attempt re-bills the full input, so the
+ signature is recorded and deterministic empties stop burning paid retries (fails
+ open: missing usage or any output keeps the budget). Returns
+ ``(action_or_None, interrupt_result, deterministic_empty)``."""
+ from agent.conversation_loop import jittered_backoff
+
+ if empty_candidate:
- _empty_guard.record_empty_attempt(agent, finish_reason=finish_reason, response=response)
++ _empty_guard.record_empty_attempt(
++ agent, finish_reason=finish_reason, response=response, observed_generation=observed_generation,
++ )
+ budget = (
+ _empty_guard.empty_retry_budget(agent, response)
+ if empty_candidate else _empty_guard.DEFAULT_EMPTY_RETRY_BUDGET
+ )
+ deterministic = empty_candidate and _empty_guard.deterministic_empty(agent)
+ if not (empty_candidate and agent._empty_content_retries < budget and not deterministic):
+ return None, None, deterministic
+ agent._empty_content_retries += 1
+ n = agent._empty_content_retries
+ wait_time = jittered_backoff(n, base_delay=5.0, max_delay=60.0)
+ logger.warning(
+ "Empty response (no content or reasoning) — retry %d/%d in %.1fs (model=%s)",
+ n, budget, wait_time, agent.model,
+ )
+ _budget_note = (
+ " — high-cost request, reduced retry budget"
+ if budget < _empty_guard.DEFAULT_EMPTY_RETRY_BUDGET else ""
+ )
+ agent._buffer_status(
+ f"⚠️ Empty response from model — retrying ({n}/{budget}) in {wait_time:.0f}s{_budget_note}"
+ )
+ _interrupted = interruptible_backoff_sleep(
+ agent, wait_time, None,
+ messages=messages,
+ conversation_history=conversation_history,
+ api_call_count=api_call_count,
+ abort_message="Interrupt detected during empty-response retry wait, aborting.",
+ interrupt_text=(
+ f"Operation interrupted: retrying empty response from model (retry {n}/{budget})."
+ ),
+ activity_label=f"empty response retry backoff ({n}/{budget})",
+ )
+ if _interrupted is not None:
+ return "return", _interrupted, deterministic
+ return "continue", None, deterministic
+
+
+def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, messages: Any) -> str:
+ """Retries and fallback exhausted: persist the ``(empty)`` sentinel row and return the
+ delivery text. Reasoning is surfaced ONLY here, for delivery — the persisted row keeps
+ the sentinel so later "continue" turns don't replay it and loop on empties."""
+ _streak_cost = _empty_guard.streak_cost_usd(agent)
+ if _streak_cost is not None:
+ agent._buffer_status(
+ f"ℹ️ Estimated cost of these empty attempts: ~${_streak_cost:.2f} (input tokens are billed "
+ f"per attempt even when no answer is produced)"
+ )
+ agent._flush_status_buffer()
+ reasoning_text = agent._extract_reasoning(assistant_message)
+ agent._drop_trailing_empty_response_scaffolding(messages)
+ assistant_msg = agent._build_assistant_message(assistant_message, finish_reason)
+ assistant_msg["content"] = "(empty)"
+ assistant_msg["_empty_terminal_sentinel"] = True
+ append_message(messages, assistant_msg)
+
+ if not reasoning_text:
+ logger.warning(
+ "Empty response (no content or reasoning) after %d retries. No fallback available. "
+ "model=%s provider=%s",
+ agent._empty_content_retries, agent.model,
+ agent.provider,
+ )
+ agent._emit_status(
+ "❌ Model returned no content after all retries"
+ + (" and fallback attempts." if agent._fallback_chain else
+ ". No fallback providers configured.")
+ )
+ return "(empty)"
+
+ reasoning_preview = reasoning_text[:500] + "..." if len(reasoning_text) > 500 else reasoning_text
+ logger.warning(
+ "Reasoning-only response (no visible content) after exhausting retries and fallback. Reasoning: %s", reasoning_preview,
+ )
+ agent._emit_status(
+ "⚠️ Model produced reasoning but no visible response after all retries. Returning empty."
+ )
+ return (
+ "⚠️ The model produced only internal reasoning and no final answer, despite retries"
+ + (" and fallback" if agent._fallback_chain else "")
+ + ". Its last reasoning, which may contain the answer:\n\n" + reasoning_preview
+ )
+
+
+def recover_empty_response(
+ agent: Any, assistant_message: Any, response: Any, finish_reason: str, *, final_response: Any,
+ messages: List[Dict[str, Any]], api_messages: Any, conversation_history: Any,
+ active_system_prompt: Any, api_call_count: int, turn_exit_reason: Any,
+ preflight_compression_blocked: bool,
+) -> EmptyResponseVerdict:
+ """Recover from a final response with no visible content (see module docstring for
+ the ladder). Role alternation is preserved: the post-tool nudge appends the empty
+ assistant row BEFORE the user-level hint (APIs reject tool→user)."""
+ from agent.conversation_loop import _EMPTY_TOOL_RESPONSE_NUDGE, _sync_failover_system_message
+
+ _turn_exit_reason = turn_exit_reason
+ _preflight_compression_blocked = preflight_compression_blocked
+
+ def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> EmptyResponseVerdict:
+ return EmptyResponseVerdict(
+ action=action, result=result, final_response=final_response,
+ turn_exit_reason=_turn_exit_reason, active_system_prompt=active_system_prompt,
+ preflight_compression_blocked=_preflight_compression_blocked,
+ )
+
+ # Partial stream recovery: content streamed before the connection died becomes the
+ # final response instead of fallback or retries.
+ _partial_streamed = getattr(agent, "_current_streamed_assistant_text", "") or ""
+ if agent._has_content_after_think_block(_partial_streamed):
+ _turn_exit_reason = "partial_stream_recovery"
+ _recovered = agent._strip_think_blocks(_partial_streamed).strip()
+ logger.info(
+ "Partial stream content delivered (%d chars) — using as final response",
+ len(_recovered),
+ )
+ agent._emit_status("↻ Stream interrupted — using delivered content " "as final response")
+ final_response = _recovered
+ # A streamed fragment isn't a confirmed preview: gateway fallback delivery
+ # sends the text plus the abnormal-turn explanation.
+ agent._response_was_previewed = False
+ return _verdict("break")
+
+ # Prior turn had real content + ONLY housekeeping tools: model is done, reuse it.
+ # With substantive tools it was mid-task narration and the empty reply is a choke;
+ # let the post-tool nudge handle it.
+ fallback = getattr(agent, '_last_content_with_tools', None)
+ if fallback and getattr(agent, '_last_content_tools_all_housekeeping', False):
+ _turn_exit_reason = "fallback_prior_turn_content"
+ logger.info("Empty follow-up after tool calls — using prior turn content as final response")
+ agent._emit_status("↻ Empty response after tool calls — using earlier content as final answer")
+ agent._last_content_with_tools = None
+ agent._last_content_tools_all_housekeeping = False
+ agent._empty_content_retries = 0
+ # Do NOT modify the assistant message content (injected text poisoned history).
+ final_response = agent._strip_think_blocks(fallback).strip()
+ agent._response_was_previewed = True
+ return _verdict("break")
+
+ # Post-tool-call empty (no prior content, or only mid-task narration): nudge once.
+ _prior_was_tool = any(m.get("role") == "tool" for m in messages[-5:])
+ # Ollama puts <think> in content, not reasoning_content, so _has_structured misses
+ # it; detect here to route to prefill.
+ _has_inline_thinking = bool(_INLINE_THINK_RE.search(final_response or ""))
+ if (
+ _prior_was_tool
+ and not getattr(agent, "_post_tool_empty_retried", False)
+ and not _has_inline_thinking # thinking model still working — let prefill handle
+ ):
+ agent._post_tool_empty_retried = True
+ # Clear stale narration so it doesn't resurface on a later empty response.
+ agent._last_content_with_tools = None
+ agent._last_content_tools_all_housekeeping = False
+ logger.info("Empty response after tool calls — nudging model " "to continue processing")
+ agent._buffer_status("⚠️ Model returned empty after tool calls — " "nudging to continue")
+ # tool → assistant("(empty)") → user keeps the sequence valid.
+ _nudge_msg = agent._build_assistant_message(assistant_message, finish_reason)
+ _nudge_msg["content"] = "(empty)"
+ _nudge_msg["_empty_recovery_synthetic"] = True
+ append_message(messages, _nudge_msg)
+ append_message(messages, {
+ "role": "user", "content": _EMPTY_TOOL_RESPONSE_NUDGE, "_empty_recovery_synthetic": True
+ })
+ return _verdict("continue")
+
+ # Thinking-only prefill: append the reasoning as-is and continue so the model sees
+ # its own reasoning and writes text.
+ _has_structured = bool(
+ getattr(assistant_message, "reasoning", None)
+ or getattr(assistant_message, "reasoning_content", None)
+ or getattr(assistant_message, "reasoning_details", None)
+ or _has_inline_thinking
+ )
+ if _has_structured and agent._thinking_prefill_retries < 2:
+ agent._thinking_prefill_retries += 1
+ logger.info(
+ "Thinking-only response (no visible content) — prefilling to continue (%d/2)",
+ agent._thinking_prefill_retries,
+ )
+ agent._buffer_status(
+ f"↻ Thinking-only response — prefilling to continue ({agent._thinking_prefill_retries}/2)"
+ )
+ interim_msg = agent._build_assistant_message(assistant_message, "incomplete")
+ interim_msg["_thinking_prefill"] = True
+ append_message(messages, interim_msg)
+ agent._session_messages = messages
+ return _verdict("continue")
+
+ # Empty-response retries: truly empty replies AND reasoning-only replies after
+ # prefill exhaustion.
+ _truly_empty = not agent._strip_think_blocks(final_response).strip()
+ _empty_candidate = _truly_empty and (not _has_structured or agent._thinking_prefill_retries >= 2)
+ action, interrupt_result, _deterministic_empty = _retry_empty(
+ agent, response, finish_reason, _empty_candidate, messages=messages,
+ conversation_history=conversation_history, api_call_count=api_call_count,
++ observed_generation=_has_structured,
+ )
+ if action is not None:
+ return _verdict(action, interrupt_result)
+
+ if _truly_empty and _deterministic_empty:
+ logger.warning(
- "Deterministic empty response detected (consecutive zero-output completions, "
- "model=%s provider=%s finish_reason=%s) — skipping remaining retries",
++ "Repeated empty response detected (model=%s provider=%s finish_reason=%s) — "
++ "skipping remaining retries",
+ agent.model, agent.provider, finish_reason,
+ )
+ agent._buffer_status(
- "⚠️ Model is deterministically returning empty (zero output tokens) — skipping further retries "
++ "⚠️ Model is repeatedly returning empty content — skipping further retries "
+ "to avoid repeat charges"
+ )
+
+ # Exhausted retries — try the next provider in the chain before "(empty)".
+ if _truly_empty and agent._fallback_chain:
+ logger.warning(
+ "Empty response after %d retries — attempting fallback (model=%s, provider=%s)",
+ agent._empty_content_retries, agent.model, agent.provider,
+ )
+ agent._buffer_status("⚠️ Model returning empty responses — " "switching to fallback provider...")
+ if agent._try_activate_fallback():
+ active_system_prompt = _sync_failover_system_message(agent, api_messages, active_system_prompt)
+ agent._empty_content_retries = 0
+ agent._buffer_status(f"↻ Switched to fallback: {agent.model} " f"({agent.provider})")
+ logger.info(
+ "Fallback activated after empty responses: now using %s on %s",
+ agent.model, agent.provider,
+ )
+ # OUTER loop: `continue` re-runs preflight against the fallback's window;
+ # `break` would end the turn without calling the fallback.
+ _preflight_compression_blocked = False
+ return _verdict("continue")
+
+ _turn_exit_reason = "empty_response_exhausted"
+ final_response = _terminal_empty(agent, assistant_message, finish_reason, messages)
+ return _verdict("break")
diff --cc agent/turn_usage.py
index 87343441d1b,00000000000..2fd8f264c72
mode 100644,000000..100644
--- a/agent/turn_usage.py
+++ b/agent/turn_usage.py
@@@ -1,255 -1,0 +1,262 @@@
+"""Per-response usage accounting for the conversation turn loop.
+
+After every successful model API call, ``record_response_usage`` folds ``response.usage``
+into: the context compressor (``update_from_response`` + the compression-budget rearm
+latch), the usage anchor for display/compression math, per-session token/cost counters,
+the state.db token-delta queue, and the observability log line. MoA sessions additionally
+fold advisor fan-out usage into the reported counts and price the aggregator at its REAL
+model/provider. Logger name stays ``agent.conversation_loop`` for caplog parity.
+"""
+
+from __future__ import annotations
+
+import logging
+from contextlib import suppress
+from dataclasses import dataclass
+from typing import Any, Dict, List
+
+from agent.model_metadata import capture_usage_anchor
+from agent.usage_pricing import estimate_usage_cost, normalize_usage
+
+logger = logging.getLogger("agent.conversation_loop")
+
+
+@dataclass
+class ResponseUsageOutcome:
+ """``compression_attempts`` is the (possibly rearmed-to-zero) budget counter;
+ ``rearmed`` tells the loop to also clear its preflight-block latch."""
+
+ compression_attempts: int
+ rearmed: bool = False
+
+
+def _loop_mod():
+ """Lazy ``agent.conversation_loop`` so tests patching
+ ``agent.conversation_loop.save_context_length`` still intercept (and no import cycle)."""
+ import agent.conversation_loop as _cl
+
+ return _cl
+
+
+def _fold_moa_usage(agent, canonical_usage):
+ """MoA: fold advisor fan-out usage into REPORTED token counts (only aggregator usage is
+ returned, so advisor spend would be invisible) and flush the full-turn trace when
+ ``moa.save_traces`` is on. Returns ``(client, canonical_usage, advisor_cost)``."""
+ _moa_ref_cost = None
+ _moa_client = getattr(agent, "client", None)
+ if _moa_client is not None and hasattr(_moa_client, "consume_reference_usage"):
+ try:
+ _ref_usage, _moa_ref_cost = _moa_client.consume_reference_usage()
+ if _ref_usage is not None:
+ canonical_usage = canonical_usage + _ref_usage
+ except Exception as _moa_acct_exc: # pragma: no cover - defensive
+ logger.debug("MoA reference usage accounting failed: %s", _moa_acct_exc)
+ if _moa_client is not None and hasattr(_moa_client, "consume_and_save_trace"):
+ try:
+ # Streaming path: pass the streamed acting text so the trace is self-contained.
+ _agg_streamed_text = getattr(agent, "_current_streamed_assistant_text", "") or ""
+ _moa_client.consume_and_save_trace(
+ agent.session_id, aggregator_output_fallback=_agg_streamed_text or None
+ )
+ except Exception as _moa_trace_exc: # pragma: no cover - defensive
+ logger.debug("MoA trace flush failed: %s", _moa_trace_exc)
+ return _moa_client, canonical_usage, _moa_ref_cost
+
+
+def record_response_usage(
+ agent: Any, response: Any, *, messages: List[Dict[str, Any]], api_call_count: int,
+ api_duration: float, compression_attempts: int, max_compression_attempts: int,
+) -> ResponseUsageOutcome:
+ """Fold ``response.usage`` into compressor, anchors, session counters, state.db
+ and the API-call log line (see module docstring). No-usage responses only
+ consume a pending compaction verdict. Returns the loop-visible outcome."""
+ rearmed = False
+ compressor = agent.context_compressor
++ # Count every completed provider attempt, including providers that omit usage.
++ # Token/cost accounting below stays gated on real usage, but the request itself
++ # must remain observable.
++ agent.session_api_calls += 1
+ if not (hasattr(response, 'usage') and response.usage):
+ if getattr(compressor, "awaiting_real_usage_after_compression", False):
+ # No usage -> cannot adjudicate the prior compaction; consume the
+ # pending verdict so later readings aren't charged to it and
+ # preflight deferral isn't latched indefinitely.
+ compressor.update_from_response({})
++ logger.info(
++ "API call #%d: model=%s provider=%s in=? out=? total=? latency=%.1fs usage=unavailable",
++ agent.session_api_calls, agent.model, agent.provider or "unknown", api_duration,
++ )
+ return ResponseUsageOutcome(compression_attempts=compression_attempts, rearmed=rearmed)
+
+ canonical_usage = normalize_usage(response.usage, provider=agent.provider, api_mode=agent.api_mode)
+ # Aggregator-only usage kept for pricing: advisor tokens are priced at each advisor's
+ # OWN model rate and added as dollars below.
+ aggregator_usage = canonical_usage
+ _moa_client, canonical_usage, _moa_ref_cost = _fold_moa_usage(agent, canonical_usage)
+ prompt_tokens = canonical_usage.prompt_tokens
+ completion_tokens = canonical_usage.output_tokens
+ total_tokens = canonical_usage.total_tokens
+ # Canonical token + cache buckets for context engines; legacy keys stay for back-compat.
+ usage_dict = {
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": completion_tokens,
+ "total_tokens": total_tokens,
+ "input_tokens": canonical_usage.input_tokens,
+ "output_tokens": canonical_usage.output_tokens,
+ "cache_read_tokens": canonical_usage.cache_read_tokens,
+ "cache_write_tokens": canonical_usage.cache_write_tokens,
+ "reasoning_tokens": canonical_usage.reasoning_tokens,
+ }
+ # Capture the boundary latch before update_from_response() consumes it: only the real
+ # prompt count right after a compaction rearms the budget.
+ _completed_compaction_pending = bool(
+ getattr(compressor, "_verify_compaction_cleared_threshold", False)
+ )
+ compressor.update_from_response(usage_dict)
+ # Usage-anchored accounting: snapshot exact provider usage against the durable
+ # transcript (main-loop ONLY; MoA uses pre-fold aggregator usage). The display meter
+ # anchors on the turn's FIRST response: later same-turn responses inflate
+ # prompt_tokens with replayed thinking. Display-only; compression math uses real usage.
+ _new_anchor = capture_usage_anchor(
+ aggregator_usage.prompt_tokens, aggregator_usage.output_tokens, messages
+ )
+ if _new_anchor is not None:
+ agent._usage_anchor = _new_anchor
+ if api_call_count == 1:
+ agent._turn_base_usage_anchor = _new_anchor
+ _compression_threshold = int(getattr(compressor, "threshold_tokens", 0) or 0)
+ if _loop_mod()._should_rearm_compression_budget(
+ compression_attempts, completed_compaction_pending=_completed_compaction_pending,
+ prompt_tokens=prompt_tokens, threshold_tokens=_compression_threshold,
+ ):
+ logger.info(
+ "Compression budget rearmed after provider-confirmed "
+ "recovery: prompt=%s < threshold=%s (attempts were %s/%s)",
+ f"{prompt_tokens:,}",
+ f"{_compression_threshold:,}",
+ compression_attempts,
+ max_compression_attempts,
+ )
+ compression_attempts = 0
+ # Confirmed recovery also clears the loop's stale insufficient-progress verdict
+ # (``_preflight_compression_blocked``), else a later pressure spike grows unchecked.
+ rearmed = True
+
+ # Stash canonical usage for on_turn_complete(); keep the latest call's.
+ agent._last_turn_usage = dict(usage_dict)
+
+ # Persist only provider-confirmed context lengths, not probe tiers.
+ if getattr(compressor, "_context_probed", False):
+ ctx = compressor.context_length
+ if getattr(compressor, "_context_probe_persistable", False):
+ _loop_mod().save_context_length(agent.model, agent.base_url, ctx)
+ agent._safe_print(f"{agent.log_prefix}💾 Cached context length: {ctx:,} tokens for {agent.model}")
+ compressor._context_probed = False
+ compressor._context_probe_persistable = False
+
+ agent.session_prompt_tokens += prompt_tokens
+ agent.session_completion_tokens += completion_tokens
+ agent.session_total_tokens += total_tokens
- agent.session_api_calls += 1
+ agent.session_input_tokens += canonical_usage.input_tokens
+ agent.session_output_tokens += canonical_usage.output_tokens
+ agent.session_cache_read_tokens += canonical_usage.cache_read_tokens
+ agent.session_cache_write_tokens += canonical_usage.cache_write_tokens
+ agent.session_reasoning_tokens += canonical_usage.reasoning_tokens
+ # Rolling history for status-bar averages (last 10).
+ with suppress(Exception):
+ hist = getattr(agent, "_api_latency_history", None)
+ if hist is not None:
+ hist.append(float(api_duration))
+ ohist = getattr(agent, "_api_output_history", None)
+ if ohist is not None:
+ ohist.append(int(canonical_usage.output_tokens or 0))
+
+ _cache_pct = ""
+ if canonical_usage.cache_read_tokens and prompt_tokens:
+ _cache_pct = f" cache={canonical_usage.cache_read_tokens}/{prompt_tokens} ({100*canonical_usage.cache_read_tokens/prompt_tokens:.0f}%)"
+ logger.info(
+ "API call #%d: model=%s provider=%s in=%d out=%d total=%d latency=%.1fs%s",
+ agent.session_api_calls, agent.model, agent.provider or "unknown",
+ prompt_tokens, completion_tokens, total_tokens,
+ api_duration, _cache_pct,
+ )
+
+ # MoA: agent.model/provider are the virtual preset/"moa" with no pricing entry, silently
+ # dropping aggregator spend. Price at the REAL model/provider from the aggregator slot.
+ _agg_cost_model, _agg_cost_provider, _agg_cost_base_url = agent.model, agent.provider, agent.base_url
+ _agg_slot = getattr(_moa_client, "last_aggregator_slot", None) if _moa_client is not None else None
+ if _agg_slot and _agg_slot.get("model"):
+ _agg_cost_model = _agg_slot["model"]
+ _agg_cost_provider = _agg_slot.get("provider") or agent.provider
+ _agg_cost_base_url = _agg_slot.get("base_url") or agent.base_url
+ cost_result = estimate_usage_cost(
+ _agg_cost_model, aggregator_usage, provider=_agg_cost_provider,
+ base_url=_agg_cost_base_url, api_key=getattr(agent, "api_key", ""),
+ )
+ # Cost delta = aggregator + MoA advisor cost (already priced per-advisor at each
+ # advisor's own model rate), so state.db's estimated_cost_usd matches the folded
+ # token counts.
+ _cost_delta = None
+ if cost_result.amount_usd is not None:
+ _cost_delta = float(cost_result.amount_usd)
+ agent.session_estimated_cost_usd += _cost_delta
+ if _moa_ref_cost is not None:
+ try:
+ _moa_cost = float(_moa_ref_cost)
+ except (TypeError, ValueError): # pragma: no cover - defensive
+ _moa_cost = None
+ if _moa_cost is not None:
+ agent.session_estimated_cost_usd += _moa_cost
+ _cost_delta = (_cost_delta or 0.0) + _moa_cost
+ agent.session_cost_status = cost_result.status
+ agent.session_cost_source = cost_result.source
+
+ # Persist per-call token deltas for any session_id so non-CLI runs can't lose
+ # accounting; gateway/session-store writes use absolute totals and safely overwrite
+ # these deltas. Enqueued, not written (a cold state.db UPDATE here stalled the tool
+ # loop); drained at finalize via _persist_session.
+ if agent._session_db and agent.session_id:
+ try:
+ # Ensure the row exists: under concurrent SQLite load the initial
+ # _ensure_db_session() may fail, and UPDATE on a missing row affects 0 rows.
+ if not agent._session_db_created:
+ agent._ensure_db_session()
+ agent._session_db.queue_token_counts(
+ agent.session_id,
+ input_tokens=canonical_usage.input_tokens,
+ output_tokens=canonical_usage.output_tokens,
+ cache_read_tokens=canonical_usage.cache_read_tokens,
+ cache_write_tokens=canonical_usage.cache_write_tokens,
+ reasoning_tokens=canonical_usage.reasoning_tokens,
+ estimated_cost_usd=_cost_delta,
+ cost_status=cost_result.status,
+ cost_source=cost_result.source,
+ billing_provider=agent.provider,
+ billing_base_url=agent.base_url,
+ billing_mode="subscription_included"
+ if cost_result.status == "included" else None,
+ model=agent.model,
+ api_call_count=1,
+ )
+ except Exception as e: # silent loss here undercounts analytics
+ logger.debug(
+ "Token persistence failed (session=%s, tokens=%d): %s",
+ agent.session_id, total_tokens, e,
+ )
+
+ if agent.verbose_logging:
+ logging.debug(f"Token usage: prompt={usage_dict['prompt_tokens']:,}, completion={usage_dict['completion_tokens']:,}, total={usage_dict['total_tokens']:,}")
+
+ # Report cache stats for any provider that returns ``prompt_tokens_details.cached_tokens``,
+ # not only when we inject cache_control markers.
+ cached = canonical_usage.cache_read_tokens
+ written = canonical_usage.cache_write_tokens
+ prompt = usage_dict["prompt_tokens"]
+ if (cached or written) and not agent.quiet_mode:
+ hit_pct = (cached / prompt * 100) if prompt > 0 else 0
+ agent._vprint(
+ f"{agent.log_prefix} 💾 Cache: "
+ f"{cached:,}/{prompt:,} tokens "
+ f"({hit_pct:.0f}% hit, {written:,} written)"
+ )
+ return ResponseUsageOutcome(compression_attempts=compression_attempts, rearmed=rearmed)
diff --cc cli.py
index b8e760e8a1a,19536ffe8d2..533d69564c7
--- a/cli.py
+++ b/cli.py
@@@ -191,20 -268,61 +191,29 @@@ def _strip_reasoning_tags(text: str) -
"""
cleaned = text
for tag in _REASONING_TAGS:
- # Closed pair — case-insensitive so <THINK>…</THINK> is handled too.
- cleaned = re.sub(
- rf"<{tag}>.*?</{tag}>\s*",
- "",
- cleaned,
- flags=re.DOTALL | re.IGNORECASE,
- )
- # Unterminated open tag — strip from the tag to end of text.
- cleaned = re.sub(
- rf"<{tag}>.*$",
- "",
- cleaned,
- flags=re.DOTALL | re.IGNORECASE,
- )
- # Stray orphan close tag left behind by partial dumps.
- cleaned = re.sub(
- rf"</{tag}>\s*",
- "",
- cleaned,
- flags=re.IGNORECASE,
- )
- # Tool-call XML blocks (openclaw/openclaw#67318).
- for tc_tag in ("tool_call", "tool_calls", "tool_result",
- "function_call", "function_calls"):
- cleaned = re.sub(
- rf"<{tc_tag}\b[^>]*>.*?</{tc_tag}>\s*",
- "",
- cleaned,
- flags=re.DOTALL | re.IGNORECASE,
- )
- # <function name="..."> — boundary + attribute gated to avoid prose FPs.
+ cleaned = re.sub(rf"<{tag}>.*?</{tag}>\s*", "", cleaned, flags=re.DOTALL | re.IGNORECASE)
+ cleaned = re.sub(rf"<{tag}>.*$", "", cleaned, flags=re.DOTALL | re.IGNORECASE)
+ cleaned = re.sub(rf"</{tag}>\s*", "", cleaned, flags=re.IGNORECASE)
+ for tc_tag in _TOOL_CALL_TAGS:
+ cleaned = re.sub(rf"<{tc_tag}\b[^>]*>.*?</{tc_tag}>\s*", "", cleaned, flags=re.DOTALL | re.IGNORECASE)
+ # <function name="..."> — boundary + attribute gated to avoid prose false positives.
cleaned = re.sub(
- r'(?:(?<=^)|(?<=[\n\r.!?:]))[ \t]*'
- r'<function\b[^>]*\bname\s*=[^>]*>'
- r'(?:(?:(?!</function>).)*)</function>\s*',
- '',
- cleaned,
- flags=re.DOTALL | re.IGNORECASE,
+ r'(?:(?<=^)|(?<=[\n\r.!?:]))[ \t]*<function\b[^>]*\bname\s*=[^>]*>(?:(?:(?!</function>).)*)</function>\s*',
+ '', cleaned, flags=re.DOTALL | re.IGNORECASE,
)
- # Stray tool-call close tags.
cleaned = re.sub(
- r'</(?:tool_call|tool_calls|tool_result|function_call|function_calls|function)>\s*',
- '',
- cleaned,
+ r'</(?:tool_call|tool_calls|tool_result|function_call|function_calls|function)>\s*', '', cleaned,
flags=re.IGNORECASE,
)
+ # Unterminated opener / stray <arg_key>/<arg_value> markup = stream cut
+ # mid tool-call serialization (#101899); strip to end of text.
+ cleaned = re.sub(
+ r'(?:^|\n)[ \t]*<(?:tool_call|tool_calls|tool_result|function_call|function_calls)\b[^>]*>.*$'
+ r'|(?:^|\n)[^\n<]*</?arg_(?:key|value)\b.*$',
+ '',
+ cleaned,
+ flags=re.DOTALL | re.IGNORECASE,
+ )
return cleaned.strip()