Merge branch 'simp/r2-loop-fin' into simp/integration2
This commit is contained in:
+402
-411
@@ -1,14 +1,14 @@
|
||||
"""Post-loop turn finalization for ``run_conversation``.
|
||||
|
||||
Lifted verbatim: budget summary, trajectory save, persist, diagnostics, response
|
||||
transforms, result assembly, steer drain, memory/skill review. Synchronous, single
|
||||
return. ``logger`` is imported lazily from ``agent.conversation_loop`` (no cycle,
|
||||
same logger name)."""
|
||||
Budget summary, trajectory save, persist, diagnostics, response transforms, result
|
||||
assembly, steer drain, memory/skill review. Synchronous, single return. ``logger`` is
|
||||
imported lazily from ``agent.conversation_loop`` (no cycle, same logger name)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, Callable, List, Optional, Tuple
|
||||
|
||||
from agent.codex_responses_adapter import _summarize_user_message_for_log
|
||||
from agent.context_compressor import _DB_PERSISTED_MARKER
|
||||
@@ -16,6 +16,16 @@ from agent.message_content import flatten_message_text
|
||||
from agent.message_metadata import append_message, stamp_message_timestamp
|
||||
from agent.message_sanitization import _sanitize_surrogates
|
||||
|
||||
# Verification-continuation nudges (verify-on-stop / pre_verify) must be stripped from
|
||||
# returned/live history to avoid role-alternation breaks; the assistant response is
|
||||
# real content and is not flagged. (#65919)
|
||||
_VERIFICATION_CONTINUATION_FLAGS = (
|
||||
"_verification_stop_synthetic",
|
||||
"_pre_verify_synthetic",
|
||||
)
|
||||
|
||||
_SENTENCE_END = {".", "!", "?", "。", "!", "?", "`", ")"}
|
||||
|
||||
|
||||
def _assistant_row_missing_visible_text(msg: dict) -> bool:
|
||||
"""True when an assistant row has no visible text (blank final or tool-only)."""
|
||||
@@ -39,15 +49,6 @@ def _fill_assistant_tail_content(agent, tail: dict, final_response) -> None:
|
||||
agent._db_flush_scan_prefix = None
|
||||
|
||||
|
||||
# Verification-continuation nudges (verify-on-stop / pre_verify) must be stripped from
|
||||
# returned/live history to avoid role-alternation breaks; the assistant response is
|
||||
# real content and is not flagged. (#65919)
|
||||
_VERIFICATION_CONTINUATION_FLAGS = (
|
||||
"_verification_stop_synthetic",
|
||||
"_pre_verify_synthetic",
|
||||
)
|
||||
|
||||
|
||||
def _record_kanban_budget_exhausted(
|
||||
kanban_task: str,
|
||||
api_call_count: int,
|
||||
@@ -56,8 +57,10 @@ def _record_kanban_budget_exhausted(
|
||||
) -> None:
|
||||
"""Record a terminal ``timed_out`` outcome for a kanban worker out of budget.
|
||||
|
||||
Idempotent via the ``_end_run`` CAS (``WHERE ended_at IS NULL``): a no-op if
|
||||
another path already closed the run, so safe from multiple exit paths (#87096)."""
|
||||
Routed via ``_record_task_failure`` (not ``kanban_block``) so it counts toward the
|
||||
consecutive-failure circuit breaker (#29747). Idempotent via the ``_end_run`` CAS
|
||||
(``WHERE ended_at IS NULL``): a no-op if another path already closed the run, so
|
||||
safe from multiple exit paths (#87096)."""
|
||||
try:
|
||||
from hermes_cli import kanban_db as _kb
|
||||
_conn = _kb.connect()
|
||||
@@ -112,6 +115,306 @@ def _clone_background_review_messages(messages):
|
||||
return [_clone_message_for_send(message) for message in messages]
|
||||
|
||||
|
||||
def _invoke_hook_safely(name: str, logger: logging.Logger, **kwargs) -> list:
|
||||
"""Fire a lifecycle plugin hook; a failing hook is logged, never fatal."""
|
||||
try:
|
||||
from hermes_cli.lifecycle import invoke_hook
|
||||
return invoke_hook(name, **kwargs)
|
||||
except Exception as exc:
|
||||
logger.warning("%s hook failed: %s", name, exc)
|
||||
return []
|
||||
|
||||
|
||||
def _guarded_cleanup(label: str, fn: Callable[[], Any], errors: List[str], logger) -> None:
|
||||
"""Post-loop cleanup must never lose the response: each step is guarded
|
||||
independently and errors surface via ``cleanup_errors`` (#8049)."""
|
||||
try:
|
||||
fn()
|
||||
except Exception as err:
|
||||
errors.append(f"{label}: {err}")
|
||||
logger.error("finalize_turn: _%s failed: %s", label, err, exc_info=True)
|
||||
|
||||
|
||||
def _resolve_budget_fallback(
|
||||
agent,
|
||||
*,
|
||||
final_response,
|
||||
api_call_count,
|
||||
interrupted,
|
||||
failed,
|
||||
messages,
|
||||
_turn_exit_reason,
|
||||
_pending_verification_response,
|
||||
_pending_verification_response_previewed,
|
||||
logger,
|
||||
) -> Tuple[Any, Any, bool]:
|
||||
"""Iteration-budget exhaustion. Returns ``(final_response, _turn_exit_reason,
|
||||
preserved_verification_fallback)``."""
|
||||
budget_exhausted = (
|
||||
api_call_count >= agent.max_iterations
|
||||
or agent.iteration_budget.remaining <= 0
|
||||
)
|
||||
budget_fallback_eligible = (
|
||||
budget_exhausted
|
||||
and not interrupted
|
||||
and not failed
|
||||
and str(_turn_exit_reason) in {"unknown", "budget_exhausted"}
|
||||
)
|
||||
preserved_verification_fallback = False
|
||||
if final_response is None and budget_fallback_eligible:
|
||||
_turn_exit_reason = f"max_iterations_reached({api_call_count}/{agent.max_iterations})"
|
||||
if _pending_verification_response:
|
||||
# A verification gate withheld a composed answer, then the budget ran out:
|
||||
# preserve it rather than make another fallible call. The explicit pending
|
||||
# value is the provenance guard; unrelated error exits never enter here.
|
||||
final_response = _pending_verification_response
|
||||
# Previewed only if the reused candidate was actually streamed as interim.
|
||||
if _pending_verification_response_previewed:
|
||||
agent._response_was_previewed = True
|
||||
preserved_verification_fallback = True
|
||||
else:
|
||||
# _handle_max_iterations makes one extra toolless request for a summary.
|
||||
agent._emit_status(
|
||||
f"⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) "
|
||||
"— asking model to summarise"
|
||||
)
|
||||
if not agent.quiet_mode:
|
||||
agent._safe_print(
|
||||
f"\n⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) "
|
||||
"— requesting summary..."
|
||||
)
|
||||
final_response = agent._handle_max_iterations(messages, api_call_count)
|
||||
|
||||
if budget_exhausted:
|
||||
# A kanban worker must record a terminal outcome whether or not a fallback
|
||||
# path was eligible, so the dispatcher learns the worker could not complete.
|
||||
_kanban_task = os.environ.get("HERMES_KANBAN_TASK")
|
||||
if _kanban_task:
|
||||
_record_kanban_budget_exhausted(
|
||||
_kanban_task, api_call_count, agent.max_iterations, logger,
|
||||
)
|
||||
return final_response, _turn_exit_reason, preserved_verification_fallback
|
||||
|
||||
|
||||
def _rollback_interrupted_preflight_display(agent, interrupted) -> None:
|
||||
"""Roll back the preflight-seeded display count only when an interrupt wins before
|
||||
any provider response; compaction state (incl. ``-1``) stays with the real-usage
|
||||
path. Type-pinned guards keep MagicMock/SimpleNamespace doubles inert."""
|
||||
_preflight_snapshot = getattr(agent, "_turn_preflight_display_snapshot", None)
|
||||
if (
|
||||
interrupted is True
|
||||
and isinstance(_preflight_snapshot, int)
|
||||
and not isinstance(_preflight_snapshot, bool)
|
||||
and getattr(agent, "_turn_received_provider_response", False) is not True
|
||||
and getattr(agent, "context_compressor", None) is not None
|
||||
):
|
||||
_rollback_fn = getattr(
|
||||
agent.context_compressor,
|
||||
"rollback_interrupted_preflight_display_tokens",
|
||||
None,
|
||||
)
|
||||
if callable(_rollback_fn):
|
||||
_rollback_fn(_preflight_snapshot)
|
||||
|
||||
|
||||
def _close_transcript_tail(agent, messages, final_response, interrupted, failed):
|
||||
"""Shape the transcript tail before the durable snapshot; returns the (possibly
|
||||
stream-recovered) ``final_response``."""
|
||||
# Strip private retry scaffolding first, or a later "continue" replays
|
||||
# assistant("(empty)") / recovery nudges into the same empty-response loop. Only
|
||||
# the synthetic verification nudges go; the assistant candidate persists (#65919).
|
||||
agent._drop_trailing_empty_response_scaffolding(messages)
|
||||
_drop_verification_continuation_scaffolding(messages)
|
||||
|
||||
# An empty terminal completion is not authoritative when the stream already
|
||||
# delivered text; recover before persist so a blank tail isn't frozen (#95514).
|
||||
_recovered_from_stream = False
|
||||
if not interrupted and not failed:
|
||||
_streamed = getattr(agent, "_current_streamed_assistant_text", "") or ""
|
||||
_streamed = _streamed.strip() if isinstance(_streamed, str) else ""
|
||||
_final_visible = flatten_message_text(final_response).strip() if final_response else ""
|
||||
if not _final_visible and _streamed:
|
||||
final_response = _streamed
|
||||
_recovered_from_stream = True
|
||||
|
||||
# An interrupt can leave a tool result as the tail (no scaffolding flag rewinds
|
||||
# it); close the sequence so strict providers don't see ``tool → user``. An
|
||||
# explicit placeholder is used since final_response is usually empty (#48879).
|
||||
if interrupted:
|
||||
from agent.message_sanitization import close_interrupted_tool_sequence
|
||||
close_interrupted_tool_sequence(messages, final_response)
|
||||
|
||||
# Recovery ``break`` sites can return a final_response with no closing assistant
|
||||
# row; enforce "delivered final_response ⇒ assistant row" here. Compare content,
|
||||
# not role, so a matching verification candidate isn't dup'd.
|
||||
if final_response and not interrupted:
|
||||
try:
|
||||
_tail = messages[-1] if messages else None
|
||||
except Exception:
|
||||
_tail = None
|
||||
_tail_role = _tail.get("role") if isinstance(_tail, dict) else None
|
||||
if _tail_role != "assistant":
|
||||
# Append so the durable turn closes with the answer (#43849/#44100).
|
||||
append_message(messages, {"role": "assistant", "content": final_response})
|
||||
elif (
|
||||
isinstance(_tail, dict)
|
||||
and _tail.get("content") != final_response
|
||||
and (
|
||||
_is_pure_tool_call_tail(_tail)
|
||||
or (_recovered_from_stream and _assistant_row_missing_visible_text(_tail))
|
||||
)
|
||||
):
|
||||
# Pure tool-call turn or stream-recovered blank (#95514): fill its content
|
||||
# rather than append a second row.
|
||||
_fill_assistant_tail_content(agent, _tail, final_response)
|
||||
|
||||
# Request is complete, so replace API-local voice/model/skill guidance with the
|
||||
# clean user input before the durable snapshot; earlier flushes used the DB-only
|
||||
# override as their messages were still needed (#48677 / #63766).
|
||||
_apply_override = getattr(agent, "_apply_persist_user_message_override", None)
|
||||
if callable(_apply_override):
|
||||
_apply_override(messages)
|
||||
return final_response
|
||||
|
||||
|
||||
def _micro_compact_after_turn(agent, messages, final_response, logger) -> None:
|
||||
"""Post-turn micro-compaction: absorb the oldest uncompacted exchange into the
|
||||
rolling summary before persist, amortizing compression across turns."""
|
||||
try:
|
||||
_compressor = getattr(agent, "context_compressor", None)
|
||||
# Strict `is True` + isinstance gates: plugin context engines and MagicMock
|
||||
# compressors pass duck checks and would wipe the transcript.
|
||||
if (
|
||||
_compressor
|
||||
and getattr(_compressor, '_micro_compact_enabled', False) is True
|
||||
and callable(getattr(_compressor, '_micro_compact', None))
|
||||
and final_response
|
||||
# No checkpoint hook, so never run while compression.checkpoint_required
|
||||
# is armed.
|
||||
and getattr(agent, "compression_checkpoint_required", False) is not True
|
||||
# Persistence-isolated agents (background review fork) must not
|
||||
# micro-compact: it burns an aux-LLM call on a throwaway transcript and
|
||||
# could archive_and_compact the CANONICAL session rows.
|
||||
and not getattr(agent, "_persist_disabled", False)
|
||||
):
|
||||
_before = len(messages)
|
||||
_compacted = _compressor._micro_compact(messages)
|
||||
# Defrag rewrites the newest MICRO marker in place and pops _db_persisted;
|
||||
# the compressor flags us to invalidate the flush-scan cursor, else the
|
||||
# rewritten row is identity-skipped (stale).
|
||||
if getattr(_compressor, "_flush_scan_cursor_invalidated", False):
|
||||
_compressor._flush_scan_cursor_invalidated = False
|
||||
agent._db_flush_scan_prefix = None
|
||||
if isinstance(_compacted, list) and _compacted:
|
||||
messages[:] = _compacted
|
||||
_after = len(messages)
|
||||
if _before != _after:
|
||||
logger.info("Micro-compaction: %d -> %d messages", _before, _after)
|
||||
except Exception as _mc_err:
|
||||
logger.info("Micro-compaction failed: %s", _mc_err)
|
||||
|
||||
|
||||
def _log_turn_exit(agent, messages, final_response, api_call_count, _turn_exit_reason, interrupted, logger) -> None:
|
||||
"""Always INFO so agent.log captures WHY every turn ended; WARNING when the last
|
||||
message is a tool result (the "just stops" scenario)."""
|
||||
_last_msg_role = messages[-1].get("role") if messages else None
|
||||
_last_tool_name = None
|
||||
if _last_msg_role == "tool":
|
||||
# Walk back to the assistant message with the tool call.
|
||||
for _m in reversed(messages):
|
||||
if _m.get("role") == "assistant" and _m.get("tool_calls"):
|
||||
_tcs = _m["tool_calls"]
|
||||
if _tcs and isinstance(_tcs[0], dict):
|
||||
_last_tool_name = _tcs[-1].get("function", {}).get("name")
|
||||
break
|
||||
|
||||
_turn_tool_count = sum(
|
||||
1 for m in messages
|
||||
if isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")
|
||||
)
|
||||
_diag_msg = (
|
||||
"Turn ended: reason=%s model=%s api_calls=%d/%d budget=%d/%d "
|
||||
"tool_turns=%d last_msg_role=%s response_len=%d session=%s"
|
||||
)
|
||||
_diag_args = (
|
||||
_turn_exit_reason, agent.model, api_call_count, agent.max_iterations,
|
||||
agent.iteration_budget.used if agent.iteration_budget else 0,
|
||||
agent.iteration_budget.max_total if agent.iteration_budget else 0,
|
||||
_turn_tool_count, _last_msg_role, len(final_response) if final_response else 0,
|
||||
agent.session_id or "none",
|
||||
)
|
||||
if _last_msg_role == "tool" and not interrupted:
|
||||
logger.warning(
|
||||
"Turn ended with pending tool result (agent may appear stuck). "
|
||||
+ _diag_msg + " last_tool=%s",
|
||||
*_diag_args, _last_tool_name,
|
||||
)
|
||||
else:
|
||||
logger.info(_diag_msg, *_diag_args)
|
||||
|
||||
|
||||
def _append_file_mutation_footer(agent, final_response, logger):
|
||||
"""If ``write_file`` / ``patch`` calls failed and were never superseded by a
|
||||
successful write to the same path, append an advisory so over-claiming is
|
||||
surfaced."""
|
||||
try:
|
||||
_failed = getattr(agent, "_turn_failed_file_mutations", None) or {}
|
||||
if _failed and agent._file_mutation_verifier_enabled():
|
||||
footer = agent._format_file_mutation_failure_footer(_failed)
|
||||
if footer:
|
||||
final_response = final_response.rstrip() + "\n\n" + footer
|
||||
except Exception as _ver_err:
|
||||
logger.debug("file-mutation verifier footer failed: %s", _ver_err)
|
||||
return final_response
|
||||
|
||||
|
||||
def _explain_abnormal_exit(agent, final_response, _turn_exit_reason, preserved_verification_fallback, logger):
|
||||
"""Turn-completion explainer: on abnormal exits, surface one explanation from
|
||||
``_turn_exit_reason``. Only acts when no usable reply exists (empty, "(empty)",
|
||||
or a short unpunctuated fragment); ``text_response(...)`` exits stay silent."""
|
||||
try:
|
||||
if not agent._turn_completion_explainer_enabled():
|
||||
return final_response
|
||||
_stripped = (final_response or "").strip()
|
||||
_is_empty_terminal = _stripped == "" or _stripped == "(empty)"
|
||||
# A short fragment not from a text_response exit and lacking sentence-ending
|
||||
# punctuation is treated as a truncated partial (#34452).
|
||||
_is_partial_fragment = (
|
||||
not _is_empty_terminal
|
||||
and not preserved_verification_fallback
|
||||
and not str(_turn_exit_reason).startswith("text_response")
|
||||
and len(_stripped) <= 24
|
||||
and _stripped[-1:] not in _SENTENCE_END
|
||||
)
|
||||
if (
|
||||
_is_empty_terminal
|
||||
or _is_partial_fragment
|
||||
or str(_turn_exit_reason) == "partial_stream_recovery"
|
||||
):
|
||||
_explanation = agent._format_turn_completion_explanation(
|
||||
_turn_exit_reason,
|
||||
getattr(agent, "_last_persistence_error_cause", None),
|
||||
)
|
||||
if _explanation:
|
||||
# Replace the bare sentinel; keep a partial fragment and append why.
|
||||
final_response = _explanation if _is_empty_terminal else _stripped + "\n\n" + _explanation
|
||||
except Exception as _exp_err:
|
||||
logger.debug("turn-completion explainer failed: %s", _exp_err)
|
||||
return final_response
|
||||
|
||||
|
||||
def _last_turn_reasoning(messages) -> Optional[Any]:
|
||||
"""Reasoning from the CURRENT turn only: stop at this turn's user message (#17055),
|
||||
but take the most recent non-empty reasoning since many providers emit it on the
|
||||
tool-call step and leave the final step with reasoning=None."""
|
||||
for msg in reversed(messages):
|
||||
if msg.get("role") == "user":
|
||||
return None # turn boundary — don't cross into prior turns
|
||||
if msg.get("role") == "assistant" and msg.get("reasoning"):
|
||||
return msg["reasoning"]
|
||||
return None
|
||||
|
||||
|
||||
def finalize_turn(
|
||||
agent,
|
||||
*,
|
||||
@@ -133,234 +436,48 @@ def finalize_turn(
|
||||
"""Run the post-loop finalization and return the turn ``result`` dict."""
|
||||
from agent.conversation_loop import logger
|
||||
|
||||
budget_exhausted = (
|
||||
api_call_count >= agent.max_iterations
|
||||
or agent.iteration_budget.remaining <= 0
|
||||
)
|
||||
budget_fallback_eligible = (
|
||||
budget_exhausted
|
||||
and not interrupted
|
||||
and not failed
|
||||
and str(_turn_exit_reason) in {"unknown", "budget_exhausted"}
|
||||
)
|
||||
continuation_budget_exhausted = (
|
||||
final_response is None
|
||||
and bool(_pending_verification_response)
|
||||
and budget_fallback_eligible
|
||||
final_response, _turn_exit_reason, preserved_verification_fallback = _resolve_budget_fallback(
|
||||
agent,
|
||||
final_response=final_response,
|
||||
api_call_count=api_call_count,
|
||||
interrupted=interrupted,
|
||||
failed=failed,
|
||||
messages=messages,
|
||||
_turn_exit_reason=_turn_exit_reason,
|
||||
_pending_verification_response=_pending_verification_response,
|
||||
_pending_verification_response_previewed=_pending_verification_response_previewed,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
iteration_limit_fallback = False
|
||||
preserved_verification_fallback = False
|
||||
if continuation_budget_exhausted:
|
||||
# A verification gate withheld a composed answer, then the budget ran out:
|
||||
# preserve it rather than make another fallible call. The explicit pending
|
||||
# value is the provenance guard; unrelated error exits never enter here.
|
||||
final_response = _pending_verification_response
|
||||
# Previewed only if the reused candidate was actually streamed as interim.
|
||||
if _pending_verification_response_previewed:
|
||||
agent._response_was_previewed = True
|
||||
_turn_exit_reason = f"max_iterations_reached({api_call_count}/{agent.max_iterations})"
|
||||
iteration_limit_fallback = True
|
||||
preserved_verification_fallback = True
|
||||
elif final_response is None and budget_fallback_eligible:
|
||||
# Budget exhausted: _handle_max_iterations makes one extra toolless request
|
||||
# for a summary.
|
||||
_turn_exit_reason = f"max_iterations_reached({api_call_count}/{agent.max_iterations})"
|
||||
agent._emit_status(
|
||||
f"⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) "
|
||||
"— asking model to summarise"
|
||||
)
|
||||
if not agent.quiet_mode:
|
||||
agent._safe_print(
|
||||
f"\n⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) "
|
||||
"— requesting summary..."
|
||||
)
|
||||
final_response = agent._handle_max_iterations(messages, api_call_count)
|
||||
iteration_limit_fallback = True
|
||||
|
||||
if iteration_limit_fallback:
|
||||
# Kanban worker: signal the dispatcher the worker could not complete. Route
|
||||
# via ``_record_task_failure(outcome="timed_out")`` (not ``kanban_block``) so
|
||||
# it counts toward the consecutive-failure circuit breaker (#29747).
|
||||
_kanban_task = os.environ.get("HERMES_KANBAN_TASK")
|
||||
if _kanban_task:
|
||||
_record_kanban_budget_exhausted(
|
||||
_kanban_task, api_call_count, agent.max_iterations, logger,
|
||||
)
|
||||
elif budget_exhausted:
|
||||
# Bounded fallback: budget exhausted with no eligible fallback path. A kanban
|
||||
# worker must still record a terminal outcome; the ``_end_run`` CAS makes it
|
||||
# idempotent if another path already closed the run (#87096).
|
||||
_kanban_task = os.environ.get("HERMES_KANBAN_TASK")
|
||||
if _kanban_task:
|
||||
_record_kanban_budget_exhausted(
|
||||
_kanban_task, api_call_count, agent.max_iterations, logger,
|
||||
)
|
||||
|
||||
# Determine if conversation completed successfully
|
||||
normal_text_response = str(_turn_exit_reason).startswith("text_response(")
|
||||
completed = (
|
||||
final_response is not None
|
||||
and not failed
|
||||
and (
|
||||
api_call_count < agent.max_iterations
|
||||
or normal_text_response
|
||||
or str(_turn_exit_reason).startswith("text_response(")
|
||||
)
|
||||
)
|
||||
|
||||
# Roll back the preflight-seeded display count only when an interrupt wins
|
||||
# before any provider response; compaction state (incl. ``-1``) stays with the
|
||||
# real-usage path. Type-pinned guards keep MagicMock/SimpleNamespace doubles inert.
|
||||
_preflight_snapshot = getattr(
|
||||
agent, "_turn_preflight_display_snapshot", None
|
||||
_rollback_interrupted_preflight_display(agent, interrupted)
|
||||
|
||||
_cleanup_errors: List[str] = []
|
||||
# ``user_message`` may be a multimodal list of parts; the trajectory format wants
|
||||
# a plain string.
|
||||
_guarded_cleanup(
|
||||
"save_trajectory",
|
||||
lambda: agent._save_trajectory(messages, _summarize_user_message_for_log(user_message), completed),
|
||||
_cleanup_errors, logger,
|
||||
)
|
||||
if (
|
||||
interrupted is True
|
||||
and isinstance(_preflight_snapshot, int)
|
||||
and not isinstance(_preflight_snapshot, bool)
|
||||
and getattr(agent, "_turn_received_provider_response", False) is not True
|
||||
and getattr(agent, "context_compressor", None) is not None
|
||||
):
|
||||
_rollback_fn = getattr(
|
||||
agent.context_compressor,
|
||||
"rollback_interrupted_preflight_display_tokens",
|
||||
None,
|
||||
)
|
||||
if callable(_rollback_fn):
|
||||
_rollback_fn(_preflight_snapshot)
|
||||
|
||||
# Post-loop cleanup must never lose the response: trajectory save, teardown,
|
||||
# and session persist are guarded independently and errors surface via
|
||||
# ``cleanup_errors`` rather than killing the turn (#8049).
|
||||
_cleanup_errors = []
|
||||
|
||||
# Save trajectory if enabled. ``user_message`` may be a multimodal
|
||||
# list of parts; the trajectory format wants a plain string.
|
||||
_guarded_cleanup(
|
||||
"cleanup_task_resources",
|
||||
lambda: agent._cleanup_task_resources(effective_task_id),
|
||||
_cleanup_errors, logger,
|
||||
)
|
||||
# Persist only after the transcript tail is shaped and scaffolding removed.
|
||||
try:
|
||||
agent._save_trajectory(messages, _summarize_user_message_for_log(user_message), completed)
|
||||
except Exception as _save_err:
|
||||
_cleanup_errors.append(f"save_trajectory: {_save_err}")
|
||||
logger.error("finalize_turn: _save_trajectory failed: %s", _save_err, exc_info=True)
|
||||
|
||||
# Clean up VM and browser for this task after conversation completes
|
||||
try:
|
||||
agent._cleanup_task_resources(effective_task_id)
|
||||
except Exception as _cleanup_err:
|
||||
_cleanup_errors.append(f"cleanup_task_resources: {_cleanup_err}")
|
||||
logger.error("finalize_turn: _cleanup_task_resources failed: %s", _cleanup_err, exc_info=True)
|
||||
|
||||
# Persist only after private retry scaffolding is removed, or a later "continue"
|
||||
# replays assistant("(empty)") / recovery nudges into the same empty-response loop.
|
||||
try:
|
||||
agent._drop_trailing_empty_response_scaffolding(messages)
|
||||
|
||||
# Strip only the synthetic verification nudges before the tail-assistant
|
||||
# check; the assistant candidate persists in state.db. (#65919)
|
||||
_drop_verification_continuation_scaffolding(messages)
|
||||
|
||||
# An empty terminal completion is not authoritative when the stream already
|
||||
# delivered text; recover before persist so a blank tail isn't frozen (#95514).
|
||||
_recovered_from_stream = False
|
||||
final_response = _close_transcript_tail(agent, messages, final_response, interrupted, failed)
|
||||
if not interrupted and not failed:
|
||||
_streamed = getattr(agent, "_current_streamed_assistant_text", "") or ""
|
||||
if isinstance(_streamed, str):
|
||||
_streamed = _streamed.strip()
|
||||
else:
|
||||
_streamed = ""
|
||||
_final_visible = flatten_message_text(final_response).strip() if final_response else ""
|
||||
if not _final_visible and _streamed:
|
||||
final_response = _streamed
|
||||
_recovered_from_stream = True
|
||||
|
||||
# An interrupt can leave a tool result as the tail (no scaffolding flag rewinds
|
||||
# it); close the sequence so strict providers don't see ``tool → user``. An
|
||||
# explicit placeholder is used since final_response is usually empty (#48879).
|
||||
if interrupted:
|
||||
from agent.message_sanitization import close_interrupted_tool_sequence
|
||||
close_interrupted_tool_sequence(messages, final_response)
|
||||
|
||||
# Recovery ``break`` sites can return a final_response with no closing
|
||||
# assistant row; enforce "delivered final_response ⇒ assistant row" here.
|
||||
# Compare content, not role, so a matching verification candidate isn't dup'd.
|
||||
if final_response and not interrupted:
|
||||
try:
|
||||
_tail = messages[-1] if messages else None
|
||||
except Exception:
|
||||
_tail = None
|
||||
_tail_role = _tail.get("role") if isinstance(_tail, dict) else None
|
||||
if _tail_role != "assistant":
|
||||
# Tail is not an assistant row — append the final response
|
||||
# so the durable turn closes with the answer (#43849/#44100).
|
||||
append_message(
|
||||
messages,
|
||||
{"role": "assistant", "content": final_response},
|
||||
)
|
||||
elif (
|
||||
isinstance(_tail, dict)
|
||||
and _tail.get("content") != final_response
|
||||
and (
|
||||
_is_pure_tool_call_tail(_tail)
|
||||
or (
|
||||
_recovered_from_stream
|
||||
and _assistant_row_missing_visible_text(_tail)
|
||||
)
|
||||
)
|
||||
):
|
||||
# Tail is an assistant row (pure tool-call turn or stream-recovered
|
||||
# blank, #95514): fill its content rather than append a second row.
|
||||
_fill_assistant_tail_content(agent, _tail, final_response)
|
||||
|
||||
# Request is complete, so replace API-local voice/model/skill guidance with
|
||||
# the clean user input before the durable snapshot; earlier flushes used the
|
||||
# DB-only override as their messages were still needed (#48677 / #63766).
|
||||
_apply_override = getattr(agent, "_apply_persist_user_message_override", None)
|
||||
if callable(_apply_override):
|
||||
_apply_override(messages)
|
||||
|
||||
# ── Post-turn micro-compaction ────────────────────────────
|
||||
# Absorb the oldest uncompacted exchange into the rolling summary before
|
||||
# persist, amortizing compression across turns instead of one big pause.
|
||||
if not interrupted and not failed:
|
||||
try:
|
||||
_compressor = getattr(agent, "context_compressor", None)
|
||||
# Strict `is True` + isinstance gates: plugin context engines and
|
||||
# MagicMock compressors pass duck checks and would wipe the transcript.
|
||||
if (
|
||||
_compressor
|
||||
and getattr(_compressor, '_micro_compact_enabled', False) is True
|
||||
and callable(getattr(_compressor, '_micro_compact', None))
|
||||
and final_response
|
||||
# Micro-compaction has no checkpoint hook, so it must never run
|
||||
# while compression.checkpoint_required is armed.
|
||||
and getattr(
|
||||
agent, "compression_checkpoint_required", False
|
||||
) is not True
|
||||
# Persistence-isolated agents (background review fork) must not
|
||||
# micro-compact: it burns an aux-LLM call on a throwaway transcript
|
||||
# and could archive_and_compact the CANONICAL session rows.
|
||||
and not getattr(agent, "_persist_disabled", False)
|
||||
):
|
||||
_before = len(messages)
|
||||
_compacted = _compressor._micro_compact(messages)
|
||||
# Defrag rewrites the newest MICRO marker in place and pops
|
||||
# _db_persisted; the compressor flags us to invalidate the flush-
|
||||
# scan cursor, else the rewritten row is identity-skipped (stale).
|
||||
if getattr(
|
||||
_compressor, "_flush_scan_cursor_invalidated", False
|
||||
):
|
||||
_compressor._flush_scan_cursor_invalidated = False
|
||||
agent._db_flush_scan_prefix = None
|
||||
if isinstance(_compacted, list) and _compacted:
|
||||
messages[:] = _compacted
|
||||
_after = len(messages)
|
||||
if _before != _after:
|
||||
logger.info(
|
||||
"Micro-compaction: %d -> %d messages",
|
||||
_before, _after,
|
||||
)
|
||||
except Exception as _mc_err:
|
||||
logger.info("Micro-compaction failed: %s", _mc_err)
|
||||
|
||||
_micro_compact_after_turn(agent, messages, final_response, logger)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
except Exception as _persist_err:
|
||||
_cleanup_errors.append(f"persist_session: {_persist_err}")
|
||||
@@ -373,146 +490,47 @@ def finalize_turn(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── Turn-exit diagnostic log ─────────────────────────────────────
|
||||
# Always INFO so agent.log captures WHY every turn ended; WARNING when the last
|
||||
# message is a tool result (the "just stops" scenario).
|
||||
_last_msg_role = messages[-1].get("role") if messages else None
|
||||
_last_tool_name = None
|
||||
if _last_msg_role == "tool":
|
||||
# Walk back to find the assistant message with the tool call
|
||||
for _m in reversed(messages):
|
||||
if _m.get("role") == "assistant" and _m.get("tool_calls"):
|
||||
_tcs = _m["tool_calls"]
|
||||
if _tcs and isinstance(_tcs[0], dict):
|
||||
_last_tool_name = _tcs[-1].get("function", {}).get("name")
|
||||
break
|
||||
_log_turn_exit(agent, messages, final_response, api_call_count, _turn_exit_reason, interrupted, logger)
|
||||
|
||||
_turn_tool_count = sum(
|
||||
1 for m in messages
|
||||
if isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")
|
||||
)
|
||||
_resp_len = len(final_response) if final_response else 0
|
||||
_budget_used = agent.iteration_budget.used if agent.iteration_budget else 0
|
||||
_budget_max = agent.iteration_budget.max_total if agent.iteration_budget else 0
|
||||
|
||||
_diag_msg = (
|
||||
"Turn ended: reason=%s model=%s api_calls=%d/%d budget=%d/%d "
|
||||
"tool_turns=%d last_msg_role=%s response_len=%d session=%s"
|
||||
)
|
||||
_diag_args = (
|
||||
_turn_exit_reason, agent.model, api_call_count, agent.max_iterations,
|
||||
_budget_used, _budget_max,
|
||||
_turn_tool_count, _last_msg_role, _resp_len,
|
||||
agent.session_id or "none",
|
||||
)
|
||||
|
||||
if _last_msg_role == "tool" and not interrupted:
|
||||
# Agent was mid-work — this is the "just stops" case.
|
||||
logger.warning(
|
||||
"Turn ended with pending tool result (agent may appear stuck). "
|
||||
+ _diag_msg + " last_tool=%s",
|
||||
*_diag_args, _last_tool_name,
|
||||
)
|
||||
else:
|
||||
logger.info(_diag_msg, *_diag_args)
|
||||
|
||||
# File-mutation verifier footer: if ``write_file`` / ``patch`` calls failed and
|
||||
# were never superseded by a successful write to the same path, append an
|
||||
# advisory so over-claiming is surfaced. Only on real, uninterrupted responses.
|
||||
# Response transforms apply only to real, uninterrupted responses.
|
||||
if final_response and not interrupted:
|
||||
try:
|
||||
_failed = getattr(agent, "_turn_failed_file_mutations", None) or {}
|
||||
if _failed and agent._file_mutation_verifier_enabled():
|
||||
footer = agent._format_file_mutation_failure_footer(_failed)
|
||||
if footer:
|
||||
final_response = final_response.rstrip() + "\n\n" + footer
|
||||
except Exception as _ver_err:
|
||||
logger.debug("file-mutation verifier footer failed: %s", _ver_err)
|
||||
|
||||
# Turn-completion explainer: on abnormal exits, surface one explanation from
|
||||
# ``_turn_exit_reason``. Only acts when no usable reply exists (empty, "(empty)",
|
||||
# or a short unpunctuated fragment); ``text_response(...)`` exits stay silent.
|
||||
final_response = _append_file_mutation_footer(agent, final_response, logger)
|
||||
if not interrupted:
|
||||
try:
|
||||
if agent._turn_completion_explainer_enabled():
|
||||
_stripped = (final_response or "").strip()
|
||||
_is_empty_terminal = _stripped == "" or _stripped == "(empty)"
|
||||
# A short fragment not from a text_response exit and lacking sentence-
|
||||
# ending punctuation is treated as a truncated partial (#34452).
|
||||
_is_partial_fragment = (
|
||||
not _is_empty_terminal
|
||||
and not preserved_verification_fallback
|
||||
and not str(_turn_exit_reason).startswith("text_response")
|
||||
and len(_stripped) <= 24
|
||||
and _stripped[-1:] not in {".", "!", "?", "。", "!", "?", "`", ")"}
|
||||
)
|
||||
_is_partial_stream_recovery = (
|
||||
str(_turn_exit_reason) == "partial_stream_recovery"
|
||||
)
|
||||
if (
|
||||
_is_empty_terminal
|
||||
or _is_partial_fragment
|
||||
or _is_partial_stream_recovery
|
||||
):
|
||||
_explanation = agent._format_turn_completion_explanation(
|
||||
_turn_exit_reason,
|
||||
getattr(agent, "_last_persistence_error_cause", None),
|
||||
)
|
||||
if _explanation:
|
||||
if _is_empty_terminal:
|
||||
# Replace the bare "(empty)"/blank sentinel with
|
||||
# the actionable explanation.
|
||||
final_response = _explanation
|
||||
else:
|
||||
# Keep the partial fragment and append why it stopped.
|
||||
final_response = (
|
||||
_stripped + "\n\n" + _explanation
|
||||
)
|
||||
except Exception as _exp_err:
|
||||
logger.debug("turn-completion explainer failed: %s", _exp_err)
|
||||
final_response = _explain_abnormal_exit(
|
||||
agent, final_response, _turn_exit_reason, preserved_verification_fallback, logger,
|
||||
)
|
||||
|
||||
_platform = getattr(agent, "platform", None) or ""
|
||||
_response_transformed = False
|
||||
_pre_transform_response = None
|
||||
|
||||
# Plugin hook: transform_llm_output — fired once per turn after the tool loop.
|
||||
# First hook to return a string wins; None/empty leaves the text unchanged.
|
||||
if final_response and not interrupted:
|
||||
try:
|
||||
from hermes_cli.lifecycle import invoke_hook as _invoke_hook
|
||||
_transform_results = _invoke_hook(
|
||||
"transform_llm_output",
|
||||
response_text=final_response,
|
||||
session_id=agent.session_id or "",
|
||||
model=agent.model,
|
||||
platform=getattr(agent, "platform", None) or "",
|
||||
)
|
||||
for _hook_result in _transform_results:
|
||||
if isinstance(_hook_result, str) and _hook_result:
|
||||
_pre_transform_response = final_response
|
||||
final_response = _hook_result
|
||||
_response_transformed = True
|
||||
break # First non-empty string wins
|
||||
except Exception as exc:
|
||||
logger.warning("transform_llm_output hook failed: %s", exc)
|
||||
|
||||
# Plugin hook: post_llm_call — fired once per turn after the tool loop (e.g. sync
|
||||
# conversation data to an external memory system).
|
||||
if final_response and not interrupted:
|
||||
try:
|
||||
from hermes_cli.lifecycle import invoke_hook as _invoke_hook
|
||||
_invoke_hook(
|
||||
"post_llm_call",
|
||||
session_id=agent.session_id,
|
||||
task_id=effective_task_id,
|
||||
turn_id=turn_id,
|
||||
user_message=original_user_message,
|
||||
assistant_response=final_response,
|
||||
conversation_history=list(messages),
|
||||
model=agent.model,
|
||||
platform=getattr(agent, "platform", None) or "",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("post_llm_call hook failed: %s", exc)
|
||||
# Plugin hook: transform_llm_output — fired once per turn after the tool loop.
|
||||
# First hook to return a string wins; None/empty leaves the text unchanged.
|
||||
for _hook_result in _invoke_hook_safely(
|
||||
"transform_llm_output", logger,
|
||||
response_text=final_response,
|
||||
session_id=agent.session_id or "",
|
||||
model=agent.model,
|
||||
platform=_platform,
|
||||
):
|
||||
if isinstance(_hook_result, str) and _hook_result:
|
||||
_pre_transform_response = final_response
|
||||
final_response = _hook_result
|
||||
_response_transformed = True
|
||||
break
|
||||
# Plugin hook: post_llm_call (e.g. sync conversation data to an external
|
||||
# memory system).
|
||||
_invoke_hook_safely(
|
||||
"post_llm_call", logger,
|
||||
session_id=agent.session_id,
|
||||
task_id=effective_task_id,
|
||||
turn_id=turn_id,
|
||||
user_message=original_user_message,
|
||||
assistant_response=final_response,
|
||||
conversation_history=list(messages),
|
||||
model=agent.model,
|
||||
platform=_platform,
|
||||
)
|
||||
|
||||
# Context engine observation hook (complements per-request select_context()):
|
||||
# notify the engine the turn finished with the finalized transcript. Fail-open.
|
||||
@@ -520,11 +538,10 @@ def finalize_turn(
|
||||
from agent.conversation_loop import _notify_context_engine_turn_complete
|
||||
# ``_last_turn_usage`` holds the last API response's canonical usage dict, or
|
||||
# ``None`` on turns that never reached a provider response — by contract.
|
||||
_turn_usage = getattr(agent, "_last_turn_usage", None)
|
||||
_notify_context_engine_turn_complete(
|
||||
agent,
|
||||
messages,
|
||||
usage=_turn_usage,
|
||||
usage=getattr(agent, "_last_turn_usage", None),
|
||||
logger=logger,
|
||||
turn_id=turn_id,
|
||||
task_id=effective_task_id,
|
||||
@@ -536,27 +553,15 @@ def finalize_turn(
|
||||
except Exception as exc:
|
||||
logger.warning("on_turn_complete notification failed: %s", exc)
|
||||
|
||||
# Reasoning from the CURRENT turn only: stop at this turn's user message
|
||||
# (#17055), but take the most recent non-empty reasoning since many providers
|
||||
# emit it on the tool-call step and leave the final step with reasoning=None.
|
||||
last_reasoning = None
|
||||
for msg in reversed(messages):
|
||||
if msg.get("role") == "user":
|
||||
break # turn boundary — don't cross into prior turns
|
||||
if msg.get("role") == "assistant" and msg.get("reasoning"):
|
||||
last_reasoning = msg["reasoning"]
|
||||
break
|
||||
|
||||
# Surrogate chokepoint: ``final_response`` may be RAW SDK content, and a lone UTF-16
|
||||
# surrogate crashes downstream consumers (stdout, Telegram ``utf16_len``, JSON).
|
||||
# Scrub once where model text leaves the loop (#80366).
|
||||
if isinstance(final_response, str):
|
||||
final_response = _sanitize_surrogates(final_response)
|
||||
|
||||
# Build result with interrupt info if applicable
|
||||
result = {
|
||||
"final_response": final_response,
|
||||
"last_reasoning": last_reasoning,
|
||||
"last_reasoning": _last_turn_reasoning(messages),
|
||||
"messages": messages,
|
||||
"api_calls": api_call_count,
|
||||
"completed": completed,
|
||||
@@ -582,8 +587,8 @@ def finalize_turn(
|
||||
"estimated_cost_usd": agent.session_estimated_cost_usd,
|
||||
"cost_status": agent.session_cost_status,
|
||||
"cost_source": agent.session_cost_source,
|
||||
# Requested service tier (from request_overrides.extra_body), for
|
||||
# billing audits by callers like `hermes -z --usage-file`.
|
||||
# Requested service tier (from request_overrides.extra_body), for billing
|
||||
# audits by callers like `hermes -z --usage-file`.
|
||||
"service_tier": (
|
||||
(getattr(agent, "request_overrides", {}) or {}).get("extra_body") or {}
|
||||
).get("service_tier"),
|
||||
@@ -603,9 +608,7 @@ def finalize_turn(
|
||||
# Never clobber a failure_reason another path already stamped.
|
||||
if "failure_reason" not in result:
|
||||
_cause = getattr(agent, "_last_persistence_error_cause", None)
|
||||
result["failure_reason"] = (
|
||||
"session_persistence_failed:" + (_cause or "unknown")
|
||||
)
|
||||
result["failure_reason"] = "session_persistence_failed:" + (_cause or "unknown")
|
||||
# Surface post-loop cleanup failures so the caller can tell a clean turn from one
|
||||
# whose teardown raised; the response is returned either way (#8049).
|
||||
if _cleanup_errors:
|
||||
@@ -616,18 +619,13 @@ def finalize_turn(
|
||||
if _leftover_steer:
|
||||
result["pending_steer"] = _leftover_steer
|
||||
agent._response_was_previewed = False
|
||||
|
||||
# Include interrupt message if one triggered the interrupt
|
||||
if interrupted and agent._interrupt_message:
|
||||
result["interrupt_message"] = agent._interrupt_message
|
||||
|
||||
# Clear interrupt state after handling
|
||||
agent.clear_interrupt()
|
||||
|
||||
# Clear stream callback so it doesn't leak into future calls
|
||||
# Clear stream callback so it doesn't leak into future calls.
|
||||
agent._stream_callback = None
|
||||
|
||||
# Check skill trigger NOW — based on how many tool iterations THIS turn used.
|
||||
# Skill trigger is checked NOW — based on how many tool iterations THIS turn used.
|
||||
_should_review_skills = False
|
||||
if (agent._skill_nudge_interval > 0
|
||||
and agent._iters_since_skill >= agent._skill_nudge_interval
|
||||
@@ -653,8 +651,8 @@ def finalize_turn(
|
||||
and (_should_review_memory or _should_review_skills)
|
||||
):
|
||||
try:
|
||||
# _spawn_background_review clones the snapshot structurally so
|
||||
# the fork's in-place sanitizers can't reach the live transcript.
|
||||
# _spawn_background_review clones the snapshot structurally so the fork's
|
||||
# in-place sanitizers can't reach the live transcript.
|
||||
agent._spawn_background_review(
|
||||
messages_snapshot=list(messages),
|
||||
review_memory=_should_review_memory,
|
||||
@@ -665,26 +663,19 @@ def finalize_turn(
|
||||
|
||||
# Memory provider on_session_end()/shutdown_all() are NOT called here:
|
||||
# run_conversation() runs once per message; CLI/gateway own session-end cleanup.
|
||||
|
||||
# Plugin hook: on_session_end — fired at the end of every run_conversation call.
|
||||
try:
|
||||
from hermes_cli.lifecycle import invoke_hook as _invoke_hook
|
||||
_invoke_hook(
|
||||
"on_session_end",
|
||||
session_id=agent.session_id,
|
||||
task_id=effective_task_id,
|
||||
turn_id=turn_id,
|
||||
completed=completed,
|
||||
failed=failed,
|
||||
interrupted=interrupted,
|
||||
turn_exit_reason=_turn_exit_reason,
|
||||
model=agent.model,
|
||||
platform=getattr(agent, "platform", None) or "",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("on_session_end hook failed: %s", exc)
|
||||
_invoke_hook_safely(
|
||||
"on_session_end", logger,
|
||||
session_id=agent.session_id,
|
||||
task_id=effective_task_id,
|
||||
turn_id=turn_id,
|
||||
completed=completed,
|
||||
failed=failed,
|
||||
interrupted=interrupted,
|
||||
turn_exit_reason=_turn_exit_reason,
|
||||
model=agent.model,
|
||||
platform=_platform,
|
||||
)
|
||||
|
||||
agent._turn_preflight_display_snapshot = None
|
||||
agent._turn_received_provider_response = False
|
||||
|
||||
return result
|
||||
|
||||
+407
-465
@@ -5,7 +5,7 @@ Extracted from ``run_conversation``'s ``except`` branch. Each path either compre
|
||||
signals a restart, defers softly (compression lock / transient block), or ends the turn
|
||||
with a typed result. Nothing here imports ``agent.conversation_loop`` at module level
|
||||
(cycle); loop-internal helpers and the token estimators that tests patch on the loop
|
||||
module are imported lazily inside the handler so they keep resolving through the loop.
|
||||
module are imported lazily inside the handlers so they keep resolving through the loop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,6 +35,16 @@ from utils import base_url_host_matches
|
||||
|
||||
logger = logging.getLogger("agent.conversation_loop")
|
||||
|
||||
_RETRY_HINT = " 💡 Try /new to start a fresh conversation, or /compress to retry compression."
|
||||
|
||||
_GITHUB_MODELS_HINT = (
|
||||
" 💡 GitHub Models free tier (models.inference.ai.azure.com) caps every",
|
||||
" request at ~8K tokens. Hermes' system prompt + tool schemas baseline",
|
||||
" exceeds that floor, so this endpoint cannot run an agentic loop.",
|
||||
" Use the `copilot` provider with a Copilot subscription token (`hermes",
|
||||
" setup` → GitHub Copilot), or pick any other provider.",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OverflowVerdict:
|
||||
@@ -57,6 +67,376 @@ class OverflowVerdict:
|
||||
is_context_length_error: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Recovery:
|
||||
"""Mutable working state shared by the overflow sub-handlers; the loop locals
|
||||
they may rebind live here and are handed back through ``verdict()``."""
|
||||
|
||||
agent: Any
|
||||
api_messages: Any
|
||||
system_message: Any
|
||||
effective_task_id: Any
|
||||
api_call_count: int
|
||||
max_compression_attempts: int
|
||||
messages: List[Dict[str, Any]]
|
||||
active_system_prompt: Any
|
||||
conversation_history: Any
|
||||
approx_tokens: int
|
||||
compression_attempts: int
|
||||
provider_overflow_recovery_pending: bool = False
|
||||
is_context_length_error: bool = False
|
||||
|
||||
def verdict(self, action: str, result: Optional[Dict[str, Any]] = None) -> OverflowVerdict:
|
||||
return OverflowVerdict(
|
||||
action=action,
|
||||
result=result,
|
||||
messages=self.messages,
|
||||
active_system_prompt=self.active_system_prompt,
|
||||
conversation_history=self.conversation_history,
|
||||
approx_tokens=self.approx_tokens,
|
||||
compression_attempts=self.compression_attempts,
|
||||
provider_overflow_recovery_pending=self.provider_overflow_recovery_pending,
|
||||
is_context_length_error=self.is_context_length_error,
|
||||
)
|
||||
|
||||
def fail_turn(
|
||||
self,
|
||||
final_response: str,
|
||||
*,
|
||||
notices: tuple = (),
|
||||
log: Optional[tuple] = None,
|
||||
compression_exhausted: bool = True,
|
||||
**extra: Any,
|
||||
) -> OverflowVerdict:
|
||||
"""End the turn as failed/partial. ``notices`` flush the buffered retry trace
|
||||
first so the user sees what compression attempts were made."""
|
||||
agent = self.agent
|
||||
if notices:
|
||||
agent._flush_status_buffer()
|
||||
for line in notices:
|
||||
agent._vprint(f"{agent.log_prefix}{line}", force=True)
|
||||
if log:
|
||||
logger.error(*log)
|
||||
agent._persist_session(self.messages, self.conversation_history)
|
||||
result = {
|
||||
"final_response": final_response,
|
||||
"messages": self.messages,
|
||||
"completed": False,
|
||||
"api_calls": self.api_call_count,
|
||||
"error": final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
}
|
||||
if compression_exhausted:
|
||||
result["compression_exhausted"] = True
|
||||
result.update(extra)
|
||||
return self.verdict("return", result)
|
||||
|
||||
def exhausted(self, *, payload_too_large: bool = False) -> OverflowVerdict:
|
||||
"""Terminal: ``compression_attempts`` exceeded ``max_compression_attempts``."""
|
||||
cap = self.max_compression_attempts
|
||||
if payload_too_large:
|
||||
return self.fail_turn(
|
||||
f"Request payload too large: max compression attempts ({cap}) reached.",
|
||||
notices=(
|
||||
f"❌ Max compression attempts ({cap}) reached for payload-too-large error.",
|
||||
_RETRY_HINT,
|
||||
),
|
||||
log=("%s413 compression failed after %d attempts.", self.agent.log_prefix, cap),
|
||||
)
|
||||
return self.fail_turn(
|
||||
f"Context length exceeded: max compression attempts ({cap}) reached.",
|
||||
notices=(f"❌ Max compression attempts ({cap}) reached.", _RETRY_HINT),
|
||||
log=("%sContext compression failed after %d attempts.", self.agent.log_prefix, cap),
|
||||
)
|
||||
|
||||
def compress(self, request_tokens: int, *, fail_on_timeout: bool = False) -> Optional[OverflowVerdict]:
|
||||
"""One compression pass with the summary-failure cooldown bypassed (the
|
||||
provider proved the request doesn't fit, #100661). Returns ``None`` when
|
||||
history was compressed, or a soft-defer verdict when another path holds the
|
||||
compression lock (#69870) or a timed guard no-oped the pass (#97488): the
|
||||
attempt is refunded and the turn ends WITHOUT ``compression_exhausted`` so the
|
||||
gateway does not auto-reset. With ``fail_on_timeout`` a host timeout (recovery
|
||||
spent its wait budget with no committed summary) ends the turn via the typed
|
||||
contract, since re-sending would hit the same overflow (#98722)."""
|
||||
from agent.conversation_loop import (
|
||||
_COMPRESSION_TIMEOUT_FINAL_RESPONSE,
|
||||
_compression_deferred_result,
|
||||
conversation_history_after_compression,
|
||||
)
|
||||
|
||||
agent = self.agent
|
||||
before = self.messages
|
||||
self.messages, self.active_system_prompt = agent._compress_context(
|
||||
before, self.system_message,
|
||||
approx_tokens=request_tokens,
|
||||
task_id=self.effective_task_id,
|
||||
bypass_cooldown=True,
|
||||
)
|
||||
if self.messages is before:
|
||||
deferred = None
|
||||
if compression_skipped_due_to_lock(agent):
|
||||
deferred = _compression_deferred_result(agent, self.messages, self.api_call_count)
|
||||
elif compression_blocked_transiently(agent):
|
||||
deferred = _compression_deferred_result(
|
||||
agent, self.messages, self.api_call_count, reason="transient_block",
|
||||
)
|
||||
if deferred is not None:
|
||||
self.compression_attempts -= 1
|
||||
agent._persist_session(self.messages, self.conversation_history)
|
||||
return self.verdict("return", deferred)
|
||||
if fail_on_timeout and context_compression_timed_out(agent):
|
||||
return self.fail_turn(
|
||||
_COMPRESSION_TIMEOUT_FINAL_RESPONSE,
|
||||
turn_exit_reason="context_compression_timeout",
|
||||
)
|
||||
self.conversation_history = conversation_history_after_compression(
|
||||
agent, self.messages, self.conversation_history
|
||||
)
|
||||
return None
|
||||
|
||||
def request_tokens(self) -> int:
|
||||
"""Overhead-aware request size (msgs + tools + system) so LCM forced-overflow
|
||||
recovery arms on the TRUE request, not the tool-blind message count."""
|
||||
from agent.conversation_loop import estimate_request_tokens_rough
|
||||
|
||||
return estimate_request_tokens_rough(self.api_messages, tools=self.agent.tools or None)
|
||||
|
||||
|
||||
def _recover_payload_too_large(st: _Recovery, _retry: TurnRetryState) -> OverflowVerdict:
|
||||
"""413: compress and retry. A 413 is a BYTE-size error, so progress is scored in
|
||||
payload bytes — never the token estimate, which is deliberately byte-blind to images
|
||||
and wedged sessions on "no progress" (#88960 / #47339)."""
|
||||
from agent.conversation_loop import estimate_messages_tokens_rough
|
||||
|
||||
agent = st.agent
|
||||
st.compression_attempts += 1
|
||||
if st.compression_attempts > st.max_compression_attempts:
|
||||
return st.exhausted(payload_too_large=True)
|
||||
agent._buffer_status(
|
||||
f"⚠️ Request payload too large (413) — compression attempt "
|
||||
f"{st.compression_attempts}/{st.max_compression_attempts}..."
|
||||
)
|
||||
|
||||
messages = st.messages
|
||||
original_len = len(messages)
|
||||
original_bytes = serialized_messages_bytes(messages)
|
||||
deferred = st.compress(st.request_tokens())
|
||||
if deferred is not None:
|
||||
return deferred
|
||||
|
||||
# Re-measure: same-count compression and media aging can shrink the request
|
||||
# without shrinking the array. Tokens only for status display.
|
||||
messages = st.messages
|
||||
st.approx_tokens = estimate_messages_tokens_rough(messages)
|
||||
new_bytes = serialized_messages_bytes(messages)
|
||||
if len(messages) < original_len or (new_bytes > 0 and new_bytes < original_bytes * 0.95):
|
||||
if len(messages) < original_len:
|
||||
agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
|
||||
else:
|
||||
agent._buffer_status(
|
||||
f"🗜️ Compressed {original_bytes:,} → {new_bytes:,} "
|
||||
f"payload bytes, retrying..."
|
||||
)
|
||||
time.sleep(2) # Brief pause between compression retries
|
||||
_retry.restart_with_compressed_messages = True
|
||||
return st.verdict("break")
|
||||
|
||||
if agent._try_strip_image_parts_from_tool_messages(st.api_messages, remember_model=False):
|
||||
agent._buffer_status(
|
||||
"📐 Compression could not reduce the request further — "
|
||||
"removed retained vision payloads and retrying..."
|
||||
)
|
||||
return st.verdict("continue")
|
||||
|
||||
return st.fail_turn(
|
||||
"Request payload too large (413). Cannot compress further.",
|
||||
notices=("❌ Payload too large and cannot compress further.", _RETRY_HINT),
|
||||
log=("%s413 payload too large. Cannot compress further.", agent.log_prefix),
|
||||
)
|
||||
|
||||
|
||||
def _clamp_output_cap(st: _Recovery, _retry: TurnRetryState, available_out: int, old_ctx: int) -> OverflowVerdict:
|
||||
"""Output-cap error ("max_tokens too large": input fits but input + max_tokens >
|
||||
window). The provider's available_tokens is the authoritative bound; also estimate
|
||||
the real request shape (API-only content) and use the smaller minus a margin."""
|
||||
from agent.conversation_loop import estimate_messages_tokens_rough
|
||||
|
||||
agent = st.agent
|
||||
request_input_estimate = st.request_tokens()
|
||||
local_available_out = old_ctx - request_input_estimate
|
||||
if local_available_out > 0:
|
||||
safe_out = max(1, min(available_out, local_available_out) - 64)
|
||||
else:
|
||||
# Local estimate can overshoot; fall back to the provider-reported budget.
|
||||
safe_out = max(1, available_out - 64)
|
||||
agent._ephemeral_max_output_tokens = safe_out
|
||||
agent._buffer_vprint(
|
||||
f"⚠️ Output cap too large for current prompt — "
|
||||
f"retrying with max_tokens={safe_out:,} "
|
||||
f"(provider_available={available_out:,}, "
|
||||
f"estimated_request_tokens={request_input_estimate:,}; "
|
||||
f"context_length unchanged at {old_ctx:,})"
|
||||
)
|
||||
# Still count against compression_attempts so a recurring error can't loop forever.
|
||||
st.compression_attempts += 1
|
||||
if st.compression_attempts > st.max_compression_attempts:
|
||||
return st.exhausted()
|
||||
# Also compress history so the retry doesn't spin on max_tokens alone; dropping the
|
||||
# middle window makes the total fit (#55546). Compression must never turn an
|
||||
# output-cap error fatal — on error, fall through and retry on max_tokens alone.
|
||||
try:
|
||||
original_len = len(st.messages)
|
||||
original_tokens = estimate_messages_tokens_rough(st.messages)
|
||||
deferred = st.compress(request_input_estimate)
|
||||
if deferred is not None:
|
||||
return deferred
|
||||
messages = st.messages
|
||||
new_tokens = estimate_messages_tokens_rough(messages)
|
||||
if len(messages) < original_len:
|
||||
agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
|
||||
elif new_tokens > 0 and new_tokens < original_tokens * 0.95:
|
||||
agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"%sOutput-cap compression hit an error; retrying on max_tokens only.",
|
||||
agent.log_prefix,
|
||||
)
|
||||
_retry.restart_with_compressed_messages = True
|
||||
return st.verdict("break")
|
||||
|
||||
|
||||
def _adopt_provider_context_limit(st: _Recovery, error_msg: str, old_ctx: int) -> Optional[int]:
|
||||
"""Shrink context_length only when the provider reports the real limit; else keep
|
||||
the window and compress. Guessed probe tiers can turn a configured 1M window into
|
||||
256K/128K/64K. Returns the provider-reported limit, or ``None``."""
|
||||
from agent.conversation_loop import save_context_length
|
||||
|
||||
agent = st.agent
|
||||
compressor = agent.context_compressor
|
||||
new_ctx = get_context_length_from_provider_error(error_msg, old_ctx)
|
||||
if new_ctx is not None:
|
||||
agent._buffer_vprint(f"Context limit detected from API: {new_ctx:,} tokens (was {old_ctx:,})")
|
||||
compressor.update_model(
|
||||
model=agent.model,
|
||||
context_length=new_ctx,
|
||||
base_url=agent.base_url,
|
||||
api_key=getattr(agent, "api_key", ""),
|
||||
provider=agent.provider,
|
||||
api_mode=agent.api_mode,
|
||||
)
|
||||
# Persist the provider-reported limit BEFORE compression/retry: rate limit,
|
||||
# missing usage, or restart must not lose confirmed metadata. Probe flags
|
||||
# remain a fallback if this write fails.
|
||||
save_context_length(agent.model, agent.base_url, new_ctx)
|
||||
# Probe flags only on the built-in compressor (plugin engines manage their
|
||||
# own); provider-sourced value, so safe to cache.
|
||||
if hasattr(compressor, "_context_probed"):
|
||||
compressor._context_probed = True
|
||||
compressor._context_probe_persistable = True
|
||||
agent._buffer_vprint(f"⚠️ Context length exceeded — using provider limit: {old_ctx:,} → {new_ctx:,} tokens")
|
||||
return new_ctx
|
||||
|
||||
_provider_lower = (getattr(agent, "provider", "") or "").lower()
|
||||
_base_lower = (getattr(agent, "base_url", "") or "").rstrip("/").lower()
|
||||
is_minimax_provider = (
|
||||
_provider_lower in {"minimax", "minimax-cn"}
|
||||
or _base_lower.startswith((
|
||||
"https://api.minimax.io/anthropic",
|
||||
"https://api.minimaxi.com/anthropic",
|
||||
))
|
||||
)
|
||||
if is_minimax_provider and "context window exceeds limit (" in error_msg:
|
||||
agent._buffer_vprint(
|
||||
f"Provider reported overflow amount only; "
|
||||
f"keeping context_length at {old_ctx:,} tokens and compressing."
|
||||
)
|
||||
else:
|
||||
agent._buffer_vprint(
|
||||
f"⚠️ Context length exceeded, but provider did not report a max context length; "
|
||||
f"keeping context_length at {old_ctx:,} tokens and compressing."
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _recover_context_length(st: _Recovery, _retry: TurnRetryState, error_msg: str) -> OverflowVerdict:
|
||||
"""Context-length error. Two shapes: "prompt too long" = INPUT overflows the window
|
||||
(shrink context_length + compress); "max_tokens too large" = input fits but
|
||||
input + max_tokens > window (shrink the OUTPUT cap only)."""
|
||||
from agent.conversation_loop import estimate_messages_tokens_rough
|
||||
|
||||
agent = st.agent
|
||||
old_ctx = agent.context_compressor.context_length
|
||||
|
||||
available_out = parse_available_output_tokens_from_error(error_msg)
|
||||
if available_out is not None:
|
||||
return _clamp_output_cap(st, _retry, available_out, old_ctx)
|
||||
|
||||
# Output-cap error with unparseable budget: compression can't help (input already
|
||||
# fits) and would death-loop on the same 400. Fail fast (#55546).
|
||||
if is_output_cap_error(error_msg):
|
||||
return st.fail_turn(
|
||||
"max_tokens exceeds the provider's output cap for this model. "
|
||||
"Lower model.max_tokens in config.yaml.",
|
||||
notices=(
|
||||
"❌ The provider rejected the request because "
|
||||
"max_tokens exceeds its output cap for this model.",
|
||||
" 💡 Lower model.max_tokens in your config.yaml to "
|
||||
"at or below the model's max-output limit. "
|
||||
"(This is an output-cap error, not a context overflow — "
|
||||
"compression cannot fix it.)",
|
||||
),
|
||||
log=(
|
||||
f"{agent.log_prefix}Output-cap error not routed into compression "
|
||||
f"(max_tokens over provider cap): {error_msg[:200]}",
|
||||
),
|
||||
compression_exhausted=False,
|
||||
)
|
||||
|
||||
new_ctx = _adopt_provider_context_limit(st, error_msg, old_ctx)
|
||||
|
||||
st.compression_attempts += 1
|
||||
if st.compression_attempts > st.max_compression_attempts:
|
||||
return st.exhausted()
|
||||
agent._buffer_status(COMPRESSION_RETRY_TOO_LARGE_STATUS_TEMPLATE.format(
|
||||
tokens=st.approx_tokens, attempt=st.compression_attempts, cap=st.max_compression_attempts,
|
||||
))
|
||||
|
||||
original_len = len(st.messages)
|
||||
original_tokens = estimate_messages_tokens_rough(st.messages)
|
||||
deferred = st.compress(st.request_tokens(), fail_on_timeout=True)
|
||||
if deferred is not None:
|
||||
return deferred
|
||||
|
||||
# Re-estimate: same-message-count compression (tool-result pruning, in-place
|
||||
# summarization) can shrink the request (#39550).
|
||||
messages = st.messages
|
||||
new_tokens = estimate_messages_tokens_rough(messages)
|
||||
st.approx_tokens = new_tokens
|
||||
shrank_tokens = new_tokens > 0 and new_tokens < original_tokens * 0.95
|
||||
if len(messages) < original_len or shrank_tokens or (new_ctx and new_ctx < old_ctx):
|
||||
if len(messages) < original_len:
|
||||
agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
|
||||
elif shrank_tokens:
|
||||
agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))
|
||||
time.sleep(2) # Brief pause between compression retries
|
||||
# Rebuild the full request and force normal preflight to honor it; message
|
||||
# count alone doesn't prove system/tool-inclusive pressure fell.
|
||||
st.provider_overflow_recovery_pending = True
|
||||
_retry.restart_with_compressed_messages = True
|
||||
return st.verdict("break")
|
||||
|
||||
# Can't compress further and already at minimum tier.
|
||||
return st.fail_turn(
|
||||
f"Context length exceeded ({new_tokens:,} tokens). Cannot compress further.",
|
||||
notices=(
|
||||
"❌ Context length exceeded and cannot compress further.",
|
||||
" 💡 The conversation has accumulated too much content. Try /new to start fresh, or /compress to manually trigger compression.",
|
||||
),
|
||||
log=("%sContext length exceeded: %s tokens. Cannot compress further.", agent.log_prefix, f"{new_tokens:,}"),
|
||||
)
|
||||
|
||||
|
||||
def recover_from_overflow(
|
||||
agent: Any,
|
||||
api_error: Exception,
|
||||
@@ -83,478 +463,40 @@ def recover_from_overflow(
|
||||
errors (incl. relay-wrapped output-cap 429s) BEFORE non-retryable client errors.
|
||||
Compression progress is scored in payload BYTES for 413 (never the byte-blind token
|
||||
estimate) and in tokens/message count for context overflow."""
|
||||
# Token estimators + loop-internal helpers resolve through the loop module so
|
||||
# existing ``patch("agent.conversation_loop.X")`` mocks keep intercepting.
|
||||
from agent.conversation_loop import (
|
||||
_COMPRESSION_TIMEOUT_FINAL_RESPONSE,
|
||||
_compression_deferred_result,
|
||||
conversation_history_after_compression,
|
||||
estimate_messages_tokens_rough,
|
||||
estimate_request_tokens_rough,
|
||||
save_context_length,
|
||||
st = _Recovery(
|
||||
agent=agent,
|
||||
api_messages=api_messages,
|
||||
system_message=system_message,
|
||||
effective_task_id=effective_task_id,
|
||||
api_call_count=api_call_count,
|
||||
max_compression_attempts=max_compression_attempts,
|
||||
messages=messages,
|
||||
active_system_prompt=active_system_prompt,
|
||||
conversation_history=conversation_history,
|
||||
approx_tokens=approx_tokens,
|
||||
compression_attempts=compression_attempts,
|
||||
)
|
||||
|
||||
_provider_overflow_recovery_pending = False
|
||||
is_context_length_error = False
|
||||
_wrapped_output_cap_budget = wrapped_output_cap_budget
|
||||
|
||||
def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> OverflowVerdict:
|
||||
return OverflowVerdict(
|
||||
action=action,
|
||||
result=result,
|
||||
messages=messages,
|
||||
active_system_prompt=active_system_prompt,
|
||||
conversation_history=conversation_history,
|
||||
approx_tokens=approx_tokens,
|
||||
compression_attempts=compression_attempts,
|
||||
provider_overflow_recovery_pending=_provider_overflow_recovery_pending,
|
||||
is_context_length_error=is_context_length_error,
|
||||
)
|
||||
|
||||
is_payload_too_large = (
|
||||
classified.reason == FailoverReason.payload_too_large
|
||||
)
|
||||
|
||||
# GitHub Models free tier caps requests at 8K tokens, under the system
|
||||
# prompt + tool schema floor; compression can't help, so say so.
|
||||
# GitHub Models free tier caps requests at 8K tokens, under the system prompt +
|
||||
# tool schema floor; compression can't help, so say so.
|
||||
if (
|
||||
status_code == 413
|
||||
and isinstance(agent.base_url, str)
|
||||
and base_url_host_matches(agent.base_url, "models.inference.ai.azure.com")
|
||||
):
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix} 💡 GitHub Models free tier (models.inference.ai.azure.com) caps every",
|
||||
force=True,
|
||||
)
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix} request at ~8K tokens. Hermes' system prompt + tool schemas baseline",
|
||||
force=True,
|
||||
)
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix} exceeds that floor, so this endpoint cannot run an agentic loop.",
|
||||
force=True,
|
||||
)
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix} Use the `copilot` provider with a Copilot subscription token (`hermes",
|
||||
force=True,
|
||||
)
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix} setup` → GitHub Copilot), or pick any other provider.",
|
||||
force=True,
|
||||
)
|
||||
for line in _GITHUB_MODELS_HINT:
|
||||
agent._vprint(f"{agent.log_prefix}{line}", force=True)
|
||||
|
||||
if is_payload_too_large:
|
||||
compression_attempts += 1
|
||||
if compression_attempts > max_compression_attempts:
|
||||
# Terminal — surface the buffered retry trace.
|
||||
agent._flush_status_buffer()
|
||||
agent._vprint(f"{agent.log_prefix}❌ Max compression attempts ({max_compression_attempts}) reached for payload-too-large error.", force=True)
|
||||
agent._vprint(f"{agent.log_prefix} 💡 Try /new to start a fresh conversation, or /compress to retry compression.", force=True)
|
||||
logger.error("%s413 compression failed after %d attempts.", agent.log_prefix, max_compression_attempts)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = f"Request payload too large: max compression attempts ({max_compression_attempts}) reached."
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
"compression_exhausted": True,
|
||||
})
|
||||
agent._buffer_status(f"⚠️ Request payload too large (413) — compression attempt {compression_attempts}/{max_compression_attempts}...")
|
||||
if classified.reason == FailoverReason.payload_too_large:
|
||||
return _recover_payload_too_large(st, _retry)
|
||||
|
||||
original_len = len(messages)
|
||||
# A 413 is a BYTE-size error: score progress in payload bytes,
|
||||
# never the token estimate, which is deliberately byte-blind to
|
||||
# images and wedged sessions on "no progress" (#88960 / #47339).
|
||||
original_bytes = serialized_messages_bytes(messages)
|
||||
_overflow_input = messages
|
||||
# Option A (LCM issue 441): overhead-aware request size so recovery arms on the
|
||||
# true request (msgs + tools + system), not the tool-blind message count.
|
||||
messages, active_system_prompt = agent._compress_context(
|
||||
messages, system_message,
|
||||
approx_tokens=estimate_request_tokens_rough(api_messages, tools=agent.tools or None),
|
||||
task_id=effective_task_id,
|
||||
# Provider proved the request doesn't fit: ignore the
|
||||
# summary-failure cooldown for this ONE attempt (#100661).
|
||||
bypass_cooldown=True,
|
||||
)
|
||||
if messages is _overflow_input and compression_skipped_due_to_lock(agent):
|
||||
# Lock-skip: another path holds the compression lock. A
|
||||
# temporary defer, not exhaustion — refund the attempt and
|
||||
# end softly so the gateway does NOT auto-reset (#69870).
|
||||
compression_attempts -= 1
|
||||
agent._persist_session(messages, conversation_history)
|
||||
return _verdict("return", _compression_deferred_result(
|
||||
agent, messages, api_call_count
|
||||
))
|
||||
if messages is _overflow_input and compression_blocked_transiently(agent):
|
||||
# Transient-block: a timed guard no-oped compression. A
|
||||
# defer, never compression_exhausted (auto-reset) (#97488).
|
||||
compression_attempts -= 1
|
||||
agent._persist_session(messages, conversation_history)
|
||||
return _verdict("return", _compression_deferred_result(
|
||||
agent, messages, api_call_count,
|
||||
reason="transient_block",
|
||||
))
|
||||
conversation_history = conversation_history_after_compression(
|
||||
agent, messages, conversation_history
|
||||
)
|
||||
|
||||
# Re-measure: same-count compression and media aging can shrink
|
||||
# the request without shrinking the array. Bytes are the yardstick
|
||||
# for a 413; tokens only for status display.
|
||||
new_tokens = estimate_messages_tokens_rough(messages)
|
||||
approx_tokens = new_tokens # update for downstream logging
|
||||
new_bytes = serialized_messages_bytes(messages)
|
||||
|
||||
made_progress = (
|
||||
len(messages) < original_len
|
||||
or (new_bytes > 0 and new_bytes < original_bytes * 0.95)
|
||||
)
|
||||
if made_progress:
|
||||
if len(messages) < original_len:
|
||||
agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
|
||||
else:
|
||||
agent._buffer_status(
|
||||
f"🗜️ Compressed {original_bytes:,} → {new_bytes:,} "
|
||||
f"payload bytes, retrying..."
|
||||
)
|
||||
time.sleep(2) # Brief pause between compression retries
|
||||
_retry.restart_with_compressed_messages = True
|
||||
return _verdict("break")
|
||||
else:
|
||||
if agent._try_strip_image_parts_from_tool_messages(
|
||||
api_messages,
|
||||
remember_model=False,
|
||||
):
|
||||
agent._buffer_status(
|
||||
"📐 Compression could not reduce the request further — "
|
||||
"removed retained vision payloads and retrying..."
|
||||
)
|
||||
return _verdict("continue")
|
||||
|
||||
# Terminal — surface buffered context so the user
|
||||
# sees what compression attempts were made.
|
||||
agent._flush_status_buffer()
|
||||
agent._vprint(f"{agent.log_prefix}❌ Payload too large and cannot compress further.", force=True)
|
||||
agent._vprint(f"{agent.log_prefix} 💡 Try /new to start a fresh conversation, or /compress to retry compression.", force=True)
|
||||
logger.error("%s413 payload too large. Cannot compress further.", agent.log_prefix)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = "Request payload too large (413). Cannot compress further."
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
"compression_exhausted": True,
|
||||
})
|
||||
|
||||
# Check context-length errors BEFORE the generic 4xx handler; the
|
||||
# classifier also covers 400/disconnect + large-session heuristics.
|
||||
is_context_length_error = (
|
||||
# Relay-wrapped output-cap 429s (parsed by the caller) go to the clamp, not
|
||||
# failover or generic retries (#72281). The classifier also covers
|
||||
# 400/disconnect + large-session heuristics.
|
||||
st.is_context_length_error = (
|
||||
classified.reason == FailoverReason.context_overflow
|
||||
# Relay-wrapped output-cap 429s (parsed above) go to the clamp
|
||||
# below, not failover or generic retries (#72281).
|
||||
or _wrapped_output_cap_budget is not None
|
||||
or wrapped_output_cap_budget is not None
|
||||
)
|
||||
|
||||
if is_context_length_error:
|
||||
compressor = agent.context_compressor
|
||||
old_ctx = compressor.context_length
|
||||
|
||||
# Two errors: "prompt too long" = INPUT overflows the window (shrink
|
||||
# context_length + compress); "max_tokens too large" = input fits
|
||||
# but input + max_tokens > window (shrink OUTPUT cap only).
|
||||
available_out = parse_available_output_tokens_from_error(error_msg)
|
||||
if available_out is not None:
|
||||
# Output-cap error: provider available_tokens is the
|
||||
# authoritative bound; also estimate the real request shape
|
||||
# (API-only content), use the smaller minus a margin.
|
||||
request_input_estimate = estimate_request_tokens_rough(
|
||||
api_messages, tools=agent.tools or None,
|
||||
)
|
||||
local_available_out = old_ctx - request_input_estimate
|
||||
if local_available_out > 0:
|
||||
safe_out = max(1, min(available_out, local_available_out) - 64)
|
||||
else:
|
||||
# Local estimate can overshoot; fall back to the
|
||||
# authoritative provider-reported budget.
|
||||
safe_out = max(1, available_out - 64)
|
||||
agent._ephemeral_max_output_tokens = safe_out
|
||||
agent._buffer_vprint(
|
||||
f"⚠️ Output cap too large for current prompt — "
|
||||
f"retrying with max_tokens={safe_out:,} "
|
||||
f"(provider_available={available_out:,}, "
|
||||
f"estimated_request_tokens={request_input_estimate:,}; "
|
||||
f"context_length unchanged at {old_ctx:,})"
|
||||
)
|
||||
# Still count against compression_attempts so we don't
|
||||
# loop forever if the error keeps recurring.
|
||||
compression_attempts += 1
|
||||
if compression_attempts > max_compression_attempts:
|
||||
agent._flush_status_buffer()
|
||||
agent._vprint(f"{agent.log_prefix}❌ Max compression attempts ({max_compression_attempts}) reached.", force=True)
|
||||
agent._vprint(f"{agent.log_prefix} 💡 Try /new to start a fresh conversation, or /compress to retry compression.", force=True)
|
||||
logger.error("%sContext compression failed after %d attempts.", agent.log_prefix, max_compression_attempts)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = f"Context length exceeded: max compression attempts ({max_compression_attempts}) reached."
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
"compression_exhausted": True,
|
||||
})
|
||||
# Also compress history so the output-cap retry doesn't spin on
|
||||
# max_tokens alone; dropping the middle window makes the total
|
||||
# fit. (#55546)
|
||||
try:
|
||||
original_len = len(messages)
|
||||
original_tokens = estimate_messages_tokens_rough(messages)
|
||||
_overflow_input = messages
|
||||
messages, active_system_prompt = agent._compress_context(
|
||||
messages, system_message,
|
||||
approx_tokens=request_input_estimate,
|
||||
task_id=effective_task_id,
|
||||
bypass_cooldown=True, # #100661 provider-proven overflow
|
||||
)
|
||||
if messages is _overflow_input and compression_skipped_due_to_lock(agent):
|
||||
compression_attempts -= 1
|
||||
agent._persist_session(messages, conversation_history)
|
||||
return _verdict("return", _compression_deferred_result(
|
||||
agent, messages, api_call_count
|
||||
))
|
||||
if messages is _overflow_input and compression_blocked_transiently(agent):
|
||||
# #97488: timed transient guard — defer, never
|
||||
# exhaustion (gateway auto-reset).
|
||||
compression_attempts -= 1
|
||||
agent._persist_session(messages, conversation_history)
|
||||
return _verdict("return", _compression_deferred_result(
|
||||
agent, messages, api_call_count,
|
||||
reason="transient_block",
|
||||
))
|
||||
conversation_history = conversation_history_after_compression(
|
||||
agent, messages, conversation_history
|
||||
)
|
||||
new_tokens = estimate_messages_tokens_rough(messages)
|
||||
if len(messages) < original_len:
|
||||
agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
|
||||
elif new_tokens > 0 and new_tokens < original_tokens * 0.95:
|
||||
agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))
|
||||
except Exception:
|
||||
# Compression must never turn an output-cap error
|
||||
# fatal — fall through and retry on max_tokens alone.
|
||||
logger.warning(
|
||||
"%sOutput-cap compression hit an error; retrying on max_tokens only.",
|
||||
agent.log_prefix,
|
||||
)
|
||||
_retry.restart_with_compressed_messages = True
|
||||
return _verdict("break")
|
||||
|
||||
# Output-cap error with unparseable budget: compression can't help
|
||||
# (input already fits) and would death-loop on the same 400. Fail
|
||||
# fast. (#55546)
|
||||
if is_output_cap_error(error_msg):
|
||||
agent._flush_status_buffer()
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix}❌ The provider rejected the request because "
|
||||
f"max_tokens exceeds its output cap for this model.",
|
||||
force=True,
|
||||
)
|
||||
agent._vprint(
|
||||
f"{agent.log_prefix} 💡 Lower model.max_tokens in your config.yaml to "
|
||||
f"at or below the model's max-output limit. "
|
||||
f"(This is an output-cap error, not a context overflow — "
|
||||
f"compression cannot fix it.)",
|
||||
force=True,
|
||||
)
|
||||
logger.error(
|
||||
f"{agent.log_prefix}Output-cap error not routed into compression "
|
||||
f"(max_tokens over provider cap): {error_msg[:200]}"
|
||||
)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = (
|
||||
"max_tokens exceeds the provider's output cap for this model. "
|
||||
"Lower model.max_tokens in config.yaml."
|
||||
)
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
})
|
||||
|
||||
# Input too large: shrink context_length only when the provider
|
||||
# reports the real limit; else keep the window and compress. Guessed
|
||||
# probe tiers can turn a configured 1M window into 256K/128K/64K.
|
||||
new_ctx = get_context_length_from_provider_error(error_msg, old_ctx)
|
||||
_provider_lower = (getattr(agent, "provider", "") or "").lower()
|
||||
_base_lower = (getattr(agent, "base_url", "") or "").rstrip("/").lower()
|
||||
is_minimax_provider = (
|
||||
_provider_lower in {"minimax", "minimax-cn"}
|
||||
or _base_lower.startswith((
|
||||
"https://api.minimax.io/anthropic",
|
||||
"https://api.minimaxi.com/anthropic",
|
||||
))
|
||||
)
|
||||
minimax_delta_only_overflow = (
|
||||
is_minimax_provider
|
||||
and new_ctx is None
|
||||
and "context window exceeds limit (" in error_msg
|
||||
)
|
||||
|
||||
if new_ctx is not None:
|
||||
agent._buffer_vprint(f"Context limit detected from API: {new_ctx:,} tokens (was {old_ctx:,})")
|
||||
compressor.update_model(
|
||||
model=agent.model,
|
||||
context_length=new_ctx,
|
||||
base_url=agent.base_url,
|
||||
api_key=getattr(agent, "api_key", ""),
|
||||
provider=agent.provider,
|
||||
api_mode=agent.api_mode,
|
||||
)
|
||||
# Persist the provider-reported limit before compression/retry:
|
||||
# rate limit, missing usage, or restart must not lose confirmed
|
||||
# metadata. Probe flags remain a fallback if this write fails.
|
||||
save_context_length(agent.model, agent.base_url, new_ctx)
|
||||
# Probe flags only on the built-in compressor (plugin engines
|
||||
# manage their own); provider-sourced value, so safe to cache.
|
||||
if hasattr(compressor, "_context_probed"):
|
||||
compressor._context_probed = True
|
||||
compressor._context_probe_persistable = True
|
||||
agent._buffer_vprint(f"⚠️ Context length exceeded — using provider limit: {old_ctx:,} → {new_ctx:,} tokens")
|
||||
elif minimax_delta_only_overflow:
|
||||
agent._buffer_vprint(
|
||||
f"Provider reported overflow amount only; "
|
||||
f"keeping context_length at {old_ctx:,} tokens and compressing."
|
||||
)
|
||||
else:
|
||||
agent._buffer_vprint(
|
||||
f"⚠️ Context length exceeded, but provider did not report a max context length; "
|
||||
f"keeping context_length at {old_ctx:,} tokens and compressing."
|
||||
)
|
||||
|
||||
compression_attempts += 1
|
||||
if compression_attempts > max_compression_attempts:
|
||||
agent._flush_status_buffer()
|
||||
agent._vprint(f"{agent.log_prefix}❌ Max compression attempts ({max_compression_attempts}) reached.", force=True)
|
||||
agent._vprint(f"{agent.log_prefix} 💡 Try /new to start a fresh conversation, or /compress to retry compression.", force=True)
|
||||
logger.error("%sContext compression failed after %d attempts.", agent.log_prefix, max_compression_attempts)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = f"Context length exceeded: max compression attempts ({max_compression_attempts}) reached."
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
"compression_exhausted": True,
|
||||
})
|
||||
agent._buffer_status(COMPRESSION_RETRY_TOO_LARGE_STATUS_TEMPLATE.format(tokens=approx_tokens, attempt=compression_attempts, cap=max_compression_attempts))
|
||||
|
||||
original_len = len(messages)
|
||||
original_tokens = estimate_messages_tokens_rough(messages)
|
||||
_overflow_input = messages
|
||||
# Pass the OVERHEAD-AWARE size (msgs + tool schemas + system) so LCM
|
||||
# forced-overflow recovery arms on the TRUE request; approx_tokens
|
||||
# stays for status. See hermes-lcm _should_force_overflow_recovery.
|
||||
messages, active_system_prompt = agent._compress_context(
|
||||
messages, system_message,
|
||||
approx_tokens=estimate_request_tokens_rough(api_messages, tools=agent.tools or None),
|
||||
task_id=effective_task_id,
|
||||
# Provider proved the request doesn't fit: ignore the
|
||||
# summary-failure cooldown for this ONE attempt (bounded by
|
||||
# max_compression_attempts). (#100661)
|
||||
bypass_cooldown=True,
|
||||
)
|
||||
if messages is _overflow_input and compression_skipped_due_to_lock(agent):
|
||||
# Lock-skip: another path holds the compression lock, so this
|
||||
# pass no-oped. Temporary defer, not exhaustion — refund the
|
||||
# attempt, end the turn softly, no auto-reset. (#69870)
|
||||
compression_attempts -= 1
|
||||
agent._persist_session(messages, conversation_history)
|
||||
return _verdict("return", _compression_deferred_result(
|
||||
agent, messages, api_call_count
|
||||
))
|
||||
if messages is _overflow_input and compression_blocked_transiently(agent):
|
||||
# Transient block: a timed guard (host-timeout cooldown /
|
||||
# structural backoff) no-oped this pass — defer softly, never
|
||||
# compression_exhausted (auto-reset). (#97488)
|
||||
compression_attempts -= 1
|
||||
agent._persist_session(messages, conversation_history)
|
||||
return _verdict("return", _compression_deferred_result(
|
||||
agent, messages, api_call_count,
|
||||
reason="transient_block",
|
||||
))
|
||||
if context_compression_timed_out(agent):
|
||||
# Host timeout: recovery spent its wait budget with no committed
|
||||
# summary. Re-sending would hit the same overflow; end the turn
|
||||
# via the typed recovery contract. (#98722)
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = _COMPRESSION_TIMEOUT_FINAL_RESPONSE
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
"compression_exhausted": True,
|
||||
"turn_exit_reason": "context_compression_timeout",
|
||||
})
|
||||
conversation_history = conversation_history_after_compression(
|
||||
agent, messages, conversation_history
|
||||
)
|
||||
|
||||
# Re-estimate after compression: same-message-count compression
|
||||
# (tool-result pruning, in-place summarization) can shrink the
|
||||
# request. (#39550)
|
||||
new_tokens = estimate_messages_tokens_rough(messages)
|
||||
approx_tokens = new_tokens # update for downstream logging
|
||||
|
||||
if len(messages) < original_len or (new_tokens > 0 and new_tokens < original_tokens * 0.95) or (new_ctx and new_ctx < old_ctx):
|
||||
if len(messages) < original_len:
|
||||
agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
|
||||
elif new_tokens > 0 and new_tokens < original_tokens * 0.95:
|
||||
agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))
|
||||
time.sleep(2) # Brief pause between compression retries
|
||||
# Rebuild the full request and force normal preflight to honor
|
||||
# it; message count alone doesn't prove system/tool-inclusive
|
||||
# pressure fell.
|
||||
_provider_overflow_recovery_pending = True
|
||||
_retry.restart_with_compressed_messages = True
|
||||
return _verdict("break")
|
||||
else:
|
||||
# Can't compress further and already at minimum tier
|
||||
agent._flush_status_buffer()
|
||||
agent._vprint(f"{agent.log_prefix}❌ Context length exceeded and cannot compress further.", force=True)
|
||||
agent._vprint(f"{agent.log_prefix} 💡 The conversation has accumulated too much content. Try /new to start fresh, or /compress to manually trigger compression.", force=True)
|
||||
logger.error("%sContext length exceeded: %s tokens. Cannot compress further.", agent.log_prefix, f"{new_tokens:,}")
|
||||
agent._persist_session(messages, conversation_history)
|
||||
_final_response = f"Context length exceeded ({new_tokens:,} tokens). Cannot compress further."
|
||||
return _verdict("return", {
|
||||
"final_response": _final_response,
|
||||
"messages": messages,
|
||||
"completed": False,
|
||||
"api_calls": api_call_count,
|
||||
"error": _final_response,
|
||||
"partial": True,
|
||||
"failed": True,
|
||||
"compression_exhausted": True,
|
||||
})
|
||||
return _verdict("fallthrough")
|
||||
if st.is_context_length_error:
|
||||
return _recover_context_length(st, _retry, error_msg)
|
||||
return st.verdict("fallthrough")
|
||||
|
||||
@@ -724,7 +724,8 @@ class TestMicroCompaction:
|
||||
|
||||
from agent import turn_finalizer
|
||||
|
||||
src = inspect.getsource(turn_finalizer.finalize_turn)
|
||||
# The micro-compaction gate lives in the helper finalize_turn calls.
|
||||
src = inspect.getsource(turn_finalizer._micro_compact_after_turn)
|
||||
micro_block = src.split("Post-turn micro-compaction", 1)[1]
|
||||
# Scope to the micro block only: stop at the persist call that follows.
|
||||
micro_block = micro_block.split("agent._persist_session", 1)[0]
|
||||
@@ -810,7 +811,8 @@ class TestDefragFlushCursorInvalidation:
|
||||
|
||||
from agent import turn_finalizer
|
||||
|
||||
src = inspect.getsource(turn_finalizer.finalize_turn)
|
||||
# The micro-compaction gate lives in the helper finalize_turn calls.
|
||||
src = inspect.getsource(turn_finalizer._micro_compact_after_turn)
|
||||
micro_block = src.split("Post-turn micro-compaction", 1)[1]
|
||||
micro_block = micro_block.split("agent._persist_session", 1)[0]
|
||||
assert "_flush_scan_cursor_invalidated" in micro_block, (
|
||||
|
||||
Reference in New Issue
Block a user