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:
chengyongruandchengyongru authored and GitHub committed 2026-11-03 22:47:00 +08:00
1 parent 3545539128
commit 62c2ed4e7e
68 files changed
+2683 -1421

No files matched your search

+150 -123
View File
@@ -6,7 +6,7 @@ import os
import time
import weakref
from collections.abc import Coroutine, Iterable, Mapping
from contextlib import AbstractContextManager, ExitStack, nullcontext, suppress
from contextlib import AbstractContextManager, AsyncExitStack, ExitStack, nullcontext, suppress
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
@@ -22,7 +22,7 @@ from nanobot.agent import model_presets as preset_helpers
from nanobot.agent.autocompact import AutoCompact
from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput
from nanobot.agent.cron_turns import CronTurnCoordinator
from nanobot.agent.goal_permission import GoalInputScope
from nanobot.agent.execution_policy import ExecutionControlError, ExecutionPolicy, ExecutionScope
from nanobot.agent.hook import AgentHook, AgentTurnHookFactory
from nanobot.agent.memory import Consolidator
from nanobot.agent.model_runtime import ModelRuntimeResolver
@@ -56,8 +56,9 @@ from nanobot.bus.outbound_events import (
StreamEndEvent,
)
from nanobot.bus.queue import MessageBus
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
from nanobot.command.router import command_text
from nanobot.command import CommandContext, CommandRouter
from nanobot.command.builtin import register_core_commands
from nanobot.command.router import CommandExpansion, command_text
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
@@ -82,7 +83,6 @@ from nanobot.security.workspace_access import (
)
from nanobot.session import turn_continuation
from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.goal_state import goal_state_runtime_lines, sustained_goal_active
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy
@@ -186,11 +186,10 @@ class TurnContext:
run_extra_hooks_for_ephemeral: bool = False
hooks: list[AgentHook] = field(default_factory=list)
hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
turn_scopes: list[AbstractContextManager[Any]] = field(default_factory=list)
tools: ToolRegistry | None = None
turn_wall_started_at: float = field(default_factory=time.time)
visible_run_started_at: float | None = None
run_started_at: float = field(init=False, repr=False)
turn_latency_ms: int | None = None
usage: LLMUsage | None = None
@@ -311,12 +310,14 @@ class AgentLoop:
local_trigger_store: LocalTriggerStore | None = None,
idle_compact_check_interval_seconds: int = 0,
recovery_admission: RecoveryAdmission | None = None,
builtin_assembly: Callable[[SessionManager, MessageBus, ToolRegistry, CommandRouter], ExecutionPolicy] | None = None,
):
from nanobot.config.schema import ToolsConfig
_tc = tools_config or ToolsConfig()
defaults = AgentDefaults()
self.bus = bus
self.execution_policy: ExecutionPolicy | None = None
self._recovery_admission = recovery_admission
if turn_delivery_factory is not None:
if turn_delivery_factory.bus is not bus:
@@ -453,9 +454,11 @@ class AgentLoop:
self._next_idle_compact_check_at = time.monotonic()
if model_preset:
self.set_model_preset(model_preset, publish_update=False)
self._register_default_tools(provider_snapshot_loader=provider_snapshot_loader)
self.commands = CommandRouter()
register_builtin_commands(self.commands)
register_core_commands(self.commands)
if builtin_assembly is not None:
self.execution_policy = builtin_assembly(self.sessions, self.bus, self.tools, self.commands)
self._register_default_tools(provider_snapshot_loader=provider_snapshot_loader)
@classmethod
def from_config(
@@ -830,12 +833,38 @@ class AgentLoop:
blocks.append(skill_context)
return blocks
async def _prepare_command_expansion(
self, ctx: CommandContext, result: CommandExpansion,
) -> InboundMessage | OutboundMessage:
session = ctx.session
if session is None:
if ctx.msg.require_existing_session or ctx.msg.session_generation is not None:
session = await self.sessions.state.read(ctx.key)
if session is None:
raise SessionConflictError("command session no longer exists")
else:
session = await self.sessions.state.get(ctx.key)
if ctx.msg.session_generation is not None and session.generation != ctx.msg.session_generation:
raise SessionConflictError("command belongs to a replaced session")
if result.temporary_session_error is not None and not session.policy.persist:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content=result.temporary_session_error,
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))
await self.sessions.state.prepare_input(session)
return result.message
async def _dispatch_command_inline(
self,
msg: InboundMessage,
key: str,
raw: str,
dispatch_fn: Callable[[CommandContext], Awaitable[InboundMessage | OutboundMessage | None]],
dispatch_fn: Callable[
[CommandContext], Awaitable[CommandExpansion | InboundMessage | OutboundMessage | None],
],
) -> None:
if self.commands.requires_session_queue(raw):
await self._enqueue_session_message(msg)
@@ -852,6 +881,8 @@ class AgentLoop:
),
)
result = await dispatch_fn(ctx)
if isinstance(result, CommandExpansion):
result = await self._prepare_command_expansion(ctx, result)
if isinstance(result, InboundMessage):
await self._enqueue_session_message(result)
elif result is not None:
@@ -892,17 +923,13 @@ class AgentLoop:
log_content=session.policy.log_content,
))
workspace_token = bind_workspace_scope(scope)
turn_scope_stack = ExitStack()
try:
for turn_scope in ctx.turn_scopes:
turn_scope_stack.enter_context(turn_scope)
result = await tool.execute_to_completion(
command=ctx.args.strip(),
working_dir=str(scope.project_path),
)
content = str(result)
finally:
turn_scope_stack.close()
reset_workspace_scope(workspace_token)
reset_request_context(request_token)
return OutboundMessage(
@@ -928,6 +955,9 @@ class AgentLoop:
self._active_tasks.pop(key, None)
async def _cancel_active_tasks(self, key: str) -> int:
pending = self._pending_queues.get(key)
tasks = tuple(self._active_tasks.pop(key, set()))
cancelled = sum(1 for t in tasks if not t.done() and t.cancel())
journal_session = await self.sessions.state.read(key)
journaled_followup_ids = (
tuple(
@@ -941,12 +971,13 @@ class AgentLoop:
if journal_session is not None
else ()
)
pending = self._pending_queues.get(key)
tasks = tuple(self._active_tasks.pop(key, set()))
cancelled = sum(1 for t in tasks if not t.done() and t.cancel())
for t in tasks:
with suppress(asyncio.CancelledError, Exception):
try:
await t
except asyncio.CancelledError:
pass
except Exception:
pass
if tasks and pending is not None and self._pending_queues.get(key) is pending:
# A task cancelled before its first step never enters the worker's
# cleanup handler. Only reclaim that worker's original inbox.
@@ -1035,10 +1066,10 @@ class AgentLoop:
run_extra_hooks_for_ephemeral: bool = False,
hooks: list[AgentHook] | None = None,
hook_factories: list[AgentTurnHookFactory] | None = None,
turn_scopes: list[AbstractContextManager[Any]] | None = None,
tools: ToolRegistry | None = None,
request_context: RequestContext | None = None,
provider_state: ProviderConversationState | None = None,
initial_message: InboundMessage | None = None,
) -> AgentRunResult:
self._sync_subagent_runtime_limits()
@@ -1162,13 +1193,19 @@ class AgentLoop:
consumed = 0
try:
converted: list[dict[str, Any]] = []
consumed_inputs: list[InboundMessage] = []
for pending_msg in pending_messages:
# Independent turns are FIFO barriers. Their worker path
# owns completion, command dispatch, and control metadata.
if not self._can_inject_message(pending_msg):
break
converted.append(await _to_user_message(pending_msg))
goal_inputs.consume_inputs(pending_messages[:len(converted)])
consumed_inputs.append(pending_msg)
if execution_scope is not None:
try:
execution_scope.consume_inputs(consumed_inputs)
except Exception as exc:
raise ExecutionControlError("could not accept consumed inputs") from exc
consumed = len(converted)
return converted
finally:
@@ -1259,24 +1296,17 @@ class AgentLoop:
request_token = bind_request_context(request_ctx)
workspace_token = bind_workspace_scope(effective_scope)
turn_scope_stack = ExitStack()
# Compute lazily because create_goal may create goal metadata during this run.
async def _goal_continue() -> str | None:
current = await self.sessions.state.read_metadata(session.key) if session else None
_goal_lines = goal_state_runtime_lines(current["metadata"] if current else None)
if not _goal_lines:
return None
return (
"You have an active sustained goal:\n\n"
+ "\n".join(_goal_lines)
+ "\n\nPlease continue working toward the objective using your tools, "
"or call update_goal with action='complete' if the work is truly finished."
)
session_metadata = session.metadata if session is not None else None
execution_scope: ExecutionScope | None = None
try:
goal_inputs = turn_scope_stack.enter_context(GoalInputScope())
for scope in turn_scopes or ():
turn_scope_stack.enter_context(scope)
if self.execution_policy is not None:
execution_scope = turn_scope_stack.enter_context(self.execution_policy.scope(
active_session_key,
session.generation if session is not None else request_ctx.session_generation,
persistent=request_ctx.persist_session,
))
if initial_message is not None:
execution_scope.consume_inputs((initial_message,))
hook = build_agent_turn_hook(AgentTurnHookSpec(
events=events,
streaming=streaming,
@@ -1327,11 +1357,8 @@ class AgentLoop:
),
injection_callback=_drain_pending,
terminal_injection_callback=_wait_for_pending,
continuation_callback=_goal_continue,
finalize_on_max_iterations=turn_continuation.should_finalize_on_max_iterations(
pending_queue_available=pending_queue is not None and session is not None,
session_metadata=session_metadata,
message_metadata=request_metadata,
continuation_callback=(
execution_scope.continuation_prompt if execution_scope is not None else None
),
provider_state=provider_state,
llm_usage_source=source_from_request(
@@ -1350,15 +1377,10 @@ class AgentLoop:
session.provider_state = result.provider_state
if result.stop_reason == "max_iterations":
logger.warning("Max iterations ({}) reached", self.max_iterations)
should_stream = turn_continuation.should_stream_budget_response(
stop_reason=result.stop_reason,
pending_queue_available=pending_queue is not None and session is not None,
session_metadata=session_metadata,
message_metadata=request_metadata,
)
if result.stop_reason == "max_iterations" or result.pending_stream_content is not None:
# Push final content through stream so streaming channels (e.g. Feishu)
# update the card instead of leaving it empty.
if events.publish is not None and streaming and should_stream:
if events.publish is not None and streaming:
stream_content = (
result.pending_stream_content
if result.pending_stream_content is not None
@@ -1421,7 +1443,7 @@ class AgentLoop:
with self.bus.admission.activity():
try:
await self._dispatch_inbound(msg)
except (SessionOperationQueueFullError, SessionConflictError) as exc:
except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc:
key = self._effective_session_key(msg)
logger.warning("Session input rejected for {}: {}", key, exc)
if msg.is_user_input:
@@ -1558,14 +1580,14 @@ class AgentLoop:
try:
while self._pending_queues.get(session_key) is pending:
try:
msg = pending.get_nowait()
item = pending.get_nowait()
except asyncio.QueueEmpty:
# Idle-only automation follows all accepted user input on
# this same worker, including before the bus loop starts.
deferred = self._deferred_automation_turns.get(session_key)
if not deferred:
break
msg = deferred.pop(0)
item = deferred.pop(0)
if not deferred:
self._deferred_automation_turns.pop(session_key)
session = self.sessions.state.peek_header(session_key)
@@ -1573,10 +1595,10 @@ class AgentLoop:
session.policy.persist and session.policy.log_content
)
try:
await self._dispatch_one(msg, pending)
await self._dispatch_one(item, pending)
except asyncio.CancelledError as exc:
for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=exc)
coordinator.complete(item, error=exc)
raise
except Exception:
logger.opt(exception=log_content).error(
@@ -1600,14 +1622,11 @@ class AgentLoop:
for msg in self._deferred_automation_turns.pop(session_key, []):
pending.put_nowait(msg)
while not pending.empty():
msg = pending.get_nowait()
item = pending.get_nowait()
for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=error)
if (
msg.channel != "system"
and self.commands.requires_session_queue(command_text(msg))
):
delivery = self.turn_delivery_factory.unrouted(msg, session_key)
coordinator.complete(item, error=error)
if item.channel != "system" and self.commands.requires_session_queue(command_text(item)):
delivery = self.turn_delivery_factory.unrouted(item, session_key)
await delivery.complete(None, publish_completion=True)
async def _dispatch_one(
@@ -1625,32 +1644,28 @@ class AgentLoop:
recovery_task_registered = False
recovery_admission = self._recovery_admission
current_task: asyncio.Task[Any] | None = None
if recovery_admission is not None:
recovery_id = msg.metadata.get(RECOVERY_INBOUND_METADATA_KEY)
if isinstance(recovery_id, str) and recovery_id:
current_task = asyncio.current_task()
if current_task is not None:
recovery_admission.register_recovery_task(session_key, current_task)
recovery_task_registered = True
if not await recovery_admission.admit(msg):
logger.info("Skipped stale recovery for session {}", session_key)
if recovery_task_registered and current_task is not None:
recovery_admission.unregister_recovery_task(session_key, current_task)
return
lock = self._get_session_lock(session_key)
gate = self._concurrency_gate or nullcontext()
delivery = self.turn_delivery_factory.unrouted(msg, session_key)
completion_published = False
processing = False
skip_idle = False
try:
async with lock, gate:
# A preceding user turn may have completed or blocked the goal
# while its older continuation was still waiting in the inbox.
if turn_continuation.sustained_goal_continuation_inbound(msg.metadata) and not (
sustained_goal_active((await self.sessions.state.get(session_key)).metadata)
):
return
async with AsyncExitStack() as execution:
try:
if recovery_admission is not None:
recovery_id = msg.metadata.get(RECOVERY_INBOUND_METADATA_KEY)
if isinstance(recovery_id, str) and recovery_id:
current_task = asyncio.current_task()
if current_task is not None:
recovery_admission.register_recovery_task(session_key, current_task)
recovery_task_registered = True
if not await recovery_admission.admit(msg):
logger.info("Skipped stale recovery for session {}", session_key)
return
await execution.enter_async_context(lock)
await execution.enter_async_context(gate)
processing = True
await self.sessions.state.read(session_key)
delivery = self.turn_delivery_factory.create(
msg,
@@ -1662,18 +1677,17 @@ class AgentLoop:
pending_queue=pending,
delivery=delivery,
)
continuing = delivery.continuation_pending
await delivery.complete(
response,
publish_completion=not continuing,
)
completion_published = not continuing
await delivery.complete(response, publish_completion=True)
for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, response=response)
except asyncio.CancelledError:
except asyncio.CancelledError as exc:
logger.info("Task cancelled for session {}", session_key)
# The queued continuation is cancelled with this session worker.
delivery.continuation_pending = False
if not processing:
if self.commands.requires_session_queue(command_text(msg)):
await delivery.complete(None, publish_completion=True)
raise
if delivery.completed:
raise exc
try:
await delivery.abort_stream()
except Exception:
@@ -1689,33 +1703,51 @@ class AgentLoop:
session_key in self._discarding_sessions
or self._preserve_inflight_turns_on_shutdown
):
raise
raise exc
key = self._effective_session_key(msg)
generation = delivery.delivery_message.session_generation
try:
key = self._effective_session_key(msg)
session = await self.sessions.state.get(key)
session = await self.sessions.state.read(key)
if session is None or (generation is not None and session.generation != generation):
self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)
skip_idle = True
raise exc
restore_runtime_checkpoint(session)
await self.sessions.state.finish_turn(session)
logger.info("Saved cancelled turn for session {}", key)
except SessionConflictError:
current = await self.sessions.state.read_header(key)
if current is None or (generation is not None and current.generation != generation):
self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)
skip_idle = True
raise asyncio.CancelledError() from None
logger.opt(exception=log_content).debug(
"Could not finalize cancelled turn for session {}", session_key,
)
except Exception:
logger.opt(exception=log_content).debug(
"Could not finalize cancelled turn for session {}",
session_key,
)
raise
await delivery.cancelled()
raise exc
except Exception as exc:
if isinstance(exc, SessionConflictError):
current = await self.sessions.state.read_header(session_key)
generation = delivery.delivery_message.session_generation
if current is None or (generation is not None and current.generation != generation):
self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)
skip_idle = True
return
logger.opt(exception=log_content).error(
"Error processing message for session {}", session_key,
)
await delivery.fail(publish_completion=not delivery.continuation_pending)
await delivery.fail(publish_completion=True)
for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=exc)
finally:
if not delivery.continuation_pending:
if (processing or delivery.completed) and not skip_idle:
await delivery.idle()
except asyncio.CancelledError:
if not completion_published and self.commands.requires_session_queue(command_text(msg)):
await delivery.complete(None, publish_completion=True)
raise
finally:
if (
recovery_task_registered
@@ -1873,9 +1905,6 @@ class AgentLoop:
else msg.content
),
turn_wall_started_at=t0,
visible_run_started_at=turn_continuation.internal_continuation_run_started_at(
msg.metadata,
),
events=output_events(
default=delivery.events,
on_progress=on_progress,
@@ -2123,15 +2152,15 @@ class AgentLoop:
loop=self,
runtime=ctx.runtime,
is_user_turn=is_user_turn,
turn_scopes=ctx.turn_scopes,
)
command_matched = self.commands.command_name(raw) is not None
result = await self.commands.dispatch(cmd_ctx)
if isinstance(result, CommandExpansion):
result = await self._prepare_command_expansion(cmd_ctx, result)
if isinstance(result, InboundMessage):
ctx.msg = result
result = None
command_matched = False
ctx.turn_scopes.append(GoalInputScope(ctx.msg))
if result is not None:
ctx.outbound = result
if cmd_ctx.raw.lower() == "/new":
@@ -2270,9 +2299,8 @@ class AgentLoop:
async def _run_turn(self, ctx: TurnContext) -> None:
runtime = ctx.require_runtime()
if ctx.visible_run_started_at is None:
ctx.visible_run_started_at = time.time()
await ctx.delivery.running(started_at=ctx.visible_run_started_at)
ctx.run_started_at = time.time()
await ctx.delivery.running(started_at=ctx.run_started_at)
assert ctx.transcript_input is not None
with capture_message_deliveries() as message_sends:
result = await self._run_agent_loop(
@@ -2285,10 +2313,10 @@ class AgentLoop:
run_extra_hooks_for_ephemeral=ctx.run_extra_hooks_for_ephemeral,
hooks=ctx.hooks,
hook_factories=ctx.hook_factories,
turn_scopes=ctx.turn_scopes,
tools=ctx.tools,
request_context=ctx.request_context,
provider_state=ctx.provider_state,
initial_message=ctx.msg,
events=ctx.events,
)
ctx.final_content = result.final_content
@@ -2305,11 +2333,6 @@ class AgentLoop:
ctx.suppress_response = True
ctx.usage = result.usage
ctx.delivery.record_usage(result.round_usages)
if ctx.kind is TurnKind.USER:
current = await self.sessions.state.read_metadata(ctx.session_key)
ctx.delivery.continuation_pending = await turn_continuation.maybe_continue_turn(
ctx, session_metadata=current["metadata"] if current else {},
)
async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session()
@@ -2322,23 +2345,23 @@ class AgentLoop:
ctx.final_content = EMPTY_FINAL_RESPONSE_MESSAGE
latency_started_at = (
ctx.visible_run_started_at
if (
ctx.kind is TurnKind.SYSTEM
or turn_continuation.internal_continuation_inbound(ctx.msg.metadata)
)
and ctx.visible_run_started_at is not None
ctx.run_started_at
if ctx.kind is TurnKind.SYSTEM or turn_continuation.internal_continuation_inbound(ctx.msg.metadata)
else ctx.turn_wall_started_at
)
ctx.turn_latency_ms = max(0, int((time.time() - latency_started_at) * 1000))
ctx.delivery.record_latency(ctx.turn_latency_ms)
turn_continuation.prepare_save_boundary(ctx)
assert ctx.transcript_input is not None
ctx.save_skip = turn_continuation.save_skip_for_turn(
message_metadata=ctx.msg.metadata,
initial_message_count=ctx.transcript_input.message_count,
input_persisted_early=ctx.input_persisted_early,
)
if ctx.usage is not None and not ctx.ephemeral:
session.metadata["_last_usage"] = ctx.usage.to_dict()
if ctx.kind is TurnKind.USER and not ctx.ephemeral:
turn_continuation.record_iteration_limit(
session.metadata, ctx.stop_reason,
continuation_pending=ctx.delivery.continuation_pending,
)
self._save_turn(
session, ctx.all_messages, ctx.save_skip,
@@ -2648,6 +2671,7 @@ class AgentLoop:
lock = self._get_session_lock(session_key)
with self.bus.admission.activity():
temporary_parent = False
delivery: TurnDelivery | None = None
try:
async with lock:
kwargs: dict[str, Any] = {
@@ -2684,6 +2708,8 @@ class AgentLoop:
kwargs["on_runtime_admitted"] = on_runtime_admitted
if attributes is not None:
kwargs["attributes"] = dict(attributes)
delivery = self.turn_delivery_factory.create(msg, session_key)
kwargs["delivery"] = delivery
try:
return await self._process_message(msg, **kwargs)
finally:
@@ -2693,7 +2719,8 @@ class AgentLoop:
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
finally:
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
self.runtime_event_publisher.clear_turn(session_key)
if delivery is not None:
self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)
def _get_session_lock(self, session_key: str) -> asyncio.Lock:
lock = self._session_locks.get(session_key)