Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 57 additions & 6 deletions agent/agent_runtime_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,39 @@ def note_turn_persisted(agent):
agent._inflight_turn_id = None


REPAIRED_USER_PREFIX_KEY = "_hermes_repaired_user_prefix"


def provider_visible_message_copy(message: Dict[str, Any]) -> Dict[str, Any]:
"""Copy one message exactly as provider and local sizing may observe it."""
api_message = message.copy()
repaired_user_prefix = api_message.get(REPAIRED_USER_PREFIX_KEY)
if (
message.get("role") == "user"
and isinstance(repaired_user_prefix, str)
and repaired_user_prefix
):
content = api_message.get("content", "")
if isinstance(content, str):
api_message["content"] = (
repaired_user_prefix + "\n\n" + content
if content
else repaired_user_prefix
)
for internal_key in [

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: this blanket underscore-key removal also drops _anthropic_content_blocks. The Anthropic converter explicitly consumes that back-compat field in agent/anthropic_adapter.py:2069-2077, and this helper is now used before provider conversion at agent/conversation_loop.py:979. Preserve that field until Anthropic conversion (or narrow this filter) and add a request-path regression test.

key for key in api_message if isinstance(key, str) and key.startswith("_")
]:
api_message.pop(internal_key, None)
return api_message


def provider_visible_messages(
messages: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Project an internal transcript into the provider-visible message shape."""
return [provider_visible_message_copy(message) for message in messages]


def repair_message_sequence(agent, messages: List[Dict]) -> int:
"""Collapse malformed role-alternation left in the live history.

Expand Down Expand Up @@ -580,13 +613,31 @@ def _is_codex_interim(m: Dict) -> bool:
new_content = msg.get("content", "")
# Only merge plain-text content; leave multimodal (list)
# content alone — collapsing image/audio blocks risks
# mangling the attachment structure.
# mangling the attachment structure. A marked current-turn user
# must remain the survivor: it owns the durable turn marker and
# its identity tells repair_message_sequence_with_cursor whether
# an unflushed input displaced a flushed row. Do not rewrite its
# transcript content after the crash-resilience persist, though:
# keep historical user text in private API-only metadata instead.
if isinstance(prev_content, str) and isinstance(new_content, str):
prev["content"] = (
(prev_content + "\n\n" + new_content)
if prev_content and new_content
else (prev_content or new_content)
)
from agent.iteration_budget import CURRENT_TURN_ID_KEY

if msg.get(CURRENT_TURN_ID_KEY):
prefix_parts = [
prev.get(REPAIRED_USER_PREFIX_KEY, ""),
prev_content,
msg.get(REPAIRED_USER_PREFIX_KEY, ""),
]
msg[REPAIRED_USER_PREFIX_KEY] = "\n\n".join(
part for part in prefix_parts if isinstance(part, str) and part
)
merged[-1] = msg
else:
prev["content"] = (
(prev_content + "\n\n" + new_content)
if prev_content and new_content
else (prev_content or new_content)
)
repairs += 1
continue
merged.append(msg)
Expand Down
35 changes: 29 additions & 6 deletions agent/chat_completion_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from types import SimpleNamespace
from typing import Any, Dict, Optional

from agent.agent_runtime_helpers import provider_visible_messages
from hermes_cli.timeouts import get_provider_request_timeout, get_provider_stale_timeout
from hermes_constants import PARTIAL_STREAM_STUB_ID, FINISH_REASON_LENGTH
from agent.error_classifier import FailoverReason
Expand Down Expand Up @@ -1872,14 +1873,37 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool



def _iteration_limit_summary_request(*, is_kanban: bool) -> str:
"""Return a general summary request or a reusable Kanban handoff contract."""
if not is_kanban:
return (
"You've reached the maximum number of tool-calling iterations allowed. "
"Please provide a final response summarizing what you've found and "
"accomplished so far, without calling any more tools."
)
return (
"You've reached the maximum number of tool-calling iterations allowed; "
"without calling any more tools, return a compact continuation record "
"using exactly these headings:\n\n"
"PARTIAL_UNVERIFIED_HANDOFF\n"
"COMPLETED: verified work actually finished\n"
"CHANGED_FILES: exact paths, or none\n"
"TESTS: exact commands/results already observed\n"
"REMAINING: unfinished work and required reviews\n"
"RESUME: the first concrete next action\n"
"INVARIANTS: safety boundaries and actions not taken\n\n"
"Do not claim PASS, approval, deployment, or completion unless it was "
"actually verified before exhaustion. Keep this handoff concise; it will "
"be marked partial_unverified and supplied to a continuation worker."
)


def handle_max_iterations(agent, messages: list, api_call_count: int) -> str:
"""Request a summary when max iterations are reached. Returns the final response text."""
print(f"⚠️ Reached maximum iterations ({agent.max_iterations}). Requesting summary...")

summary_request = (
"You've reached the maximum number of tool-calling iterations allowed. "
"Please provide a final response summarizing what you've found and accomplished so far, "
"without calling any more tools."
summary_request = _iteration_limit_summary_request(
is_kanban=bool(os.environ.get("HERMES_KANBAN_TASK"))
)
messages.append({"role": "user", "content": summary_request})

Expand All @@ -1888,8 +1912,7 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str:
# (finish_reason, reasoning) that strict APIs like Mistral reject with 422
_needs_sanitize = agent._should_sanitize_tool_calls()
api_messages = []
for msg in messages:
api_msg = msg.copy()
for msg, api_msg in zip(messages, provider_visible_messages(messages)):
agent._copy_reasoning_content_for_api(msg, api_msg)
for internal_field in ("reasoning", "finish_reason", "_thinking_prefill"):
api_msg.pop(internal_field, None)
Expand Down
Loading