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,
+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
+30 -24
View File
@@ -114,10 +114,10 @@ class RuntimeEventPublisher:
def __init__(self, bus: MessageBus) -> None:
self.bus = bus
self._turn_latency_ms: dict[str, int] = {}
self._turn_runtime: dict[str, LLMRuntime] = {}
self._turn_usage: dict[str, LLMUsage] = {}
self._turn_round_usages: dict[str, tuple[LLMUsage, ...]] = {}
self._turn_latency_ms: dict[tuple[str, str | None], int] = {}
self._turn_runtime: dict[tuple[str, str | None], LLMRuntime] = {}
self._turn_usage: dict[tuple[str, str | None], LLMUsage] = {}
self._turn_round_usages: dict[tuple[str, str | None], tuple[LLMUsage, ...]] = {}
@staticmethod
def _context(
@@ -138,17 +138,22 @@ class RuntimeEventPublisher:
attributes=dict(attributes or {}),
)
def record_turn_runtime(self, session_key: str, runtime: LLMRuntime) -> None:
self._turn_runtime[session_key] = runtime
def record_turn_runtime(
self, session_key: str, runtime: LLMRuntime, *, run_id: str | None = None,
) -> None:
self._turn_runtime[(session_key, run_id)] = runtime
def record_turn_latency(self, session_key: str, latency_ms: int | None) -> None:
def record_turn_latency(
self, session_key: str, latency_ms: int | None, *, run_id: str | None = None,
) -> None:
if latency_ms is not None:
self._turn_latency_ms[session_key] = int(latency_ms)
self._turn_latency_ms[(session_key, run_id)] = int(latency_ms)
def record_turn_usage(
self,
session_key: str,
round_usages: list[LLMUsage],
*, run_id: str | None = None,
) -> None:
if not round_usages:
return
@@ -156,18 +161,16 @@ class RuntimeEventPublisher:
usage = round_usages[0]
for round_usage in round_usages[1:]:
usage += round_usage
previous = self._turn_usage.get(session_key)
self._turn_usage[session_key] = usage if previous is None else previous + usage
self._turn_round_usages[session_key] = (
*self._turn_round_usages.get(session_key, ()),
*round_usages,
)
key = (session_key, run_id)
self._turn_usage[key] = usage
self._turn_round_usages[key] = tuple(round_usages)
def clear_turn(self, session_key: str) -> None:
self._turn_latency_ms.pop(session_key, None)
self._turn_runtime.pop(session_key, None)
self._turn_usage.pop(session_key, None)
self._turn_round_usages.pop(session_key, None)
def clear_turn(self, session_key: str, *, run_id: str | None = None) -> None:
key = (session_key, run_id)
self._turn_latency_ms.pop(key, None)
self._turn_runtime.pop(key, None)
self._turn_usage.pop(key, None)
self._turn_round_usages.pop(key, None)
async def user_input_accepted(
self,
@@ -209,9 +212,10 @@ class RuntimeEventPublisher:
msg: InboundMessage,
session_key: str,
runtime: LLMRuntime,
*, run_id: str | None = None,
) -> None:
"""Record and publish the runtime selected for one turn."""
self.record_turn_runtime(session_key, runtime)
self.record_turn_runtime(session_key, runtime, run_id=run_id)
await self.bus.publish(
TurnRuntimeAdmitted(
context=self._context(
@@ -281,7 +285,9 @@ class RuntimeEventPublisher:
failure_kind: str | None = None,
failure_error_kind: str | None = None,
failure_attempts: int | None = None,
run_id: str | None = None,
) -> None:
key = (session_key, run_id)
await self.bus.publish(
TurnCompleted(
context=self._context(
@@ -290,10 +296,10 @@ class RuntimeEventPublisher:
session_key=session_key,
metadata=metadata,
),
latency_ms=self._turn_latency_ms.pop(session_key, None),
runtime=self._turn_runtime.pop(session_key, None),
usage=self._turn_usage.pop(session_key, None),
round_usages=self._turn_round_usages.pop(session_key, ()),
latency_ms=self._turn_latency_ms.pop(key, None),
runtime=self._turn_runtime.pop(key, None),
usage=self._turn_usage.pop(key, None),
round_usages=self._turn_round_usages.pop(key, ()),
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=failure_error_kind,
+1 -1
View File
@@ -17,7 +17,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.command.builtin import build_help_text
from nanobot.command.application import build_help_text
from nanobot.config.network import NetworkConfig
from nanobot.config.paths import get_media_dir
from nanobot.config_base import Base
@@ -21,7 +21,7 @@ from nanobot.channels.discord.runtime import (
DiscordChannel,
DiscordConfig,
)
from nanobot.command.builtin import build_help_text
from nanobot.command.application import build_help_text
from nanobot.config.network import NetworkConfig
+1 -1
View File
@@ -63,7 +63,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.command.builtin import BUILTIN_COMMAND_SPECS
from nanobot.command.application import BUILTIN_COMMAND_SPECS
from nanobot.command.router import normalize_command_text
from nanobot.config.network import NetworkConfig
from nanobot.config.paths import get_data_dir, get_media_dir
+1 -1
View File
@@ -32,7 +32,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.command.builtin import build_help_text
from nanobot.command.application import build_help_text
from nanobot.config.network import NetworkConfig
from nanobot.config.paths import get_media_dir
from nanobot.config_base import Base
+2
View File
@@ -179,6 +179,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: str
mcp_provider = MCPProvider.from_config(runtime_config, tools)
_set_nanobot_logs(logs)
from nanobot.goal.assembly import install_goal
try:
agent_loop = agent_loop_class.from_config(
@@ -188,6 +189,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: str
cron_service=cron,
hook_factories=[create_file_edit_activity_hook],
tool_registry=tools,
builtin_assembly=install_goal,
)
except ValueError as exc:
_print_agent_start_error(exc)
+3
View File
@@ -381,6 +381,8 @@ def serve(
build_unconfigured_provider_snapshot(runtime_config, setup_error).provider
if setup_error else None
)
from nanobot.goal.assembly import install_goal
try:
agent_loop = AgentLoop.from_config(
runtime_config, bus,
@@ -388,6 +390,7 @@ def serve(
session_manager=session_manager,
hook_factories=[create_file_edit_activity_hook],
tool_registry=tools,
builtin_assembly=install_goal,
)
except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]")
+4
View File
@@ -593,6 +593,8 @@ def _run_claimed_gateway(
unified_session=config.agents.defaults.unified_session,
)
from nanobot.goal.assembly import install_goal
agent = AgentLoop.from_config(
config, bus,
provider=provider_snapshot.provider,
@@ -609,7 +611,9 @@ def _run_claimed_gateway(
hook_factories=[create_file_edit_activity_hook],
tool_registry=tools,
recovery_admission=recovery,
builtin_assembly=install_goal,
)
def _schedule_webui_background(awaitable: Awaitable[None]) -> None:
agent.schedule_background(cast(Coroutine[Any, Any, None], awaitable))
+15 -1
View File
@@ -1,4 +1,18 @@
from nanobot.command.builtin import register_builtin_commands
from typing import TYPE_CHECKING, Callable
from nanobot.command.router import CommandContext, CommandRouter
if TYPE_CHECKING:
from nanobot.command.application import register_builtin_commands
def __getattr__(name: str) -> Callable[[CommandRouter], None]:
if name == "register_builtin_commands":
from nanobot.command.application import register_builtin_commands
globals()[name] = register_builtin_commands
return register_builtin_commands
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = ["CommandContext", "CommandRouter", "register_builtin_commands"]
+48
View File
@@ -0,0 +1,48 @@
"""The standard application's composed command registrations and display catalog."""
from __future__ import annotations
from nanobot.command.builtin import build_help_text as build_registered_help_text
from nanobot.command.builtin import register_core_commands
from nanobot.command.router import CommandRouter, normalize_command_text
from nanobot.command.spec import BuiltinCommandSpec
from nanobot.goal.command import register_goal_command
def register_builtin_commands(router: CommandRouter) -> None:
"""Register the standard application commands."""
register_core_commands(router)
register_goal_command(router)
def _builtin_specs() -> tuple[BuiltinCommandSpec, ...]:
router = CommandRouter()
register_builtin_commands(router)
return router.specs
BUILTIN_COMMAND_SPECS = _builtin_specs()
def build_help_text() -> str:
return build_registered_help_text(BUILTIN_COMMAND_SPECS)
def builtin_command_palette() -> list[dict[str, str | bool]]:
"""Return structured command metadata for UI command palettes."""
return [spec.as_dict() for spec in BUILTIN_COMMAND_SPECS]
def builtin_command_starts_agent_turn(text: str) -> bool:
"""Return whether WebUI ingress should expect a normal agent lifecycle."""
normalized = normalize_command_text(text)
command, separator, args = normalized.partition(" ")
spec = next(
(item for item in BUILTIN_COMMAND_SPECS if item.command == command.lower()),
None,
)
if spec is None or (separator and not spec.accepts_args):
return True
if spec.lifecycle == "agent_turn":
return True
return spec.lifecycle == "agent_turn_with_args" and bool(args.strip())
+15 -115
View File
@@ -4,18 +4,18 @@ import asyncio
import os
import subprocess
import sys
import time
from contextlib import suppress
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, Any, Literal, cast
from dataclasses import replace
from typing import TYPE_CHECKING, Any, cast
from loguru import logger
from nanobot import __version__
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage
from nanobot.command.router import CommandContext, CommandRouter
from nanobot.command.spec import BuiltinCommandSpec
from nanobot.command.spec import CommandLifecycle as CommandLifecycle
from nanobot.providers.base import LLMUsage
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import build_status_content
from nanobot.utils.restart import set_restart_notice_to_env
@@ -26,46 +26,10 @@ if TYPE_CHECKING:
from nanobot.session.manager import Session
from nanobot.utils.gitstore import CommitInfo
# WebUI protocol contract for how a slash command participates in turn state:
# - side_channel: returns control text without starting or ending an agent turn.
# - finalize_active_turn: side-channel command that also closes the active UI turn.
# - stop_active_turn: cancels the active turn; WebUI may intercept exact submits.
# - agent_turn: always enters the normal agent path.
# - agent_turn_with_args: no args is side-channel usage; args enter the agent path.
CommandLifecycle = Literal[
"side_channel",
"finalize_active_turn",
"stop_active_turn",
"agent_turn",
"agent_turn_with_args",
]
USER_SHELL_COMMAND = "/__shell"
@dataclass(frozen=True)
class BuiltinCommandSpec:
command: str
title: str
description: str
icon: str
arg_hint: str = ""
lifecycle: CommandLifecycle = "side_channel"
accepts_args: bool = False
def as_dict(self) -> dict[str, str | bool]:
return {
"command": self.command,
"title": self.title,
"description": self.description,
"icon": self.icon,
"arg_hint": self.arg_hint,
"lifecycle": self.lifecycle,
"accepts_args": self.accepts_args,
}
BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
CORE_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
BuiltinCommandSpec(
"/new",
"New chat",
@@ -114,15 +78,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
"[n]",
accepts_args=True,
),
BuiltinCommandSpec(
"/goal",
"Start long-running goal",
"Tell the agent to treat the request as a long-running goal.",
"activity",
"<goal>",
lifecycle="agent_turn_with_args",
accepts_args=True,
),
BuiltinCommandSpec(
"/trigger",
"Create named local trigger",
@@ -190,26 +145,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
)
def builtin_command_palette() -> list[dict[str, str | bool]]:
"""Return structured command metadata for UI command palettes."""
return [spec.as_dict() for spec in BUILTIN_COMMAND_SPECS]
def builtin_command_starts_agent_turn(text: str) -> bool:
"""Return whether WebUI ingress should expect a normal agent lifecycle."""
normalized = normalize_command_text(text)
command, separator, args = normalized.partition(" ")
spec = next(
(item for item in BUILTIN_COMMAND_SPECS if item.command == command.lower()),
None,
)
if spec is None or (separator and not spec.accepts_args):
return True
if spec.lifecycle == "agent_turn":
return True
return spec.lifecycle == "agent_turn_with_args" and bool(args.strip())
async def cmd_stop(ctx: CommandContext) -> OutboundMessage:
"""Cancel all active tasks and subagents for the session."""
loop = ctx.loop
@@ -894,41 +829,6 @@ async def cmd_history(ctx: CommandContext) -> OutboundMessage:
)
async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:
"""Expand an explicit goal command into model-only input."""
goal = ctx.args.strip()
if not goal:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content="Usage: /goal <long-running task description>",
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
if not ctx.is_user_turn:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content="Goal mode can only be started by a user `/goal <task>` command.",
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
session = ctx.session or await ctx.loop.sessions.state.get(ctx.key)
session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))
await ctx.loop.sessions.state.prepare_input(session)
return replace(
ctx.msg,
content=goal,
metadata={
**ctx.msg.metadata,
"original_command": "/goal",
"original_content": ctx.msg.content,
"goal_requested": True,
"goal_started_at": time.time(),
HIDDEN_HISTORY_META: {"kind": "goal_request"},
},
)
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
"""List, approve, deny or revoke pairing requests."""
from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command
@@ -1019,7 +919,7 @@ async def cmd_help(ctx: CommandContext) -> OutboundMessage:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content=build_help_text(),
content=build_help_text(ctx.loop.commands.specs),
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
@@ -1048,10 +948,10 @@ async def cmd_user_shell(ctx: CommandContext) -> OutboundMessage:
return await ctx.loop.execute_user_shell_command(ctx)
def build_help_text() -> str:
"""Build canonical help text shared across channels."""
def build_help_text(specs: tuple[BuiltinCommandSpec, ...] = CORE_COMMAND_SPECS) -> str:
"""Build help text for the commands registered in one application."""
lines = ["🐈 nanobot commands:"]
for spec in BUILTIN_COMMAND_SPECS:
for spec in specs:
command = spec.command
if spec.arg_hint:
command = f"{command} {spec.arg_hint}"
@@ -1059,8 +959,10 @@ def build_help_text() -> str:
return "\n".join(lines)
def register_builtin_commands(router: CommandRouter) -> None:
"""Register the default set of slash commands."""
def register_core_commands(router: CommandRouter) -> None:
"""Register slash commands owned by the core runtime."""
for spec in CORE_COMMAND_SPECS:
router.add_spec(spec)
router.priority("/stop", cmd_stop)
router.priority("/restart", cmd_restart)
router.priority("/status", cmd_status)
@@ -1071,8 +973,6 @@ def register_builtin_commands(router: CommandRouter) -> None:
router.prefix("/model ", cmd_model)
router.exact("/history", cmd_history)
router.prefix("/history ", cmd_history)
router.exact("/goal", cmd_goal)
router.prefix("/goal ", cmd_goal)
router.exact("/trigger", cmd_trigger)
router.prefix("/trigger ", cmd_trigger)
router.exact("/dream", cmd_dream)
+45 -6
View File
@@ -1,21 +1,39 @@
from __future__ import annotations
import re
from contextlib import AbstractContextManager
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Awaitable, Callable
from typing import TYPE_CHECKING, Awaitable, Callable
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.command.spec import BuiltinCommandSpec
if TYPE_CHECKING:
from nanobot.agent.loop import AgentLoop
from nanobot.session.manager import Session
from nanobot.utils.llm_runtime import LLMRuntime
Handler = Callable[["CommandContext"], Awaitable["InboundMessage | OutboundMessage | None"]]
Handler = Callable[["CommandContext"], Awaitable["CommandExpansion | InboundMessage | OutboundMessage | None"]]
InputHandler = Callable[["CommandInput"], Awaitable["CommandExpansion | OutboundMessage"]]
_BOT_SUFFIX_RE = re.compile(r"^[A-Za-z0-9_]+$")
@dataclass(frozen=True, slots=True)
class CommandInput:
"""Inputs available to a command that only transforms a user request."""
msg: InboundMessage
args: str
is_user_turn: bool
@dataclass(frozen=True, slots=True)
class CommandExpansion:
"""A transformed input whose original command is persisted by the runtime."""
message: InboundMessage
temporary_session_error: str | None = None
def command_text(message: InboundMessage) -> str:
"""Return routable text; command-generated agent input must not be dispatched again."""
return "" if message.metadata.get("original_command") else message.content.strip()
@@ -52,7 +70,6 @@ class CommandContext:
loop: AgentLoop = field(kw_only=True)
runtime: LLMRuntime | None = None
is_user_turn: bool = False
turn_scopes: list[AbstractContextManager[Any]] = field(default_factory=list)
class CommandRouter:
@@ -70,6 +87,24 @@ class CommandRouter:
self._exact: dict[str, Handler] = {}
self._prefix: list[tuple[str, Handler]] = []
self._session_commands: set[str] = set()
self._specs: list[BuiltinCommandSpec] = []
@property
def specs(self) -> tuple[BuiltinCommandSpec, ...]:
return tuple(self._specs)
def add_spec(self, spec: BuiltinCommandSpec, *, after: str | None = None) -> None:
self._specs = [item for item in self._specs if item.command != spec.command]
index = next((i + 1 for i, item in enumerate(self._specs) if item.command == after), len(self._specs))
self._specs.insert(index, spec)
def input_command(self, cmd: str, handler: InputHandler) -> None:
"""Register a command that receives only input facts and returns an expansion."""
async def invoke(ctx: CommandContext) -> CommandExpansion | OutboundMessage:
return await handler(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
self.exact(cmd, invoke)
self.prefix(f"{cmd} ", invoke)
def priority(self, cmd: str, handler: Handler) -> None:
self._priority[cmd] = handler
@@ -119,7 +154,9 @@ class CommandRouter:
return True
return self.command_name(text) is not None
async def dispatch_priority(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
async def dispatch_priority(
self, ctx: CommandContext,
) -> CommandExpansion | InboundMessage | OutboundMessage | None:
"""Dispatch a priority command. Called from run() without the lock."""
ctx.raw = normalize_command_text(ctx.raw)
handler = self._priority.get(ctx.raw.lower())
@@ -127,7 +164,9 @@ class CommandRouter:
return await handler(ctx)
return None
async def dispatch(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
async def dispatch(
self, ctx: CommandContext,
) -> CommandExpansion | InboundMessage | OutboundMessage | None:
"""Try exact and prefix handlers, then validate registered commands."""
if ctx.msg.metadata.get("original_command"):
return None
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
# WebUI protocol contract for how a slash command participates in turn state:
# - side_channel: returns control text without starting or ending an agent turn.
# - finalize_active_turn: side-channel command that also closes the active UI turn.
# - stop_active_turn: cancels the active turn; WebUI may intercept exact submits.
# - agent_turn: always enters the normal agent path.
# - agent_turn_with_args: no args is side-channel usage; args enter the agent path.
CommandLifecycle = Literal[
"side_channel",
"finalize_active_turn",
"stop_active_turn",
"agent_turn",
"agent_turn_with_args",
]
@dataclass(frozen=True)
class BuiltinCommandSpec:
command: str
title: str
description: str
icon: str
arg_hint: str = ""
lifecycle: CommandLifecycle = "side_channel"
accepts_args: bool = False
def as_dict(self) -> dict[str, str | bool]:
return {
"command": self.command,
"title": self.title,
"description": self.description,
"icon": self.icon,
"arg_hint": self.arg_hint,
"lifecycle": self.lifecycle,
"accepts_args": self.accepts_args,
}
+1
View File
@@ -0,0 +1 @@
"""Built-in sustained-goal feature."""
+26
View File
@@ -0,0 +1,26 @@
"""Assemble the built-in sustained-goal feature at application entrypoints."""
from __future__ import annotations
from typing import TYPE_CHECKING
from nanobot.goal.command import register_goal_command
from nanobot.goal.runtime import GOAL_GENERATION_VOLATILE_KEYS, GoalExecutionPolicy
from nanobot.goal.tools import CreateGoalTool, UpdateGoalTool
if TYPE_CHECKING:
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.queue import MessageBus
from nanobot.command.router import CommandRouter
from nanobot.session.manager import SessionManager
def install_goal(
sessions: SessionManager, bus: MessageBus, tools: ToolRegistry, commands: CommandRouter,
) -> GoalExecutionPolicy:
register_goal_command(commands)
sessions.exclude_generation_metadata(GOAL_GENERATION_VOLATILE_KEYS)
for tool in (CreateGoalTool.bind(sessions, bus), UpdateGoalTool.bind(sessions, bus)):
if not tools.has(tool.name):
tools.register(tool)
return GoalExecutionPolicy(sessions.state)
+61
View File
@@ -0,0 +1,61 @@
"""Command adapter for explicitly starting a sustained goal."""
from __future__ import annotations
from dataclasses import replace
from nanobot.bus.events import OutboundMessage
from nanobot.command.router import CommandExpansion, CommandInput, CommandRouter
from nanobot.command.spec import BuiltinCommandSpec
from nanobot.session.goal_state import GOAL_COMMAND
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
GOAL_COMMAND_SPEC = BuiltinCommandSpec(
GOAL_COMMAND,
"Start long-running goal",
"Tell the agent to treat the request as a long-running goal.",
"activity",
"<goal>",
lifecycle="agent_turn_with_args",
accepts_args=True,
)
async def cmd_goal(ctx: CommandInput) -> CommandExpansion | OutboundMessage:
"""Expand an explicit goal command into model-only input."""
goal = ctx.args.strip()
if not goal:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content="Usage: /goal <long-running task description>",
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
if not ctx.is_user_turn:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content="Goal mode can only be started by a user `/goal <task>` command.",
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
return CommandExpansion(
message=replace(
ctx.msg,
content=goal,
metadata={
**ctx.msg.metadata,
"original_command": GOAL_COMMAND,
"original_content": ctx.msg.content,
"goal_requested": True,
HIDDEN_HISTORY_META: {"kind": "goal_request"},
},
),
temporary_session_error="Goals can't start in a temporary session. Use a persistent session for `/goal`.",
)
def register_goal_command(router: CommandRouter) -> None:
"""Register the exact usage and task-bearing forms of /goal."""
router.input_command(GOAL_COMMAND, cmd_goal)
router.add_spec(GOAL_COMMAND_SPEC, after="/history")
+52
View File
@@ -0,0 +1,52 @@
"""Authorization and in-run guidance for sustained goals."""
from __future__ import annotations
from typing import TYPE_CHECKING
from nanobot.agent.goal_permission import GoalInputScope
from nanobot.session.goal_state import goal_state_runtime_lines, sustained_goal_active
if TYPE_CHECKING:
from nanobot.session.state import SessionState
GOAL_GENERATION_VOLATILE_KEYS = frozenset({
"goal_state", "thread_goal", "_sustained_goal_continuation_rounds",
})
class GoalExecutionScope(GoalInputScope):
def __init__(
self, state: SessionState, session_key: str | None, generation: str | None,
*, persistent: bool,
) -> None:
super().__init__()
self._state = state
self._session_key = session_key
self._generation = generation
self._persistent = persistent
async def continuation_prompt(self) -> str | None:
key = self._session_key
current = await self._state.read_header(key) if key and self._persistent else None
if current is None or current.generation != self._generation:
return None
if not sustained_goal_active(current.metadata):
return None
lines = "\n".join(goal_state_runtime_lines(current.metadata))
return (
f"You have an active sustained goal:\n\n{lines}\n\n"
"Please continue working toward the objective using your tools, or call update_goal "
"with action='complete' if the work is truly finished. "
"If required conditions are unavailable, use action='block' with an honest recap."
)
class GoalExecutionPolicy:
def __init__(self, state: SessionState) -> None:
self._state = state
def scope(
self, session_key: str | None, generation: str | None, *, persistent: bool,
) -> GoalExecutionScope:
return GoalExecutionScope(self._state, session_key, generation, persistent=persistent)
@@ -11,7 +11,7 @@ from nanobot.agent.goal_permission import (
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.context import RequestContext, 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
@@ -26,7 +26,6 @@ from nanobot.session.goal_state import (
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
@@ -62,12 +61,16 @@ class _GoalToolsMixin:
async def _session(self) -> Session | None:
request_ctx = current_request_context()
if request_ctx is None:
if request_ctx is None or not request_ctx.persist_session:
return None
key = request_ctx.session_key
if not key:
generation = request_ctx.session_generation
if not key or not generation:
return None
return await self._sessions.state.get_header(key)
session = await self._sessions.state.read_header(key)
if session is None or session.generation != generation:
return None
return session
def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed()
@@ -77,7 +80,6 @@ class _GoalToolsMixin:
sess: Session,
blob: dict[str, Any],
*,
reset_continuation: bool = False,
revoke_permission: bool = False,
) -> None:
saved = False
@@ -87,8 +89,6 @@ class _GoalToolsMixin:
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,
)
@@ -150,18 +150,8 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
_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
def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:
return cls(sessions=sessions, bus=bus)
@property
def name(self) -> str:
@@ -236,7 +226,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
"ui_summary": summary,
"started_at": _iso_now(),
}
await self._save_goal_state(sess, blob, reset_continuation=True)
await self._save_goal_state(sess, blob)
extra = f"\nSummary line: {summary}" if summary else ""
return (
"Goal recorded. Keep working toward the objective using ordinary tools. "
@@ -281,18 +271,8 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
_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
def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:
return cls(sessions=sessions, bus=bus)
@property
def name(self) -> str:
@@ -350,7 +330,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
"previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(),
}
await self._save_goal_state(sess, blob, reset_continuation=True)
await self._save_goal_state(sess, blob)
extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
+3
View File
@@ -132,10 +132,13 @@ class Nanobot:
tools = ToolRegistry()
register_image_generation_tool(config, tools, workspace=config.workspace_path)
mcp_provider = MCPProvider.from_config(config, tools)
from nanobot.goal.assembly import install_goal
loop = AgentLoop.from_config(
config,
hook_factories=[create_file_edit_activity_hook],
tool_registry=tools,
builtin_assembly=install_goal,
)
return cls(loop, config=config, mcp_provider=mcp_provider)
+1 -33
View File
@@ -1,8 +1,7 @@
"""Session metadata helpers for explicit sustained goals.
Tools set ``metadata[GOAL_STATE_KEY]``. Reads accept the legacy session key ``thread_goal``
for older sessions. Callers use ``goal_state_runtime_lines`` and ``goal_state_ws_blob`` without
importing tool implementations.
for older sessions. Callers can read the goal without importing tool implementations.
"""
from __future__ import annotations
@@ -15,7 +14,6 @@ GOAL_COMMAND = "/goal"
MAX_GOAL_OBJECTIVE_CHARS = 4000
# Older builds stored the same JSON blob under this key.
_LEGACY_GOAL_STATE_SESSION_KEY = "thread_goal"
_MAX_OBJECTIVE_WS = 600
def _session_goal_raw(metadata: Mapping[str, Any] | None) -> Any:
@@ -51,15 +49,6 @@ def explicit_goal_requested(message_metadata: Mapping[str, Any] | None) -> bool:
return str(message_metadata.get("original_command") or "").strip() == GOAL_COMMAND
def sustained_goal_turn(
metadata: Mapping[str, Any] | None,
*,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
"""True when this turn should use sustained-goal runtime limits."""
return sustained_goal_active(metadata) or explicit_goal_requested(message_metadata)
def parse_goal_state(blob: Any) -> dict[str, Any] | None:
if blob is None:
return None
@@ -91,24 +80,3 @@ def goal_state_runtime_lines(metadata: Mapping[str, Any] | None) -> list[str]:
if hint:
out.append(f"Summary: {hint}")
return out
def goal_state_ws_blob(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
"""JSON-safe snapshot for WebSocket ``goal_state`` events (one chat_id per frame)."""
goal = parse_goal_state(_session_goal_raw(metadata)) if metadata else None
if isinstance(goal, dict) and goal.get("status") in {"active", "blocked"}:
status = str(goal.get("status"))
objective = str(goal.get("objective") or "").strip()
if len(objective) > _MAX_OBJECTIVE_WS:
objective = objective[:_MAX_OBJECTIVE_WS].rstrip() + "…"
summary = str(goal.get("ui_summary") or "").strip()[:120]
blob: dict[str, Any] = {"active": status == "active", "status": status}
if summary:
blob["ui_summary"] = summary
if objective:
blob["objective"] = objective
recap = str(goal.get("recap") or "").strip()[:240]
if recap:
blob["recap"] = recap
return blob
return {"active": False}
+17 -6
View File
@@ -42,13 +42,11 @@ _FORK_VOLATILE_METADATA_KEYS = {
"_stopped_at_iteration_limit",
PARENT_SESSION_KEY,
SESSION_TYPE_KEY,
"goal_state",
"pending_user_turn",
"pending_user_followups",
"runtime_checkpoint",
"session_handle",
"webui_recovery",
"thread_goal",
"title",
"title_user_edited",
}
@@ -374,7 +372,10 @@ class SessionInfo(TypedDict):
path: str
def fork_session(source: Session, target_key: str, before_user_index: int) -> Session | None:
def fork_session(
source: Session, target_key: str, before_user_index: int,
*, exclude_metadata: frozenset[str] = frozenset(),
) -> Session | None:
"""Build a portable fork ending before the requested visible user message."""
if before_user_index < 0:
return None
@@ -394,7 +395,7 @@ def fork_session(source: Session, target_key: str, before_user_index: int) -> Se
return None
metadata = deepcopy(source.metadata)
for key in _FORK_VOLATILE_METADATA_KEYS:
for key in _FORK_VOLATILE_METADATA_KEYS | exclude_metadata:
metadata.pop(key, None)
last_consolidated = min(source.last_archived, len(copied))
@@ -432,15 +433,23 @@ class SessionManager:
self._store.initialize()
self._delete_observer: Callable[[str], None] | None = None
self.types = SessionTypes()
self._generation_exclusions: set[str] = set()
self._state: SessionState | None = None
def exclude_generation_metadata(self, keys: frozenset[str]) -> None:
"""Register feature metadata that cannot cross a fork or reset."""
self._generation_exclusions.update(keys)
@property
def state(self) -> SessionState:
"""The asynchronous owner of session state transitions."""
if self._state is None:
from nanobot.session.state import SessionState
self._state = SessionState(self._store, on_delete=self._notify_delete, types=self.types)
self._state = SessionState(
self._store, on_delete=self._notify_delete, types=self.types,
generation_exclusions=self._generation_exclusions,
)
return self._state
def _notify_delete(self, key: str) -> None:
@@ -555,7 +564,9 @@ class SessionManager:
source = self._store.load(source_key)
if source is None:
return None
target = fork_session(source, target_key, before_user_index)
target = fork_session(
source, target_key, before_user_index, exclude_metadata=frozenset(self._generation_exclusions),
)
if target is not None:
self._store.save(target)
self._store.copy_history_prefix(source_key, target, before_user_index)
+19 -2
View File
@@ -53,12 +53,16 @@ class SessionState:
workers: int = _DEFAULT_WORKERS,
on_delete: Callable[[str], None] | None = None,
types: SessionTypes | None = None,
generation_exclusions: set[str] | None = None,
) -> None:
if capacity < 1:
raise ValueError("session operation capacity must be positive")
if workers < 1:
raise ValueError("session operation worker count must be positive")
self._types = types if types is not None else SessionTypes()
self._generation_exclusions: set[str] = (
generation_exclusions if generation_exclusions is not None else set()
)
self._store = store
self._on_delete = on_delete
self._snapshots: dict[str, Session] = {}
@@ -426,6 +430,15 @@ class SessionState:
return self._draft(session)
return await self._execute(key, read, write=False)
async def read_header(self, key: str) -> Session | None:
"""Read committed identity and metadata without creating a session."""
def read() -> Session | None:
session = self._load(key, history=False)
if session is None:
return None
return replace(session, messages=[], provider_state=None, _baseline=None)
return await self._execute(key, read, write=False)
async def get(self, key: str) -> Session:
"""Read an existing conversation; create missing state on the writer."""
return await self._get(key, history=True)
@@ -661,7 +674,7 @@ class SessionState:
await self._submit_draft(session)
async def finish_turn(self, session: Session) -> None:
"""Commit the assembled transcript and clear its recovery markers."""
"""Commit the assembled transcript and clear its recovery checkpoint."""
session.metadata.pop(_PENDING_KEY, None)
session.metadata.pop(_CHECKPOINT_KEY, None)
await self._submit_draft(session)
@@ -997,7 +1010,9 @@ class SessionState:
source = self._load(source_key)
if source is None:
return None
target = fork_session(source, target_key, before_user_index)
target = fork_session(
source, target_key, before_user_index, exclude_metadata=frozenset(self._generation_exclusions),
)
if target is None:
return None
if title:
@@ -1145,6 +1160,8 @@ class SessionState:
session.metadata = deepcopy(old.metadata)
for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"):
session.metadata.pop(name, None)
for name in self._generation_exclusions:
session.metadata.pop(name, None)
if session.policy.persist:
self._store.delete(key, preserve_archive=True)
self._commit(session)
+8 -260
View File
@@ -1,51 +1,23 @@
"""Internal turn continuation helpers.
This module keeps budget-boundary continuation policy out of ``AgentLoop``.
The loop calls a small set of helpers; those helpers decide whether an internal
continuation is allowed and, when it is, queue the next turn directly.
"""
"""Bookkeeping for explicit recovery inputs and ordinary iteration-limit stops."""
from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, Mapping, MutableMapping
from loguru import logger
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
from nanobot.session.goal_state import (
goal_state_runtime_lines,
sustained_goal_active,
sustained_goal_turn,
)
from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
if TYPE_CHECKING:
from nanobot.agent.loop import TurnContext
from nanobot.agent.tools.context import RequestContext
from nanobot.session.state import SessionState
INTERNAL_CONTINUATION_META = "_internal_continuation"
INTERNAL_CONTINUATION_KIND_META = "_internal_continuation_kind"
INTERNAL_CONTINUATION_RUN_STARTED_AT_META = "_internal_continuation_run_started_at"
SKIP_USER_PERSIST_META = "_skip_user_persist"
_ITERATION_LIMIT_META = "_stopped_at_iteration_limit"
_GOAL_CONTINUATION_KIND = "sustained_goal"
_GOAL_CONTINUATION_SENDER = "system:continuation"
_GOAL_CONTINUATION_ROUNDS_KEY = "_sustained_goal_continuation_rounds"
_MAX_GOAL_CONTINUATION_ROUNDS = 12
_STRIPPED_INBOUND_META_KEYS = {
"goal_requested",
"original_command",
}
def record_iteration_limit(
metadata: MutableMapping[str, Any], stop_reason: str, *, continuation_pending: bool,
) -> None:
"""Remember a terminal budget stop, not an internal continuation handoff."""
if stop_reason == "max_iterations" and not continuation_pending:
def record_iteration_limit(metadata: MutableMapping[str, Any], stop_reason: str) -> None:
"""Remember an ordinary execution stopped at its iteration limit."""
if stop_reason == "max_iterations":
metadata[_ITERATION_LIMIT_META] = True
else:
metadata.pop(_ITERATION_LIMIT_META, None)
@@ -73,245 +45,21 @@ async def iteration_limit_context(
def internal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool:
"""True for an inbound message created by an internal continuation policy."""
return bool(metadata and metadata.get(INTERNAL_CONTINUATION_META) is True)
def sustained_goal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool:
"""True only for an internal continuation owned by sustained-goal policy."""
return bool(
internal_continuation_inbound(metadata)
and metadata
and metadata.get(INTERNAL_CONTINUATION_KIND_META) == _GOAL_CONTINUATION_KIND
)
def internal_continuation_run_started_at(metadata: Mapping[str, Any] | None) -> float | None:
"""Return the user-visible run start propagated across continuation slices."""
if not metadata:
return None
value = metadata.get(INTERNAL_CONTINUATION_RUN_STARTED_AT_META)
if not isinstance(value, int | float):
return None
started_at = float(value)
return started_at if started_at > 0 else None
def should_persist_user_message(metadata: Mapping[str, Any] | None) -> bool:
"""Return whether this inbound message should be persisted as user input."""
if metadata and metadata.get(SKIP_USER_PERSIST_META) is True:
return False
return not internal_continuation_inbound(metadata)
def should_stream_budget_response(
*,
stop_reason: str,
pending_queue_available: bool,
session_metadata: Mapping[str, Any] | None,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
"""Return whether the budget-boundary response should be sent to the user."""
if stop_reason != "max_iterations":
return True
return should_finalize_on_max_iterations(
pending_queue_available=pending_queue_available,
session_metadata=session_metadata,
message_metadata=message_metadata,
)
def should_finalize_on_max_iterations(
*,
pending_queue_available: bool,
session_metadata: Mapping[str, Any] | None,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
"""Return whether a max-iteration boundary should produce a final response.
When a sustained goal can continue internally, the current runner slice
should stop without spending an extra no-tools finalization call. The next
queued continuation slice owns the eventual user-visible response.
"""
return not (
pending_queue_available
and _goal_continuation_available(
session_metadata,
message_metadata=message_metadata,
)
)
async def maybe_continue_turn(
ctx: TurnContext, *, session_metadata: Mapping[str, Any],
) -> bool:
"""Queue an internal continuation for *ctx* when policy allows it."""
if ctx.session is None or ctx.pending_queue is None:
return False
if not _continuation_available(
stop_reason=ctx.stop_reason,
pending_queue_available=True,
session_metadata=session_metadata,
message_metadata=ctx.msg.metadata,
):
return False
metadata = _internal_continuation_metadata(
ctx.msg.metadata,
run_started_at=ctx.visible_run_started_at,
)
request = ctx.request_context
assert request is not None and request.turn_id is not None
metadata[REQUEST_ORIGIN_METADATA_KEY] = {
"message_id": request.message_id,
"turn_id": request.turn_id,
}
content = _goal_continuation_prompt(session_metadata)
messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)
_increment_goal_continuation_round(ctx.session.metadata)
logger.info("Turn budget reached; scheduling internal continuation")
ctx.final_content = ""
ctx.all_messages = messages
ctx.suppress_response = True
await ctx.pending_queue.put(
dataclasses.replace(
ctx.msg,
sender_id=_GOAL_CONTINUATION_SENDER,
content=content,
media=[],
metadata=metadata,
session_key_override=ctx.session_key,
)
)
return True
def prepare_save_boundary(ctx: TurnContext) -> None:
"""Prepare continuation bookkeeping and the history append boundary."""
if ctx.session is not None:
clear_internal_continuation_state(ctx.session.metadata)
assert ctx.transcript_input is not None
ctx.save_skip = _save_skip_for_turn(
message_metadata=ctx.msg.metadata,
initial_message_count=ctx.transcript_input.message_count,
input_persisted_early=ctx.input_persisted_early,
)
def _continuation_available(
*,
stop_reason: str,
pending_queue_available: bool,
session_metadata: Mapping[str, Any] | None,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
if stop_reason != "max_iterations" or not pending_queue_available:
return False
return _goal_continuation_available(
session_metadata,
message_metadata=message_metadata,
)
def clear_internal_continuation_state(metadata: MutableMapping[str, Any]) -> None:
"""Reset policy bookkeeping once its owning runtime mode is inactive."""
if not sustained_goal_active(metadata):
reset_goal_continuation_rounds(metadata)
def reset_goal_continuation_rounds(metadata: MutableMapping[str, Any]) -> None:
"""Start a newly created or replaced goal with a fresh continuation budget."""
metadata.pop(_GOAL_CONTINUATION_ROUNDS_KEY, None)
def _save_skip_for_turn(
*,
message_metadata: Mapping[str, Any] | None,
initial_message_count: int,
input_persisted_early: bool,
def save_skip_for_turn(
*, message_metadata: Mapping[str, Any] | None,
initial_message_count: int, input_persisted_early: bool,
) -> int:
if message_metadata and message_metadata.get(SKIP_USER_PERSIST_META) is True:
return initial_message_count
if internal_continuation_inbound(message_metadata):
return initial_message_count
if not input_persisted_early:
return initial_message_count - 1
return initial_message_count
def _goal_continuation_available(
session_metadata: Mapping[str, Any] | None,
*,
message_metadata: Mapping[str, Any] | None = None,
max_rounds: int = _MAX_GOAL_CONTINUATION_ROUNDS,
) -> bool:
if not sustained_goal_turn(session_metadata, message_metadata=message_metadata):
return False
if not sustained_goal_active(session_metadata):
return False
try:
rounds = int((session_metadata or {}).get(_GOAL_CONTINUATION_ROUNDS_KEY) or 0)
except (TypeError, ValueError):
rounds = 0
return rounds < max(0, max_rounds)
def _increment_goal_continuation_round(session_metadata: MutableMapping[str, Any]) -> None:
try:
rounds = int(session_metadata.get(_GOAL_CONTINUATION_ROUNDS_KEY) or 0)
except (TypeError, ValueError):
rounds = 0
session_metadata[_GOAL_CONTINUATION_ROUNDS_KEY] = rounds + 1
def _internal_continuation_metadata(
message_metadata: Mapping[str, Any] | None,
*,
run_started_at: float | None = None,
) -> dict[str, Any]:
metadata = dict(message_metadata or {})
metadata[INTERNAL_CONTINUATION_META] = True
metadata[INTERNAL_CONTINUATION_KIND_META] = _GOAL_CONTINUATION_KIND
if run_started_at is not None:
metadata[INTERNAL_CONTINUATION_RUN_STARTED_AT_META] = float(run_started_at)
for key in _STRIPPED_INBOUND_META_KEYS:
metadata.pop(key, None)
return metadata
def _goal_continuation_prompt(metadata: Mapping[str, Any] | None) -> str:
lines = goal_state_runtime_lines(metadata)
if lines:
goal = "\n".join(lines)
return (
"Continue the active sustained goal after the previous turn reached "
"its tool-call budget.\n\n"
f"{goal}\n\n"
"Continue from the saved context. Do not mention the continuation "
"boundary to the user. Use tools as needed, and call update_goal "
"with action='complete' when the objective is truly finished."
)
return (
"Continue the active sustained goal after the previous turn reached "
"its tool-call budget. Continue from the saved context. Do not mention "
"the continuation boundary to the user. Use tools as needed, and call "
"update_goal with action='complete' when the objective is truly finished."
)
def _strip_terminal_assistant(
messages: list[dict[str, Any]],
final_content: str | None,
) -> list[dict[str, Any]]:
if not messages:
return messages
last = messages[-1]
if last.get("role") != "assistant":
return messages
if final_content is None or last.get("content") != final_content:
return messages
if last.get("tool_calls"):
return messages
return messages[:-1]
return initial_message_count if input_persisted_early else initial_message_count - 1
+1 -1
View File
@@ -40,7 +40,6 @@ from nanobot.providers.base import LLMProvider, LLMUsage
from nanobot.providers.fallback_provider import FallbackModelObserver, FallbackModelSelection
from nanobot.runtime_context import public_history_message
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import session_handle_for_name
@@ -51,6 +50,7 @@ from nanobot.session.session_messages import (
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.utils.helpers import strip_think, truncate_text
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.goal_state import goal_state_ws_blob
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_TURN_METADATA_KEY,
+30
View File
@@ -0,0 +1,30 @@
"""WebUI projection of persisted sustained-goal state."""
from __future__ import annotations
from typing import Any, Mapping
from nanobot.session.goal_state import goal_state_raw, parse_goal_state
_MAX_OBJECTIVE_WS = 600
def goal_state_ws_blob(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
"""JSON-safe snapshot for WebSocket ``goal_state`` events (one chat_id per frame)."""
goal = parse_goal_state(goal_state_raw(metadata))
if isinstance(goal, dict) and goal.get("status") in {"active", "blocked"}:
status = str(goal.get("status"))
objective = str(goal.get("objective") or "").strip()
if len(objective) > _MAX_OBJECTIVE_WS:
objective = objective[:_MAX_OBJECTIVE_WS].rstrip() + "…"
summary = str(goal.get("ui_summary") or "").strip()[:120]
blob: dict[str, Any] = {"active": status == "active", "status": status}
if summary:
blob["ui_summary"] = summary
if objective:
blob["objective"] = objective
recap = str(goal.get("recap") or "").strip()[:240]
if recap:
blob["recap"] = recap
return blob
return {"active": False}
+2 -1
View File
@@ -16,7 +16,8 @@ from websockets.asyncio.server import ServerConnection
from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_USER_SHELL
from nanobot.channels.websocket.attachment_policy import validate_attachment_batch
from nanobot.channels.websocket.attachment_store import AttachmentUploadError
from nanobot.command.builtin import USER_SHELL_COMMAND, builtin_command_starts_agent_turn
from nanobot.command.application import builtin_command_starts_agent_turn
from nanobot.command.builtin import USER_SHELL_COMMAND
from nanobot.runtime_context import (
RUNTIME_CONTEXT_INPUT_META,
WEBUI_QUOTE_METADATA,
+6 -7
View File
@@ -6,11 +6,11 @@ from loguru import logger as default_logger
from nanobot.agent.subagent import SubagentControlError
from nanobot.providers.base import LLMUsage
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.session.state import SessionState
from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at
from nanobot.webui.goal_state import goal_state_ws_blob
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
@@ -98,16 +98,15 @@ class WebUISessionProjection:
return tuple(events)
async def persisted_goal_state(self, session_key: str) -> dict[str, Any] | None:
"""Return an actionable persisted goal state for reconnect hydration."""
"""Return the persisted goal snapshot, including an inactive state on reconnect."""
if self._sessions is None:
return None
snapshot = await self._sessions.state.read_metadata(session_key)
raw_metadata = snapshot.get("metadata") if snapshot is not None else None
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
goal_state = goal_state_ws_blob(metadata)
if not goal_state.get("active") and goal_state.get("status") != "blocked":
if snapshot is None:
return None
return goal_state
raw_metadata = snapshot.get("metadata")
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
return goal_state_ws_blob(metadata)
@staticmethod
def active_turn_status(chat_id: str) -> tuple[float, str | None] | None:
+1 -1
View File
@@ -11,7 +11,7 @@ from nanobot.bus.events import (
InboundMessage,
)
from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import register_builtin_commands
from nanobot.command.application import register_builtin_commands
from nanobot.command.router import CommandRouter
from nanobot.security.workspace_access import WorkspaceScope
from nanobot.session.manager import SessionManager
+1 -1
View File
@@ -28,7 +28,7 @@ from websockets.http11 import Response
from nanobot.agent.subagent import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError
from nanobot.command.builtin import builtin_command_palette
from nanobot.command.application import builtin_command_palette
from nanobot.cron.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule