The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): re-prompt once when a turn that did tool work ends on a collapsed fragment
kshitijk4poor80f0d1b52f97
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 02f298bcde3..5c9974862c5 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2961,6 +2961,42 @@ def looks_like_codex_intermediate_ack()+# Degenerate-final detector (#103483): after real tool work a text stop whose ENTIRE answer is a+# fragment — a stray wrong-script word ("пар"), a token starting mid-punctuation ("?warming up") —+# is a provider-side collapse, not an answer, yet the loop accepted it and the turn reported+# completed. Shape alone cannot PROVE a collapse, so this is deliberately narrower than "short":+# a terse legitimate answer ("42", "SQLite", "report.csv", "€12.50", "你好。", "Done.") never+# matches, and the re-prompt it triggers asks for the same answer again if it was complete.+_DEGENERATE_FINAL_MAX_CHARS = 24+_SENTENCE_TERMINALS = (".", "!", "?", "\u3002", "\uff01", "\uff1f")+# Punctuation no answer begins with; "$5", "#123", "-1", "/tmp", ".env", "(a)" all stay answers.+_DEGENERATE_LEADING_PUNCT = "?!,;:)]}"+++def looks_like_degenerate_final(text: str) -> bool:+ """Whether a text stop reads as a collapsed fragment rather than a (terse) answer."""+ t = (text or "").strip()+ if not t or len(t) > _DEGENERATE_FINAL_MAX_CHARS or t.endswith(_SENTENCE_TERMINALS):+ return False+ if t[0] in _DEGENERATE_LEADING_PUNCT:+ return True+ # A word with letters but no ASCII letter or digit at all: the wrong-script fragment.+ return any(ch.isalpha() for ch in t) and not any(ch.isascii() and ch.isalnum() for ch in t)+++def tool_results_this_turn(messages: List[Dict[str, Any]]) -> int:+ """Tool-result rows after the most recent user row — whether the turn did real tool work."""+ count = 0+ for msg in reversed(messages or ()):+ if not isinstance(msg, dict):+ continue+ if msg.get("role") == "user":+ break+ if msg.get("role") == "tool":+ count += 1+ return count++# Narrow "trailing continue-intent" detector for the stall guard (agent.stall_guards): only the# message TAIL announcing a next action, so mid-sentence "I will" never trips it._TRAILING_CONTINUE_INTENT_RE = re.compile(diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex e2750fc09d2..6c03642e49a 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -3771,15 +3771,15 @@ Write only the summary body. Do not include any preamble or prefix."""text = _content_text_for_contains(message.get("content")).strip()# Recovery nudges are scaffolding, not human turns; lazy import avoids an import cycle.from agent.conversation_loop import (- _CODEX_ACK_CONTINUATION_NUDGE, _CODEX_INCOMPLETE_NUDGE, _DROPPED_TOOLCALL_NUDGE_CONTENT,- _EMPTY_TOOL_RESPONSE_NUDGE, _LENGTH_CONTINUATION_DROPPED_TOOLS_PREFIX, _LENGTH_CONTINUATION_NETWORK_STUB,- _LENGTH_CONTINUATION_OUTPUT_LIMIT,+ _CODEX_ACK_CONTINUATION_NUDGE, _CODEX_INCOMPLETE_NUDGE, _DEGENERATE_FINAL_NUDGE,+ _DROPPED_TOOLCALL_NUDGE_CONTENT, _EMPTY_TOOL_RESPONSE_NUDGE, _LENGTH_CONTINUATION_DROPPED_TOOLS_PREFIX,+ _LENGTH_CONTINUATION_NETWORK_STUB, _LENGTH_CONTINUATION_OUTPUT_LIMIT,)return text in {COMPRESSION_CONTINUATION_USER_CONTENT, _LEGACY_COMPRESSION_CONTINUATION_USER_CONTENT,MAX_ITERATIONS_SUMMARY_REQUEST, _CODEX_INCOMPLETE_NUDGE, _CODEX_ACK_CONTINUATION_NUDGE,- _DROPPED_TOOLCALL_NUDGE_CONTENT, _EMPTY_TOOL_RESPONSE_NUDGE, _LENGTH_CONTINUATION_NETWORK_STUB,- _LENGTH_CONTINUATION_OUTPUT_LIMIT,+ _DEGENERATE_FINAL_NUDGE, _DROPPED_TOOLCALL_NUDGE_CONTENT, _EMPTY_TOOL_RESPONSE_NUDGE,+ _LENGTH_CONTINUATION_NETWORK_STUB, _LENGTH_CONTINUATION_OUTPUT_LIMIT,} or text.startswith((_BACKGROUND_PROCESS_NOTIFICATION_PREFIX, TODO_INJECTION_HEADER + "\n", _LENGTH_CONTINUATION_DROPPED_TOOLS_PREFIX,))diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 4ce70089353..2343c74547f 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -870,6 +870,14 @@ _CODEX_ACK_CONTINUATION_NUDGE = ("after completing the task.]")+# Re-prompt after a collapsed fragment ended a turn that had done real tool work (#103483). Asks+# for the same answer again when it WAS complete, so a false positive costs one call, never the answer.+_DEGENERATE_FINAL_NUDGE = (+ "[System: Your previous message ended the turn with a fragment that is not a usable answer. "+ "If the task is unfinished, continue it and then give the complete answer. If that fragment "+ "WAS your complete answer, send it again exactly as before.]"+)+# Re-prompt for finish_reason="tool_calls" with empty tool_calls (an interrupt mid-retry can persist it)._DROPPED_TOOLCALL_NUDGE_CONTENT = ("Your previous turn indicated a tool call but none was included. Do not narrate a plan or "diff --git a/agent/turn_final_response.py b/agent/turn_final_response.pyindex ecda17c965d..dd568cf2173 100644--- a/agent/turn_final_response.py+++ b/agent/turn_final_response.py@@ -56,7 +56,8 @@ def finish_text_response(iteration-limit summarization; the final message is appended and flushed only after thestop gates accept it."""from agent.conversation_loop import (- _CODEX_ACK_CONTINUATION_NUDGE, _DROPPED_TOOLCALL_NUDGE_CONTENT, _join_truncated_parts+ _CODEX_ACK_CONTINUATION_NUDGE, _DEGENERATE_FINAL_NUDGE, _DROPPED_TOOLCALL_NUDGE_CONTENT,+ _join_truncated_parts)def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> FinalResponseVerdict:@@ -142,7 +143,8 @@ def finish_text_response(# delivery channel (gateway status message / CLI print). NEVER appended to messages/api_messages:# conversation context and the cached prompt prefix stay byte-identical.from agent.agent_runtime_helpers import (- intent_ack_continuation_mode, promoted_reasoning_announces_action, trailing_continue_intent+ intent_ack_continuation_mode, looks_like_degenerate_final, promoted_reasoning_announces_action,+ tool_results_this_turn, trailing_continue_intent,)_ack_mode = intent_ack_continuation_mode(agent)@@ -162,7 +164,17 @@ def finish_text_response(or (bool(_promoted) and promoted_reasoning_announces_action(_stall_text))))- if _stall_continue_intent or (+ # Degenerate-final guard (#103483): the turn did real tool work and then stopped on a+ # fragment. Same scope knob and the SAME bounded counter as the ack continuation; the nudge+ # row itself closes the tool-work window, so a second fragment ends the turn as the answer.+ _degenerate_final = (+ bool(getattr(agent, "_stall_guards", True))+ and _ack_mode != "off"+ and codex_ack_continuations < 2+ and tool_results_this_turn(messages) > 0+ and looks_like_degenerate_final(_stall_text)+ )+ if _stall_continue_intent or _degenerate_final or (_ack_mode != "off"and agent.valid_tool_namesand codex_ack_continuations < 2@@ -177,6 +189,12 @@ def finish_text_response("intent with no tool calls — re-prompting to act ""(%d/2)", codex_ack_continuations + 1,)+ elif _degenerate_final:+ logger.warning(+ "Degenerate final: %d-char fragment %r ended the turn after %d tool result(s) — "+ "re-prompting (%d/2)", len(_stall_text), _stall_text[:40],+ tool_results_this_turn(messages), codex_ack_continuations + 1,+ )codex_ack_continuations += 1interim_msg = agent._build_assistant_message(assistant_message, "incomplete")if _promoted:@@ -185,7 +203,13 @@ def finish_text_response(interim_msg["api_content"] = final_responseappend_message(messages, interim_msg)agent._emit_interim_assistant_message(interim_msg)- append_message(messages, {"role": "user", "content": _CODEX_ACK_CONTINUATION_NUDGE})+ append_message(messages, {+ "role": "user",+ "content": (+ _DEGENERATE_FINAL_NUDGE if _degenerate_final and not _stall_continue_intent+ else _CODEX_ACK_CONTINUATION_NUDGE+ ),+ })agent._session_messages = messages# An acknowledgment is non-final: its text must not suppress iteration-limit# summarization if the continuation exhausts budget.