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

+25
View File
@@ -0,0 +1,25 @@
"""Execution-local input authorization and optional sustained-run guidance."""
from __future__ import annotations
from collections.abc import Iterable
from contextlib import AbstractContextManager
from typing import Protocol
from nanobot.bus.events import InboundMessage
class ExecutionControlError(RuntimeError):
"""An input control operation failed."""
class ExecutionScope(Protocol):
def consume_inputs(self, messages: Iterable[InboundMessage]) -> None: ...
async def continuation_prompt(self) -> str | None: ...
class ExecutionPolicy(Protocol):
def scope(
self, session_key: str | None, generation: str | None, *, persistent: bool,
) -> AbstractContextManager[ExecutionScope]: ...
+2 -7
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
from collections.abc import Iterable
from contextlib import ExitStack, contextmanager
from contextvars import ContextVar
from typing import Self
from nanobot.bus.events import InboundMessage
from nanobot.session.automation_turns import automation_history_overrides
@@ -35,15 +36,9 @@ def goal_mutation_permission(allowed: bool):
class GoalInputScope(ExitStack):
"""Own goal authorization for fresh inputs consumed during one agent run."""
def __init__(self, initial_message: InboundMessage | None = None) -> None:
super().__init__()
self._initial_message = initial_message
def __enter__(self) -> GoalInputScope:
def __enter__(self) -> Self:
super().__enter__()
self.enter_context(goal_mutation_permission(False))
if self._initial_message is not None:
self.consume_inputs((self._initial_message,))
return self
def consume_inputs(self, messages: Iterable[InboundMessage]) -> None:
+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)
+109 -139
View File
@@ -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,
-381
View File
@@ -1,381 +0,0 @@
# pyright: reportIncompatibleMethodOverride=false
from __future__ import annotations
from copy import deepcopy
from datetime import datetime
from typing import TYPE_CHECKING, Any
from nanobot.agent.goal_permission import (
goal_mutation_allowed,
revoke_goal_mutation_permission,
)
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import RequestContext, ToolContext, current_request_context
from nanobot.agent.tools.schema import StringSchema, tool_parameters_schema
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
from nanobot.session.goal_state import (
GOAL_STATE_KEY,
MAX_GOAL_OBJECTIVE_CHARS,
discard_legacy_goal_state_key,
explicit_goal_requested,
goal_state_raw,
goal_state_runtime_lines,
parse_goal_state,
sustained_goal_active,
)
from nanobot.session.turn_continuation import reset_goal_continuation_rounds
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.prompt_templates import render_template
if TYPE_CHECKING:
from nanobot.session.manager import Session, SessionManager
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
_CREATE_UNAVAILABLE_ERROR = (
"Error: create_goal is unavailable for this turn. Ask the user to submit the complete "
"objective as `/goal <task>`."
)
_REPLACE_UNAVAILABLE_ERROR = (
"Error: replacing the goal is unavailable for this turn. Ask the user to submit the "
"replacement objective as `/goal <task>`."
)
def _iso_now() -> str:
return datetime.now().isoformat()
class _GoalToolsMixin:
"""Shared routing context and session lookup."""
def __init__(
self,
sessions: SessionManager,
bus: MessageBus | None = None,
) -> None:
self._sessions = sessions
self._bus = bus
async def _session(self) -> Session | None:
request_ctx = current_request_context()
if request_ctx is None:
return None
key = request_ctx.session_key
if not key:
return None
return await self._sessions.state.get_header(key)
def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed()
async def _save_goal_state(
self,
sess: Session,
blob: dict[str, Any],
*,
reset_continuation: bool = False,
revoke_permission: bool = False,
) -> None:
saved = False
async def save_and_publish() -> None:
nonlocal saved
def change(metadata: dict[str, Any]) -> None:
metadata[GOAL_STATE_KEY] = deepcopy(blob)
discard_legacy_goal_state_key(metadata)
if reset_continuation:
reset_goal_continuation_rounds(metadata)
_, sess.metadata = await self._sessions.state.mutate_metadata(
sess.key, change, expected_generation=sess.generation,
)
saved = True
await self._publish_goal_state_changed(sess.metadata)
try:
await shield_and_drain(save_and_publish())
finally:
# This ContextVar belongs to the caller task, not the settlement task.
if revoke_permission and saved:
revoke_goal_mutation_permission()
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
bus = self._bus
rc = current_request_context()
if bus is None or rc is None:
return
cid = (rc.chat_id or "").strip()
if not cid:
return
await bus.publish(
GoalStateChanged(
context=RuntimeEventContext(
channel=rc.channel,
chat_id=cid,
session_key=rc.session_key or f"{rc.channel}:{cid}",
metadata=dict(rc.metadata or {}),
),
session_metadata=dict(metadata),
)
)
@tool_parameters(
tool_parameters_schema(
objective=StringSchema(
"Self-contained goal with explicit completion criteria, bounded and safe to repeat. "
"May incorporate prior discussion.",
min_length=1,
max_length=MAX_GOAL_OBJECTIVE_CHARS,
),
ui_summary=StringSchema(
"One-line display label for session lists and logs; objective defines the goal.",
max_length=120,
nullable=True,
),
required=["objective"],
)
)
class CreateGoalTool(Tool, _GoalToolsMixin):
"""Create one explicit sustained objective for the current session."""
def __init__(
self,
sessions: SessionManager,
bus: MessageBus | None = None,
) -> None:
_GoalToolsMixin.__init__(self, sessions, bus)
@classmethod
def create(cls, ctx: ToolContext) -> Tool:
sess = ctx.sessions
if sess is None:
raise RuntimeError("CreateGoalTool requires an initialized session manager")
return cls(
sessions=sess,
bus=ctx.bus,
)
@classmethod
def enabled(cls, ctx: ToolContext) -> bool:
return ctx.sessions is not None
@property
def name(self) -> str:
return "create_goal"
@property
def description(self) -> str:
return (
"Create one sustained goal for the current session only when Goal Runtime Guidance "
"asks you to record it. Do not retry after successful creation."
)
def runtime_context_provider(self):
return self._provide_runtime_context
async def _provide_runtime_context(
self,
request: RequestContext,
) -> RuntimeContextBlock | None:
if not request.session_key or not request.persist_session:
return None
payload = await self._sessions.state.read_metadata(request.session_key)
if payload is None:
return None
metadata = payload["metadata"]
goal_start_requested = explicit_goal_requested(request.metadata)
goal_active = sustained_goal_active(metadata)
if not goal_start_requested and not goal_active:
return None
guidance = render_template(
"agent/goal_runtime.md",
strip=True,
goal_start_requested=goal_start_requested,
goal_active=goal_active,
)
state = wrap_runtime_context_lines(goal_state_runtime_lines(metadata))
content = "\n\n".join(part for part in (guidance, state) if part)
return RuntimeContextBlock(source="goal", content=content)
async def execute(
self,
objective: str,
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
sess = await self._session()
if sess is None:
return ToolResult.error(
"Error: create_goal requires an active chat session (missing routing context)."
)
if not self._goal_mutation_allowed():
return ToolResult.error(_CREATE_UNAVAILABLE_ERROR)
prior = parse_goal_state(goal_state_raw(sess.metadata))
if isinstance(prior, dict) and prior.get("status") == "active":
return ToolResult.error(
"Error: a sustained goal is already active. Use update_goal with "
"action='replace' only if the user explicitly changes the objective."
)
objective_text = objective.strip()
if not objective_text:
return ToolResult.error("Error: objective must not be empty.")
if len(objective_text) > MAX_GOAL_OBJECTIVE_CHARS:
return ToolResult.error(
f"Error: objective must not exceed {MAX_GOAL_OBJECTIVE_CHARS} characters."
)
summary = (ui_summary or "").strip()[:120]
blob = {
"status": "active",
"objective": objective_text,
"ui_summary": summary,
"started_at": _iso_now(),
}
await self._save_goal_state(sess, blob, reset_continuation=True)
extra = f"\nSummary line: {summary}" if summary else ""
return (
"Goal recorded. Keep working toward the objective using ordinary tools. "
"When fully done and verified, call update_goal with action='complete'."
f"{extra}"
)
@tool_parameters(
tool_parameters_schema(
action=StringSchema(
"How to update the active goal.",
enum=_GOAL_ACTIONS,
),
recap=StringSchema(
"Brief honest recap for the user. Required in practice for complete, cancel, and block.",
max_length=8000,
nullable=True,
),
objective=StringSchema(
"Replacement objective. Required only when action is 'replace'; make it durable, "
"self-contained, bounded, and explicit about done-ness.",
max_length=MAX_GOAL_OBJECTIVE_CHARS,
nullable=True,
),
ui_summary=StringSchema(
"Optional one-line display label for a replacement goal.",
max_length=120,
nullable=True,
),
required=["action"],
)
)
class UpdateGoalTool(Tool, _GoalToolsMixin):
"""Complete, cancel, block, or replace the active sustained goal."""
def __init__(
self,
sessions: SessionManager,
bus: MessageBus | None = None,
) -> None:
_GoalToolsMixin.__init__(self, sessions, bus)
@classmethod
def create(cls, ctx: ToolContext) -> Tool:
sess = ctx.sessions
if sess is None:
raise RuntimeError("UpdateGoalTool requires an initialized session manager")
return cls(
sessions=sess,
bus=ctx.bus,
)
@classmethod
def enabled(cls, ctx: ToolContext) -> bool:
return ctx.sessions is not None
@property
def name(self) -> str:
return "update_goal"
@property
def description(self) -> str:
return (
"Update the active sustained goal. Use action='complete' only after the objective "
"is actually achieved and verified. Use action='cancel' when the user cancels, "
"action='block' when progress is genuinely blocked, and action='replace' only when "
"the requested objective changes."
)
async def execute(
self,
action: str,
recap: str | None = None,
objective: str | None = None,
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
sess = await self._session()
if sess is None:
return ToolResult.error("Error: update_goal requires an active chat session.")
prior = parse_goal_state(goal_state_raw(sess.metadata))
if not isinstance(prior, dict) or prior.get("status") != "active":
return "No active goal to update."
normalized = (action or "").strip().lower()
if normalized not in _GOAL_ACTIONS:
return ToolResult.error(
"Error: action must be one of complete, cancel, block, or replace."
)
if normalized == "replace":
if not self._goal_mutation_allowed():
return ToolResult.error(_REPLACE_UNAVAILABLE_ERROR)
objective_text = (objective or "").strip()
if not objective_text:
return ToolResult.error(
"Error: update_goal action='replace' requires a replacement objective."
)
if len(objective_text) > MAX_GOAL_OBJECTIVE_CHARS:
return ToolResult.error(
f"Error: objective must not exceed {MAX_GOAL_OBJECTIVE_CHARS} characters."
)
summary = (ui_summary or "").strip()[:120]
blob = {
"status": "active",
"objective": objective_text,
"ui_summary": summary,
"started_at": _iso_now(),
"replaced_at": _iso_now(),
"previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(),
}
await self._save_goal_state(sess, blob, reset_continuation=True)
extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
ended = _iso_now()
status = {
"complete": "completed",
"cancel": "cancelled",
"block": "blocked",
}[normalized]
blob = {
**prior,
"status": status,
"ended_at": ended,
"recap": (recap or "").strip(),
}
if normalized == "complete":
blob["completed_at"] = ended
await self._save_goal_state(sess, blob, revoke_permission=True)
tail = (recap or "").strip()
label = {
"complete": "complete",
"cancel": "cancelled",
"block": "blocked",
}[normalized]
if tail:
return f"Goal marked {label} ({ended}). Recap:\n{tail}"
return f"Goal marked {label} ({ended})."
+35 -12
View File
@@ -6,6 +6,7 @@ from collections.abc import Awaitable, Callable
from copy import deepcopy
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast
from uuid import uuid4
from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -33,6 +34,7 @@ from nanobot.session.keys import (
is_internal_session,
last_channel_from_metadata,
)
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import strip_think
if TYPE_CHECKING:
@@ -205,7 +207,7 @@ class TurnDelivery:
route: TurnRoute
route_admission: TurnRouteAdmission | None = None
enable_stream: bool = False
continuation_pending: bool = field(init=False, default=False)
run_id: str = field(init=False)
delivery_message: InboundMessage = field(init=False)
lifecycle_message: InboundMessage = field(init=False)
_stream_base_id: str | None = field(init=False, default=None)
@@ -213,6 +215,7 @@ class TurnDelivery:
_stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False)
_routed_events: EventSink = field(init=False)
completed: bool = field(init=False, default=False)
_stop_reason: str | None = field(init=False, default=None)
_failure_error_kind: str | None = field(init=False, default=None)
_retry_status: RetryStatusEvent | None = field(init=False, default=None)
@@ -223,6 +226,7 @@ class TurnDelivery:
_stream_source_unknown: bool = field(init=False, default=False)
def __post_init__(self) -> None:
self.run_id = uuid4().hex
self._routed_events = _bind_events(self.bus, self.route, self.session_key)
self.events = EventSink(self._publish_event, self._routed_events.accepts)
self.delivery_message = dataclasses.replace(
@@ -299,15 +303,16 @@ class TurnDelivery:
self.delivery_message,
self.session_key,
runtime,
run_id=self.run_id,
)
return
self.runtime_event_publisher.record_turn_runtime(self.session_key, runtime)
self.runtime_event_publisher.record_turn_runtime(self.session_key, runtime, run_id=self.run_id)
def record_latency(self, latency_ms: int | None) -> None:
self.runtime_event_publisher.record_turn_latency(self.session_key, latency_ms)
self.runtime_event_publisher.record_turn_latency(self.session_key, latency_ms, run_id=self.run_id)
def record_usage(self, round_usages: list[LLMUsage]) -> None:
self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages)
self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages, run_id=self.run_id)
def record_stop_reason(
self,
@@ -390,11 +395,9 @@ class TurnDelivery:
)
if publish_completion:
outcome, failure_kind = _turn_outcome(stop_reason)
await self.runtime_event_publisher.turn_completed(
await self._publish_completion(
channel=completed_channel,
chat_id=completed_chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=(self._failure_error_kind or (
@@ -405,6 +408,9 @@ class TurnDelivery:
),
)
async def cancelled(self) -> None:
await self._publish_completion(outcome="cancelled")
async def fail(self, *, publish_completion: bool) -> None:
await self.bus.publish_outbound(
OutboundMessage(
@@ -415,14 +421,31 @@ class TurnDelivery:
)
)
if publish_completion:
await self._publish_completion(outcome="failed", failure_kind="internal")
async def _publish_completion(
self, *, outcome: str, channel: str | None = None, chat_id: str | None = None,
failure_kind: str | None = None, failure_error_kind: str | None = None,
failure_attempts: int | None = None,
) -> None:
if self.completed:
return
async def publish() -> None:
await self.runtime_event_publisher.turn_completed(
channel=self.lifecycle_message.channel,
chat_id=self.lifecycle_message.chat_id,
channel=channel if channel is not None else self.lifecycle_message.channel,
chat_id=chat_id if chat_id is not None else self.lifecycle_message.chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome="failed",
failure_kind="internal",
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=failure_error_kind,
failure_attempts=failure_attempts,
run_id=self.run_id,
)
self.completed = True
await shield_and_drain(publish())
async def idle(self) -> None:
await self.runtime_event_publisher.run_status_changed(
@@ -430,7 +453,7 @@ class TurnDelivery:
self.session_key,
"idle",
)
self.runtime_event_publisher.clear_turn(self.session_key)
self.runtime_event_publisher.clear_turn(self.session_key, run_id=self.run_id)
def _stream_id(self) -> str:
assert self._stream_base_id is not None