refactor(goal): sustain one ReAct run until the goal closes (#6538)
* refactor(goal): sustain one ReAct run until the goal closes Keep active goals in the same runner beyond the ordinary iteration limit, with a final answer after successful closure. Remove cross-turn goal handoffs, continuation allowances and rollback bookkeeping while preserving input authorization, recovery, cancellation and terminal lifecycle ownership. Contributes to NAN-392 Co-authored-by: chengyongru <chengyongru.ai@gmail.com> * test(goal): consolidate sustained-run regression coverage Retain lifecycle, history, usage, provider-state privacy and checkpoint cancellation assertions in the existing long-run scenarios. Remove duplicate smoke cases and parameter combinations that do not exercise distinct behavior; keep real Gateway, authorization and generation regressions.
This commit is contained in:
1 parent
3545539128
commit
62c2ed4e7e
68 files changed
+2683
-1421
No files matched your search
+109
-139
@@ -20,6 +20,7 @@ from nanobot.agent.context_governance import (
|
||||
ProviderCompactionConsolidator,
|
||||
TranscriptBuilder,
|
||||
)
|
||||
from nanobot.agent.execution_policy import ExecutionControlError
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
|
||||
from nanobot.agent.tools.context import tool_log_content_allowed
|
||||
from nanobot.agent.tools.execution import execute_tool_calls
|
||||
@@ -39,7 +40,7 @@ from nanobot.providers.base import (
|
||||
ProviderConversationState,
|
||||
)
|
||||
from nanobot.providers.conversation_state import ProviderConversationStateController
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
|
||||
from nanobot.session.summary import SessionSummaryCheckpoint
|
||||
from nanobot.utils.helpers import (
|
||||
build_assistant_message,
|
||||
@@ -138,7 +139,7 @@ class AgentRunResult:
|
||||
failure_error_kind: str | None = None
|
||||
tool_events: list[dict[str, str]] = field(default_factory=list)
|
||||
had_injections: bool = False
|
||||
# Terminal tail to emit when the preceding final-content prefix was already streamed.
|
||||
# Unstreamed terminal content or tail; excludes any prefix already delivered.
|
||||
pending_stream_content: str | None = None
|
||||
provider_state: ProviderConversationState | None = field(default=None, repr=False)
|
||||
summary_checkpoint: SessionSummaryCheckpoint | None = field(default=None, repr=False)
|
||||
@@ -177,84 +178,33 @@ class AgentRunner:
|
||||
self,
|
||||
spec: AgentRunSpec,
|
||||
messages: list[dict[str, Any]],
|
||||
assistant_message: dict[str, Any] | None,
|
||||
injection_cycles: int,
|
||||
*,
|
||||
conversation_state: ProviderConversationStateController | None = None,
|
||||
phase: str = "after error",
|
||||
iteration: int | None = None,
|
||||
allow_continuation: bool = False,
|
||||
wait_at_terminal: bool = False,
|
||||
drain_callback: bool = True,
|
||||
) -> tuple[bool, int]:
|
||||
injections = await self._drain_injections(spec) if drain_callback else []
|
||||
real_injection = bool(injections)
|
||||
if not injections and allow_continuation and assistant_message is not None:
|
||||
continuation = await self._build_continuation_message(spec)
|
||||
if continuation is not None:
|
||||
injections = [continuation]
|
||||
if (
|
||||
not injections
|
||||
and wait_at_terminal
|
||||
and drain_callback
|
||||
):
|
||||
injections = await self._drain_injections(spec, terminal=True)
|
||||
real_injection = bool(injections)
|
||||
phase: str,
|
||||
terminal: bool = False,
|
||||
) -> bool:
|
||||
injections = await self._drain_injections(spec, terminal=terminal)
|
||||
if not injections:
|
||||
return False, injection_cycles
|
||||
if real_injection:
|
||||
injection_cycles += 1
|
||||
if assistant_message is not None:
|
||||
messages.append(assistant_message)
|
||||
if iteration is not None:
|
||||
checkpoint: dict[str, Any] = {
|
||||
"phase": "final_response",
|
||||
"iteration": iteration,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": assistant_message,
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
}
|
||||
if conversation_state is not None:
|
||||
checkpoint["provider_state"] = conversation_state.checkpoint(
|
||||
messages
|
||||
)
|
||||
await self._emit_checkpoint(
|
||||
spec,
|
||||
checkpoint,
|
||||
messages,
|
||||
)
|
||||
return False
|
||||
self._append_injected_messages(messages, injections)
|
||||
if real_injection:
|
||||
preview = "[content hidden]"
|
||||
if tool_log_content_allowed():
|
||||
preview = "\n\n".join(
|
||||
message["content"] for message in injections
|
||||
if isinstance(message.get("content"), str)
|
||||
and not is_hidden_history_message(message)
|
||||
)
|
||||
preview = preview[:80] + "..." if len(preview) > 80 else preview
|
||||
logger.info(
|
||||
"Injected {} follow-up message(s) {} (snapshot {}): {}",
|
||||
len(injections), phase, injection_cycles, preview,
|
||||
preview = "[content hidden]"
|
||||
if tool_log_content_allowed():
|
||||
preview = "\n\n".join(
|
||||
content for message in injections
|
||||
if isinstance(content := message.get("content"), str)
|
||||
and not is_hidden_history_message(message)
|
||||
)
|
||||
else:
|
||||
logger.info("Injected caller-requested continuation {}", phase)
|
||||
return True, injection_cycles
|
||||
preview = preview[:80] + "..." if len(preview) > 80 else preview
|
||||
logger.info(
|
||||
"Injected {} follow-up message(s) {}: {}",
|
||||
len(injections), phase, preview,
|
||||
)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
|
||||
callback = spec.continuation_callback
|
||||
if callback is None:
|
||||
return None
|
||||
try:
|
||||
content = await callback()
|
||||
except Exception:
|
||||
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
|
||||
return None
|
||||
if content is None or not content.strip():
|
||||
return None
|
||||
return {"role": "user", "content": content}
|
||||
async def _continuation_prompt(spec: AgentRunSpec) -> str | None:
|
||||
prompt = await spec.continuation_callback() if spec.continuation_callback is not None else None
|
||||
_raise_if_cancelling()
|
||||
return prompt
|
||||
|
||||
async def _drain_injections(
|
||||
self,
|
||||
@@ -271,6 +221,8 @@ class AgentRunner:
|
||||
return []
|
||||
try:
|
||||
items = await callback()
|
||||
except ExecutionControlError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.opt(exception=tool_log_content_allowed()).error("injection_callback failed")
|
||||
return []
|
||||
@@ -424,7 +376,6 @@ class AgentRunner:
|
||||
length_recovery_parts: list[str] = []
|
||||
pending_length_segment: tuple[AgentHookContext, str] | None = None
|
||||
had_injections = False
|
||||
injection_cycles = 0
|
||||
pending_stream_content: str | None = None
|
||||
conversation_state = ProviderConversationStateController(
|
||||
provider=spec.runtime.provider,
|
||||
@@ -464,19 +415,25 @@ class AgentRunner:
|
||||
segment_context.stream_continues_current_message = not interrupted
|
||||
await hook.on_stream_end(segment_context, resuming=True)
|
||||
|
||||
for iteration in range(spec.max_iterations):
|
||||
iteration = -1
|
||||
followup_requested = False
|
||||
while (
|
||||
iteration + 1 < spec.max_iterations
|
||||
or followup_requested
|
||||
or await self._continuation_prompt(spec) is not None
|
||||
):
|
||||
iteration += 1
|
||||
# A response boundary already admitted its follow-up request. Do not
|
||||
# reread continuation state for that same decision at loop entry.
|
||||
followup_requested = False
|
||||
# A resumed iteration must not inherit a previous iteration's failure.
|
||||
stop_reason = "completed"
|
||||
error = None
|
||||
# The session inbox cuts a finite snapshot before every model call.
|
||||
# This includes follow-ups that arrived before the first request and
|
||||
# messages received while the previous request or tools were running.
|
||||
drained_before_request, injection_cycles = await self._try_drain_injections(
|
||||
spec,
|
||||
messages,
|
||||
None,
|
||||
injection_cycles,
|
||||
phase="before model call",
|
||||
drained_before_request = await self._try_drain_injections(
|
||||
spec, messages, phase="before model call",
|
||||
)
|
||||
if drained_before_request:
|
||||
had_injections = True
|
||||
@@ -722,6 +679,20 @@ class AgentRunner:
|
||||
assistant_message,
|
||||
response,
|
||||
)
|
||||
messages.append(assistant_message)
|
||||
await self._emit_checkpoint(
|
||||
spec,
|
||||
{
|
||||
"phase": "final_response",
|
||||
"iteration": iteration,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": assistant_message,
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
"provider_state": conversation_state.checkpoint(messages),
|
||||
},
|
||||
messages,
|
||||
)
|
||||
|
||||
if response.finish_reason == "error":
|
||||
interrupted_parts = [
|
||||
@@ -743,22 +714,32 @@ class AgentRunner:
|
||||
# Check for mid-turn injections BEFORE signaling stream end.
|
||||
# If injections are found we keep the stream alive (resuming=True)
|
||||
# so streaming channels don't prematurely finalize the card.
|
||||
can_make_followup_request = iteration + 1 < spec.max_iterations
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, assistant_message, injection_cycles,
|
||||
conversation_state=conversation_state,
|
||||
phase="after final response",
|
||||
iteration=iteration,
|
||||
allow_continuation=(
|
||||
response.finish_reason not in {"refusal", "content_filter"}
|
||||
),
|
||||
wait_at_terminal=(
|
||||
assistant_message is not None
|
||||
and response.finish_reason
|
||||
not in {"error", "length", "refusal", "content_filter"}
|
||||
),
|
||||
drain_callback=can_make_followup_request,
|
||||
normal_response = (
|
||||
assistant_message is not None
|
||||
and response.finish_reason not in {"error", "length", "refusal", "content_filter"}
|
||||
)
|
||||
ordinary_budget_remaining = iteration + 1 < spec.max_iterations
|
||||
continuation_prompt = None
|
||||
if normal_response and not ordinary_budget_remaining:
|
||||
continuation_prompt = await self._continuation_prompt(spec)
|
||||
can_make_followup_request = ordinary_budget_remaining or continuation_prompt is not None
|
||||
should_continue = can_make_followup_request and await self._try_drain_injections(
|
||||
spec, messages, phase="after final response",
|
||||
)
|
||||
if not should_continue and normal_response:
|
||||
if ordinary_budget_remaining:
|
||||
continuation_prompt = await self._continuation_prompt(spec)
|
||||
if continuation_prompt is not None:
|
||||
messages.append({
|
||||
"role": "user", "content": continuation_prompt,
|
||||
HIDDEN_HISTORY_META: {"kind": "internal_continuation"},
|
||||
})
|
||||
should_continue = True
|
||||
logger.info("Injected caller-requested continuation after final response")
|
||||
elif can_make_followup_request:
|
||||
should_continue = await self._try_drain_injections(
|
||||
spec, messages, phase="at terminal response", terminal=True,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
|
||||
@@ -766,6 +747,7 @@ class AgentRunner:
|
||||
await hook.on_stream_end(context, resuming=should_continue)
|
||||
|
||||
if should_continue:
|
||||
followup_requested = True
|
||||
length_recovery_parts.clear()
|
||||
await hook.after_iteration(context)
|
||||
continue
|
||||
@@ -782,12 +764,9 @@ class AgentRunner:
|
||||
context.error = error
|
||||
context.stop_reason = stop_reason
|
||||
await hook.after_iteration(context)
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after LLM error",
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
if can_make_followup_request and await self._try_drain_injections(
|
||||
spec, messages, phase="after LLM error",
|
||||
):
|
||||
had_injections = True
|
||||
length_recovery_parts.clear()
|
||||
continue
|
||||
@@ -802,41 +781,14 @@ class AgentRunner:
|
||||
context.error = error
|
||||
context.stop_reason = stop_reason
|
||||
await hook.after_iteration(context)
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after empty response",
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
if can_make_followup_request and await self._try_drain_injections(
|
||||
spec, messages, phase="after empty response",
|
||||
):
|
||||
had_injections = True
|
||||
length_recovery_parts.clear()
|
||||
continue
|
||||
break
|
||||
|
||||
messages.append(
|
||||
assistant_message
|
||||
or conversation_state.project_response_message(
|
||||
build_assistant_message(
|
||||
clean,
|
||||
reasoning_content=response.reasoning_content,
|
||||
thinking_blocks=response.thinking_blocks,
|
||||
),
|
||||
response,
|
||||
)
|
||||
)
|
||||
await self._emit_checkpoint(
|
||||
spec,
|
||||
{
|
||||
"phase": "final_response",
|
||||
"iteration": iteration,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": messages[-1],
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
"provider_state": conversation_state.checkpoint(messages),
|
||||
},
|
||||
messages,
|
||||
)
|
||||
if length_recovery_parts:
|
||||
final_content = (
|
||||
"".join(length_recovery_parts)
|
||||
@@ -849,20 +801,33 @@ class AgentRunner:
|
||||
await hook.after_iteration(context)
|
||||
break
|
||||
else:
|
||||
stop_reason = "max_iterations"
|
||||
terminal_content = None
|
||||
await end_length_segment(interrupted=False)
|
||||
stop_reason = "max_iterations"
|
||||
# Once a goal allowed tool work beyond the ordinary budget, its
|
||||
# closure deserves an answer, not a claim that work is unfinished.
|
||||
goal_overrun = iteration + 1 > spec.max_iterations
|
||||
terminal_content = None
|
||||
if spec.finalize_on_max_iterations:
|
||||
terminal_content, usage = await self._try_finalize_after_max_iterations(
|
||||
spec,
|
||||
hook,
|
||||
messages,
|
||||
usage,
|
||||
iteration=iteration + 1,
|
||||
request_state=request_state,
|
||||
round_usages=round_usages,
|
||||
)
|
||||
if terminal_content is not None and goal_overrun:
|
||||
stop_reason = "completed"
|
||||
pending_stream_content = terminal_content
|
||||
if terminal_content is None:
|
||||
terminal_content = self._max_iterations_fallback(spec)
|
||||
if goal_overrun and spec.finalize_on_max_iterations:
|
||||
terminal_content = EMPTY_FINAL_RESPONSE_MESSAGE
|
||||
stop_reason = "empty_final_response"
|
||||
error = terminal_content
|
||||
pending_stream_content = terminal_content
|
||||
else:
|
||||
terminal_content = self._max_iterations_fallback(spec)
|
||||
if length_recovery_parts:
|
||||
terminal_tail = f"\n\n{terminal_content.lstrip()}"
|
||||
final_content = (
|
||||
@@ -1169,7 +1134,7 @@ class AgentRunner:
|
||||
# Advancing it after dropping even one call would replay an unmatched
|
||||
# call without a corresponding tool output on the next request.
|
||||
response.provider_state = None
|
||||
if not valid:
|
||||
if not valid and original_finish_reason in ("tool_calls", "function_call"):
|
||||
response.finish_reason = "stop"
|
||||
return (dropped, not valid, original_finish_reason)
|
||||
|
||||
@@ -1229,12 +1194,17 @@ class AgentRunner:
|
||||
messages: list[dict[str, Any]],
|
||||
usage: LLMUsage | None,
|
||||
*,
|
||||
iteration: int,
|
||||
request_state: ModelRequestState,
|
||||
round_usages: list[LLMUsage],
|
||||
) -> tuple[str | None, LLMUsage | None]:
|
||||
compaction = request_state.compaction
|
||||
request_messages = await self.prepare_prompt(compaction.request_messages, messages)
|
||||
retry_messages = self._budget_exhausted_finalization_messages(request_messages)
|
||||
retry_messages = (
|
||||
self._finalization_retry_messages(request_messages)
|
||||
if iteration > spec.max_iterations
|
||||
else self._budget_exhausted_finalization_messages(request_messages)
|
||||
)
|
||||
try:
|
||||
response = await self._request_no_tools(
|
||||
spec,
|
||||
@@ -1263,7 +1233,7 @@ class AgentRunner:
|
||||
return None, usage
|
||||
|
||||
context = AgentHookContext(
|
||||
iteration=spec.max_iterations,
|
||||
iteration=iteration,
|
||||
messages=messages,
|
||||
response=response,
|
||||
usage=raw_usage,
|
||||
|
||||
Reference in new issue
Block a user