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

+1 -1
View File
@@ -301,7 +301,7 @@ Use a regular topic for a bounded objective with a clear completion condition, f
/goal Review this project's tests and list the smallest missing test case. /goal Review this project's tests and list the smallest missing test case.
``` ```
The goal lets nanobot continue work across model turns while the gateway runs; a scheduled automation instead starts a turn at specified times. Use `/stop` to interrupt the current work, and ask nanobot to cancel the goal if you want to abandon it. Keep the gateway running for unattended work using the background or service options below. An active goal keeps nanobot working beyond the ordinary iteration limit until it records completion, cancellation, or a blocked state. This can use more model tokens; `/stop` interrupts the current work, while asking nanobot to cancel the goal abandons the objective. Execution errors can also stop the work. A scheduled automation instead starts work at specified times. Keep the gateway running for unattended work using the background or service options below.
After a gateway restart, reopen the original topic and review saved results before explicitly continuing any interrupted work. Recovery does not blindly replay uncertain tool actions. See the [long-running agent guide](./docs/guides/long-running-ai-agent.md) for starting conditions and related automation options. After a gateway restart, reopen the original topic and review saved results before explicitly continuing any interrupted work. Recovery does not blindly replay uncertain tool actions. See the [long-running agent guide](./docs/guides/long-running-ai-agent.md) for starting conditions and related automation options.
+2 -2
View File
@@ -1,6 +1,6 @@
# How to Run a Long-Running AI Agent with nanobot # How to Run a Long-Running AI Agent with nanobot
nanobot can keep agent work alive across turns through sustained goals, persistent sessions, scheduled automations, local triggers, and a gateway process that stays running. nanobot supports sustained goals, persistent sessions, scheduled automations, and local triggers for work that needs more than a single answer.
## What you will build ## What you will build
@@ -40,7 +40,7 @@ Use the same `--config` and explicit `--workspace` selectors as your instance. I
- Keep the gateway running for chat apps, WebUI sessions, automations, and local triggers. - Keep the gateway running for chat apps, WebUI sessions, automations, and local triggers.
- Use stable session keys or chat sessions for work that should preserve context. - Use stable session keys or chat sessions for work that should preserve context.
- Keep goals bounded and explicit about done-ness. - Keep goals bounded and explicit about done-ness. Active goals can exceed the ordinary iteration limit and consume more model tokens. Use `/stop` to interrupt work; stopping does not cancel the saved goal.
- Review Automations in the WebUI before relying on a schedule. - Review Automations in the WebUI before relying on a schedule.
## Security notes ## Security notes
+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 collections.abc import Iterable
from contextlib import ExitStack, contextmanager from contextlib import ExitStack, contextmanager
from contextvars import ContextVar from contextvars import ContextVar
from typing import Self
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.session.automation_turns import automation_history_overrides from nanobot.session.automation_turns import automation_history_overrides
@@ -35,15 +36,9 @@ def goal_mutation_permission(allowed: bool):
class GoalInputScope(ExitStack): class GoalInputScope(ExitStack):
"""Own goal authorization for fresh inputs consumed during one agent run.""" """Own goal authorization for fresh inputs consumed during one agent run."""
def __init__(self, initial_message: InboundMessage | None = None) -> None: def __enter__(self) -> Self:
super().__init__()
self._initial_message = initial_message
def __enter__(self) -> GoalInputScope:
super().__enter__() super().__enter__()
self.enter_context(goal_mutation_permission(False)) self.enter_context(goal_mutation_permission(False))
if self._initial_message is not None:
self.consume_inputs((self._initial_message,))
return self return self
def consume_inputs(self, messages: Iterable[InboundMessage]) -> None: def consume_inputs(self, messages: Iterable[InboundMessage]) -> None:
+150 -123
View File
@@ -6,7 +6,7 @@ import os
import time import time
import weakref import weakref
from collections.abc import Coroutine, Iterable, Mapping 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 copy import deepcopy
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import datetime 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.autocompact import AutoCompact
from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput
from nanobot.agent.cron_turns import CronTurnCoordinator 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.hook import AgentHook, AgentTurnHookFactory
from nanobot.agent.memory import Consolidator from nanobot.agent.memory import Consolidator
from nanobot.agent.model_runtime import ModelRuntimeResolver from nanobot.agent.model_runtime import ModelRuntimeResolver
@@ -56,8 +56,9 @@ from nanobot.bus.outbound_events import (
StreamEndEvent, StreamEndEvent,
) )
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands from nanobot.command import CommandContext, CommandRouter
from nanobot.command.router import command_text 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.network import NetworkConfig
from nanobot.config.schema import AgentDefaults, ModelPresetConfig from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.events import NO_EVENTS, AgentEvent, EventSink 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 import turn_continuation
from nanobot.session.automation_turns import automation_history_overrides 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.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy 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 run_extra_hooks_for_ephemeral: bool = False
hooks: list[AgentHook] = field(default_factory=list) hooks: list[AgentHook] = field(default_factory=list)
hook_factories: list[AgentTurnHookFactory] = 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 tools: ToolRegistry | None = None
turn_wall_started_at: float = field(default_factory=time.time) 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 turn_latency_ms: int | None = None
usage: LLMUsage | None = None usage: LLMUsage | None = None
@@ -311,12 +310,14 @@ class AgentLoop:
local_trigger_store: LocalTriggerStore | None = None, local_trigger_store: LocalTriggerStore | None = None,
idle_compact_check_interval_seconds: int = 0, idle_compact_check_interval_seconds: int = 0,
recovery_admission: RecoveryAdmission | None = None, recovery_admission: RecoveryAdmission | None = None,
builtin_assembly: Callable[[SessionManager, MessageBus, ToolRegistry, CommandRouter], ExecutionPolicy] | None = None,
): ):
from nanobot.config.schema import ToolsConfig from nanobot.config.schema import ToolsConfig
_tc = tools_config or ToolsConfig() _tc = tools_config or ToolsConfig()
defaults = AgentDefaults() defaults = AgentDefaults()
self.bus = bus self.bus = bus
self.execution_policy: ExecutionPolicy | None = None
self._recovery_admission = recovery_admission self._recovery_admission = recovery_admission
if turn_delivery_factory is not None: if turn_delivery_factory is not None:
if turn_delivery_factory.bus is not bus: if turn_delivery_factory.bus is not bus:
@@ -453,9 +454,11 @@ class AgentLoop:
self._next_idle_compact_check_at = time.monotonic() self._next_idle_compact_check_at = time.monotonic()
if model_preset: if model_preset:
self.set_model_preset(model_preset, publish_update=False) self.set_model_preset(model_preset, publish_update=False)
self._register_default_tools(provider_snapshot_loader=provider_snapshot_loader)
self.commands = CommandRouter() 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 @classmethod
def from_config( def from_config(
@@ -830,12 +833,38 @@ class AgentLoop:
blocks.append(skill_context) blocks.append(skill_context)
return blocks 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( async def _dispatch_command_inline(
self, self,
msg: InboundMessage, msg: InboundMessage,
key: str, key: str,
raw: str, raw: str,
dispatch_fn: Callable[[CommandContext], Awaitable[InboundMessage | OutboundMessage | None]], dispatch_fn: Callable[
[CommandContext], Awaitable[CommandExpansion | InboundMessage | OutboundMessage | None],
],
) -> None: ) -> None:
if self.commands.requires_session_queue(raw): if self.commands.requires_session_queue(raw):
await self._enqueue_session_message(msg) await self._enqueue_session_message(msg)
@@ -852,6 +881,8 @@ class AgentLoop:
), ),
) )
result = await dispatch_fn(ctx) result = await dispatch_fn(ctx)
if isinstance(result, CommandExpansion):
result = await self._prepare_command_expansion(ctx, result)
if isinstance(result, InboundMessage): if isinstance(result, InboundMessage):
await self._enqueue_session_message(result) await self._enqueue_session_message(result)
elif result is not None: elif result is not None:
@@ -892,17 +923,13 @@ class AgentLoop:
log_content=session.policy.log_content, log_content=session.policy.log_content,
)) ))
workspace_token = bind_workspace_scope(scope) workspace_token = bind_workspace_scope(scope)
turn_scope_stack = ExitStack()
try: try:
for turn_scope in ctx.turn_scopes:
turn_scope_stack.enter_context(turn_scope)
result = await tool.execute_to_completion( result = await tool.execute_to_completion(
command=ctx.args.strip(), command=ctx.args.strip(),
working_dir=str(scope.project_path), working_dir=str(scope.project_path),
) )
content = str(result) content = str(result)
finally: finally:
turn_scope_stack.close()
reset_workspace_scope(workspace_token) reset_workspace_scope(workspace_token)
reset_request_context(request_token) reset_request_context(request_token)
return OutboundMessage( return OutboundMessage(
@@ -928,6 +955,9 @@ class AgentLoop:
self._active_tasks.pop(key, None) self._active_tasks.pop(key, None)
async def _cancel_active_tasks(self, key: str) -> int: 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) journal_session = await self.sessions.state.read(key)
journaled_followup_ids = ( journaled_followup_ids = (
tuple( tuple(
@@ -941,12 +971,13 @@ class AgentLoop:
if journal_session is not None if journal_session is not None
else () 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: for t in tasks:
with suppress(asyncio.CancelledError, Exception): try:
await t await t
except asyncio.CancelledError:
pass
except Exception:
pass
if tasks and pending is not None and self._pending_queues.get(key) is pending: 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 # A task cancelled before its first step never enters the worker's
# cleanup handler. Only reclaim that worker's original inbox. # cleanup handler. Only reclaim that worker's original inbox.
@@ -1035,10 +1066,10 @@ class AgentLoop:
run_extra_hooks_for_ephemeral: bool = False, run_extra_hooks_for_ephemeral: bool = False,
hooks: list[AgentHook] | None = None, hooks: list[AgentHook] | None = None,
hook_factories: list[AgentTurnHookFactory] | None = None, hook_factories: list[AgentTurnHookFactory] | None = None,
turn_scopes: list[AbstractContextManager[Any]] | None = None,
tools: ToolRegistry | None = None, tools: ToolRegistry | None = None,
request_context: RequestContext | None = None, request_context: RequestContext | None = None,
provider_state: ProviderConversationState | None = None, provider_state: ProviderConversationState | None = None,
initial_message: InboundMessage | None = None,
) -> AgentRunResult: ) -> AgentRunResult:
self._sync_subagent_runtime_limits() self._sync_subagent_runtime_limits()
@@ -1162,13 +1193,19 @@ class AgentLoop:
consumed = 0 consumed = 0
try: try:
converted: list[dict[str, Any]] = [] converted: list[dict[str, Any]] = []
consumed_inputs: list[InboundMessage] = []
for pending_msg in pending_messages: for pending_msg in pending_messages:
# Independent turns are FIFO barriers. Their worker path # Independent turns are FIFO barriers. Their worker path
# owns completion, command dispatch, and control metadata. # owns completion, command dispatch, and control metadata.
if not self._can_inject_message(pending_msg): if not self._can_inject_message(pending_msg):
break break
converted.append(await _to_user_message(pending_msg)) 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) consumed = len(converted)
return converted return converted
finally: finally:
@@ -1259,24 +1296,17 @@ class AgentLoop:
request_token = bind_request_context(request_ctx) request_token = bind_request_context(request_ctx)
workspace_token = bind_workspace_scope(effective_scope) workspace_token = bind_workspace_scope(effective_scope)
turn_scope_stack = ExitStack() turn_scope_stack = ExitStack()
# Compute lazily because create_goal may create goal metadata during this run. execution_scope: ExecutionScope | None = None
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
try: try:
goal_inputs = turn_scope_stack.enter_context(GoalInputScope()) if self.execution_policy is not None:
for scope in turn_scopes or (): execution_scope = turn_scope_stack.enter_context(self.execution_policy.scope(
turn_scope_stack.enter_context(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( hook = build_agent_turn_hook(AgentTurnHookSpec(
events=events, events=events,
streaming=streaming, streaming=streaming,
@@ -1327,11 +1357,8 @@ class AgentLoop:
), ),
injection_callback=_drain_pending, injection_callback=_drain_pending,
terminal_injection_callback=_wait_for_pending, terminal_injection_callback=_wait_for_pending,
continuation_callback=_goal_continue, continuation_callback=(
finalize_on_max_iterations=turn_continuation.should_finalize_on_max_iterations( execution_scope.continuation_prompt if execution_scope is not None else None
pending_queue_available=pending_queue is not None and session is not None,
session_metadata=session_metadata,
message_metadata=request_metadata,
), ),
provider_state=provider_state, provider_state=provider_state,
llm_usage_source=source_from_request( llm_usage_source=source_from_request(
@@ -1350,15 +1377,10 @@ class AgentLoop:
session.provider_state = result.provider_state session.provider_state = result.provider_state
if result.stop_reason == "max_iterations": if result.stop_reason == "max_iterations":
logger.warning("Max iterations ({}) reached", self.max_iterations) logger.warning("Max iterations ({}) reached", self.max_iterations)
should_stream = turn_continuation.should_stream_budget_response( if result.stop_reason == "max_iterations" or result.pending_stream_content is not None:
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,
)
# Push final content through stream so streaming channels (e.g. Feishu) # Push final content through stream so streaming channels (e.g. Feishu)
# update the card instead of leaving it empty. # 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 = ( stream_content = (
result.pending_stream_content result.pending_stream_content
if result.pending_stream_content is not None if result.pending_stream_content is not None
@@ -1421,7 +1443,7 @@ class AgentLoop:
with self.bus.admission.activity(): with self.bus.admission.activity():
try: try:
await self._dispatch_inbound(msg) await self._dispatch_inbound(msg)
except (SessionOperationQueueFullError, SessionConflictError) as exc: except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc:
key = self._effective_session_key(msg) key = self._effective_session_key(msg)
logger.warning("Session input rejected for {}: {}", key, exc) logger.warning("Session input rejected for {}: {}", key, exc)
if msg.is_user_input: if msg.is_user_input:
@@ -1558,14 +1580,14 @@ class AgentLoop:
try: try:
while self._pending_queues.get(session_key) is pending: while self._pending_queues.get(session_key) is pending:
try: try:
msg = pending.get_nowait() item = pending.get_nowait()
except asyncio.QueueEmpty: except asyncio.QueueEmpty:
# Idle-only automation follows all accepted user input on # Idle-only automation follows all accepted user input on
# this same worker, including before the bus loop starts. # this same worker, including before the bus loop starts.
deferred = self._deferred_automation_turns.get(session_key) deferred = self._deferred_automation_turns.get(session_key)
if not deferred: if not deferred:
break break
msg = deferred.pop(0) item = deferred.pop(0)
if not deferred: if not deferred:
self._deferred_automation_turns.pop(session_key) self._deferred_automation_turns.pop(session_key)
session = self.sessions.state.peek_header(session_key) session = self.sessions.state.peek_header(session_key)
@@ -1573,10 +1595,10 @@ class AgentLoop:
session.policy.persist and session.policy.log_content session.policy.persist and session.policy.log_content
) )
try: try:
await self._dispatch_one(msg, pending) await self._dispatch_one(item, pending)
except asyncio.CancelledError as exc: except asyncio.CancelledError as exc:
for coordinator in self._automation_turn_coordinators: for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=exc) coordinator.complete(item, error=exc)
raise raise
except Exception: except Exception:
logger.opt(exception=log_content).error( logger.opt(exception=log_content).error(
@@ -1600,14 +1622,11 @@ class AgentLoop:
for msg in self._deferred_automation_turns.pop(session_key, []): for msg in self._deferred_automation_turns.pop(session_key, []):
pending.put_nowait(msg) pending.put_nowait(msg)
while not pending.empty(): while not pending.empty():
msg = pending.get_nowait() item = pending.get_nowait()
for coordinator in self._automation_turn_coordinators: for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=error) coordinator.complete(item, error=error)
if ( if item.channel != "system" and self.commands.requires_session_queue(command_text(item)):
msg.channel != "system" delivery = self.turn_delivery_factory.unrouted(item, session_key)
and self.commands.requires_session_queue(command_text(msg))
):
delivery = self.turn_delivery_factory.unrouted(msg, session_key)
await delivery.complete(None, publish_completion=True) await delivery.complete(None, publish_completion=True)
async def _dispatch_one( async def _dispatch_one(
@@ -1625,32 +1644,28 @@ class AgentLoop:
recovery_task_registered = False recovery_task_registered = False
recovery_admission = self._recovery_admission recovery_admission = self._recovery_admission
current_task: asyncio.Task[Any] | None = None 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) lock = self._get_session_lock(session_key)
gate = self._concurrency_gate or nullcontext() gate = self._concurrency_gate or nullcontext()
delivery = self.turn_delivery_factory.unrouted(msg, session_key) delivery = self.turn_delivery_factory.unrouted(msg, session_key)
completion_published = False processing = False
skip_idle = False
try: try:
async with lock, gate: async with AsyncExitStack() as execution:
# 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
try: 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) await self.sessions.state.read(session_key)
delivery = self.turn_delivery_factory.create( delivery = self.turn_delivery_factory.create(
msg, msg,
@@ -1662,18 +1677,17 @@ class AgentLoop:
pending_queue=pending, pending_queue=pending,
delivery=delivery, delivery=delivery,
) )
continuing = delivery.continuation_pending await delivery.complete(response, publish_completion=True)
await delivery.complete(
response,
publish_completion=not continuing,
)
completion_published = not continuing
for coordinator in self._automation_turn_coordinators: for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, response=response) coordinator.complete(msg, response=response)
except asyncio.CancelledError: except asyncio.CancelledError as exc:
logger.info("Task cancelled for session {}", session_key) logger.info("Task cancelled for session {}", session_key)
# The queued continuation is cancelled with this session worker. if not processing:
delivery.continuation_pending = False if self.commands.requires_session_queue(command_text(msg)):
await delivery.complete(None, publish_completion=True)
raise
if delivery.completed:
raise exc
try: try:
await delivery.abort_stream() await delivery.abort_stream()
except Exception: except Exception:
@@ -1689,33 +1703,51 @@ class AgentLoop:
session_key in self._discarding_sessions session_key in self._discarding_sessions
or self._preserve_inflight_turns_on_shutdown or self._preserve_inflight_turns_on_shutdown
): ):
raise raise exc
key = self._effective_session_key(msg)
generation = delivery.delivery_message.session_generation
try: try:
key = self._effective_session_key(msg) session = await self.sessions.state.read(key)
session = await self.sessions.state.get(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) restore_runtime_checkpoint(session)
await self.sessions.state.finish_turn(session) await self.sessions.state.finish_turn(session)
logger.info("Saved cancelled turn for session {}", key) 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: except Exception:
logger.opt(exception=log_content).debug( logger.opt(exception=log_content).debug(
"Could not finalize cancelled turn for session {}", "Could not finalize cancelled turn for session {}",
session_key, session_key,
) )
raise await delivery.cancelled()
raise exc
except Exception as 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( logger.opt(exception=log_content).error(
"Error processing message for session {}", session_key, "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: for coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, error=exc) coordinator.complete(msg, error=exc)
finally: finally:
if not delivery.continuation_pending: if (processing or delivery.completed) and not skip_idle:
await delivery.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: finally:
if ( if (
recovery_task_registered recovery_task_registered
@@ -1873,9 +1905,6 @@ class AgentLoop:
else msg.content else msg.content
), ),
turn_wall_started_at=t0, turn_wall_started_at=t0,
visible_run_started_at=turn_continuation.internal_continuation_run_started_at(
msg.metadata,
),
events=output_events( events=output_events(
default=delivery.events, default=delivery.events,
on_progress=on_progress, on_progress=on_progress,
@@ -2123,15 +2152,15 @@ class AgentLoop:
loop=self, loop=self,
runtime=ctx.runtime, runtime=ctx.runtime,
is_user_turn=is_user_turn, is_user_turn=is_user_turn,
turn_scopes=ctx.turn_scopes,
) )
command_matched = self.commands.command_name(raw) is not None command_matched = self.commands.command_name(raw) is not None
result = await self.commands.dispatch(cmd_ctx) result = await self.commands.dispatch(cmd_ctx)
if isinstance(result, CommandExpansion):
result = await self._prepare_command_expansion(cmd_ctx, result)
if isinstance(result, InboundMessage): if isinstance(result, InboundMessage):
ctx.msg = result ctx.msg = result
result = None result = None
command_matched = False command_matched = False
ctx.turn_scopes.append(GoalInputScope(ctx.msg))
if result is not None: if result is not None:
ctx.outbound = result ctx.outbound = result
if cmd_ctx.raw.lower() == "/new": if cmd_ctx.raw.lower() == "/new":
@@ -2270,9 +2299,8 @@ class AgentLoop:
async def _run_turn(self, ctx: TurnContext) -> None: async def _run_turn(self, ctx: TurnContext) -> None:
runtime = ctx.require_runtime() runtime = ctx.require_runtime()
if ctx.visible_run_started_at is None: ctx.run_started_at = time.time()
ctx.visible_run_started_at = time.time() await ctx.delivery.running(started_at=ctx.run_started_at)
await ctx.delivery.running(started_at=ctx.visible_run_started_at)
assert ctx.transcript_input is not None assert ctx.transcript_input is not None
with capture_message_deliveries() as message_sends: with capture_message_deliveries() as message_sends:
result = await self._run_agent_loop( result = await self._run_agent_loop(
@@ -2285,10 +2313,10 @@ class AgentLoop:
run_extra_hooks_for_ephemeral=ctx.run_extra_hooks_for_ephemeral, run_extra_hooks_for_ephemeral=ctx.run_extra_hooks_for_ephemeral,
hooks=ctx.hooks, hooks=ctx.hooks,
hook_factories=ctx.hook_factories, hook_factories=ctx.hook_factories,
turn_scopes=ctx.turn_scopes,
tools=ctx.tools, tools=ctx.tools,
request_context=ctx.request_context, request_context=ctx.request_context,
provider_state=ctx.provider_state, provider_state=ctx.provider_state,
initial_message=ctx.msg,
events=ctx.events, events=ctx.events,
) )
ctx.final_content = result.final_content ctx.final_content = result.final_content
@@ -2305,11 +2333,6 @@ class AgentLoop:
ctx.suppress_response = True ctx.suppress_response = True
ctx.usage = result.usage ctx.usage = result.usage
ctx.delivery.record_usage(result.round_usages) 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: async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session() session = ctx.require_session()
@@ -2322,23 +2345,23 @@ class AgentLoop:
ctx.final_content = EMPTY_FINAL_RESPONSE_MESSAGE ctx.final_content = EMPTY_FINAL_RESPONSE_MESSAGE
latency_started_at = ( latency_started_at = (
ctx.visible_run_started_at ctx.run_started_at
if ( if ctx.kind is TurnKind.SYSTEM or turn_continuation.internal_continuation_inbound(ctx.msg.metadata)
ctx.kind is TurnKind.SYSTEM
or turn_continuation.internal_continuation_inbound(ctx.msg.metadata)
)
and ctx.visible_run_started_at is not None
else ctx.turn_wall_started_at else ctx.turn_wall_started_at
) )
ctx.turn_latency_ms = max(0, int((time.time() - latency_started_at) * 1000)) ctx.turn_latency_ms = max(0, int((time.time() - latency_started_at) * 1000))
ctx.delivery.record_latency(ctx.turn_latency_ms) 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: if ctx.usage is not None and not ctx.ephemeral:
session.metadata["_last_usage"] = ctx.usage.to_dict() session.metadata["_last_usage"] = ctx.usage.to_dict()
if ctx.kind is TurnKind.USER and not ctx.ephemeral: if ctx.kind is TurnKind.USER and not ctx.ephemeral:
turn_continuation.record_iteration_limit( turn_continuation.record_iteration_limit(
session.metadata, ctx.stop_reason, session.metadata, ctx.stop_reason,
continuation_pending=ctx.delivery.continuation_pending,
) )
self._save_turn( self._save_turn(
session, ctx.all_messages, ctx.save_skip, session, ctx.all_messages, ctx.save_skip,
@@ -2648,6 +2671,7 @@ class AgentLoop:
lock = self._get_session_lock(session_key) lock = self._get_session_lock(session_key)
with self.bus.admission.activity(): with self.bus.admission.activity():
temporary_parent = False temporary_parent = False
delivery: TurnDelivery | None = None
try: try:
async with lock: async with lock:
kwargs: dict[str, Any] = { kwargs: dict[str, Any] = {
@@ -2684,6 +2708,8 @@ class AgentLoop:
kwargs["on_runtime_admitted"] = on_runtime_admitted kwargs["on_runtime_admitted"] = on_runtime_admitted
if attributes is not None: if attributes is not None:
kwargs["attributes"] = dict(attributes) kwargs["attributes"] = dict(attributes)
delivery = self.turn_delivery_factory.create(msg, session_key)
kwargs["delivery"] = delivery
try: try:
return await self._process_message(msg, **kwargs) return await self._process_message(msg, **kwargs)
finally: finally:
@@ -2693,7 +2719,8 @@ class AgentLoop:
await self.sessions.state.delete(session_key, expected_generation=parent.generation) await self.sessions.state.delete(session_key, expected_generation=parent.generation)
finally: finally:
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle") 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: def _get_session_lock(self, session_key: str) -> asyncio.Lock:
lock = self._session_locks.get(session_key) lock = self._session_locks.get(session_key)
+109 -139
View File
@@ -20,6 +20,7 @@ from nanobot.agent.context_governance import (
ProviderCompactionConsolidator, ProviderCompactionConsolidator,
TranscriptBuilder, TranscriptBuilder,
) )
from nanobot.agent.execution_policy import ExecutionControlError
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.context import tool_log_content_allowed from nanobot.agent.tools.context import tool_log_content_allowed
from nanobot.agent.tools.execution import execute_tool_calls from nanobot.agent.tools.execution import execute_tool_calls
@@ -39,7 +40,7 @@ from nanobot.providers.base import (
ProviderConversationState, ProviderConversationState,
) )
from nanobot.providers.conversation_state import ProviderConversationStateController 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.session.summary import SessionSummaryCheckpoint
from nanobot.utils.helpers import ( from nanobot.utils.helpers import (
build_assistant_message, build_assistant_message,
@@ -138,7 +139,7 @@ class AgentRunResult:
failure_error_kind: str | None = None failure_error_kind: str | None = None
tool_events: list[dict[str, str]] = field(default_factory=list) tool_events: list[dict[str, str]] = field(default_factory=list)
had_injections: bool = False 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 pending_stream_content: str | None = None
provider_state: ProviderConversationState | None = field(default=None, repr=False) provider_state: ProviderConversationState | None = field(default=None, repr=False)
summary_checkpoint: SessionSummaryCheckpoint | None = field(default=None, repr=False) summary_checkpoint: SessionSummaryCheckpoint | None = field(default=None, repr=False)
@@ -177,84 +178,33 @@ class AgentRunner:
self, self,
spec: AgentRunSpec, spec: AgentRunSpec,
messages: list[dict[str, Any]], messages: list[dict[str, Any]],
assistant_message: dict[str, Any] | None,
injection_cycles: int,
*, *,
conversation_state: ProviderConversationStateController | None = None, phase: str,
phase: str = "after error", terminal: bool = False,
iteration: int | None = None, ) -> bool:
allow_continuation: bool = False, injections = await self._drain_injections(spec, terminal=terminal)
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)
if not injections: if not injections:
return False, injection_cycles return False
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,
)
self._append_injected_messages(messages, injections) self._append_injected_messages(messages, injections)
if real_injection: preview = "[content hidden]"
preview = "[content hidden]" if tool_log_content_allowed():
if tool_log_content_allowed(): preview = "\n\n".join(
preview = "\n\n".join( content for message in injections
message["content"] for message in injections if isinstance(content := message.get("content"), str)
if isinstance(message.get("content"), str) and not is_hidden_history_message(message)
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,
) )
else: preview = preview[:80] + "..." if len(preview) > 80 else preview
logger.info("Injected caller-requested continuation {}", phase) logger.info(
return True, injection_cycles "Injected {} follow-up message(s) {}: {}",
len(injections), phase, preview,
)
return True
@staticmethod @staticmethod
async def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None: async def _continuation_prompt(spec: AgentRunSpec) -> str | None:
callback = spec.continuation_callback prompt = await spec.continuation_callback() if spec.continuation_callback is not None else None
if callback is None: _raise_if_cancelling()
return None return prompt
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 _drain_injections( async def _drain_injections(
self, self,
@@ -271,6 +221,8 @@ class AgentRunner:
return [] return []
try: try:
items = await callback() items = await callback()
except ExecutionControlError:
raise
except Exception: except Exception:
logger.opt(exception=tool_log_content_allowed()).error("injection_callback failed") logger.opt(exception=tool_log_content_allowed()).error("injection_callback failed")
return [] return []
@@ -424,7 +376,6 @@ class AgentRunner:
length_recovery_parts: list[str] = [] length_recovery_parts: list[str] = []
pending_length_segment: tuple[AgentHookContext, str] | None = None pending_length_segment: tuple[AgentHookContext, str] | None = None
had_injections = False had_injections = False
injection_cycles = 0
pending_stream_content: str | None = None pending_stream_content: str | None = None
conversation_state = ProviderConversationStateController( conversation_state = ProviderConversationStateController(
provider=spec.runtime.provider, provider=spec.runtime.provider,
@@ -464,19 +415,25 @@ class AgentRunner:
segment_context.stream_continues_current_message = not interrupted segment_context.stream_continues_current_message = not interrupted
await hook.on_stream_end(segment_context, resuming=True) 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. # A resumed iteration must not inherit a previous iteration's failure.
stop_reason = "completed" stop_reason = "completed"
error = None error = None
# The session inbox cuts a finite snapshot before every model call. # The session inbox cuts a finite snapshot before every model call.
# This includes follow-ups that arrived before the first request and # This includes follow-ups that arrived before the first request and
# messages received while the previous request or tools were running. # messages received while the previous request or tools were running.
drained_before_request, injection_cycles = await self._try_drain_injections( drained_before_request = await self._try_drain_injections(
spec, spec, messages, phase="before model call",
messages,
None,
injection_cycles,
phase="before model call",
) )
if drained_before_request: if drained_before_request:
had_injections = True had_injections = True
@@ -722,6 +679,20 @@ class AgentRunner:
assistant_message, assistant_message,
response, 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": if response.finish_reason == "error":
interrupted_parts = [ interrupted_parts = [
@@ -743,22 +714,32 @@ class AgentRunner:
# Check for mid-turn injections BEFORE signaling stream end. # Check for mid-turn injections BEFORE signaling stream end.
# If injections are found we keep the stream alive (resuming=True) # If injections are found we keep the stream alive (resuming=True)
# so streaming channels don't prematurely finalize the card. # so streaming channels don't prematurely finalize the card.
can_make_followup_request = iteration + 1 < spec.max_iterations normal_response = (
should_continue, injection_cycles = await self._try_drain_injections( assistant_message is not None
spec, messages, assistant_message, injection_cycles, and response.finish_reason not in {"error", "length", "refusal", "content_filter"}
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,
) )
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: if should_continue:
had_injections = True had_injections = True
@@ -766,6 +747,7 @@ class AgentRunner:
await hook.on_stream_end(context, resuming=should_continue) await hook.on_stream_end(context, resuming=should_continue)
if should_continue: if should_continue:
followup_requested = True
length_recovery_parts.clear() length_recovery_parts.clear()
await hook.after_iteration(context) await hook.after_iteration(context)
continue continue
@@ -782,12 +764,9 @@ class AgentRunner:
context.error = error context.error = error
context.stop_reason = stop_reason context.stop_reason = stop_reason
await hook.after_iteration(context) await hook.after_iteration(context)
should_continue, injection_cycles = await self._try_drain_injections( if can_make_followup_request and await self._try_drain_injections(
spec, messages, None, injection_cycles, spec, messages, phase="after LLM error",
phase="after LLM error", ):
drain_callback=can_make_followup_request,
)
if should_continue:
had_injections = True had_injections = True
length_recovery_parts.clear() length_recovery_parts.clear()
continue continue
@@ -802,41 +781,14 @@ class AgentRunner:
context.error = error context.error = error
context.stop_reason = stop_reason context.stop_reason = stop_reason
await hook.after_iteration(context) await hook.after_iteration(context)
should_continue, injection_cycles = await self._try_drain_injections( if can_make_followup_request and await self._try_drain_injections(
spec, messages, None, injection_cycles, spec, messages, phase="after empty response",
phase="after empty response", ):
drain_callback=can_make_followup_request,
)
if should_continue:
had_injections = True had_injections = True
length_recovery_parts.clear() length_recovery_parts.clear()
continue continue
break 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: if length_recovery_parts:
final_content = ( final_content = (
"".join(length_recovery_parts) "".join(length_recovery_parts)
@@ -849,20 +801,33 @@ class AgentRunner:
await hook.after_iteration(context) await hook.after_iteration(context)
break break
else: else:
stop_reason = "max_iterations"
terminal_content = None
await end_length_segment(interrupted=False) 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: if spec.finalize_on_max_iterations:
terminal_content, usage = await self._try_finalize_after_max_iterations( terminal_content, usage = await self._try_finalize_after_max_iterations(
spec, spec,
hook, hook,
messages, messages,
usage, usage,
iteration=iteration + 1,
request_state=request_state, request_state=request_state,
round_usages=round_usages, 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: 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: if length_recovery_parts:
terminal_tail = f"\n\n{terminal_content.lstrip()}" terminal_tail = f"\n\n{terminal_content.lstrip()}"
final_content = ( final_content = (
@@ -1169,7 +1134,7 @@ class AgentRunner:
# Advancing it after dropping even one call would replay an unmatched # Advancing it after dropping even one call would replay an unmatched
# call without a corresponding tool output on the next request. # call without a corresponding tool output on the next request.
response.provider_state = None response.provider_state = None
if not valid: if not valid and original_finish_reason in ("tool_calls", "function_call"):
response.finish_reason = "stop" response.finish_reason = "stop"
return (dropped, not valid, original_finish_reason) return (dropped, not valid, original_finish_reason)
@@ -1229,12 +1194,17 @@ class AgentRunner:
messages: list[dict[str, Any]], messages: list[dict[str, Any]],
usage: LLMUsage | None, usage: LLMUsage | None,
*, *,
iteration: int,
request_state: ModelRequestState, request_state: ModelRequestState,
round_usages: list[LLMUsage], round_usages: list[LLMUsage],
) -> tuple[str | None, LLMUsage | None]: ) -> tuple[str | None, LLMUsage | None]:
compaction = request_state.compaction compaction = request_state.compaction
request_messages = await self.prepare_prompt(compaction.request_messages, messages) 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: try:
response = await self._request_no_tools( response = await self._request_no_tools(
spec, spec,
@@ -1263,7 +1233,7 @@ class AgentRunner:
return None, usage return None, usage
context = AgentHookContext( context = AgentHookContext(
iteration=spec.max_iterations, iteration=iteration,
messages=messages, messages=messages,
response=response, response=response,
usage=raw_usage, usage=raw_usage,
+35 -12
View File
@@ -6,6 +6,7 @@ from collections.abc import Awaitable, Callable
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast from typing import TYPE_CHECKING, Any, cast
from uuid import uuid4
from nanobot.bus.delivery import DeliveryRequest from nanobot.bus.delivery import DeliveryRequest
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -33,6 +34,7 @@ from nanobot.session.keys import (
is_internal_session, is_internal_session,
last_channel_from_metadata, last_channel_from_metadata,
) )
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import strip_think from nanobot.utils.helpers import strip_think
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -205,7 +207,7 @@ class TurnDelivery:
route: TurnRoute route: TurnRoute
route_admission: TurnRouteAdmission | None = None route_admission: TurnRouteAdmission | None = None
enable_stream: bool = False enable_stream: bool = False
continuation_pending: bool = field(init=False, default=False) run_id: str = field(init=False)
delivery_message: InboundMessage = field(init=False) delivery_message: InboundMessage = field(init=False)
lifecycle_message: InboundMessage = field(init=False) lifecycle_message: InboundMessage = field(init=False)
_stream_base_id: str | None = field(init=False, default=None) _stream_base_id: str | None = field(init=False, default=None)
@@ -213,6 +215,7 @@ class TurnDelivery:
_stream_open: bool = field(init=False, default=False) _stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False) events: EventSink = field(init=False)
_routed_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) _stop_reason: str | None = field(init=False, default=None)
_failure_error_kind: 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) _retry_status: RetryStatusEvent | None = field(init=False, default=None)
@@ -223,6 +226,7 @@ class TurnDelivery:
_stream_source_unknown: bool = field(init=False, default=False) _stream_source_unknown: bool = field(init=False, default=False)
def __post_init__(self) -> None: def __post_init__(self) -> None:
self.run_id = uuid4().hex
self._routed_events = _bind_events(self.bus, self.route, self.session_key) self._routed_events = _bind_events(self.bus, self.route, self.session_key)
self.events = EventSink(self._publish_event, self._routed_events.accepts) self.events = EventSink(self._publish_event, self._routed_events.accepts)
self.delivery_message = dataclasses.replace( self.delivery_message = dataclasses.replace(
@@ -299,15 +303,16 @@ class TurnDelivery:
self.delivery_message, self.delivery_message,
self.session_key, self.session_key,
runtime, runtime,
run_id=self.run_id,
) )
return 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: 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: 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( def record_stop_reason(
self, self,
@@ -390,11 +395,9 @@ class TurnDelivery:
) )
if publish_completion: if publish_completion:
outcome, failure_kind = _turn_outcome(stop_reason) outcome, failure_kind = _turn_outcome(stop_reason)
await self.runtime_event_publisher.turn_completed( await self._publish_completion(
channel=completed_channel, channel=completed_channel,
chat_id=completed_chat_id, chat_id=completed_chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome=outcome, outcome=outcome,
failure_kind=failure_kind, failure_kind=failure_kind,
failure_error_kind=(self._failure_error_kind or ( 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: async def fail(self, *, publish_completion: bool) -> None:
await self.bus.publish_outbound( await self.bus.publish_outbound(
OutboundMessage( OutboundMessage(
@@ -415,14 +421,31 @@ class TurnDelivery:
) )
) )
if publish_completion: 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( await self.runtime_event_publisher.turn_completed(
channel=self.lifecycle_message.channel, channel=channel if channel is not None else self.lifecycle_message.channel,
chat_id=self.lifecycle_message.chat_id, chat_id=chat_id if chat_id is not None else self.lifecycle_message.chat_id,
session_key=self.session_key, session_key=self.session_key,
metadata=self.lifecycle_message.metadata, metadata=self.lifecycle_message.metadata,
outcome="failed", outcome=outcome,
failure_kind="internal", 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: async def idle(self) -> None:
await self.runtime_event_publisher.run_status_changed( await self.runtime_event_publisher.run_status_changed(
@@ -430,7 +453,7 @@ class TurnDelivery:
self.session_key, self.session_key,
"idle", "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: def _stream_id(self) -> str:
assert self._stream_base_id is not None assert self._stream_base_id is not None
+30 -24
View File
@@ -114,10 +114,10 @@ class RuntimeEventPublisher:
def __init__(self, bus: MessageBus) -> None: def __init__(self, bus: MessageBus) -> None:
self.bus = bus self.bus = bus
self._turn_latency_ms: dict[str, int] = {} self._turn_latency_ms: dict[tuple[str, str | None], int] = {}
self._turn_runtime: dict[str, LLMRuntime] = {} self._turn_runtime: dict[tuple[str, str | None], LLMRuntime] = {}
self._turn_usage: dict[str, LLMUsage] = {} self._turn_usage: dict[tuple[str, str | None], LLMUsage] = {}
self._turn_round_usages: dict[str, tuple[LLMUsage, ...]] = {} self._turn_round_usages: dict[tuple[str, str | None], tuple[LLMUsage, ...]] = {}
@staticmethod @staticmethod
def _context( def _context(
@@ -138,17 +138,22 @@ class RuntimeEventPublisher:
attributes=dict(attributes or {}), attributes=dict(attributes or {}),
) )
def record_turn_runtime(self, session_key: str, runtime: LLMRuntime) -> None: def record_turn_runtime(
self._turn_runtime[session_key] = 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: 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( def record_turn_usage(
self, self,
session_key: str, session_key: str,
round_usages: list[LLMUsage], round_usages: list[LLMUsage],
*, run_id: str | None = None,
) -> None: ) -> None:
if not round_usages: if not round_usages:
return return
@@ -156,18 +161,16 @@ class RuntimeEventPublisher:
usage = round_usages[0] usage = round_usages[0]
for round_usage in round_usages[1:]: for round_usage in round_usages[1:]:
usage += round_usage usage += round_usage
previous = self._turn_usage.get(session_key) key = (session_key, run_id)
self._turn_usage[session_key] = usage if previous is None else previous + usage self._turn_usage[key] = usage
self._turn_round_usages[session_key] = ( self._turn_round_usages[key] = tuple(round_usages)
*self._turn_round_usages.get(session_key, ()),
*round_usages,
)
def clear_turn(self, session_key: str) -> None: def clear_turn(self, session_key: str, *, run_id: str | None = None) -> None:
self._turn_latency_ms.pop(session_key, None) key = (session_key, run_id)
self._turn_runtime.pop(session_key, None) self._turn_latency_ms.pop(key, None)
self._turn_usage.pop(session_key, None) self._turn_runtime.pop(key, None)
self._turn_round_usages.pop(session_key, None) self._turn_usage.pop(key, None)
self._turn_round_usages.pop(key, None)
async def user_input_accepted( async def user_input_accepted(
self, self,
@@ -209,9 +212,10 @@ class RuntimeEventPublisher:
msg: InboundMessage, msg: InboundMessage,
session_key: str, session_key: str,
runtime: LLMRuntime, runtime: LLMRuntime,
*, run_id: str | None = None,
) -> None: ) -> None:
"""Record and publish the runtime selected for one turn.""" """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( await self.bus.publish(
TurnRuntimeAdmitted( TurnRuntimeAdmitted(
context=self._context( context=self._context(
@@ -281,7 +285,9 @@ class RuntimeEventPublisher:
failure_kind: str | None = None, failure_kind: str | None = None,
failure_error_kind: str | None = None, failure_error_kind: str | None = None,
failure_attempts: int | None = None, failure_attempts: int | None = None,
run_id: str | None = None,
) -> None: ) -> None:
key = (session_key, run_id)
await self.bus.publish( await self.bus.publish(
TurnCompleted( TurnCompleted(
context=self._context( context=self._context(
@@ -290,10 +296,10 @@ class RuntimeEventPublisher:
session_key=session_key, session_key=session_key,
metadata=metadata, metadata=metadata,
), ),
latency_ms=self._turn_latency_ms.pop(session_key, None), latency_ms=self._turn_latency_ms.pop(key, None),
runtime=self._turn_runtime.pop(session_key, None), runtime=self._turn_runtime.pop(key, None),
usage=self._turn_usage.pop(session_key, None), usage=self._turn_usage.pop(key, None),
round_usages=self._turn_round_usages.pop(session_key, ()), round_usages=self._turn_round_usages.pop(key, ()),
outcome=outcome, outcome=outcome,
failure_kind=failure_kind, failure_kind=failure_kind,
failure_error_kind=failure_error_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.outbound_events import ContextCompactionEvent, ProgressEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel 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.network import NetworkConfig
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config_base import Base from nanobot.config_base import Base
@@ -21,7 +21,7 @@ from nanobot.channels.discord.runtime import (
DiscordChannel, DiscordChannel,
DiscordConfig, DiscordConfig,
) )
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.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.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel 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.command.router import normalize_command_text
from nanobot.config.network import NetworkConfig from nanobot.config.network import NetworkConfig
from nanobot.config.paths import get_data_dir, get_media_dir 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.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel 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.network import NetworkConfig
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config_base import Base 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) mcp_provider = MCPProvider.from_config(runtime_config, tools)
_set_nanobot_logs(logs) _set_nanobot_logs(logs)
from nanobot.goal.assembly import install_goal
try: try:
agent_loop = agent_loop_class.from_config( 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, cron_service=cron,
hook_factories=[create_file_edit_activity_hook], hook_factories=[create_file_edit_activity_hook],
tool_registry=tools, tool_registry=tools,
builtin_assembly=install_goal,
) )
except ValueError as exc: except ValueError as exc:
_print_agent_start_error(exc) _print_agent_start_error(exc)
+3
View File
@@ -381,6 +381,8 @@ def serve(
build_unconfigured_provider_snapshot(runtime_config, setup_error).provider build_unconfigured_provider_snapshot(runtime_config, setup_error).provider
if setup_error else None if setup_error else None
) )
from nanobot.goal.assembly import install_goal
try: try:
agent_loop = AgentLoop.from_config( agent_loop = AgentLoop.from_config(
runtime_config, bus, runtime_config, bus,
@@ -388,6 +390,7 @@ def serve(
session_manager=session_manager, session_manager=session_manager,
hook_factories=[create_file_edit_activity_hook], hook_factories=[create_file_edit_activity_hook],
tool_registry=tools, tool_registry=tools,
builtin_assembly=install_goal,
) )
except ValueError as exc: except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]") 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, unified_session=config.agents.defaults.unified_session,
) )
from nanobot.goal.assembly import install_goal
agent = AgentLoop.from_config( agent = AgentLoop.from_config(
config, bus, config, bus,
provider=provider_snapshot.provider, provider=provider_snapshot.provider,
@@ -609,7 +611,9 @@ def _run_claimed_gateway(
hook_factories=[create_file_edit_activity_hook], hook_factories=[create_file_edit_activity_hook],
tool_registry=tools, tool_registry=tools,
recovery_admission=recovery, recovery_admission=recovery,
builtin_assembly=install_goal,
) )
def _schedule_webui_background(awaitable: Awaitable[None]) -> None: def _schedule_webui_background(awaitable: Awaitable[None]) -> None:
agent.schedule_background(cast(Coroutine[Any, Any, None], awaitable)) 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 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"] __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 os
import subprocess import subprocess
import sys import sys
import time
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass, replace from dataclasses import replace
from typing import TYPE_CHECKING, Any, Literal, cast from typing import TYPE_CHECKING, Any, cast
from loguru import logger from loguru import logger
from nanobot import __version__ from nanobot import __version__
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text 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.providers.base import LLMUsage
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.utils.cancellation import shield_and_drain from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import build_status_content from nanobot.utils.helpers import build_status_content
from nanobot.utils.restart import set_restart_notice_to_env 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.session.manager import Session
from nanobot.utils.gitstore import CommitInfo 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" USER_SHELL_COMMAND = "/__shell"
@dataclass(frozen=True) CORE_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
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, ...] = (
BuiltinCommandSpec( BuiltinCommandSpec(
"/new", "/new",
"New chat", "New chat",
@@ -114,15 +78,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
"[n]", "[n]",
accepts_args=True, 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( BuiltinCommandSpec(
"/trigger", "/trigger",
"Create named local 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: async def cmd_stop(ctx: CommandContext) -> OutboundMessage:
"""Cancel all active tasks and subagents for the session.""" """Cancel all active tasks and subagents for the session."""
loop = ctx.loop 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: async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
"""List, approve, deny or revoke pairing requests.""" """List, approve, deny or revoke pairing requests."""
from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command
@@ -1019,7 +919,7 @@ async def cmd_help(ctx: CommandContext) -> OutboundMessage:
return OutboundMessage( return OutboundMessage(
channel=ctx.msg.channel, channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id, 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"}, 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) return await ctx.loop.execute_user_shell_command(ctx)
def build_help_text() -> str: def build_help_text(specs: tuple[BuiltinCommandSpec, ...] = CORE_COMMAND_SPECS) -> str:
"""Build canonical help text shared across channels.""" """Build help text for the commands registered in one application."""
lines = ["🐈 nanobot commands:"] lines = ["🐈 nanobot commands:"]
for spec in BUILTIN_COMMAND_SPECS: for spec in specs:
command = spec.command command = spec.command
if spec.arg_hint: if spec.arg_hint:
command = f"{command} {spec.arg_hint}" command = f"{command} {spec.arg_hint}"
@@ -1059,8 +959,10 @@ def build_help_text() -> str:
return "\n".join(lines) return "\n".join(lines)
def register_builtin_commands(router: CommandRouter) -> None: def register_core_commands(router: CommandRouter) -> None:
"""Register the default set of slash commands.""" """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("/stop", cmd_stop)
router.priority("/restart", cmd_restart) router.priority("/restart", cmd_restart)
router.priority("/status", cmd_status) router.priority("/status", cmd_status)
@@ -1071,8 +973,6 @@ def register_builtin_commands(router: CommandRouter) -> None:
router.prefix("/model ", cmd_model) router.prefix("/model ", cmd_model)
router.exact("/history", cmd_history) router.exact("/history", cmd_history)
router.prefix("/history ", cmd_history) router.prefix("/history ", cmd_history)
router.exact("/goal", cmd_goal)
router.prefix("/goal ", cmd_goal)
router.exact("/trigger", cmd_trigger) router.exact("/trigger", cmd_trigger)
router.prefix("/trigger ", cmd_trigger) router.prefix("/trigger ", cmd_trigger)
router.exact("/dream", cmd_dream) router.exact("/dream", cmd_dream)
+45 -6
View File
@@ -1,21 +1,39 @@
from __future__ import annotations from __future__ import annotations
import re import re
from contextlib import AbstractContextManager
from dataclasses import dataclass, field 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.bus.events import InboundMessage, OutboundMessage
from nanobot.command.spec import BuiltinCommandSpec
if TYPE_CHECKING: if TYPE_CHECKING:
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.session.manager import Session from nanobot.session.manager import Session
from nanobot.utils.llm_runtime import LLMRuntime 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_]+$") _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: def command_text(message: InboundMessage) -> str:
"""Return routable text; command-generated agent input must not be dispatched again.""" """Return routable text; command-generated agent input must not be dispatched again."""
return "" if message.metadata.get("original_command") else message.content.strip() return "" if message.metadata.get("original_command") else message.content.strip()
@@ -52,7 +70,6 @@ class CommandContext:
loop: AgentLoop = field(kw_only=True) loop: AgentLoop = field(kw_only=True)
runtime: LLMRuntime | None = None runtime: LLMRuntime | None = None
is_user_turn: bool = False is_user_turn: bool = False
turn_scopes: list[AbstractContextManager[Any]] = field(default_factory=list)
class CommandRouter: class CommandRouter:
@@ -70,6 +87,24 @@ class CommandRouter:
self._exact: dict[str, Handler] = {} self._exact: dict[str, Handler] = {}
self._prefix: list[tuple[str, Handler]] = [] self._prefix: list[tuple[str, Handler]] = []
self._session_commands: set[str] = set() 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: def priority(self, cmd: str, handler: Handler) -> None:
self._priority[cmd] = handler self._priority[cmd] = handler
@@ -119,7 +154,9 @@ class CommandRouter:
return True return True
return self.command_name(text) is not None 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.""" """Dispatch a priority command. Called from run() without the lock."""
ctx.raw = normalize_command_text(ctx.raw) ctx.raw = normalize_command_text(ctx.raw)
handler = self._priority.get(ctx.raw.lower()) handler = self._priority.get(ctx.raw.lower())
@@ -127,7 +164,9 @@ class CommandRouter:
return await handler(ctx) return await handler(ctx)
return None 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.""" """Try exact and prefix handlers, then validate registered commands."""
if ctx.msg.metadata.get("original_command"): if ctx.msg.metadata.get("original_command"):
return None 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, revoke_goal_mutation_permission,
) )
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters 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.agent.tools.schema import StringSchema, tool_parameters_schema
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
@@ -26,7 +26,6 @@ from nanobot.session.goal_state import (
parse_goal_state, parse_goal_state,
sustained_goal_active, sustained_goal_active,
) )
from nanobot.session.turn_continuation import reset_goal_continuation_rounds
from nanobot.utils.cancellation import shield_and_drain from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.prompt_templates import render_template from nanobot.utils.prompt_templates import render_template
@@ -62,12 +61,16 @@ class _GoalToolsMixin:
async def _session(self) -> Session | None: async def _session(self) -> Session | None:
request_ctx = current_request_context() request_ctx = current_request_context()
if request_ctx is None: if request_ctx is None or not request_ctx.persist_session:
return None return None
key = request_ctx.session_key key = request_ctx.session_key
if not key: generation = request_ctx.session_generation
if not key or not generation:
return None 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: def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed() return current_request_context() is not None and goal_mutation_allowed()
@@ -77,7 +80,6 @@ class _GoalToolsMixin:
sess: Session, sess: Session,
blob: dict[str, Any], blob: dict[str, Any],
*, *,
reset_continuation: bool = False,
revoke_permission: bool = False, revoke_permission: bool = False,
) -> None: ) -> None:
saved = False saved = False
@@ -87,8 +89,6 @@ class _GoalToolsMixin:
def change(metadata: dict[str, Any]) -> None: def change(metadata: dict[str, Any]) -> None:
metadata[GOAL_STATE_KEY] = deepcopy(blob) metadata[GOAL_STATE_KEY] = deepcopy(blob)
discard_legacy_goal_state_key(metadata) discard_legacy_goal_state_key(metadata)
if reset_continuation:
reset_goal_continuation_rounds(metadata)
_, sess.metadata = await self._sessions.state.mutate_metadata( _, sess.metadata = await self._sessions.state.mutate_metadata(
sess.key, change, expected_generation=sess.generation, sess.key, change, expected_generation=sess.generation,
) )
@@ -150,18 +150,8 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
_GoalToolsMixin.__init__(self, sessions, bus) _GoalToolsMixin.__init__(self, sessions, bus)
@classmethod @classmethod
def create(cls, ctx: ToolContext) -> Tool: def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:
sess = ctx.sessions return cls(sessions=sessions, bus=bus)
if sess is None:
raise RuntimeError("CreateGoalTool requires an initialized session manager")
return cls(
sessions=sess,
bus=ctx.bus,
)
@classmethod
def enabled(cls, ctx: ToolContext) -> bool:
return ctx.sessions is not None
@property @property
def name(self) -> str: def name(self) -> str:
@@ -236,7 +226,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
"ui_summary": summary, "ui_summary": summary,
"started_at": _iso_now(), "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 "" extra = f"\nSummary line: {summary}" if summary else ""
return ( return (
"Goal recorded. Keep working toward the objective using ordinary tools. " "Goal recorded. Keep working toward the objective using ordinary tools. "
@@ -281,18 +271,8 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
_GoalToolsMixin.__init__(self, sessions, bus) _GoalToolsMixin.__init__(self, sessions, bus)
@classmethod @classmethod
def create(cls, ctx: ToolContext) -> Tool: def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:
sess = ctx.sessions return cls(sessions=sessions, bus=bus)
if sess is None:
raise RuntimeError("UpdateGoalTool requires an initialized session manager")
return cls(
sessions=sess,
bus=ctx.bus,
)
@classmethod
def enabled(cls, ctx: ToolContext) -> bool:
return ctx.sessions is not None
@property @property
def name(self) -> str: def name(self) -> str:
@@ -350,7 +330,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
"previous_objective": str(prior.get("objective") or ""), "previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(), "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 "" extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
+3
View File
@@ -132,10 +132,13 @@ class Nanobot:
tools = ToolRegistry() tools = ToolRegistry()
register_image_generation_tool(config, tools, workspace=config.workspace_path) register_image_generation_tool(config, tools, workspace=config.workspace_path)
mcp_provider = MCPProvider.from_config(config, tools) mcp_provider = MCPProvider.from_config(config, tools)
from nanobot.goal.assembly import install_goal
loop = AgentLoop.from_config( loop = AgentLoop.from_config(
config, config,
hook_factories=[create_file_edit_activity_hook], hook_factories=[create_file_edit_activity_hook],
tool_registry=tools, tool_registry=tools,
builtin_assembly=install_goal,
) )
return cls(loop, config=config, mcp_provider=mcp_provider) return cls(loop, config=config, mcp_provider=mcp_provider)
+1 -33
View File
@@ -1,8 +1,7 @@
"""Session metadata helpers for explicit sustained goals. """Session metadata helpers for explicit sustained goals.
Tools set ``metadata[GOAL_STATE_KEY]``. Reads accept the legacy session key ``thread_goal`` 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 for older sessions. Callers can read the goal without importing tool implementations.
importing tool implementations.
""" """
from __future__ import annotations from __future__ import annotations
@@ -15,7 +14,6 @@ GOAL_COMMAND = "/goal"
MAX_GOAL_OBJECTIVE_CHARS = 4000 MAX_GOAL_OBJECTIVE_CHARS = 4000
# Older builds stored the same JSON blob under this key. # Older builds stored the same JSON blob under this key.
_LEGACY_GOAL_STATE_SESSION_KEY = "thread_goal" _LEGACY_GOAL_STATE_SESSION_KEY = "thread_goal"
_MAX_OBJECTIVE_WS = 600
def _session_goal_raw(metadata: Mapping[str, Any] | None) -> Any: 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 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: def parse_goal_state(blob: Any) -> dict[str, Any] | None:
if blob is None: if blob is None:
return None return None
@@ -91,24 +80,3 @@ def goal_state_runtime_lines(metadata: Mapping[str, Any] | None) -> list[str]:
if hint: if hint:
out.append(f"Summary: {hint}") out.append(f"Summary: {hint}")
return out 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", "_stopped_at_iteration_limit",
PARENT_SESSION_KEY, PARENT_SESSION_KEY,
SESSION_TYPE_KEY, SESSION_TYPE_KEY,
"goal_state",
"pending_user_turn", "pending_user_turn",
"pending_user_followups", "pending_user_followups",
"runtime_checkpoint", "runtime_checkpoint",
"session_handle", "session_handle",
"webui_recovery", "webui_recovery",
"thread_goal",
"title", "title",
"title_user_edited", "title_user_edited",
} }
@@ -374,7 +372,10 @@ class SessionInfo(TypedDict):
path: str 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.""" """Build a portable fork ending before the requested visible user message."""
if before_user_index < 0: if before_user_index < 0:
return None return None
@@ -394,7 +395,7 @@ def fork_session(source: Session, target_key: str, before_user_index: int) -> Se
return None return None
metadata = deepcopy(source.metadata) metadata = deepcopy(source.metadata)
for key in _FORK_VOLATILE_METADATA_KEYS: for key in _FORK_VOLATILE_METADATA_KEYS | exclude_metadata:
metadata.pop(key, None) metadata.pop(key, None)
last_consolidated = min(source.last_archived, len(copied)) last_consolidated = min(source.last_archived, len(copied))
@@ -432,15 +433,23 @@ class SessionManager:
self._store.initialize() self._store.initialize()
self._delete_observer: Callable[[str], None] | None = None self._delete_observer: Callable[[str], None] | None = None
self.types = SessionTypes() self.types = SessionTypes()
self._generation_exclusions: set[str] = set()
self._state: SessionState | None = None 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 @property
def state(self) -> SessionState: def state(self) -> SessionState:
"""The asynchronous owner of session state transitions.""" """The asynchronous owner of session state transitions."""
if self._state is None: if self._state is None:
from nanobot.session.state import SessionState 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 return self._state
def _notify_delete(self, key: str) -> None: def _notify_delete(self, key: str) -> None:
@@ -555,7 +564,9 @@ class SessionManager:
source = self._store.load(source_key) source = self._store.load(source_key)
if source is None: if source is None:
return 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: if target is not None:
self._store.save(target) self._store.save(target)
self._store.copy_history_prefix(source_key, target, before_user_index) 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, workers: int = _DEFAULT_WORKERS,
on_delete: Callable[[str], None] | None = None, on_delete: Callable[[str], None] | None = None,
types: SessionTypes | None = None, types: SessionTypes | None = None,
generation_exclusions: set[str] | None = None,
) -> None: ) -> None:
if capacity < 1: if capacity < 1:
raise ValueError("session operation capacity must be positive") raise ValueError("session operation capacity must be positive")
if workers < 1: if workers < 1:
raise ValueError("session operation worker count must be positive") raise ValueError("session operation worker count must be positive")
self._types = types if types is not None else SessionTypes() 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._store = store
self._on_delete = on_delete self._on_delete = on_delete
self._snapshots: dict[str, Session] = {} self._snapshots: dict[str, Session] = {}
@@ -426,6 +430,15 @@ class SessionState:
return self._draft(session) return self._draft(session)
return await self._execute(key, read, write=False) 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: async def get(self, key: str) -> Session:
"""Read an existing conversation; create missing state on the writer.""" """Read an existing conversation; create missing state on the writer."""
return await self._get(key, history=True) return await self._get(key, history=True)
@@ -661,7 +674,7 @@ class SessionState:
await self._submit_draft(session) await self._submit_draft(session)
async def finish_turn(self, session: Session) -> None: 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(_PENDING_KEY, None)
session.metadata.pop(_CHECKPOINT_KEY, None) session.metadata.pop(_CHECKPOINT_KEY, None)
await self._submit_draft(session) await self._submit_draft(session)
@@ -997,7 +1010,9 @@ class SessionState:
source = self._load(source_key) source = self._load(source_key)
if source is None: if source is None:
return 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: if target is None:
return None return None
if title: if title:
@@ -1145,6 +1160,8 @@ class SessionState:
session.metadata = deepcopy(old.metadata) session.metadata = deepcopy(old.metadata)
for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"): for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"):
session.metadata.pop(name, None) session.metadata.pop(name, None)
for name in self._generation_exclusions:
session.metadata.pop(name, None)
if session.policy.persist: if session.policy.persist:
self._store.delete(key, preserve_archive=True) self._store.delete(key, preserve_archive=True)
self._commit(session) self._commit(session)
+8 -260
View File
@@ -1,51 +1,23 @@
"""Internal turn continuation helpers. """Bookkeeping for explicit recovery inputs and ordinary iteration-limit stops."""
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.
"""
from __future__ import annotations from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, Mapping, MutableMapping from typing import TYPE_CHECKING, Any, Mapping, MutableMapping
from loguru import logger
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines 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: if TYPE_CHECKING:
from nanobot.agent.loop import TurnContext
from nanobot.agent.tools.context import RequestContext from nanobot.agent.tools.context import RequestContext
from nanobot.session.state import SessionState from nanobot.session.state import SessionState
INTERNAL_CONTINUATION_META = "_internal_continuation" 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" SKIP_USER_PERSIST_META = "_skip_user_persist"
_ITERATION_LIMIT_META = "_stopped_at_iteration_limit" _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) -> None:
def record_iteration_limit( """Remember an ordinary execution stopped at its iteration limit."""
metadata: MutableMapping[str, Any], stop_reason: str, *, continuation_pending: bool, if stop_reason == "max_iterations":
) -> None:
"""Remember a terminal budget stop, not an internal continuation handoff."""
if stop_reason == "max_iterations" and not continuation_pending:
metadata[_ITERATION_LIMIT_META] = True metadata[_ITERATION_LIMIT_META] = True
else: else:
metadata.pop(_ITERATION_LIMIT_META, None) 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: 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) 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: 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: if metadata and metadata.get(SKIP_USER_PERSIST_META) is True:
return False return False
return not internal_continuation_inbound(metadata) return not internal_continuation_inbound(metadata)
def should_stream_budget_response( def save_skip_for_turn(
*, *, message_metadata: Mapping[str, Any] | None,
stop_reason: str, initial_message_count: int, input_persisted_early: bool,
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,
) -> int: ) -> int:
if message_metadata and message_metadata.get(SKIP_USER_PERSIST_META) is True: if message_metadata and message_metadata.get(SKIP_USER_PERSIST_META) is True:
return initial_message_count return initial_message_count
if internal_continuation_inbound(message_metadata): if internal_continuation_inbound(message_metadata):
return initial_message_count return initial_message_count
if not input_persisted_early: return initial_message_count if input_persisted_early else initial_message_count - 1
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]
+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.providers.fallback_provider import FallbackModelObserver, FallbackModelSelection
from nanobot.runtime_context import public_history_message from nanobot.runtime_context import public_history_message
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY 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.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import session_handle_for_name 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.session.sqlite_store import SessionConflictError
from nanobot.utils.helpers import strip_think, truncate_text from nanobot.utils.helpers import strip_think, truncate_text
from nanobot.utils.llm_runtime import LLMRuntime from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.goal_state import goal_state_ws_blob
from nanobot.webui.metadata import ( from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY, WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_TURN_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.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_policy import validate_attachment_batch
from nanobot.channels.websocket.attachment_store import AttachmentUploadError 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 ( from nanobot.runtime_context import (
RUNTIME_CONTEXT_INPUT_META, RUNTIME_CONTEXT_INPUT_META,
WEBUI_QUOTE_METADATA, 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.agent.subagent import SubagentControlError
from nanobot.providers.base import LLMUsage 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.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.session.state import SessionState from nanobot.session.state import SessionState
from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at 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: if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager from nanobot.agent.subagent import SubagentManager
@@ -98,16 +98,15 @@ class WebUISessionProjection:
return tuple(events) return tuple(events)
async def persisted_goal_state(self, session_key: str) -> dict[str, Any] | None: 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: if self._sessions is None:
return None return None
snapshot = await self._sessions.state.read_metadata(session_key) snapshot = await self._sessions.state.read_metadata(session_key)
raw_metadata = snapshot.get("metadata") if snapshot is not None else None if snapshot is 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":
return 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 @staticmethod
def active_turn_status(chat_id: str) -> tuple[float, str | None] | None: 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, InboundMessage,
) )
from nanobot.bus.queue import MessageBus 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.command.router import CommandRouter
from nanobot.security.workspace_access import WorkspaceScope from nanobot.security.workspace_access import WorkspaceScope
from nanobot.session.manager import SessionManager 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 import SubagentControlError
from nanobot.agent.subagent_status import SubagentSessionError 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.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule from nanobot.cron.types import CronJob, CronSchedule
+5 -3
View File
@@ -28,10 +28,10 @@ def goal_message(**overrides):
{"metadata": {"goal_requested": True, "_cron_trigger": {"job_id": "job"}}}, {"metadata": {"goal_requested": True, "_cron_trigger": {"job_id": "job"}}},
{"metadata": {"goal_requested": True, "_local_trigger": {"trigger_id": "trigger"}}}, {"metadata": {"goal_requested": True, "_local_trigger": {"trigger_id": "trigger"}}},
]) ])
def test_background_input_cannot_authorize_initial_or_injected_work(overrides): def test_consumed_background_input_cannot_authorize_work(overrides):
message = goal_message(**overrides) message = goal_message(**overrides)
with goal_mutation_permission(True): with goal_mutation_permission(True):
with GoalInputScope(message) as scope: with GoalInputScope() as scope:
assert goal_mutation_allowed() is False assert goal_mutation_allowed() is False
scope.consume_inputs([message]) scope.consume_inputs([message])
assert goal_mutation_allowed() is False assert goal_mutation_allowed() is False
@@ -39,7 +39,9 @@ def test_background_input_cannot_authorize_initial_or_injected_work(overrides):
def test_revoked_permission_requires_a_new_explicit_request_to_reauthorize(): def test_revoked_permission_requires_a_new_explicit_request_to_reauthorize():
with GoalInputScope(goal_message()) as scope: with GoalInputScope() as scope:
assert goal_mutation_allowed() is False
scope.consume_inputs([goal_message()])
assert goal_mutation_allowed() is True assert goal_mutation_allowed() is True
revoke_goal_mutation_permission() revoke_goal_mutation_permission()
scope.consume_inputs([goal_message(content="ok", metadata={})]) scope.consume_inputs([goal_message(content="ok", metadata={})])
+25 -15
View File
@@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import json import json
from copy import deepcopy from copy import deepcopy
from typing import Any from typing import Any
@@ -11,8 +10,8 @@ from unittest.mock import AsyncMock
import pytest import pytest
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.goal.assembly import install_goal
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
from nanobot.runtime_context import public_history_messages from nanobot.runtime_context import public_history_messages
from nanobot.session.goal_state import GOAL_STATE_KEY from nanobot.session.goal_state import GOAL_STATE_KEY
@@ -55,6 +54,7 @@ def _make_loop(tmp_path, requests: list[list[dict[str, Any]]]) -> AgentLoop:
model="test-model", model="test-model",
context_window_tokens=128_000, context_window_tokens=128_000,
max_iterations=2, max_iterations=2,
builtin_assembly=install_goal,
) )
exec_tool = loop.tools.get("exec") exec_tool = loop.tools.get("exec")
assert exec_tool is not None assert exec_tool is not None
@@ -115,28 +115,38 @@ async def test_stop_survives_restart_and_keeps_history_prefix(tmp_path):
await loop.aclose() await loop.aclose()
async def test_goal_budget_handoff_is_not_an_abandoned_turn(tmp_path): async def test_goal_completed_after_iteration_limit_is_not_an_abandoned_turn(tmp_path):
requests: list[list[dict[str, Any]]] = [] requests: list[list[dict[str, Any]]] = []
loop = _make_loop(tmp_path, requests) loop = _make_loop(tmp_path, requests)
pending: asyncio.Queue[InboundMessage] = asyncio.Queue() chat = loop.provider.chat
async def complete_after_overrun(messages, tools=None, **kwargs):
if len(requests) == 3:
requests.append(deepcopy(messages))
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
)])
return await chat(messages, tools=tools, **kwargs)
loop.provider.chat = complete_after_overrun
loop.runner.run = AsyncMock(wraps=loop.runner.run)
try: try:
await loop.sessions.state.get("cli:goal") await loop.sessions.state.get("cli:goal")
await loop.sessions.state.update_metadata("cli:goal", { await loop.sessions.state.update_metadata("cli:goal", {
GOAL_STATE_KEY: {"status": "active", "objective": "run the tests"}, GOAL_STATE_KEY: {"status": "active", "objective": "run the tests"},
}) })
await loop._process_message( result = await loop.process_direct("run the tests", session_key="cli:goal")
InboundMessage(channel="cli", sender_id="user", chat_id="goal", content="run the tests"), assert result.content == "done"
pending_queue=pending, assert len(requests) == 5
) loop.runner.run.assert_awaited_once()
continuation = pending.get_nowait() session = await loop.sessions.state.read("cli:goal")
assert continuation.sender_id == "system:continuation" assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert [row["tool_call_id"] for row in session.messages if row["role"] == "tool"] == [
"call_1", "call_2", "call_3", "complete",
]
next_request = len(requests)
await loop.process_direct("give me a progress update", session_key="cli:goal") await loop.process_direct("give me a progress update", session_key="cli:goal")
assert _STOP_MARKER not in _last_user_content(requests[next_request]) assert _STOP_MARKER not in _last_user_content(requests[-1])
next_request = len(requests)
await loop._process_message(continuation, pending_queue=pending)
assert _STOP_MARKER not in _last_user_content(requests[next_request])
finally: finally:
await loop.aclose() await loop.aclose()
+3
View File
@@ -333,12 +333,15 @@ class TestToolEventProgress:
provider.chat_stream_with_retry = chat_stream_with_retry provider.chat_stream_with_retry = chat_stream_with_retry
provider.chat_with_retry = AsyncMock() provider.chat_with_retry = AsyncMock()
from nanobot.goal.assembly import install_goal
loop = AgentLoop( loop = AgentLoop(
bus=bus, bus=bus,
provider=provider, provider=provider,
workspace=tmp_path, workspace=tmp_path,
model="test-model", model="test-model",
hook_factories=[create_file_edit_activity_hook], hook_factories=[create_file_edit_activity_hook],
builtin_assembly=install_goal,
) )
tool = WriteFileTool(workspace=tmp_path) tool = WriteFileTool(workspace=tmp_path)
loop.tools.get_definitions = MagicMock(return_value=[ loop.tools.get_definitions = MagicMock(return_value=[
+6 -24
View File
@@ -7,13 +7,14 @@ import pytest
from agent.session_helpers import mock_session_manager from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput from nanobot.agent.context import TranscriptInput
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission from nanobot.agent.goal_permission import goal_mutation_allowed
from nanobot.agent.tools.context import RequestContext from nanobot.agent.tools.context import RequestContext
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import StreamedResponseEvent from nanobot.bus.outbound_events import StreamedResponseEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.config.schema import AgentDefaults from nanobot.config.schema import AgentDefaults
from nanobot.events import RetryStatusEvent from nanobot.events import RetryStatusEvent
from nanobot.goal.assembly import install_goal
from nanobot.providers.base import ( from nanobot.providers.base import (
GenerationSettings, GenerationSettings,
LLMProvider, LLMProvider,
@@ -98,27 +99,6 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
assert outbound.chat_id == "chat-a" assert outbound.chat_id == "chat-a"
@pytest.mark.asyncio
async def test_ephemeral_runner_enters_and_restores_turn_scopes(tmp_path):
loop = _make_loop(tmp_path)
async def chat_stream_with_retry(**_kwargs):
assert goal_mutation_allowed() is True
return LLMResponse(content="done", tool_calls=[], usage=None)
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=chat_stream_with_retry)
loop.tools.get_definitions = MagicMock(return_value=[])
await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
ephemeral=True,
turn_scopes=[goal_mutation_permission(True)],
)
assert goal_mutation_allowed() is False
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path): async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
@@ -154,7 +134,8 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
), ),
LLMResponse(content="done", tool_calls=[], usage=None), LLMResponse(content="done", tool_calls=[], usage=None),
]) ])
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal)
session = loop.sessions.get_or_create("cli:direct") session = loop.sessions.get_or_create("cli:direct")
session.add_message("user", "Let's agree on the migration implementation.") session.add_message("user", "Let's agree on the migration implementation.")
session.add_message("assistant", "Use the staged migration plan and run integration tests.") session.add_message("assistant", "Use the staged migration plan and run integration tests.")
@@ -349,7 +330,8 @@ async def test_non_goal_direct_turn_cannot_reuse_prior_goal_command(tmp_path):
), ),
LLMResponse(content="handled as a one-time task", tool_calls=[], usage=None), LLMResponse(content="handled as a one-time task", tool_calls=[], usage=None),
]) ])
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal)
session = loop.sessions.get_or_create("api:default") session = loop.sessions.get_or_create("api:default")
session.add_message("user", "/goal old completed request") session.add_message("user", "/goal old completed request")
session.add_message("assistant", "The old request is complete.") session.add_message("assistant", "The old request is complete.")
+332 -247
View File
@@ -1,5 +1,6 @@
import asyncio import asyncio
import json import json
import threading
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
@@ -21,8 +22,17 @@ from nanobot.bus.outbound_events import (
TurnEndEvent, TurnEndEvent,
) )
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import TurnCompleted, TurnRunStatusChanged
from nanobot.cron.session_turns import CRON_HISTORY_META, CRON_TRIGGER_META from nanobot.cron.session_turns import CRON_HISTORY_META, CRON_TRIGGER_META
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage, ProviderConversationState from nanobot.goal.assembly import install_goal
from nanobot.providers.base import (
GenerationSettings,
LLMProvider,
LLMResponse,
LLMUsage,
ProviderConversationState,
ToolCallRequest,
)
from nanobot.providers.factory import ProviderSnapshot from nanobot.providers.factory import ProviderSnapshot
from nanobot.runtime_context import ( from nanobot.runtime_context import (
RUNTIME_CONTEXT_HISTORY_META, RUNTIME_CONTEXT_HISTORY_META,
@@ -119,14 +129,16 @@ def _runtime_message(content, blocks: list[RuntimeContextBlock]) -> dict:
def _make_full_loop(tmp_path: Path) -> AgentLoop: def _make_full_loop(tmp_path: Path) -> AgentLoop:
provider = MagicMock() provider = MagicMock(aclose=AsyncMock())
provider.provider_name = "test" provider.provider_name = "test"
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
provider.generation = SimpleNamespace(max_tokens=4096) provider.generation = GenerationSettings(max_tokens=4096)
provider.estimate_prompt_tokens.return_value = (100, "test")
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Test title")) provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Test title"))
bus = MessageBus() bus = MessageBus()
loop = AgentLoop( loop = AgentLoop(
bus=bus, provider=provider, workspace=tmp_path, model="test-model", bus=bus, provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal,
) )
WebuiTurnCoordinator( WebuiTurnCoordinator(
bus=loop.bus, bus=loop.bus,
@@ -1382,256 +1394,270 @@ async def test_process_message_does_not_duplicate_early_persisted_user_message(t
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_internal_continuation_queues_turn_without_fake_user_history( async def test_explicit_recovery_continues_without_fake_user_history(tmp_path: Path) -> None:
tmp_path: Path,
) -> None:
loop = _make_full_loop(tmp_path) loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("feishu:c-auto") session = loop.sessions.get_or_create("feishu:recovery")
session.metadata[GOAL_STATE_KEY] = { session.add_message("user", "Inspect the migration")
"status": "active", session.add_message("assistant", "Evidence collected before interruption.")
"objective": "Finish the long goal.",
}
loop.sessions.save(session) loop.sessions.save(session)
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
calls: list[dict] = []
async def fake_run_agent_loop(transcript_input, *, metadata=None, **_kwargs):
initial_messages = _assembled_messages(loop.context, transcript_input)
calls.append({"initial_messages": initial_messages, "metadata": metadata})
if len(calls) == 1:
return _agent_run_result(
"paused",
[*initial_messages, {"role": "assistant", "content": "paused"}],
stop_reason="max_iterations",
)
return _agent_run_result(
"done",
[*initial_messages, {"role": "assistant", "content": "done"}],
)
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
first = await loop._process_message(
InboundMessage(
channel="feishu",
sender_id="u1",
chat_id="c-auto",
content="start the goal",
),
pending_queue=pending,
)
assert first is None
queued = pending.get_nowait()
assert queued.sender_id == "system:continuation"
assert queued.metadata[INTERNAL_CONTINUATION_META] is True
assert "Finish the long goal." in queued.content
session = loop.sessions.get_or_create("feishu:c-auto")
assert "Finish the long goal." in str(session.messages[0]["content"])
assert [
{k: v for k, v in m.items() if k in {"role", "content"}}
for m in map(public_history_message, session.messages)
] == [{"role": "user", "content": "start the goal"}]
second = await loop._process_message(queued, pending_queue=asyncio.Queue())
assert second is not None
assert second.content == "done"
session = loop.sessions.get_or_create("feishu:c-auto")
assert [
{k: v for k, v in m.items() if k in {"role", "content"}}
for m in map(public_history_message, session.messages)
] == [
{"role": "user", "content": "start the goal"},
{"role": "assistant", "content": "done"},
]
@pytest.mark.asyncio
async def test_internal_continuation_preserves_streaming_route_metadata(
tmp_path: Path,
) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("feishu:c-stream")
session.metadata[GOAL_STATE_KEY] = {
"status": "active",
"objective": "Finish the streamed long goal.",
}
loop.sessions.save(session)
calls = 0
async def fake_run_agent_loop(transcript_input, *, events, streaming, **_kwargs):
nonlocal calls
initial_messages = _assembled_messages(loop.context, transcript_input)
calls += 1
if calls == 1:
return _agent_run_result(
"paused",
[*initial_messages, {"role": "assistant", "content": "paused"}],
stop_reason="max_iterations",
)
assert streaming
await events.emit(StreamDeltaEvent(content="done"))
await events.emit(StreamEndEvent())
return _agent_run_result(
"done",
[*initial_messages, {"role": "assistant", "content": "done"}],
)
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
await run_session(loop, InboundMessage(
channel="feishu",
sender_id="u1",
chat_id="c-stream",
content="start the goal",
metadata={
"_wants_stream": True,
"message_id": "om_001",
"origin_message_id": "root_001",
},
))
outbound = []
while loop.bus.outbound_size:
outbound.append(await loop.bus.consume_outbound())
deltas = [m for m in outbound if isinstance(m.event, StreamDeltaEvent)]
ends = [m for m in outbound if isinstance(m.event, StreamEndEvent)]
streamed_markers = [m for m in outbound if isinstance(m.event, StreamedResponseEvent)]
assert [m.content for m in deltas] == ["done"]
assert len(ends) == 1
assert isinstance(ends[0].event, StreamEndEvent)
assert ends[0].event.resuming is False
assert ends[0].metadata["message_id"] == "om_001"
assert ends[0].metadata["origin_message_id"] == "root_001"
assert isinstance(ends[0].event.stream_id, str)
assert streamed_markers and streamed_markers[-1].content == "done"
assert loop.bus.inbound_size == 0
assert calls == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("content", ["start the goal", "/goal start the goal"])
async def test_websocket_internal_continuation_keeps_single_visible_run(
tmp_path: Path, content: str,
) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:c-auto")
session.metadata[GOAL_STATE_KEY] = {
"status": "active",
"objective": "Finish the long goal.",
}
loop.sessions.save(session)
calls = 0
async def fake_run_agent_loop(transcript_input, **_kwargs):
nonlocal calls
initial_messages = _assembled_messages(loop.context, transcript_input)
calls += 1
if calls == 1:
return _agent_run_result(
"paused",
[*initial_messages, {"role": "assistant", "content": "paused"}],
stop_reason="max_iterations",
)
return _agent_run_result(
"done",
[*initial_messages, {"role": "assistant", "content": "done"}],
)
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
await run_session(loop, InboundMessage(
channel="websocket",
sender_id="u1",
chat_id="c-auto",
content=content,
metadata={"webui": True},
))
first_outbound = []
while loop.bus.outbound_size:
first_outbound.append(await loop.bus.consume_outbound())
first_statuses = [m.event for m in first_outbound if isinstance(m.event, GoalStatusEvent)]
assert [m.status for m in first_statuses] == ["running", "running", "idle"]
started_at = first_statuses[0].started_at
assert first_statuses[1].started_at == started_at
turn_end = [m for m in first_outbound if isinstance(m.event, TurnEndEvent)]
assert len(turn_end) == 1
assert isinstance(turn_end[0].event, TurnEndEvent)
assert isinstance(turn_end[0].event.latency_ms, int)
assert loop.bus.inbound_size == 0
assert calls == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("content", ["start the goal", "/goal start the goal"])
async def test_stop_after_continuation_queued_ends_visible_run(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, content: str,
) -> None:
from nanobot.command.builtin import cmd_stop
from nanobot.command.router import CommandContext
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:c-stop-continuation")
session.metadata[GOAL_STATE_KEY] = {
"status": "active",
"objective": "Finish the long goal.",
}
loop.sessions.save(session)
calls = 0
async def fake_run_agent_loop(transcript_input, **_kwargs):
nonlocal calls
calls += 1
initial_messages = _assembled_messages(loop.context, transcript_input)
return _agent_run_result(
"paused",
[*initial_messages, {"role": "assistant", "content": "paused"}],
stop_reason="max_iterations",
)
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
saving = asyncio.Event()
finish_turn = loop.sessions.state.finish_turn
async def hold_first_save(session):
if not saving.is_set():
saving.set()
await asyncio.Event().wait()
await finish_turn(session)
monkeypatch.setattr(loop.sessions.state, "finish_turn", hold_first_save)
msg = InboundMessage(
channel="websocket", sender_id="u1", chat_id="c-stop-continuation",
content=content, metadata={"webui": True},
)
await loop._enqueue_session_message(msg)
try: try:
await asyncio.wait_for(saving.wait(), timeout=5) result = await loop._process_message(InboundMessage(
channel="feishu", sender_id="system:recovery", chat_id="recovery",
content="Continue the interrupted request from saved context.",
metadata={INTERNAL_CONTINUATION_META: True},
))
assert result is not None and result.content == "done"
saved = await loop.sessions.state.read(session.key)
assert [
{k: v for k, v in row.items() if k in {"role", "content"}}
for row in map(public_history_message, saved.messages)
] == [
{"role": "user", "content": "Inspect the migration"},
{"role": "assistant", "content": "Evidence collected before interruption."},
{"role": "assistant", "content": "done"},
]
prompt = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "Continue the interrupted request from saved context." in str(prompt)
finally:
await loop.aclose()
@pytest.mark.asyncio
async def test_same_run_goal_preserves_streaming_route_metadata(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
loop.max_iterations = 1
session = await loop.sessions.state.get("feishu:c-stream")
await loop.sessions.state.update_metadata(session.key, {GOAL_STATE_KEY: {
"status": "active", "objective": "Finish the streamed long goal.",
}})
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="list", name="list_dir", arguments={"path": "."},
)]),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "done"},
)]),
LLMResponse(content="done"),
])
loop.runner.run = AsyncMock(wraps=loop.runner.run)
try:
await run_session(loop, InboundMessage(
channel="feishu", sender_id="u1", chat_id="c-stream", content="start the goal",
metadata={"_wants_stream": True, "message_id": "om_001", "origin_message_id": "root_001"},
))
outbound = []
while loop.bus.outbound_size:
outbound.append(await loop.bus.consume_outbound())
deltas = [m for m in outbound if isinstance(m.event, StreamDeltaEvent)]
ends = [m for m in outbound if isinstance(m.event, StreamEndEvent)]
streamed_markers = [m for m in outbound if isinstance(m.event, StreamedResponseEvent)]
assert [m.content for m in deltas] == ["done"]
assert [item.event.resuming for item in ends] == [True, True, False]
assert all(item.metadata["message_id"] == "om_001" for item in ends)
assert all(item.metadata["origin_message_id"] == "root_001" for item in ends)
assert all(isinstance(item.event.stream_id, str) for item in ends)
assert streamed_markers and streamed_markers[-1].content == "done"
assert loop.bus.inbound_size == 0
assert loop.provider.chat_stream_with_retry.await_count == 3
loop.runner.run.assert_awaited_once()
finally:
await loop.aclose()
@pytest.mark.asyncio
async def test_stop_during_committed_goal_checkpoint_settles_queued_command(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
):
loop = _make_full_loop(tmp_path)
loop.provider.aclose = AsyncMock()
loop.consolidator.compact_idle_session = AsyncMock()
loop.max_iterations = 1
gate = asyncio.Semaphore(1)
loop._concurrency_gate = gate
session = loop.sessions.get_or_create("websocket:committed-checkpoint")
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal."}
loop.sessions.save(session)
calls = 0
async def respond(*args, **kwargs):
nonlocal calls
if args and "You write short, neutral chat titles" in str(args[0]):
return LLMResponse(content="Goal checkpoint")
calls += 1
if calls == 3:
await loop._dispatch_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="committed-checkpoint",
content="/compact", metadata={"webui": True, "message_id": "queued-compact"},
))
if calls <= 3:
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id=f"list-{calls}", name="list_dir", arguments={"path": "."},
)])
if calls == 4:
assert "list-1" in str(kwargs["messages"]) and "list-3" in str(kwargs["messages"])
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="cancel", name="update_goal", arguments={"action": "cancel", "recap": "Stopped work."},
)])
assert calls == 5
return LLMResponse(content="handled later")
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
loop.runner.run = AsyncMock(wraps=loop.runner.run)
committed, release = threading.Event(), threading.Event()
publish = loop.sessions.state._publish
def hold_after_commit(saved, *args, **kwargs):
checkpoint = saved.metadata.get(RUNTIME_CHECKPOINT_KEY, {})
if checkpoint.get("phase") == "tools_completed" and calls == 3 and not committed.is_set():
committed.set()
if not release.wait(5):
raise TimeoutError("test did not release the committed save")
return publish(saved, *args, **kwargs)
monkeypatch.setattr(loop.sessions.state, "_publish", hold_after_commit)
msg = InboundMessage(
channel="websocket", sender_id="user", chat_id="committed-checkpoint", content="Continue",
metadata={"webui": True, "message_id": "goal-input"},
)
completed = []
statuses = []
loop.bus.subscribe(completed.append, TurnCompleted)
loop.bus.subscribe(statuses.append, TurnRunStatusChanged)
stop_acknowledged = asyncio.Event()
publish_outbound = loop.bus.publish_outbound
async def observe_stop_reply(message):
await publish_outbound(message)
if message.metadata.get("message_id") == "stop-attempt" and message.content.startswith("Stopped "):
stop_acknowledged.set()
monkeypatch.setattr(loop.bus, "publish_outbound", observe_stop_reply)
bus_task = asyncio.create_task(loop.run())
try:
await loop.bus.publish_inbound(msg)
assert await asyncio.wait_for(asyncio.to_thread(committed.wait), 5)
worker, = loop._active_tasks[msg.session_key]
assert gate.locked()
assert loop._pending_queues[msg.session_key].qsize() == 1 assert loop._pending_queues[msg.session_key].qsize() == 1
stop_msg = InboundMessage( stop_msg = InboundMessage(
channel="websocket", sender_id="u1", chat_id=msg.chat_id, content="/stop", channel="websocket", sender_id="user", chat_id=msg.chat_id, content="/stop",
metadata={"message_id": "stop-attempt"},
) )
result = await cmd_stop(CommandContext( await loop.bus.publish_inbound(stop_msg)
msg=stop_msg, session=None, key=msg.session_key, raw="/stop", loop=loop, async with asyncio.timeout(5):
)) while not worker.cancelling():
assert "Stopped 1 task(s)" in result.content await asyncio.sleep(0)
finally: release.set()
await loop._cancel_active_tasks(msg.session_key) await asyncio.wait_for(stop_acknowledged.wait(), 5)
assert not bus_task.done(), "Stop terminated the inbound loop"
assert not gate.locked()
saved = await loop.sessions.state.read(msg.session_key)
assert saved.metadata[GOAL_STATE_KEY]["status"] == "active"
assert RUNTIME_CHECKPOINT_KEY not in saved.metadata
assert [row["tool_call_id"] for row in saved.messages if row["role"] == "tool"] == [
"list-1", "list-2", "list-3",
]
assert msg.session_key not in loop._pending_queues
assert not loop._active_tasks.get(msg.session_key)
assert calls == 3
loop.runner.run.assert_awaited_once()
assert [(event.context.metadata.get("message_id"), event.outcome) for event in completed
if event.context.metadata.get("message_id") in {"goal-input", "queued-compact"}] == [
("goal-input", "cancelled"), ("queued-compact", "completed"),
]
assert [(event.context.metadata.get("message_id"), event.status) for event in statuses] == [
("goal-input", "running"), ("goal-input", "idle"),
]
loop.consolidator.compact_idle_session.assert_not_awaited()
outbound = [] outbound = []
while loop.bus.outbound_size: while loop.bus.outbound_size:
outbound.append(await loop.bus.consume_outbound()) outbound.append(await loop.bus.consume_outbound())
statuses = [m.event.status for m in outbound if isinstance(m.event, GoalStatusEvent)] stop_responses = [item.content for item in outbound if item.content.startswith("Stopped ")]
assert statuses == ["running", "idle"] assert stop_responses == ["Stopped 1 task(s)."]
assert calls == 1 endings = [item.event for item in outbound if isinstance(item.event, TurnEndEvent)]
assert msg.session_key not in loop._pending_queues cancelled = [event for event in endings if event.outcome == "cancelled"]
assert len(cancelled) == 1 and cancelled[0].goal_state["status"] == "active"
assert [item.event.status for item in outbound if isinstance(item.event, GoalStatusEvent)] == [
"running", "idle",
]
followup = InboundMessage(
channel="websocket", sender_id="user", chat_id=msg.chat_id, content="Independent input",
metadata={"webui": True, "message_id": "independent-input"},
)
await loop.bus.publish_inbound(followup)
async with asyncio.timeout(5):
while msg.session_key in loop._pending_queues or not any(
event.context.metadata.get("message_id") == "independent-input"
for event in completed
):
await asyncio.sleep(0)
assert calls == 5 and loop.runner.run.await_count == 2
assert msg.session_key not in loop._pending_queues
followup_outbound = []
while loop.bus.outbound_size:
followup_outbound.append(await loop.bus.consume_outbound())
assert any(item.content == "handled later" for item in followup_outbound)
loop.consolidator.compact_idle_session.assert_not_awaited()
finally:
release.set()
loop.stop()
await asyncio.wait_for(asyncio.gather(bus_task, return_exceptions=True), 5)
await loop.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["reset", "delete"])
async def test_active_goal_checkpoint_cannot_revive_an_old_generation(tmp_path: Path, operation):
loop = _make_full_loop(tmp_path)
loop.max_iterations = 1
session = await loop.sessions.state.get("websocket:old-generation")
await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "active", "objective": "Old goal."},
})
waiting, release = asyncio.Event(), asyncio.Event()
calls = 0
async def respond(**kwargs):
nonlocal calls
calls += 1
assert calls <= 2
if calls == 1:
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="list", name="list_dir", arguments={"path": "."},
)])
waiting.set()
await release.wait()
return LLMResponse(content="Old generation's late answer.")
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
worker = asyncio.create_task(run_session(loop, InboundMessage(
channel="websocket", sender_id="user", chat_id="old-generation", content="Continue",
metadata={"webui": True},
)))
try:
await asyncio.wait_for(waiting.wait(), 5)
if operation == "reset":
await loop.sessions.state.reset(session.key)
else:
assert await loop.sessions.state.delete(session.key, expected_generation=session.generation)
release.set()
await asyncio.wait_for(worker, 5)
current = await loop.sessions.state.read(session.key)
if operation == "reset":
assert current is not None and current.generation != session.generation
assert current.messages == []
assert GOAL_STATE_KEY not in current.metadata
else:
assert current is None
assert calls == 2
finally:
release.set()
await loop._cancel_active_tasks(session.key)
await asyncio.gather(worker, return_exceptions=True)
await loop.aclose()
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -2034,7 +2060,9 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
assert request.sender_id == "subagent" assert request.sender_id == "subagent"
assert request.metadata == {"subagent_task_id": "sub-1"} assert request.metadata == {"subagent_task_id": "sub-1"}
assert request.turn_id assert request.turn_id
record_runtime.assert_called_once_with("cli:test", runtime) assert record_runtime.call_count == 1
assert record_runtime.call_args.args == ("cli:test", runtime)
assert isinstance(record_runtime.call_args.kwargs["run_id"], str)
initial_messages = seen["initial_messages"] initial_messages = seen["initial_messages"]
assert isinstance(initial_messages, list) assert isinstance(initial_messages, list)
non_system = [m for m in initial_messages if m.get("role") != "system"] non_system = [m for m in initial_messages if m.get("role") != "system"]
@@ -2624,3 +2652,60 @@ def test_save_turn_drops_duplicate_tool_result_ids() -> None:
assert [m["role"] for m in session.messages] == ["assistant", "tool"] assert [m["role"] for m in session.messages] == ["assistant", "tool"]
assert session.messages[1]["content"] == "first" assert session.messages[1]["content"] == "first"
async def test_stop_during_goal_completion_publishes_one_terminal_event(tmp_path):
loop = _make_full_loop(tmp_path)
loop.max_iterations = 1
key = "websocket:goal-completion"
await loop.sessions.state.get(key)
await loop.sessions.state.update_metadata(key, {
GOAL_STATE_KEY: {"status": "active", "objective": "Verify the result."},
"title": "Goal completion", "title_user_edited": True,
})
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
)]),
LLMResponse(content="Verified."),
])
publishing, release = asyncio.Event(), asyncio.Event()
completed = []
async def hold_completion(event):
completed.append(event)
publishing.set()
await release.wait()
loop.bus.subscribe(hold_completion, TurnCompleted)
stop = None
try:
await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="user", chat_id="goal-completion", content="Continue",
metadata={"webui": True},
))
await asyncio.wait_for(publishing.wait(), 5)
worker, = loop._active_tasks[key]
stop = asyncio.create_task(loop._cancel_active_tasks(key))
async with asyncio.timeout(5):
while not worker.cancelling():
await asyncio.sleep(0)
release.set()
assert await asyncio.wait_for(stop, 5) == 1
assert [event.outcome for event in completed] == ["completed"]
outbound = []
while not loop.bus.outbound.empty():
outbound.append(loop.bus.outbound.get_nowait())
endings = [item.event for item in outbound if isinstance(item.event, TurnEndEvent)]
assert len(endings) == 1 and endings[0].outcome == "completed"
assert [item.event.status for item in outbound if isinstance(item.event, GoalStatusEvent)] == [
"running", "idle",
]
saved = await loop.sessions.state.read(key)
assert saved.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert saved.messages[-1]["content"] == "Verified."
finally:
release.set()
if stop is not None:
await asyncio.gather(stop, return_exceptions=True)
await loop.aclose()
+317 -11
View File
@@ -5,14 +5,27 @@ import pytest
from agent.session_helpers import stop_loop from agent.session_helpers import stop_loop
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop as CoreAgentLoop
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import GoalStatusEvent, TurnEndEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest from nanobot.goal.assembly import install_goal
from nanobot.providers.base import (
GenerationSettings,
LLMResponse,
LLMUsage,
ProviderConversationState,
ToolCallRequest,
)
from nanobot.runtime_context import public_history_messages from nanobot.runtime_context import public_history_messages
from nanobot.session.goal_state import GOAL_STATE_KEY from nanobot.session.goal_state import GOAL_STATE_KEY
from nanobot.session.history_visibility import is_hidden_history_message from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import SessionManager from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import WebuiTurnCoordinator
def _assembled_loop(*args, **kwargs):
return CoreAgentLoop(*args, builtin_assembly=install_goal, **kwargs)
@pytest.mark.parametrize("command", [ @pytest.mark.parametrize("command", [
@@ -51,7 +64,7 @@ async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, c
return LLMResponse(content="done") return LLMResponse(content="done")
provider.chat_stream_with_retry = AsyncMock(side_effect=respond) provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
process = AsyncMock(wraps=loop._process_message) process = AsyncMock(wraps=loop._process_message)
loop._process_message = process loop._process_message = process
run = asyncio.create_task(loop.run()) run = asyncio.create_task(loop.run())
@@ -96,7 +109,7 @@ async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
channel="cli", sender_id="user", chat_id="test", content="/goal execute", channel="cli", sender_id="user", chat_id="test", content="/goal execute",
metadata={"_cron_trigger": {"job_id": "job"}}, metadata={"_cron_trigger": {"job_id": "job"}},
) )
loop = AgentLoop(bus=MessageBus(), provider=MagicMock(aclose=AsyncMock()), workspace=tmp_path, model="test-model") loop = _assembled_loop(bus=MessageBus(), provider=MagicMock(aclose=AsyncMock()), workspace=tmp_path, model="test-model")
try: try:
await loop._dispatch_command_inline(msg, msg.session_key, msg.content, loop.commands.dispatch) await loop._dispatch_command_inline(msg, msg.session_key, msg.content, loop.commands.dispatch)
response = loop.bus.outbound.get_nowait() response = loop.bus.outbound.get_nowait()
@@ -116,7 +129,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings() provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test") provider.estimate_prompt_tokens.return_value = (100, "test")
loop = AgentLoop( loop = _assembled_loop(
bus=MessageBus(), provider=provider, workspace=tmp_path, bus=MessageBus(), provider=provider, workspace=tmp_path,
model="test-model", max_iterations=1, model="test-model", max_iterations=1,
) )
@@ -170,28 +183,31 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path): async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
from nanobot.command.router import CommandContext from nanobot.command.router import CommandContext, CommandExpansion
from nanobot.session.recovery import pending_followups from nanobot.session.recovery import pending_followups
provider = MagicMock(aclose=AsyncMock()) provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings() provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test") provider.estimate_prompt_tokens.return_value = (100, "test")
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
message = InboundMessage( message = InboundMessage(
channel="websocket", sender_id="user", chat_id="test", content="/goal /stop", channel="websocket", sender_id="user", chat_id="test", content="/goal /stop",
) )
try: try:
generated = await loop.commands.dispatch(CommandContext( context = CommandContext(
msg=message, session=None, key=message.session_key, msg=message, session=None, key=message.session_key,
raw=message.content, loop=loop, is_user_turn=True, raw=message.content, loop=loop, is_user_turn=True,
)) )
expansion = await loop.commands.dispatch(context)
assert isinstance(expansion, CommandExpansion)
generated = await loop._prepare_command_expansion(context, expansion)
assert isinstance(generated, InboundMessage) assert isinstance(generated, InboundMessage)
assert await loop.sessions.state.queue_followup(message.session_key, generated) assert await loop.sessions.state.queue_followup(message.session_key, generated)
finally: finally:
await loop.aclose() await loop.aclose()
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
session = (await loop.sessions.state.get(message.session_key)) session = (await loop.sessions.state.get(message.session_key))
recovered, = pending_followups(session) recovered, = pending_followups(session)
responses = iter([ responses = iter([
@@ -237,7 +253,7 @@ async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings() provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test") provider.estimate_prompt_tokens.return_value = (100, "test")
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
message = InboundMessage( message = InboundMessage(
channel="cli", sender_id="automation", chat_id="test", content="Continue working", channel="cli", sender_id="automation", chat_id="test", content="Continue working",
metadata={"goal_requested": True, "_internal_continuation": True}, metadata={"goal_requested": True, "_internal_continuation": True},
@@ -258,3 +274,293 @@ async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
assert goal_mutation_allowed() is False assert goal_mutation_allowed() is False
finally: finally:
await loop.aclose() await loop.aclose()
async def test_goal_checkpoint_failure_finishes_visible_run_without_restarting(tmp_path, monkeypatch):
from agent.session_helpers import run_session
bus = MessageBus()
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="list", name="list_dir", arguments={"path": "."},
)]))
loop = _assembled_loop(bus=bus, provider=provider, workspace=tmp_path, model="test-model", max_iterations=1)
WebuiTurnCoordinator(
bus=bus, sessions=loop.sessions,
schedule_background=lambda coro: loop.schedule_background(coro),
).subscribe()
session = await loop.sessions.state.get("websocket:goal-save-fail")
await loop.sessions.state.update_metadata(session.key, {
"webui": True, "title": "Goal", "title_user_edited": True,
GOAL_STATE_KEY: {"status": "active", "objective": "Verify the task."},
})
checkpoint_view = loop.sessions.state.checkpoint_view
checkpoints = 0
async def fail_checkpoint(session, payload):
nonlocal checkpoints
if payload["phase"] == "tools_completed":
checkpoints += 1
if checkpoints == 3:
raise OSError("synthetic checkpoint failure")
await checkpoint_view(session, payload)
monkeypatch.setattr(loop.sessions.state, "checkpoint_view", fail_checkpoint)
loop.runner.run = AsyncMock(wraps=loop.runner.run)
try:
await run_session(loop, InboundMessage(
channel="websocket", sender_id="user", chat_id="goal-save-fail", content="Continue",
metadata={"webui": True, "webui_turn_id": "save-fail-turn"},
))
events = []
while not bus.outbound.empty():
events.append(bus.outbound.get_nowait())
endings = [m.event for m in events if isinstance(m.event, TurnEndEvent)]
assert len(endings) == 1 and endings[0].outcome == "failed"
assert [m.event.status for m in events if isinstance(m.event, GoalStatusEvent)] == ["running", "idle"]
assert provider.chat_stream_with_retry.await_count == 3
loop.runner.run.assert_awaited_once()
assert session.key not in loop._pending_queues
saved = await loop.sessions.state.read(session.key)
assert saved.metadata[GOAL_STATE_KEY]["status"] == "active"
finally:
await loop.aclose()
async def test_active_goal_keeps_candidate_history_until_successful_closure(tmp_path):
from agent.session_helpers import run_session
bus = MessageBus()
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
provider.can_resume_conversation_state.return_value = True
state = ProviderConversationState(
kind="openai_responses", provider="openai:test", model="test-model", version=1,
payload={"items": [{"type": "reasoning", "encrypted_content": "private-goal-state"}]},
)
usage = LLMUsage(input_tokens=10, output_tokens=5, total_tokens=15, reported_tokens=15)
entered, release = asyncio.Event(), asyncio.Event()
calls = []
async def respond(**kwargs):
calls.append(kwargs)
if len(calls) > 1:
resumed = kwargs["provider_context"].conversation_state
assert resumed is not None and resumed.payload == state.payload
assert any(row.get("content") == "Evidence 1 recorded." for row in kwargs["messages"])
if len(calls) <= 16:
assert any("Please continue working toward the objective" in str(row.get("content"))
for row in resumed.pending_messages)
else:
assert any(row.get("tool_call_id") == "close" for row in resumed.pending_messages)
if len(calls) <= 15:
assert kwargs.get("tools")
return LLMResponse(content=f"Evidence {len(calls)} recorded.", usage=usage, provider_state=state)
if len(calls) == 16:
assert kwargs.get("tools")
entered.set()
await release.wait()
return LLMResponse(content=None, usage=usage, provider_state=state, tool_calls=[ToolCallRequest(
id="close", name="update_goal", arguments={"action": "complete", "recap": "Evidence reviewed."},
)])
assert len(calls) == 17 and not kwargs.get("tools")
return LLMResponse(content="Evidence reviewed.", usage=usage, provider_state=state)
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
loop = _assembled_loop(bus=bus, provider=provider, workspace=tmp_path,
model="test-model", max_iterations=1)
loop.runner.run = AsyncMock(wraps=loop.runner.run)
loop._process_message = AsyncMock(wraps=loop._process_message)
WebuiTurnCoordinator(
bus=bus, sessions=loop.sessions,
schedule_background=lambda coro: loop.schedule_background(coro),
).subscribe()
session = await loop.sessions.state.get("websocket:goal-limit")
await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "active", "objective": "Keep investigating."},
"webui": True, "title": "Goal", "title_user_edited": True,
})
run = asyncio.create_task(run_session(loop, InboundMessage(
channel="websocket", sender_id="user", chat_id="goal-limit", content="/goal Keep investigating.",
metadata={"webui": True, "webui_turn_id": "goal-turn"},
)))
try:
await asyncio.wait_for(entered.wait(), 5)
events = []
while not bus.outbound.empty():
events.append(bus.outbound.get_nowait())
assert [m.event.status for m in events if isinstance(m.event, GoalStatusEvent)] == ["running"]
assert not any(isinstance(m.event, TurnEndEvent) for m in events)
release.set()
await asyncio.wait_for(run, 5)
while not bus.outbound.empty():
events.append(bus.outbound.get_nowait())
statuses = [m.event for m in events if isinstance(m.event, GoalStatusEvent)]
assert [event.status for event in statuses] == ["running", "idle"]
assert statuses[0].started_at is not None
endings = [m.event for m in events if isinstance(m.event, TurnEndEvent)]
assert len(endings) == 1 and endings[0].outcome == "completed"
assert isinstance(endings[0].latency_ms, int)
assert endings[0].usage is not None and endings[0].usage.total_tokens == 255
assert len(endings[0].round_usages) == 17
assert len(calls) == 17
loop.runner.run.assert_awaited_once()
loop._process_message.assert_awaited_once()
saved = await loop.sessions.state.read(session.key)
assert saved.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert saved.provider_state is not None and saved.provider_state.payload == state.payload
visible = public_history_messages([row for row in saved.messages if not is_hidden_history_message(row)])
assert [row["content"] for row in visible if row["role"] == "user"] == ["/goal Keep investigating."]
for number in range(1, 16):
assert sum(row.get("content") == f"Evidence {number} recorded." for row in visible) == 1
assert sum(row.get("content") == "Evidence reviewed." for row in visible) == 1
assert visible[-1]["content"] == "Evidence reviewed."
assert [row["tool_call_id"] for row in saved.messages if row["role"] == "tool"] == ["close"]
assert sum(row.get("_hidden_history") == {"kind": "internal_continuation"} for row in saved.messages) == 15
assert "private-goal-state" not in str(visible)
assert session.key not in loop._pending_queues
finally:
release.set()
if not run.done():
await loop._cancel_active_tasks(session.key)
await asyncio.gather(run, return_exceptions=True)
await loop.aclose()
async def test_replaced_goal_uses_current_objective_for_same_run_prompt(tmp_path):
from agent.session_helpers import run_session
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path,
model="test-model", max_iterations=1)
session = await loop.sessions.state.get("cli:replacement")
await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "active", "objective": "Old objective."},
})
calls = []
replacement = InboundMessage(
channel="cli", sender_id="user", chat_id="replacement", content="/goal New objective.",
)
async def respond(**kwargs):
calls.append(kwargs)
if len(calls) == 1:
await loop._dispatch_command_inline(
replacement, replacement.session_key, replacement.content, loop.commands.dispatch,
)
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="list", name="list_dir", arguments={"path": "."},
)])
if len(calls) == 2:
assert goal_mutation_allowed()
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="replace", name="update_goal", arguments={"action": "replace", "objective": "New objective."},
)])
if len(calls) == 3:
return LLMResponse(content="The replacement objective needs one more check.")
if len(calls) == 4:
prompts = [
message["content"] for message in kwargs["messages"]
if is_hidden_history_message(message) and message.get("role") == "user"
]
assert prompts and "New objective." in prompts[-1] and "Old objective." not in prompts[-1]
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Done."},
)])
return LLMResponse(content="Done.")
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
try:
await run_session(loop, InboundMessage(
channel="cli", sender_id="user", chat_id="replacement", content="Continue the old objective.",
))
assert len(calls) == 5
saved = await loop.sessions.state.read(session.key)
assert saved.metadata[GOAL_STATE_KEY]["objective"] == "New objective."
assert saved.metadata[GOAL_STATE_KEY]["status"] == "completed"
visible = public_history_messages([row for row in saved.messages if not is_hidden_history_message(row)])
assert sum(row.get("content") == replacement.content for row in visible) == 1
finally:
await loop.aclose()
async def test_failed_goal_completion_keeps_running_until_a_successful_block(tmp_path, monkeypatch):
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Done."},
)]),
LLMResponse(content="The task is done."),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="block", name="update_goal", arguments={"action": "block", "recap": "Save failed."},
)]),
LLMResponse(content="The goal is blocked."),
])
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path,
model="test-model", max_iterations=4)
session = await loop.sessions.state.get("cli:failed-goal-update")
await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "active", "objective": "Verify the task."},
})
replace_metadata = loop.sessions._store.replace_metadata
def fail_completion(key, metadata, **kwargs):
if metadata.get(GOAL_STATE_KEY, {}).get("status") == "completed":
raise OSError("synthetic goal commit failure")
return replace_metadata(key, metadata, **kwargs)
monkeypatch.setattr(loop.sessions._store, "replace_metadata", fail_completion)
try:
result = await loop.process_direct("Continue", session_key=session.key)
assert result.content == "The goal is blocked."
assert provider.chat_stream_with_retry.await_count == 4
calls = provider.chat_stream_with_retry.await_args_list
assert "synthetic goal commit failure" in str(calls[1].kwargs["messages"])
assert "Please continue working toward the objective" in str(calls[2].kwargs["messages"])
saved = await loop.sessions.state.read(session.key)
assert saved.metadata[GOAL_STATE_KEY]["status"] == "blocked"
finally:
await loop.aclose()
@pytest.mark.parametrize("operation", ["reset", "delete"])
async def test_queued_goal_command_does_not_write_to_an_obsolete_generation(tmp_path, operation):
from nanobot.session.sqlite_store import SessionConflictError
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
key = "websocket:old-goal-command"
session = await loop.sessions.state.get(key)
message = InboundMessage(
channel="websocket", sender_id="user", chat_id="old-goal-command", content="/goal Old task",
session_generation=session.generation, require_existing_session=True,
)
try:
if operation == "reset":
await loop.sessions.state.reset(key)
else:
assert await loop.sessions.state.delete(key)
with pytest.raises(SessionConflictError):
await loop._dispatch_command_inline(message, key, message.content, loop.commands.dispatch)
current = await loop.sessions.state.read(key)
if operation == "delete":
assert current is None
else:
assert current is not None and current.generation != session.generation
assert current.messages == []
assert key not in loop._pending_queues
finally:
await loop.aclose()
+2 -1
View File
@@ -864,7 +864,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
model="test-model", model="test-model",
max_iterations=3, max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=AsyncMock(return_value="Continue working."), continuation_callback=AsyncMock(return_value="Continue the goal."),
terminal_injection_callback=terminal_injection_callback, terminal_injection_callback=terminal_injection_callback,
)) ))
@@ -1005,6 +1005,7 @@ async def test_runner_length_recovery_preserves_prefix_at_max_iterations():
max_iterations_message="limit reached", max_iterations_message="limit reached",
)) ))
assert provider.chat_stream_with_retry.await_count == 1
assert result.stop_reason == "max_iterations" assert result.stop_reason == "max_iterations"
assert result.final_content == "partial answer\n\nlimit reached" assert result.final_content == "partial answer\n\nlimit reached"
assert result.pending_stream_content == "\n\nlimit reached" assert result.pending_stream_content == "\n\nlimit reached"
+246 -37
View File
@@ -3,17 +3,27 @@ from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from agent.runner_helpers import make_run_spec from agent.runner_helpers import make_run_spec
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner from nanobot.agent.runner import AgentRunner
from nanobot.config.schema import AgentDefaults from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMProvider, LLMResponse from nanobot.providers.base import (
LLMProvider,
LLMResponse,
LLMUsage,
ProviderConversationState,
ToolCallRequest,
)
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
@pytest.fixture @pytest.fixture
def run_spec(): def run_spec():
provider = MagicMock(spec=LLMProvider) provider = MagicMock(spec=LLMProvider)
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done")) provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done"))
provider.supports_native_compaction.return_value = False
tools = MagicMock() tools = MagicMock()
tools.get_definitions.return_value = [] tools.get_definitions.return_value = []
tools.execute = AsyncMock(return_value="tool result")
return make_run_spec( return make_run_spec(
provider, provider,
initial_messages=[{"role": "user", "content": "do task"}], initial_messages=[{"role": "user", "content": "do task"}],
@@ -27,66 +37,265 @@ def run_spec():
@pytest.mark.parametrize("callback", [None, AsyncMock(return_value=None)], ids=["absent", "no-request"]) @pytest.mark.parametrize("callback", [None, AsyncMock(return_value=None)], ids=["absent", "no-request"])
async def test_runner_completes_without_a_continuation_request(run_spec, callback): async def test_runner_completes_without_a_continuation_request(run_spec, callback):
run_spec.continuation_callback = callback run_spec.continuation_callback = callback
result = await AgentRunner().run(run_spec) result = await AgentRunner().run(run_spec)
assert result.stop_reason == "completed" assert result.stop_reason == "completed"
assert result.final_content == "all done" assert result.final_content == "all done"
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1 assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
@pytest.mark.parametrize("max_iterations,finalize", [(1, True), (3, True), (8, False)]) async def test_continuation_extends_budget_without_reset(run_spec):
async def test_continuation_injects_text_without_exceeding_budget(run_spec, max_iterations, finalize): run_spec.max_iterations = 1
continuation = "Continue working toward the active sustained goal." total_rounds = 14
run_spec.max_iterations = max_iterations calls = 0
run_spec.finalize_on_max_iterations = finalize
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation) async def respond(**kwargs):
nonlocal calls
calls += 1
if calls > 1:
assert kwargs["messages"][-1]["content"] == f"Continue goal step {calls - 1}."
return LLMResponse(
content="all done" if calls == total_rounds else f"Progress {calls}.",
usage=LLMUsage.reported(input_tokens=1, output_tokens=1),
)
async def continuation():
return f"Continue goal step {calls}." if calls < total_rounds else None
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.continuation_callback = AsyncMock(side_effect=continuation)
run_spec.hook = AgentHook()
run_spec.hook.before_iteration = AsyncMock()
result = await AgentRunner().run(run_spec) result = await AgentRunner().run(run_spec)
assert result.stop_reason == "max_iterations" assert result.stop_reason == "completed"
requests = run_spec.runtime.provider.chat_stream_with_retry.await_args_list assert result.final_content == "all done"
assert len(requests) == max_iterations + int(finalize) assert result.had_injections is True
assert {"role": "user", "content": continuation} in result.messages assert calls == total_rounds
if max_iterations > 1: assert run_spec.continuation_callback.await_count == total_rounds
assert {"role": "user", "content": continuation} in requests[1].kwargs["messages"] assert [
if finalize: call.args[0].iteration for call in run_spec.hook.before_iteration.await_args_list
assert not requests[-1].kwargs.get("tools") ] == list(range(total_rounds))
continuations = [row for row in result.messages if row.get("_hidden_history")]
assert len(continuations) == total_rounds - 1
assert all(row["_hidden_history"] == {"kind": "internal_continuation"} for row in continuations)
assert len(result.round_usages) == total_rounds
assert result.usage.request_count == total_rounds
assert result.usage.total_tokens == total_rounds * 2
async def test_runner_does_not_request_continuation_on_error(run_spec): @pytest.mark.parametrize("finalize,finalization_fails", [(True, False), (False, False), (True, True)])
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse( async def test_goal_closing_after_tool_overrun_gets_bounded_finalization(run_spec, finalize, finalization_fails):
content=None, finish_reason="error", run_spec.max_iterations = 1
) run_spec.finalize_on_max_iterations = finalize
run_spec.max_iterations_message = "limit reached"
goal_active = True
tool_rounds = 14
completed_tools = 0
async def respond(**kwargs):
if goal_active:
assert kwargs["tools"] is not None
return LLMResponse(
content=None,
tool_calls=[ToolCallRequest(id=f"work-{completed_tools}", name="work", arguments={})],
usage=LLMUsage.reported(input_tokens=1, output_tokens=1),
)
assert kwargs["tools"] is None
assert kwargs["messages"][-2]["content"] == "goal completed"
assert kwargs["messages"][-1]["content"] == (
"Please provide your response to the user based on the conversation above."
)
return LLMResponse(
content="Provider unavailable." if finalization_fails else "All goal work is complete.",
finish_reason="error" if finalization_fails else "stop",
usage=LLMUsage.reported(input_tokens=2, output_tokens=3),
)
async def execute(*_args, **_kwargs):
nonlocal goal_active, completed_tools
completed_tools += 1
goal_active = completed_tools < tool_rounds
return "work completed" if goal_active else "goal completed"
async def continuation():
return "Continue the goal." if goal_active else None
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.tools.execute.side_effect = execute
run_spec.continuation_callback = AsyncMock(side_effect=continuation)
run_spec.hook = AgentHook()
run_spec.hook.finalize_content = MagicMock(side_effect=lambda _context, content: content)
result = await AgentRunner().run(run_spec)
assert completed_tools == tool_rounds
assert result.tools_used == ["work"] * tool_rounds
if finalization_fails:
assert result.stop_reason == "empty_final_response"
assert result.error == result.final_content == EMPTY_FINAL_RESPONSE_MESSAGE
else:
assert result.stop_reason == ("completed" if finalize else "max_iterations")
assert result.final_content == ("All goal work is complete." if finalize else "limit reached")
assert result.pending_stream_content == (result.final_content if finalize else None)
assert result.messages[-1]["content"] == result.final_content
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == tool_rounds + int(finalize)
assert run_spec.continuation_callback.await_count == tool_rounds
assert result.usage.request_count == tool_rounds + int(finalize)
assert len(result.round_usages) == tool_rounds + int(finalize)
if finalize and not finalization_fails:
assert run_spec.hook.finalize_content.call_args.args[0].iteration == tool_rounds
@pytest.mark.parametrize("finish_reason", ["error", "refusal", "content_filter"])
@pytest.mark.parametrize("tool_name", ["work", ""], ids=["valid-call", "malformed-call"])
async def test_runner_does_not_auto_continue_terminal_provider_response(run_spec, finish_reason, tool_name):
run_spec.max_iterations = 1
run_spec.runtime.provider.chat_stream_with_retry.side_effect = [
LLMResponse(
content="Provider stopped this request.", finish_reason=finish_reason,
tool_calls=[ToolCallRequest(id="blocked", name=tool_name, arguments={})],
),
AssertionError("terminal response must not trigger another model request"),
]
callback = AsyncMock(return_value="Continue working.") callback = AsyncMock(return_value="Continue working.")
run_spec.continuation_callback = callback run_spec.continuation_callback = callback
result = await AgentRunner().run(run_spec) result = await AgentRunner().run(run_spec)
assert result.stop_reason == "error" assert result.stop_reason == ("error" if finish_reason == "error" else "completed")
assert result.final_content == "Provider stopped this request."
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1 assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
callback.assert_not_called() run_spec.tools.execute.assert_not_awaited()
callback.assert_not_awaited()
async def test_runner_reads_continuation_state_after_each_response(run_spec): @pytest.mark.parametrize("response_kind", ["text", "tool"])
continuation = None async def test_real_followup_precedes_goal_at_iteration_cap(run_spec, response_kind):
calls = 0 followup = {"role": "user", "content": "Stop the goal and answer this instead."}
pending = []
goal_active = True
requests = []
run_spec.max_iterations = 1
async def respond(**kwargs): async def respond(**kwargs):
nonlocal continuation, calls requests.append(kwargs["messages"])
calls += 1 if len(requests) == 1:
if calls == 1: pending.append(followup)
continuation = "Write the article draft." return (
return LLMResponse(content="The goal is now active.") LLMResponse(content="Goal checkpoint.") if response_kind == "text" else
assert {"role": "user", "content": continuation} in kwargs["messages"] LLMResponse(content=None, tool_calls=[
continuation = None ToolCallRequest(id="work", name="work", arguments={}),
return LLMResponse(content="The draft is complete.") ])
)
assert kwargs["messages"][-1] == followup
assert not goal_active
return LLMResponse(content="Follow-up answered.")
async def drain():
nonlocal goal_active
batch = list(pending)
pending.clear()
if batch:
goal_active = False
return batch
async def continuation():
return "Continue the goal." if goal_active else None
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation) run_spec.injection_callback = drain
run_spec.continuation_callback = continuation
result = await AgentRunner().run(run_spec)
assert len(requests) == 2
assert pending == []
assert result.stop_reason == "completed"
assert result.final_content == "Follow-up answered."
assert result.had_injections is True
@pytest.mark.parametrize("response_kind", ["text", "tool"])
async def test_runner_propagates_continuation_failure(run_spec, response_kind):
run_spec.max_iterations = 1
if response_kind == "tool":
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
content=None, tool_calls=[ToolCallRequest(id="work", name="work", arguments={})],
)
run_spec.continuation_callback = AsyncMock(side_effect=RuntimeError("goal lookup failed"))
with pytest.raises(RuntimeError, match="goal lookup failed"):
await AgentRunner().run(run_spec)
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
@pytest.mark.parametrize("response_kind", ["text", "tool"])
async def test_continuation_preserves_transcript_checkpoints_and_provider_state(run_spec, tmp_path, response_kind):
from nanobot.agent.tools.filesystem import ListDirTool
from nanobot.agent.tools.registry import ToolRegistry
(tmp_path / "evidence.txt").write_text("evidence", encoding="utf-8")
tools = ToolRegistry()
tools.register(ListDirTool(workspace=tmp_path, allowed_dir=tmp_path))
run_spec.tools = tools
run_spec.max_iterations = 1
state = ProviderConversationState(
kind="openai_responses", provider="openai:test", model="test-model",
version=1, payload={"items": []},
)
final_state = ProviderConversationState(
kind="openai_responses", provider="openai:test", model="test-model",
version=1, payload={"items": [{"type": "message", "role": "assistant"}]},
)
run_spec.runtime.provider.can_resume_conversation_state.return_value = True
goal_active = True
requests = []
async def respond(**kwargs):
nonlocal goal_active
requests.append(kwargs)
if len(requests) == 1:
return (
LLMResponse(content="Observed evidence.", provider_state=state)
if response_kind == "text" else
LLMResponse(content=None, provider_state=state, tool_calls=[
ToolCallRequest(id="list", name="list_dir", arguments={"path": "."}),
])
)
goal_active = False
return LLMResponse(content="Final evidence summary.", provider_state=final_state)
async def continuation():
return "Continue." if goal_active else None
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.continuation_callback = continuation
run_spec.checkpoint_callback = AsyncMock()
run_spec.hook = AgentHook()
run_spec.hook.wants_streaming = MagicMock(return_value=True)
run_spec.hook.on_stream_end = AsyncMock()
result = await AgentRunner().run(run_spec) result = await AgentRunner().run(run_spec)
assert calls == 2
assert result.stop_reason == "completed" assert result.stop_reason == "completed"
assert result.final_content == "The draft is complete." assert result.final_content == "Final evidence summary."
assert len(requests) == 2
assert [call.kwargs["resuming"] for call in run_spec.hook.on_stream_end.await_args_list] == [True, False]
checkpoint = run_spec.checkpoint_callback.await_args.args[0]
assert checkpoint["phase"] == "final_response"
assert checkpoint["iteration"] == 1
assert checkpoint["assistant_message"] == result.messages[-1]
assert checkpoint["preceding_messages"] == result.messages[1:-1]
assert checkpoint["provider_state"] == result.provider_state
assert result.provider_state is not None
assert result.provider_state.payload == final_state.payload
assert result.provider_state.pending_messages == []
resumed_state = requests[1]["provider_context"].conversation_state
assert resumed_state.payload == state.payload
if response_kind == "text":
assert resumed_state.pending_messages == [{
"role": "user", "content": "Continue.",
"_hidden_history": {"kind": "internal_continuation"},
}]
else:
assert resumed_state.pending_messages[0]["role"] == "tool"
assert "evidence.txt" in resumed_state.pending_messages[0]["content"]
+2 -2
View File
@@ -379,7 +379,7 @@ async def test_goal_continuation_precedes_terminal_wait():
continuation_checks = 0 continuation_checks = 0
terminal_waits = 0 terminal_waits = 0
async def continue_goal() -> str | None: async def continue_goal():
nonlocal continuation_checks nonlocal continuation_checks
continuation_checks += 1 continuation_checks += 1
return "Continue the active goal." if continuation_checks == 1 else None return "Continue the active goal." if continuation_checks == 1 else None
@@ -1599,7 +1599,7 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
if log_content else "[content hidden]" if log_content else "[content hidden]"
) )
assert record["message"] == ( assert record["message"] == (
f"Injected {len(followups)} follow-up message(s) after final response (snapshot 1): {preview}" f"Injected {len(followups)} follow-up message(s) after final response: {preview}"
) )
assert record["level"].name == "INFO" assert record["level"].name == "INFO"
assert record["extra"]["session_key"] == "cli:c" assert record["extra"]["session_key"] == "cli:c"
+98 -23
View File
@@ -4,19 +4,22 @@ from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from agent.session_helpers import run_session, stop_loop from agent.session_helpers import run_session, stop_loop, visible_message
from nanobot.agent.automation_turns import AutomationTurnError from nanobot.agent.automation_turns import AutomationTurnError
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.cron import CronTool from nanobot.agent.tools.cron import CronTool
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import TurnCompleted
from nanobot.cron.service import CronService from nanobot.cron.service import CronService
from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META from nanobot.cron.session_turns import CRON_DEFER_UNTIL_IDLE_META, CRON_TRIGGER_META
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest from nanobot.goal.assembly import install_goal
from nanobot.providers.base import GenerationSettings, LLMResponse, LLMUsage, ToolCallRequest
from nanobot.runtime_context import public_history_messages from nanobot.runtime_context import public_history_messages
from nanobot.session.automation_turns import AUTOMATION_HISTORY_META from nanobot.session.automation_turns import AUTOMATION_HISTORY_META
from nanobot.session.goal_state import GOAL_STATE_KEY from nanobot.session.goal_state import GOAL_STATE_KEY
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import SessionManager from nanobot.session.manager import SessionManager
from nanobot.session.recovery import ( from nanobot.session.recovery import (
PENDING_FOLLOWUPS_KEY, PENDING_FOLLOWUPS_KEY,
@@ -36,6 +39,7 @@ async def loop(tmp_path):
provider.estimate_prompt_tokens.return_value = (100, "test") provider.estimate_prompt_tokens.return_value = (100, "test")
agent = AgentLoop( agent = AgentLoop(
bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model", bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal,
) )
agent.tools.get_definitions = MagicMock(return_value=[]) agent.tools.get_definitions = MagicMock(return_value=[])
try: try:
@@ -592,7 +596,7 @@ async def test_cron_restriction_follows_the_current_turn(loop, tmp_path, start_w
@pytest.mark.parametrize("complete_on_followup", [False, True]) @pytest.mark.parametrize("complete_on_followup", [False, True])
async def test_goal_continuation_after_followup_keeps_control_identity(loop, complete_on_followup): async def test_active_goal_prioritizes_real_followup_before_internal_prompt(loop, complete_on_followup):
loop.max_iterations = 1 loop.max_iterations = 1
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None)) loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
loop.tools.execute = AsyncMock(return_value="ok") loop.tools.execute = AsyncMock(return_value="ok")
@@ -612,15 +616,14 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
await asyncio.sleep(0) await asyncio.sleep(0)
elif complete_on_followup or len(requests) == 3: elif complete_on_followup or len(requests) == 3:
await loop.sessions.state.update_metadata(session.key, { await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "complete", "objective": "Finish the long goal"}, GOAL_STATE_KEY: {"status": "completed", "objective": "Finish the long goal"},
}) })
return LLMResponse(content="done") return LLMResponse(content="done")
return LLMResponse( assert len(requests) <= 3
content="working", finish_reason="tool_calls", return LLMResponse(content="One more check is needed.")
tool_calls=[ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={})],
)
loop.provider.chat_stream_with_retry = chat loop.provider.chat_stream_with_retry = chat
loop.runner.run = AsyncMock(wraps=loop.runner.run)
run_task = asyncio.create_task(loop.run()) run_task = asyncio.create_task(loop.run())
try: try:
await loop.bus.publish_inbound(InboundMessage( await loop.bus.publish_inbound(InboundMessage(
@@ -630,12 +633,15 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
while not requests or "cli:test" in loop._pending_queues: while not requests or "cli:test" in loop._pending_queues:
await asyncio.sleep(0.01) await asyncio.sleep(0.01)
assert len(requests) == (2 if complete_on_followup else 3) assert len(requests) == (2 if complete_on_followup else 3)
continuation_text = "Continue the active sustained goal after the previous turn" assert visible_message(requests[1][-1])["content"] == "Inspect file B first"
assert continuation_text not in str(requests[1])
if not complete_on_followup: if not complete_on_followup:
assert continuation_text in str(requests[2]) assert is_hidden_history_message(requests[2][-1])
assert "Please continue working toward the objective" in requests[2][-1]["content"]
loop.runner.run.assert_awaited_once()
loop.sessions.invalidate("cli:test") loop.sessions.invalidate("cli:test")
history = public_history_messages(loop.sessions.get_or_create("cli:test").messages) history = public_history_messages([
row for row in loop.sessions.get_or_create("cli:test").messages if not is_hidden_history_message(row)
])
assert [message["content"] for message in history if message["role"] == "user"] == [ assert [message["content"] for message in history if message["role"] == "user"] == [
"Start the goal", "Inspect file B first", "Start the goal", "Inspect file B first",
] ]
@@ -644,7 +650,7 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
await asyncio.wait_for(run_task, timeout=3) await asyncio.wait_for(run_task, timeout=3)
async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop): async def test_active_goal_keeps_origin_until_queued_independent_command_runs(loop):
loop._unified_session = True loop._unified_session = True
loop.max_iterations = 1 loop.max_iterations = 1
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None)) loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
@@ -654,15 +660,21 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"} session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"}
loop.sessions.save(session) loop.sessions.save(session)
requests = [] requests = []
completed = []
loop.bus.subscribe(completed.append, TurnCompleted)
loop.consolidator.compact_idle_session = AsyncMock()
loop.runner.run = AsyncMock(wraps=loop.runner.run)
persisted_origin = None persisted_origin = None
async def chat(**kwargs): async def chat(**kwargs):
nonlocal persisted_origin nonlocal persisted_origin
context = current_request_context() context = current_request_context()
requests.append((context.chat_id, context.message_id, context.turn_id)) requests.append((context.chat_id, context.message_id, context.turn_id))
tokens = len(requests) * 10
usage = LLMUsage(input_tokens=tokens, output_tokens=0, total_tokens=tokens, reported_tokens=tokens)
if len(requests) == 1: if len(requests) == 1:
await loop.bus.publish_inbound(InboundMessage( await loop.bus.publish_inbound(InboundMessage(
channel="feishu", sender_id="user", chat_id="chat-b", content="Inspect B first", channel="feishu", sender_id="user", chat_id="chat-b", content="/compact",
metadata={"message_id": "message-b"}, metadata={"message_id": "message-b"},
)) ))
async with asyncio.timeout(3): async with asyncio.timeout(3):
@@ -671,12 +683,13 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
elif len(requests) == 3: elif len(requests) == 3:
persisted = SessionManager(loop.workspace).get_or_create(key) persisted = SessionManager(loop.workspace).get_or_create(key)
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY] persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
await loop.tools.get("message").execute(content="Continuation reply") loop.consolidator.compact_idle_session.assert_not_awaited()
await loop.tools.get("message").execute(content="Goal reply")
await loop.sessions.state.mutate_metadata( await loop.sessions.state.mutate_metadata(
key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="complete"), key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="completed"),
) )
return LLMResponse(content="done") return LLMResponse(content="done", usage=usage)
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[ return LLMResponse(content="working", finish_reason="tool_calls", usage=usage, tool_calls=[
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}), ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}),
]) ])
@@ -690,16 +703,78 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
async with asyncio.timeout(5): async with asyncio.timeout(5):
while not requests or key in loop._pending_queues: while not requests or key in loop._pending_queues:
await asyncio.sleep(0.01) await asyncio.sleep(0.01)
assert [request[:2] for request in requests] == [ assert [request[:2] for request in requests] == [("chat-a", "message-a")] * 3
("chat-a", "message-a"), ("chat-b", "message-b"), ("chat-a", "message-a"), assert len({request[2] for request in requests}) == 1
] loop.runner.run.assert_awaited_once()
assert requests[2][2] == requests[0][2] loop.consolidator.compact_idle_session.assert_awaited_once()
assert persisted_origin == {"message_id": "message-a", "turn_id": requests[0][2]} assert persisted_origin == {"message_id": "message-a", "turn_id": requests[0][2]}
by_chat = {event.context.chat_id: event for event in completed}
assert set(by_chat) == {"chat-a", "chat-b"}
assert by_chat["chat-a"].outcome == "completed"
assert len(completed) == 2
assert by_chat["chat-a"].usage.total_tokens == 60
assert [usage.total_tokens for usage in by_chat["chat-a"].round_usages] == [10, 20, 30]
assert by_chat["chat-b"].outcome == "completed"
assert by_chat["chat-b"].context.metadata["message_id"] == "message-b"
assert by_chat["chat-b"].usage is None
assert by_chat["chat-b"].round_usages == ()
replies = [] replies = []
while not loop.bus.outbound.empty(): while not loop.bus.outbound.empty():
reply = loop.bus.outbound.get_nowait() reply = loop.bus.outbound.get_nowait()
if reply.content == "Continuation reply": if reply.content == "Goal reply":
replies.append((reply.chat_id, reply.metadata.get("message_id"))) replies.append((reply.chat_id, reply.metadata.get("message_id")))
assert replies == [("chat-a", "message-a")] assert replies == [("chat-a", "message-a")]
finally: finally:
await stop_loop(loop, worker, timeout=3) await stop_loop(loop, worker, timeout=3)
@pytest.mark.parametrize("operation", ["reset", "delete"])
async def test_stop_does_not_restore_an_obsolete_generation(loop, operation):
key = "websocket:stop-old-generation"
session = loop.sessions.get_or_create(key)
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Old goal"}
loop.sessions.save(session)
waiting = asyncio.Event()
release = asyncio.Event()
calls = 0
async def chat(**_kwargs):
nonlocal calls
calls += 1
if calls == 1:
waiting.set()
await release.wait()
return LLMResponse(content="New turn handled.", finish_reason="content_filter")
loop.provider.chat_stream_with_retry = chat
worker = asyncio.create_task(loop.run())
try:
await loop.bus.publish_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="stop-old-generation", content="Work",
))
await asyncio.wait_for(waiting.wait(), 5)
if operation == "reset":
await loop.sessions.state.reset(key)
else:
assert await loop.sessions.state.delete(key)
assert await loop._cancel_active_tasks(key) == 1
current = await loop.sessions.state.read_header(key)
if operation == "delete":
assert current is None
else:
assert current is not None and current.generation != session.generation
assert GOAL_STATE_KEY not in current.metadata
release.set()
await loop.bus.publish_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="stop-old-generation", content="Fresh input",
))
async with asyncio.timeout(5):
while calls < 2 or key in loop._pending_queues:
await asyncio.sleep(0)
current = await loop.sessions.state.read_header(key)
assert current is not None and current.generation != session.generation
assert GOAL_STATE_KEY not in current.metadata
finally:
release.set()
await stop_loop(loop, worker, timeout=5)
@@ -491,11 +491,15 @@ def test_public_history_omits_cli_app_breadcrumb():
def test_fork_session_before_user_index_copies_only_prefix(tmp_path): def test_fork_session_before_user_index_copies_only_prefix(tmp_path):
from nanobot.goal.runtime import GOAL_GENERATION_VOLATILE_KEYS
manager = SessionManager(tmp_path) manager = SessionManager(tmp_path)
manager.exclude_generation_metadata(GOAL_GENERATION_VOLATILE_KEYS)
source = manager.get_or_create("websocket:source") source = manager.get_or_create("websocket:source")
source.metadata["webui"] = True source.metadata["webui"] = True
source.metadata["title"] = "Old title" source.metadata["title"] = "Old title"
source.metadata["goal_state"] = {"status": "active", "objective": "do not inherit"} source.metadata["goal_state"] = {"status": "active", "objective": "do not inherit"}
source.metadata["_sustained_goal_continuation_rounds"] = 7
source.add_message("user", "round1") source.add_message("user", "round1")
source.add_message("assistant", "answer1") source.add_message("assistant", "answer1")
source.add_message("user", "round2 fork me") source.add_message("user", "round2 fork me")
@@ -514,6 +518,7 @@ def test_fork_session_before_user_index_copies_only_prefix(tmp_path):
assert forked.metadata["webui"] is True assert forked.metadata["webui"] is True
assert "title" not in forked.metadata assert "title" not in forked.metadata
assert "goal_state" not in forked.metadata assert "goal_state" not in forked.metadata
assert "_sustained_goal_continuation_rounds" not in forked.metadata
saved = manager.read_session_file("websocket:fork") saved = manager.read_session_file("websocket:fork")
assert [m["content"] for m in saved["messages"]] == ["round1", "answer1"] assert [m["content"] for m in saved["messages"]] == ["round1", "answer1"]
@@ -93,6 +93,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
) )
loop.sessions.get_or_create = MagicMock(return_value=session) loop.sessions.get_or_create = MagicMock(return_value=session)
loop.sessions.state.read = AsyncMock(return_value=session)
loop.sessions.save = MagicMock() loop.sessions.save = MagicMock()
async def _cancel(*_args, **_kwargs): async def _cancel(*_args, **_kwargs):
+2 -1
View File
@@ -11,7 +11,8 @@ from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.file_state import FileStateStore from nanobot.agent.tools.file_state import FileStateStore
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import cmd_new, register_builtin_commands from nanobot.command.application import register_builtin_commands
from nanobot.command.builtin import cmd_new
from nanobot.command.router import CommandContext, CommandRouter from nanobot.command.router import CommandContext, CommandRouter
from nanobot.config.schema import AgentDefaults, Config from nanobot.config.schema import AgentDefaults, Config
from nanobot.session.keys import UNIFIED_SESSION_KEY from nanobot.session.keys import UNIFIED_SESSION_KEY
+70 -44
View File
@@ -1,27 +1,27 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from dataclasses import replace
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.context import ( from nanobot.agent.tools.context import (
RequestContext, RequestContext,
current_request_context, current_request_context,
request_context, request_context,
) )
from nanobot.agent.tools.long_task import (
CreateGoalTool,
UpdateGoalTool,
)
from nanobot.agent.tools.registry import ToolRegistry from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.outbound_events import GoalStateSyncEvent from nanobot.bus.outbound_events import GoalStateSyncEvent
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.goal.assembly import install_goal
from nanobot.goal.runtime import GoalExecutionPolicy
from nanobot.goal.tools import CreateGoalTool, UpdateGoalTool
from nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARS from nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARS
from nanobot.session.manager import SessionManager from nanobot.session.manager import SessionManager
from nanobot.session.turn_continuation import should_finalize_on_max_iterations
from nanobot.session.webui_turns import WebuiTurnCoordinator from nanobot.session.webui_turns import WebuiTurnCoordinator
@@ -60,7 +60,15 @@ def _tools(
return create, update, rc return create, update, rc
async def _bound_context(sm: SessionManager, ctx: RequestContext) -> RequestContext:
if ctx.session_generation is not None or ctx.session_key is None:
return ctx
session = await sm.state.get_header(ctx.session_key)
return replace(ctx, session_generation=session.generation)
async def _execute(tool, ctx: RequestContext, *, allowed: bool = True, **kwargs): async def _execute(tool, ctx: RequestContext, *, allowed: bool = True, **kwargs):
ctx = await _bound_context(tool._sessions, ctx)
with request_context(ctx), goal_mutation_permission(allowed): with request_context(ctx), goal_mutation_permission(allowed):
return await tool.execute(**kwargs) return await tool.execute(**kwargs)
@@ -70,7 +78,6 @@ async def test_create_goal_records_goal_metadata(tmp_path):
sm = SessionManager(tmp_path) sm = SessionManager(tmp_path)
create, _update, ctx = _tools(sm) create, _update, ctx = _tools(sm)
await sm.state.get("websocket:c1") await sm.state.get("websocket:c1")
await sm.state.update_metadata("websocket:c1", {"_sustained_goal_continuation_rounds": 12})
out = await _execute( out = await _execute(
create, create,
@@ -86,15 +93,9 @@ async def test_create_goal_records_goal_metadata(tmp_path):
assert blob["status"] == "active" assert blob["status"] == "active"
assert blob["objective"] == "Do the thing" assert blob["objective"] == "Do the thing"
assert blob["ui_summary"] == "thing" assert blob["ui_summary"] == "thing"
sess = sm.get_or_create("websocket:c1") assert SessionManager(tmp_path).get_or_create(sess.key).metadata[GOAL_STATE_KEY] == blob
assert "_sustained_goal_continuation_rounds" not in sess.metadata with GoalExecutionPolicy(sm.state).scope(sess.key, sess.generation, persistent=True) as scope:
assert "_sustained_goal_continuation_rounds" not in ( assert "Do the thing" in await scope.continuation_prompt()
SessionManager(tmp_path).get_or_create("websocket:c1").metadata
)
assert not should_finalize_on_max_iterations(
pending_queue_available=True,
session_metadata=sess.metadata,
)
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -153,6 +154,7 @@ async def test_update_goal_complete_closes_active_goal(tmp_path):
sm = SessionManager(tmp_path) sm = SessionManager(tmp_path)
create, update, ctx = _tools(sm) create, update, ctx = _tools(sm)
ctx = await _bound_context(sm, ctx)
with request_context(ctx), goal_mutation_permission(True): with request_context(ctx), goal_mutation_permission(True):
await create.execute(objective="X") await create.execute(objective="X")
out = await update.execute(action="complete", recap="Done.") out = await update.execute(action="complete", recap="Done.")
@@ -174,10 +176,6 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_path
create, update, ctx = _tools(sm) create, update, ctx = _tools(sm)
await _execute(create, ctx, objective="Old") await _execute(create, ctx, objective="Old")
await sm.state.update_metadata(
"websocket:c1",
{"_sustained_goal_continuation_rounds": 12},
)
out = await _execute( out = await _execute(
update, update,
_request_context(), _request_context(),
@@ -193,14 +191,9 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_path
assert blob["previous_objective"] == "Old" assert blob["previous_objective"] == "Old"
assert blob["ui_summary"] == "new" assert blob["ui_summary"] == "new"
sess = sm.get_or_create("websocket:c1") sess = sm.get_or_create("websocket:c1")
assert "_sustained_goal_continuation_rounds" not in sess.metadata assert SessionManager(tmp_path).get_or_create(sess.key).metadata[GOAL_STATE_KEY] == blob
assert "_sustained_goal_continuation_rounds" not in ( with GoalExecutionPolicy(sm.state).scope(sess.key, sess.generation, persistent=True) as scope:
SessionManager(tmp_path).get_or_create("websocket:c1").metadata assert "New" in await scope.continuation_prompt()
)
assert not should_finalize_on_max_iterations(
pending_queue_available=True,
session_metadata=sess.metadata,
)
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -209,7 +202,6 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
create, update, _context = _tools(sm) create, update, _context = _tools(sm)
sess = sm.get_or_create("websocket:c1") sess = sm.get_or_create("websocket:c1")
sess.metadata["marker"] = {"keep": True} sess.metadata["marker"] = {"keep": True}
sess.metadata["_sustained_goal_continuation_rounds"] = 12
sm.save(sess) sm.save(sess)
original_save = sm._store.replace_metadata original_save = sm._store.replace_metadata
create_context = _request_context() create_context = _request_context()
@@ -221,18 +213,11 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
with pytest.raises(OSError, match="disk unavailable"): with pytest.raises(OSError, match="disk unavailable"):
await _execute(create, create_context, objective="Old") await _execute(create, create_context, objective="Old")
assert sess.metadata == { assert sess.metadata == {"marker": {"keep": True}}
"marker": {"keep": True},
"_sustained_goal_continuation_rounds": 12,
}
assert GOAL_STATE_KEY not in SessionManager(tmp_path).get_or_create("websocket:c1").metadata assert GOAL_STATE_KEY not in SessionManager(tmp_path).get_or_create("websocket:c1").metadata
monkeypatch.setattr(sm._store, "replace_metadata", original_save) monkeypatch.setattr(sm._store, "replace_metadata", original_save)
assert "Goal recorded" in await _execute(create, create_context, objective="Old") assert "Goal recorded" in await _execute(create, create_context, objective="Old")
await sm.state.update_metadata(
"websocket:c1",
{"_sustained_goal_continuation_rounds": 12},
)
sess = sm.get_or_create("websocket:c1") sess = sm.get_or_create("websocket:c1")
replace_context = _request_context() replace_context = _request_context()
@@ -241,10 +226,10 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
await _execute(update, replace_context, action="replace", objective="New") await _execute(update, replace_context, action="replace", objective="New")
assert sess.metadata[GOAL_STATE_KEY]["objective"] == "Old" assert sess.metadata[GOAL_STATE_KEY]["objective"] == "Old"
assert sess.metadata["_sustained_goal_continuation_rounds"] == 12 assert sess.metadata["marker"] == {"keep": True}
persisted = SessionManager(tmp_path).get_or_create("websocket:c1").metadata persisted = SessionManager(tmp_path).get_or_create("websocket:c1").metadata
assert persisted[GOAL_STATE_KEY]["objective"] == "Old" assert persisted[GOAL_STATE_KEY]["objective"] == "Old"
assert persisted["_sustained_goal_continuation_rounds"] == 12 assert persisted["marker"] == {"keep": True}
monkeypatch.setattr(sm._store, "replace_metadata", original_save) monkeypatch.setattr(sm._store, "replace_metadata", original_save)
assert "Goal replaced" in await _execute( assert "Goal replaced" in await _execute(
@@ -254,7 +239,7 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypa
objective="New", objective="New",
) )
sess = sm.get_or_create("websocket:c1") sess = sm.get_or_create("websocket:c1")
assert "_sustained_goal_continuation_rounds" not in sess.metadata assert sess.metadata["marker"] == {"keep": True}
assert ( assert (
SessionManager(tmp_path).get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"] SessionManager(tmp_path).get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"]
== "New" == "New"
@@ -294,7 +279,7 @@ async def test_active_goal_create_failure_preserves_permission_for_replace(tmp_p
create, update, initial_context = _tools(sm) create, update, initial_context = _tools(sm)
assert "Goal recorded" in await _execute(create, initial_context, objective="Old") assert "Goal recorded" in await _execute(create, initial_context, objective="Old")
replacement_context = _request_context() replacement_context = await _bound_context(sm, _request_context())
with request_context(replacement_context), goal_mutation_permission(True): with request_context(replacement_context), goal_mutation_permission(True):
create_out = await create.execute(objective="New") create_out = await create.execute(objective="New")
assert goal_mutation_allowed() is True assert goal_mutation_allowed() is True
@@ -323,7 +308,7 @@ async def test_update_goal_replace_requires_explicit_goal_permission(tmp_path):
assert "replacing the goal is unavailable for this turn" in str(unauthorized) assert "replacing the goal is unavailable for this turn" in str(unauthorized)
assert "/goal <task>" in str(unauthorized) assert "/goal <task>" in str(unauthorized)
assert sm.get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"] == "Old" assert sm.get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"] == "Old"
replace_context = _request_context() replace_context = await _bound_context(sm, _request_context())
with request_context(replace_context), goal_mutation_permission(True): with request_context(replace_context), goal_mutation_permission(True):
assert "Goal replaced" in await update.execute(action="replace", objective="New") assert "Goal replaced" in await update.execute(action="replace", objective="New")
@@ -352,6 +337,8 @@ async def test_goal_tools_keep_request_context_per_task(tmp_path):
metadata=_goal_metadata(), metadata=_goal_metadata(),
) )
ctx_a = await _bound_context(sm, ctx_a)
ctx_b = await _bound_context(sm, ctx_b)
task_a = asyncio.create_task(_execute(create, ctx_a, objective="Goal A")) task_a = asyncio.create_task(_execute(create, ctx_a, objective="Goal A"))
task_b = asyncio.create_task(_execute(create, ctx_b, objective="Goal B")) task_b = asyncio.create_task(_execute(create, ctx_b, objective="Goal B"))
await asyncio.gather(task_a, task_b) await asyncio.gather(task_a, task_b)
@@ -390,7 +377,7 @@ async def test_registry_does_not_reuse_goal_context_after_request_scope(tmp_path
sess = sm.get_or_create("websocket:c1") sess = sm.get_or_create("websocket:c1")
sess.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Old"} sess.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Old"}
sm.save(sess) sm.save(sess)
ctx = _request_context() ctx = await _bound_context(sm, _request_context())
with request_context(ctx), goal_mutation_permission(True): with request_context(ctx), goal_mutation_permission(True):
create_out = await registry.execute("create_goal", {"objective": "New"}) create_out = await registry.execute("create_goal", {"objective": "New"})
@@ -472,11 +459,12 @@ async def test_update_goal_without_active_is_noop_message(tmp_path):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_goal_tools_registered_in_base_registry(tmp_path): async def test_goal_tools_registered_by_builtin_assembly(tmp_path):
bus = MessageBus() bus = MessageBus()
provider = MagicMock() provider = MagicMock()
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model") loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal)
create = loop.tools.get("create_goal") create = loop.tools.get("create_goal")
update = loop.tools.get("update_goal") update = loop.tools.get("update_goal")
@@ -502,3 +490,41 @@ async def test_goal_tools_registered_in_base_registry(tmp_path):
).lower() ).lower()
assert "authoriz" not in model_visible_contract assert "authoriz" not in model_visible_contract
assert "/goal" not in model_visible_contract assert "/goal" not in model_visible_contract
@pytest.mark.parametrize("caller_supplied", [False, True])
async def test_goal_assembly_preserves_builtin_plugin_precedence(tmp_path, monkeypatch, caller_supplied):
from nanobot.agent.tools.loader import ToolLoader
class ConflictingTool(Tool):
@property
def name(self):
return "create_goal"
@property
def description(self):
return "Synthetic conflicting tool"
@property
def parameters(self):
return {"type": "object", "properties": {}}
async def execute(self, **kwargs):
return "external"
monkeypatch.setattr(ToolLoader, "_discover_plugins", lambda _self: {"external": ConflictingTool})
registry = ToolRegistry()
supplied = ConflictingTool()
if caller_supplied:
registry.register(supplied)
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
tool_registry=registry, builtin_assembly=install_goal)
try:
if caller_supplied:
assert loop.tools.get("create_goal") is supplied
else:
assert isinstance(loop.tools.get("create_goal"), CreateGoalTool)
finally:
await loop.aclose()
+1 -2
View File
@@ -206,8 +206,7 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
publisher.record_turn_latency("cli:direct", 123) publisher.record_turn_latency("cli:direct", 123)
first_round = LLMUsage.reported(input_tokens=40, output_tokens=2) first_round = LLMUsage.reported(input_tokens=40, output_tokens=2)
second_round = LLMUsage.reported(input_tokens=60, output_tokens=3) second_round = LLMUsage.reported(input_tokens=60, output_tokens=3)
publisher.record_turn_usage("cli:direct", [first_round]) publisher.record_turn_usage("cli:direct", [first_round, second_round])
publisher.record_turn_usage("cli:direct", [second_round])
await publisher.turn_completed( await publisher.turn_completed(
channel="cli", channel="cli",
+5 -1
View File
@@ -56,8 +56,9 @@ def test_interactive_agent_routes_a_complete_user_turn(
channels_config = None channels_config = None
@classmethod @classmethod
def from_config(cls, _config, bus, **_kwargs): def from_config(cls, _config, bus, **kwargs):
instance = cls(bus) instance = cls(bus)
seen["builtin_assembly"] = kwargs["builtin_assembly"]
seen["loop"] = instance seen["loop"] = instance
return instance return instance
@@ -109,6 +110,8 @@ def test_interactive_agent_routes_a_complete_user_turn(
monkeypatch.setattr("nanobot.cli.agent._model_display", lambda *_args: ("test-model", "")) monkeypatch.setattr("nanobot.cli.agent._model_display", lambda *_args: ("test-model", ""))
monkeypatch.setattr("nanobot.cli.agent.consume_restart_notice_from_env", lambda: None) monkeypatch.setattr("nanobot.cli.agent.consume_restart_notice_from_env", lambda: None)
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _AgentLoop) monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _AgentLoop)
install_goal = MagicMock()
monkeypatch.setattr("nanobot.goal.assembly.install_goal", install_goal)
monkeypatch.setattr("nanobot.cli.agent.StreamRenderer", _Renderer) monkeypatch.setattr("nanobot.cli.agent.StreamRenderer", _Renderer)
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: object()) monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: object())
monkeypatch.setattr( monkeypatch.setattr(
@@ -136,6 +139,7 @@ def test_interactive_agent_routes_a_complete_user_turn(
assert inbound.metadata == {"_wants_stream": True} assert inbound.metadata == {"_wants_stream": True}
loop = seen["loop"] loop = seen["loop"]
assert isinstance(loop, _AgentLoop) assert isinstance(loop, _AgentLoop)
assert seen["builtin_assembly"] is install_goal
assert loop.aclose_calls == 1 assert loop.aclose_calls == 1
assert len(renderers) == 1 assert len(renderers) == 1
renderer = renderers[0] renderer = renderers[0]
+57 -12
View File
@@ -91,6 +91,11 @@ class _StopGatewayError(RuntimeError):
pass pass
def _patch_fake_agent_loop(monkeypatch, target, fake):
monkeypatch.setattr(target, fake)
monkeypatch.setattr("nanobot.goal.assembly.install_goal", MagicMock())
class _GatewayAgentContractStub: class _GatewayAgentContractStub:
"""Minimal stable AgentLoop surface required by gateway assembly tests.""" """Minimal stable AgentLoop surface required by gateway assembly tests."""
@@ -1689,6 +1694,46 @@ def test_agent_uses_explicit_config_path(mock_agent_runtime, tmp_path: Path):
assert mock_agent_runtime["load_config"].call_args.args == (config_path.resolve(),) assert mock_agent_runtime["load_config"].call_args.args == (config_path.resolve(),)
def test_one_shot_agent_assembles_goal_without_background_queue(monkeypatch, tmp_path: Path) -> None:
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
from nanobot.session.manager import SessionManager
config = Config()
config.agents.defaults.workspace = str(tmp_path / "workspace")
config.agents.defaults.max_tool_iterations = 1
config.bind_source_path(tmp_path / "instance" / "config.json")
provider = _fake_provider()
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="goal", name="create_goal", arguments={"objective": "Do the synthetic task."},
)]),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
)]),
LLMResponse(content="Verified."),
])
monkeypatch.setattr("nanobot.cli.agent._load_runtime_config", lambda *_args: config)
monkeypatch.setattr("nanobot.cli.agent.sync_workspace_templates", lambda *_args: None)
monkeypatch.setattr("nanobot.cli.agent.is_default_workspace", lambda *_args: False)
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: provider)
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "instance" / "config.json")
result = runner.invoke(app, ["agent", "--classic", "-m", "/goal Do the synthetic task."])
assert result.exit_code == 0, result.output
assert provider.chat_stream_with_retry.await_count == 3
calls = provider.chat_stream_with_retry.await_args_list
assert all(call.kwargs["tools"] for call in calls[:2])
assert not calls[2].kwargs.get("tools")
assert "Verified." in result.output
sessions = SessionManager(config.workspace_path, sessions_root=tmp_path / "instance" / "sessions")
goal = sessions.get_or_create("cli:direct").metadata["goal_state"]
assert goal["status"] == "completed" and goal["objective"] == "Do the synthetic task."
def test_agent_config_sets_active_path(monkeypatch, tmp_path: Path) -> None: def test_agent_config_sets_active_path(monkeypatch, tmp_path: Path) -> None:
config_file = tmp_path / "instance" / "config.json" config_file = tmp_path / "instance" / "config.json"
config_file.parent.mkdir(parents=True) config_file.parent.mkdir(parents=True)
@@ -1720,7 +1765,7 @@ def test_agent_config_sets_active_path(monkeypatch, tmp_path: Path) -> None:
async def aclose(self) -> None: async def aclose(self) -> None:
return None return None
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None) monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None)
result = runner.invoke(app, ["agent", "-m", "hello", "-c", str(config_file)]) result = runner.invoke(app, ["agent", "-m", "hello", "-c", str(config_file)])
@@ -1762,7 +1807,7 @@ def test_agent_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path: Pa
return None return None
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None) monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None)
result = runner.invoke(app, ["agent", "-m", "hello", "-c", str(config_file)]) result = runner.invoke(app, ["agent", "-m", "hello", "-c", str(config_file)])
@@ -1812,7 +1857,7 @@ def test_agent_workspace_override_does_not_migrate_legacy_cron(
return None return None
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None) monkeypatch.setattr("nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None)
result = runner.invoke( result = runner.invoke(
@@ -1868,7 +1913,7 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
return None return None
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
monkeypatch.setattr("nanobot.cli.agent.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.agent.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None "nanobot.cli.terminal._print_agent_response", lambda *_args, **_kwargs: None
) )
@@ -2248,7 +2293,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
session_manager=_FakeSessionManager, session_manager=_FakeSessionManager,
cron_service=_FakeCron, cron_service=_FakeCron,
) )
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
monkeypatch.setattr("nanobot.cli.gateway_runtime.ensure_webui_session_archives", AsyncMock(return_value=[])) monkeypatch.setattr("nanobot.cli.gateway_runtime.ensure_webui_session_archives", AsyncMock(return_value=[]))
monkeypatch.setattr("nanobot.cli.gateway_runtime.evaluate_response", _unexpected_evaluator) monkeypatch.setattr("nanobot.cli.gateway_runtime.evaluate_response", _unexpected_evaluator)
@@ -3156,7 +3201,7 @@ def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -
message_bus=MessageBus, message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(), session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
) )
monkeypatch.setattr("nanobot.cli.commands.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.api.server.create_app", _fake_create_app) monkeypatch.setattr("nanobot.api.server.create_app", _fake_create_app)
monkeypatch.setattr("aiohttp.web.run_app", _fake_run_app) monkeypatch.setattr("aiohttp.web.run_app", _fake_run_app)
@@ -3341,7 +3386,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
raise AssertionError("unbound cron job must not be evaluated for delivery") raise AssertionError("unbound cron job must not be evaluated for delivery")
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _StopAfterCronSetup) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _StopAfterCronSetup)
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.cli.gateway_runtime.evaluate_response", "nanobot.cli.gateway_runtime.evaluate_response",
@@ -3457,7 +3502,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
raise AssertionError("bound cron must not use legacy response evaluator") raise AssertionError("bound cron must not use legacy response evaluator")
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCron)
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _StopAfterCronSetup) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _StopAfterCronSetup)
monkeypatch.setattr("nanobot.cli.gateway_runtime.evaluate_response", _unexpected_evaluator) monkeypatch.setattr("nanobot.cli.gateway_runtime.evaluate_response", _unexpected_evaluator)
@@ -3699,7 +3744,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
seen["local_trigger_queue_kwargs"] = kwargs seen["local_trigger_queue_kwargs"] = kwargs
raise _StopGatewayError("stop") raise _StopGatewayError("stop")
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.triggers.local_runner.run_local_trigger_queue", "nanobot.triggers.local_runner.run_local_trigger_queue",
@@ -4017,7 +4062,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
message_bus=MessageBus, message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(), session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
) )
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)
monkeypatch.setattr("asyncio.start_server", _fake_start_server) monkeypatch.setattr("asyncio.start_server", _fake_start_server)
@@ -4235,7 +4280,7 @@ def test_gateway_failure_exits_nonzero_after_cleanup(
message_bus=MessageBus, message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(), session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
) )
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.cli.gateway_runtime.MCPProvider", _FakeMCPProvider) monkeypatch.setattr("nanobot.cli.gateway_runtime.MCPProvider", _FakeMCPProvider)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)
@@ -4404,7 +4449,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
message_bus=MessageBus, message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(), session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
) )
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop) _patch_fake_agent_loop(monkeypatch, "nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager) monkeypatch.setattr("nanobot.channels.manager.ChannelManager", _FakeChannelManager)
monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService) monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)
monkeypatch.setattr("asyncio.start_server", _fake_start_server) monkeypatch.setattr("asyncio.start_server", _fake_start_server)
+1 -2
View File
@@ -7,9 +7,8 @@ import pytest
from nanobot.agent.memory import MemoryStore from nanobot.agent.memory import MemoryStore
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.command.application import build_help_text, builtin_command_palette
from nanobot.command.builtin import ( from nanobot.command.builtin import (
build_help_text,
builtin_command_palette,
cmd_dream, cmd_dream,
cmd_dream_log, cmd_dream_log,
cmd_dream_prompt, cmd_dream_prompt,
@@ -5,11 +5,8 @@ from types import SimpleNamespace
import pytest import pytest
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.command.builtin import ( from nanobot.command.application import build_help_text, builtin_command_palette
build_help_text, from nanobot.command.builtin import cmd_evaluator_prompt
builtin_command_palette,
cmd_evaluator_prompt,
)
from nanobot.command.router import CommandContext from nanobot.command.router import CommandContext
from nanobot.utils.evaluator import default_evaluator_prompt from nanobot.utils.evaluator import default_evaluator_prompt
+21
View File
@@ -0,0 +1,21 @@
import subprocess
import sys
import pytest
@pytest.mark.parametrize("first_module", ["nanobot.goal.command", "nanobot.command.builtin"])
def test_goal_and_builtin_commands_import_in_either_order(first_module):
script = f"""
import {first_module}
from nanobot.goal.command import register_goal_command
from nanobot.command import CommandRouter, register_builtin_commands
router = CommandRouter()
register_builtin_commands(router)
assert router.is_dispatchable_command('/goal ship it')
standalone = CommandRouter()
register_goal_command(standalone)
assert standalone.is_dispatchable_command('/goal ship it')
"""
subprocess.run([sys.executable, "-B", "-c", script], check=True)
+89 -15
View File
@@ -1,5 +1,5 @@
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
@@ -7,15 +7,15 @@ from nanobot.agent.goal_permission import goal_mutation_allowed
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import ( from nanobot.command.application import (
build_help_text, build_help_text,
builtin_command_palette, builtin_command_palette,
cmd_goal,
cmd_model,
register_builtin_commands, register_builtin_commands,
) )
from nanobot.command.router import CommandContext, CommandRouter from nanobot.command.builtin import cmd_model
from nanobot.command.router import CommandContext, CommandExpansion, CommandInput, CommandRouter
from nanobot.config.schema import ModelPresetConfig from nanobot.config.schema import ModelPresetConfig
from nanobot.goal.command import cmd_goal, register_goal_command
from nanobot.session.history_visibility import HIDDEN_HISTORY_META from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.session.model_selection import ( from nanobot.session.model_selection import (
SESSION_MODEL_PRESET_METADATA_KEY, SESSION_MODEL_PRESET_METADATA_KEY,
@@ -241,7 +241,8 @@ def test_model_command_in_help_and_palette() -> None:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_goal_command_shows_usage_without_args(tmp_path) -> None: async def test_goal_command_shows_usage_without_args(tmp_path) -> None:
loop = _make_loop(tmp_path) loop = _make_loop(tmp_path)
out = await cmd_goal(_ctx(loop, "/goal")) ctx = _ctx(loop, "/goal")
out = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
assert out is not None assert out is not None
assert out.channel == "cli" assert out.channel == "cli"
assert out.chat_id == "direct" assert out.chat_id == "direct"
@@ -256,11 +257,18 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_se
task = "检查 /tmp/project\n保留现有文件。" task = "检查 /tmp/project\n保留现有文件。"
command = f"/goal {task}" command = f"/goal {task}"
ctx = _ctx_session(loop, command, args=task) ctx = _ctx_session(loop, command, args=task)
ctx.msg.media = ["attachment.png"]
ctx.msg.metadata = {"request_id": "request-1"}
ctx.session = await loop.sessions.state.get(ctx.key) if with_session else None ctx.session = await loop.sessions.state.get(ctx.key) if with_session else None
out = await cmd_goal(ctx) expansion = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
assert isinstance(expansion, CommandExpansion)
out = await loop._prepare_command_expansion(ctx, expansion)
assert isinstance(out, InboundMessage) assert isinstance(out, InboundMessage)
assert ctx.msg.content == command assert ctx.msg.content == command
assert out.content == task assert out.content == task
assert out.media == ["attachment.png"]
assert out.metadata["request_id"] == "request-1"
assert out.metadata["original_command"] == "/goal"
assert out.metadata["original_content"] == command assert out.metadata["original_content"] == command
assert out.metadata["goal_requested"] is True assert out.metadata["goal_requested"] is True
assert out.metadata[HIDDEN_HISTORY_META] == {"kind": "goal_request"} assert out.metadata[HIDDEN_HISTORY_META] == {"kind": "goal_request"}
@@ -269,6 +277,8 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_se
assert [(row["role"], row["content"]) for row in session.messages] == [ assert [(row["role"], row["content"]) for row in session.messages] == [
("user", command), ("user", command),
] ]
assert session.messages[0]["_command"] is True
assert session.messages[0]["media"] == ["attachment.png"]
@@ -277,16 +287,72 @@ async def test_goal_command_registered_on_router(tmp_path) -> None:
router = CommandRouter() router = CommandRouter()
register_builtin_commands(router) register_builtin_commands(router)
loop = _make_loop(tmp_path) loop = _make_loop(tmp_path)
usage = await router.dispatch(_ctx(loop, "/goal"))
assert isinstance(usage, OutboundMessage)
assert usage.content == "Usage: /goal <long-running task description>"
assert usage.metadata == {"render_as": "text"}
ctx = _ctx_session(loop, "/goal ship it", args="ship it") ctx = _ctx_session(loop, "/goal ship it", args="ship it")
ctx.session = await loop.sessions.state.get(ctx.key) ctx.session = await loop.sessions.state.get(ctx.key)
out = await router.dispatch(ctx) out = await router.dispatch(ctx)
assert isinstance(out, InboundMessage) assert isinstance(out, CommandExpansion)
assert out.content == "ship it" assert out.message.content == "ship it"
assert out.metadata["goal_requested"] is True assert out.message.metadata["goal_requested"] is True
assert goal_mutation_allowed() is False assert goal_mutation_allowed() is False
@pytest.mark.asyncio
async def test_goal_command_can_be_registered_independently(tmp_path) -> None:
router = CommandRouter()
register_goal_command(router)
loop = _make_loop(tmp_path)
usage = await router.dispatch(_ctx(loop, "/goal"))
ctx = _ctx_session(loop, "/goal ship it")
ctx.session = await loop.sessions.state.get(ctx.key)
task = await router.dispatch(ctx)
assert isinstance(usage, OutboundMessage)
assert usage.content == "Usage: /goal <long-running task description>"
assert isinstance(task, CommandExpansion)
assert task.message.content == "ship it"
assert task.message.metadata["goal_requested"] is True
@pytest.mark.asyncio
@pytest.mark.parametrize("with_session", [False, True])
async def test_goal_command_rejects_transient_session_without_changing_history(
tmp_path, monkeypatch, with_session,
) -> None:
loop = _make_loop(tmp_path)
loop.provider.aclose = AsyncMock()
ctx = _ctx(loop, "/goal keep going", args="keep going")
ctx.is_user_turn = True
ctx.msg.metadata = {"request_id": "request-1"}
session = await loop.sessions.state.register_transient(ctx.key)
session.add_message("user", "Earlier private message")
await loop.sessions.state.prepare_input(session)
ctx.session = session if with_session else None
prepare_input = AsyncMock(wraps=loop.sessions.state.prepare_input)
monkeypatch.setattr(loop.sessions.state, "prepare_input", prepare_input)
try:
expansion = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
assert isinstance(expansion, CommandExpansion)
out = await loop._prepare_command_expansion(ctx, expansion)
assert isinstance(out, OutboundMessage)
assert out.content == "Goals can't start in a temporary session. Use a persistent session for `/goal`."
assert out.metadata == {"request_id": "request-1", "render_as": "text"}
prepare_input.assert_not_awaited()
assert [row["content"] for row in session.messages] == ["Earlier private message"]
current = await loop.sessions.state.read(ctx.key)
assert current is not None and not current.policy.persist
assert [row["content"] for row in current.messages] == ["Earlier private message"]
assert loop.sessions.read_session_file(ctx.key) is None
finally:
await loop.aclose()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None: async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
loop = _make_loop(tmp_path) loop = _make_loop(tmp_path)
@@ -305,17 +371,25 @@ async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
is_user_turn=False, is_user_turn=False,
) )
out = await cmd_goal(ctx) out = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
assert isinstance(out, OutboundMessage) assert isinstance(out, OutboundMessage)
assert "only be started by a user" in out.content assert "only be started by a user" in out.content
assert ctx.turn_scopes == []
def test_goal_command_in_help_and_palette() -> None: def test_goal_command_in_help_and_palette() -> None:
palette = builtin_command_palette() palette = builtin_command_palette()
goal = next(item for item in palette if item["command"] == "/goal") goal = next(item for item in palette if item["command"] == "/goal")
assert goal["arg_hint"] == "<goal>" assert goal == {
assert goal["lifecycle"] == "agent_turn_with_args" "command": "/goal",
assert goal["accepts_args"] is True "title": "Start long-running goal",
"description": "Tell the agent to treat the request as a long-running goal.",
"icon": "activity",
"arg_hint": "<goal>",
"lifecycle": "agent_turn_with_args",
"accepts_args": True,
}
commands = [item["command"] for item in palette]
goal_index = commands.index("/goal")
assert commands[goal_index - 1:goal_index + 2] == ["/history", "/goal", "/trigger"]
assert "/goal <goal>" in build_help_text() assert "/goal <goal>" in build_help_text()
+3 -1
View File
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from nanobot.command.builtin import ( from nanobot.command.application import (
builtin_command_starts_agent_turn, builtin_command_starts_agent_turn,
register_builtin_commands, register_builtin_commands,
) )
@@ -141,6 +141,7 @@ class TestMidTurnCommandDispatchedDirectly:
async def test_help_dispatched_with_session_none( async def test_help_dispatched_with_session_none(
self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock, self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock,
) -> None: ) -> None:
fake_loop.commands = router
ctx = CommandContext( ctx = CommandContext(
msg=fake_msg, session=None, msg=fake_msg, session=None,
key="test:chat1", raw="/help", loop=fake_loop, key="test:chat1", raw="/help", loop=fake_loop,
@@ -151,6 +152,7 @@ class TestMidTurnCommandDispatchedDirectly:
assert result.chat_id == "chat1" assert result.chat_id == "chat1"
assert result.metadata["render_as"] == "text" assert result.metadata["render_as"] == "text"
assert "/new" in result.content assert "/new" in result.content
assert "/goal <goal>" in result.content
assert "/pairing [list|approve <code>|deny <code>|revoke <user_id>]" in result.content assert "/pairing [list|approve <code>|deny <code>|revoke <user_id>]" in result.content
@pytest.mark.asyncio @pytest.mark.asyncio
+2 -1
View File
@@ -7,7 +7,8 @@ from nanobot.agent.loop import AgentLoop
from nanobot.agent.skills import SkillsLoader from nanobot.agent.skills import SkillsLoader
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import cmd_skill, register_builtin_commands from nanobot.command.application import register_builtin_commands
from nanobot.command.builtin import cmd_skill
from nanobot.command.router import CommandContext, CommandRouter from nanobot.command.router import CommandContext, CommandRouter
from nanobot.config.schema import ModelPresetConfig from nanobot.config.schema import ModelPresetConfig
+1 -1
View File
@@ -6,7 +6,7 @@ from types import SimpleNamespace
import pytest import pytest
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.command.builtin import build_help_text, register_builtin_commands from nanobot.command.application import build_help_text, register_builtin_commands
from nanobot.command.router import CommandContext, CommandRouter from nanobot.command.router import CommandContext, CommandRouter
from nanobot.session.keys import UNIFIED_SESSION_KEY from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.triggers.local_store import LocalTriggerStore from nanobot.triggers.local_store import LocalTriggerStore
-43
View File
@@ -6,7 +6,6 @@ from nanobot.session.goal_state import (
discard_legacy_goal_state_key, discard_legacy_goal_state_key,
explicit_goal_requested, explicit_goal_requested,
goal_state_runtime_lines, goal_state_runtime_lines,
goal_state_ws_blob,
parse_goal_state, parse_goal_state,
sustained_goal_active, sustained_goal_active,
) )
@@ -78,48 +77,6 @@ def test_parse_goal_state_accepts_json_string():
} }
def test_goal_state_ws_blob_inactive_when_missing_or_completed():
assert goal_state_ws_blob(None) == {"active": False}
assert goal_state_ws_blob({}) == {"active": False}
assert goal_state_ws_blob({GOAL_STATE_KEY: {"status": "completed", "objective": "x"}}) == {
"active": False,
}
def test_goal_state_ws_blob_active_shape():
meta = {
GOAL_STATE_KEY: {
"status": "active",
"objective": "Build feature.",
"ui_summary": "feat",
},
}
assert goal_state_ws_blob(meta) == {
"active": True,
"status": "active",
"ui_summary": "feat",
"objective": "Build feature.",
}
def test_goal_state_ws_blob_preserves_blocked_state_for_host_attention():
meta = {
GOAL_STATE_KEY: {
"status": "blocked",
"objective": "Deploy safely.",
"ui_summary": "Approval required",
"recap": "Production access is required.",
},
}
assert goal_state_ws_blob(meta) == {
"active": False,
"status": "blocked",
"ui_summary": "Approval required",
"objective": "Deploy safely.",
"recap": "Production access is required.",
}
def test_sustained_goal_active_false_when_missing_or_completed(): def test_sustained_goal_active_false_when_missing_or_completed():
assert sustained_goal_active(None) is False assert sustained_goal_active(None) is False
assert sustained_goal_active({}) is False assert sustained_goal_active({}) is False
+86 -142
View File
@@ -1,163 +1,107 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from types import SimpleNamespace
import pytest import pytest
from nanobot.agent.tools.context import RequestContext from nanobot.agent.tools.context import RequestContext
from nanobot.bus.events import InboundMessage from nanobot.goal.runtime import GoalExecutionPolicy
from nanobot.session.goal_state import ( from nanobot.session.goal_state import GOAL_STATE_KEY
GOAL_STATE_KEY, from nanobot.session.manager import SessionManager
explicit_goal_requested,
sustained_goal_turn,
)
from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
from nanobot.session.turn_continuation import ( from nanobot.session.turn_continuation import (
INTERNAL_CONTINUATION_KIND_META,
INTERNAL_CONTINUATION_META, INTERNAL_CONTINUATION_META,
INTERNAL_CONTINUATION_RUN_STARTED_AT_META, iteration_limit_context,
_save_skip_for_turn, record_iteration_limit,
internal_continuation_run_started_at, save_skip_for_turn,
maybe_continue_turn, should_persist_user_message,
should_finalize_on_max_iterations,
should_stream_budget_response,
sustained_goal_continuation_inbound,
) )
@pytest.mark.asyncio @pytest.mark.parametrize("status", ["completed", "cancelled", "blocked"])
async def test_maybe_continue_turn_queues_internal_message(): async def test_goal_scope_reads_current_objective_and_closure(tmp_path, status):
meta = { sessions = SessionManager(tmp_path)
GOAL_STATE_KEY: { session = await sessions.state.get("feishu:c1")
"status": "active", try:
"objective": "Finish the migration.", with GoalExecutionPolicy(sessions.state).scope(session.key, session.generation, persistent=True) as scope:
"ui_summary": "migration", assert await scope.continuation_prompt() is None
}, await sessions.state.update_metadata(session.key, {
} GOAL_STATE_KEY: {"status": "active", "objective": "Finish the migration."},
messages = [ })
{"role": "system", "content": "system"}, assert "Finish the migration." in await scope.continuation_prompt()
{"role": "user", "content": "start"}, await sessions.state.update_metadata(session.key, {
{"role": "assistant", "content": "paused"}, GOAL_STATE_KEY: {"status": "active", "objective": "A replacement."},
] })
pending: asyncio.Queue[InboundMessage] = asyncio.Queue() prompt = await scope.continuation_prompt()
ctx = SimpleNamespace( assert "A replacement." in prompt and "Finish the migration." not in prompt
session=SimpleNamespace(metadata=meta), await sessions.state.update_metadata(session.key, {
msg=InboundMessage( GOAL_STATE_KEY: {"status": status, "objective": "A replacement."},
channel="feishu", })
sender_id="u1", assert await scope.continuation_prompt() is None
chat_id="c1", finally:
content="start", await sessions.state.aclose()
metadata={
"message_id": "msg-1",
"origin_message_id": "msg-0",
"_wants_stream": True,
"webui": True,
"original_command": "/goal",
"goal_requested": True,
},
),
session_key="feishu:c1",
request_context=RequestContext(
channel="feishu", chat_id="c1", message_id="msg-1", turn_id="turn-1",
),
pending_queue=pending,
stop_reason="max_iterations",
final_content="paused",
all_messages=messages,
suppress_response=False,
visible_run_started_at=1234.5,
)
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is True
queued = pending.get_nowait()
assert queued.sender_id == "system:continuation"
assert queued.metadata[INTERNAL_CONTINUATION_META] is True
assert queued.metadata[INTERNAL_CONTINUATION_KIND_META] == "sustained_goal"
assert sustained_goal_continuation_inbound(queued.metadata) is True
assert queued.metadata[INTERNAL_CONTINUATION_RUN_STARTED_AT_META] == 1234.5
assert internal_continuation_run_started_at(queued.metadata) == 1234.5
assert queued.metadata["webui"] is True
assert queued.metadata["message_id"] == "msg-1"
assert queued.metadata[REQUEST_ORIGIN_METADATA_KEY] == {
"message_id": "msg-1", "turn_id": "turn-1",
}
assert REQUEST_ORIGIN_METADATA_KEY not in ctx.msg.metadata
assert queued.metadata["origin_message_id"] == "msg-0"
assert queued.metadata["_wants_stream"] is True
assert not explicit_goal_requested(queued.metadata)
assert sustained_goal_turn(meta, message_metadata=queued.metadata)
assert "Finish the migration." in queued.content
assert ctx.all_messages == messages[:-1]
assert ctx.final_content == ""
assert ctx.suppress_response is True
assert meta["_sustained_goal_continuation_rounds"] == 1
def test_generic_internal_continuation_is_not_a_sustained_goal_continuation() -> None: @pytest.mark.parametrize("operation", ["reset", "delete"])
assert sustained_goal_continuation_inbound({INTERNAL_CONTINUATION_META: True}) is False async def test_goal_scope_does_not_continue_a_replaced_generation(tmp_path, operation):
sessions = SessionManager(tmp_path)
session = await sessions.state.get("cli:test")
await sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "active", "objective": "Old objective."},
})
try:
with GoalExecutionPolicy(sessions.state).scope(session.key, session.generation, persistent=True) as scope:
assert "Old objective." in await scope.continuation_prompt()
if operation == "reset":
await sessions.state.reset(session.key)
else:
assert await sessions.state.delete(session.key)
assert await scope.continuation_prompt() is None
replacement = await sessions.state.get(session.key)
await sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "active", "objective": "New generation's objective."},
})
assert replacement.generation != session.generation
assert await scope.continuation_prompt() is None
with GoalExecutionPolicy(sessions.state).scope(session.key, replacement.generation, persistent=True) as scope:
assert "New generation's objective." in await scope.continuation_prompt()
finally:
await sessions.state.aclose()
@pytest.mark.asyncio async def test_iteration_limit_guidance_is_for_the_next_user_request_not_recovery(tmp_path):
async def test_internal_continuation_respects_round_limit(): sessions = SessionManager(tmp_path)
meta = { session = await sessions.state.get("cli:test")
GOAL_STATE_KEY: {"status": "active", "objective": "x"}, request = RequestContext(channel="cli", chat_id="test", session_key=session.key)
"_sustained_goal_continuation_rounds": 12, try:
} await sessions.state.mutate_metadata(
ctx = SimpleNamespace( session.key, lambda metadata: record_iteration_limit(metadata, "max_iterations"),
session=SimpleNamespace(metadata=meta), )
msg=InboundMessage(channel="feishu", sender_id="u1", chat_id="c1", content="start"), context = await iteration_limit_context(sessions.state, request)
session_key="feishu:c1", assert context is not None and "Follow the current request" in context.content
pending_queue=asyncio.Queue(), recovery = RequestContext(
stop_reason="max_iterations", channel="cli", chat_id="test", session_key=session.key,
final_content="paused", metadata={INTERNAL_CONTINUATION_META: True},
all_messages=[], )
) assert await iteration_limit_context(sessions.state, recovery) is None
await sessions.state.mutate_metadata(
assert should_stream_budget_response( session.key, lambda metadata: record_iteration_limit(metadata, "completed"),
stop_reason="max_iterations", )
pending_queue_available=True, assert await iteration_limit_context(sessions.state, request) is None
session_metadata=meta, finally:
) await sessions.state.aclose()
assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is False
def test_internal_continuation_requires_budget_boundary_and_queue(): def test_explicit_recovery_does_not_persist_a_synthetic_user_input():
meta = {GOAL_STATE_KEY: {"status": "active", "objective": "x"}} metadata = {INTERNAL_CONTINUATION_META: True}
assert not should_persist_user_message(metadata)
assert should_stream_budget_response( assert save_skip_for_turn(
stop_reason="completed", message_metadata=metadata, initial_message_count=3, input_persisted_early=False,
pending_queue_available=True, ) == 3
session_metadata=meta, assert should_persist_user_message(None)
)
assert should_stream_budget_response(
stop_reason="max_iterations",
pending_queue_available=False,
session_metadata=meta,
)
assert not should_finalize_on_max_iterations(
pending_queue_available=True,
session_metadata=meta,
)
assert should_finalize_on_max_iterations(
pending_queue_available=False,
session_metadata=meta,
)
assert should_finalize_on_max_iterations(
pending_queue_available=True,
session_metadata={},
)
def test_save_skip_unchanged_for_standalone_current_message(): def test_save_skip_unchanged_for_standalone_current_message():
assert _save_skip_for_turn( assert save_skip_for_turn(
message_metadata=None, message_metadata=None, initial_message_count=3, input_persisted_early=True,
initial_message_count=3,
input_persisted_early=True,
) == 3 ) == 3
assert _save_skip_for_turn( assert save_skip_for_turn(
message_metadata=None, message_metadata=None, initial_message_count=3, input_persisted_early=False,
initial_message_count=3,
input_persisted_early=False,
) == 2 ) == 2
+183
View File
@@ -506,6 +506,189 @@ async def test_ephemeral_run_does_not_invoke_persisted_turn_callback(tmp_path):
assert seen == [] assert seen == []
@pytest.mark.asyncio
@pytest.mark.parametrize("existing_session", [False, True])
@pytest.mark.parametrize("streamed", [False, True])
async def test_ephemeral_goal_is_rejected_without_changing_session(
tmp_path, monkeypatch, existing_session, streamed,
):
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.goal.assembly import install_goal
provider = _fake_provider("test-model")
provider.aclose = AsyncMock()
provider.chat_stream_with_retry = AsyncMock()
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal)
bot = Nanobot(loop)
key = "sdk:temporary-goal"
if existing_session:
session = await loop.sessions.state.get(key)
session.add_message("user", "Earlier durable message")
await loop.sessions.state.prepare_input(session)
before = loop.sessions.read_session_file(key)
prepare_input = AsyncMock(wraps=loop.sessions.state.prepare_input)
monkeypatch.setattr(loop.sessions.state, "prepare_input", prepare_input)
try:
if streamed:
run = await bot.run_streamed("/goal temporary task", session_key=key, ephemeral=True)
result = await run.wait()
else:
result = await bot.run("/goal temporary task", session_key=key, ephemeral=True)
assert result.content == "Goals can't start in a temporary session. Use a persistent session for `/goal`."
provider.chat_stream_with_retry.assert_not_awaited()
prepare_input.assert_not_awaited()
assert loop.sessions.read_session_file(key) == before
current = await loop.sessions.state.read(key)
if existing_session:
assert current is not None and current.policy.persist
assert [row["content"] for row in current.messages] == ["Earlier durable message"]
else:
assert current is None
finally:
await bot.aclose()
@pytest.mark.asyncio
async def test_sdk_from_config_assembles_goal_for_direct_runs(tmp_path, monkeypatch):
import json
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
config = tmp_path / "instance" / "config.json"
config.parent.mkdir()
config.write_text(json.dumps({"agents": {"defaults": {
"workspace": str(tmp_path / "workspace"), "model": "test-model", "maxToolIterations": 1,
}}}), encoding="utf-8")
provider = _fake_provider("test-model")
provider.aclose = AsyncMock()
provider.generation = GenerationSettings()
provider.estimate_prompt_tokens.return_value = (100, "test")
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal", arguments={"objective": "Verify the SDK task."},
)]),
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
)]),
LLMResponse(content="Verified."),
])
monkeypatch.setattr("nanobot.providers.factory.make_provider", lambda *_args: provider)
bot = Nanobot.from_config(config)
try:
result = await bot.run("/goal Verify the SDK task", session_key="sdk:goal")
assert result.content == "Verified."
session = await bot._loop.sessions.state.read("sdk:goal")
assert session.metadata["goal_state"]["status"] == "completed"
assert provider.chat_stream_with_retry.await_count == 3
assert all(call.kwargs["tools"] for call in provider.chat_stream_with_retry.await_args_list[:2])
assert not provider.chat_stream_with_retry.await_args.kwargs.get("tools")
finally:
await bot.aclose()
@pytest.mark.asyncio
async def test_ephemeral_sdk_turn_cannot_update_a_durable_goal(tmp_path):
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.goal.assembly import install_goal
from nanobot.providers.base import LLMResponse, ToolCallRequest
provider = _fake_provider("test-model")
provider.aclose = AsyncMock()
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="update", name="update_goal", arguments={"action": "complete", "recap": "Not allowed."},
)]),
LLMResponse(content="Temporary reply."),
])
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal)
bot = Nanobot(loop)
session = await loop.sessions.state.get("sdk:existing-goal")
await loop.sessions.state.update_metadata(session.key, {
"goal_state": {"status": "active", "objective": "Keep this durable goal."},
})
before = loop.sessions.read_session_file(session.key)
try:
result = await bot.run("Temporary question", session_key=session.key, ephemeral=True)
assert result.content == "Temporary reply."
assert "requires an active chat session" in str(provider.chat_stream_with_retry.await_args.kwargs["messages"])
assert loop.sessions.read_session_file(session.key) == before
current = await loop.sessions.state.read(session.key)
assert current.metadata["goal_state"]["status"] == "active"
finally:
await bot.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["clear", "delete"])
async def test_sdk_goal_tool_cannot_write_after_session_generation_changes(tmp_path, operation):
from nanobot.agent.hook import AgentHook
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.goal.assembly import install_goal
from nanobot.providers.base import LLMResponse, ToolCallRequest
waiting = asyncio.Event()
release = asyncio.Event()
executed = asyncio.Event()
finish = asyncio.Event()
class HoldTool(AgentHook):
async def before_execute_tools(self, _context):
waiting.set()
await release.wait()
async def _settle(self):
executed.set()
await finish.wait()
async def after_execute_tool(self, _context, _call, _tool, _params, _result):
await self._settle()
async def on_execute_tool_error(self, _context, _call, _tool, _params, _error):
await self._settle()
provider = _fake_provider("test-model")
provider.aclose = AsyncMock()
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content=None, tool_calls=[
ToolCallRequest(id="create", name="create_goal", arguments={"objective": "Old execution."}),
]))
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal)
bot = Nanobot(loop)
key = "sdk:generation-check"
run = asyncio.create_task(bot.run("/goal Old execution", session_key=key, hooks=[HoldTool()]))
try:
await asyncio.wait_for(waiting.wait(), 5)
if operation == "clear":
await bot.sessions.clear(key)
else:
assert await bot.sessions.delete(key)
release.set()
await asyncio.wait_for(executed.wait(), 5)
current = await loop.sessions.state.read_header(key)
if operation == "delete":
assert current is None
else:
assert current is not None and "goal_state" not in current.metadata
finish.set()
await asyncio.gather(run, return_exceptions=True)
current = await loop.sessions.state.read_header(key)
if operation == "delete":
assert current is None
else:
assert current is not None and "goal_state" not in current.metadata
finally:
release.set()
finish.set()
await asyncio.gather(run, return_exceptions=True)
await bot.aclose()
def test_import_from_top_level(): def test_import_from_top_level():
import nanobot import nanobot
+6 -3
View File
@@ -619,17 +619,20 @@ async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_process_direct_accepts_media() -> None: async def test_process_direct_accepts_media() -> None:
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventPublisher
loop = AgentLoop.__new__(AgentLoop) loop = AgentLoop.__new__(AgentLoop)
loop._session_locks = {} loop._session_locks = {}
loop.bus = MessageBus() loop.bus = MessageBus()
loop.runtime_event_publisher = RuntimeEventPublisher(loop.bus) loop.turn_delivery_factory = TurnDeliveryFactory(loop.bus)
loop.runtime_event_publisher = loop.turn_delivery_factory.runtime_event_publisher
captured_msg = None captured_msg = None
async def fake_process(msg, *, session_key="", on_progress=None, on_stream=None, on_stream_end=None, ephemeral=False): async def fake_process(
msg, *, session_key="", on_progress=None, on_stream=None, on_stream_end=None, ephemeral=False, delivery=None,
):
nonlocal captured_msg nonlocal captured_msg
captured_msg = msg captured_msg = msg
return None return None
+5 -2
View File
@@ -86,7 +86,7 @@ async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kind
if kind == "injection": if kind == "injection":
spec.injection_callback = AsyncMock(side_effect=ValueError(_SECRET)) spec.injection_callback = AsyncMock(side_effect=ValueError(_SECRET))
elif kind == "continuation": elif kind == "continuation":
spec.continuation_callback = MagicMock(side_effect=ValueError(_SECRET)) spec.continuation_callback = AsyncMock(side_effect=ValueError(_SECRET))
elif kind == "finalization": elif kind == "finalization":
spec.max_iterations = 0 spec.max_iterations = 0
provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(_SECRET)) provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(_SECRET))
@@ -101,11 +101,14 @@ async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kind
spec.hook = BrokenFinallyHook() spec.hook = BrokenFinallyHook()
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)): with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
if kind == "finally": if kind in {"finally", "continuation"}:
with pytest.raises(ValueError, match=_SECRET): with pytest.raises(ValueError, match=_SECRET):
await AgentRunner().run(spec) await AgentRunner().run(spec)
else: else:
await AgentRunner().run(spec) await AgentRunner().run(spec)
if kind == "continuation":
assert all(_SECRET not in r["message"] for r in diagnostic_records)
return
errors = [r for r in diagnostic_records if r["level"].name == "ERROR"] errors = [r for r in diagnostic_records if r["level"].name == "ERROR"]
assert errors assert errors
assert all((r["exception"] is not None) is log_content for r in errors) assert all((r["exception"] is not None) is log_content for r in errors)
+200
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio import asyncio
import json import json
import os
import signal import signal
import socket import socket
import subprocess import subprocess
@@ -14,6 +15,7 @@ from urllib.parse import quote
import httpx import httpx
import pytest import pytest
import websockets import websockets
from aiohttp import web
from nanobot.agent.subagent_sessions import SubagentSessions from nanobot.agent.subagent_sessions import SubagentSessions
from nanobot.agent.subagent_status import SubagentStatus from nanobot.agent.subagent_status import SubagentStatus
@@ -473,3 +475,201 @@ def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
asyncio.run(assert_attach_state()) asyncio.run(assert_attach_state())
finally: finally:
_stop_gateway(second) _stop_gateway(second)
@pytest.mark.parametrize("stop_during_checkpoint", [False, True])
async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during_checkpoint: bool) -> None:
"""Exercise the actual gateway and WebSocket with a synthetic local model."""
checkpoint_waiting = asyncio.Event()
closing_request = asyncio.Event()
release_close = asyncio.Event()
requests: list[dict] = []
async def barrier(_request: web.Request) -> web.Response:
checkpoint_waiting.set()
return web.Response(text="ready")
async def model(request: web.Request) -> web.StreamResponse:
payload = await request.json()
is_title = any(
"You write short, neutral chat titles" in str(message.get("content"))
for message in payload.get("messages", [])
)
if is_title:
text, reason, tool = "Synthetic goal", "stop", None
else:
requests.append(payload)
number = len(requests)
text, reason, tool = None, "tool_calls", None
if number == 1:
tool = ("create_goal", {"objective": "Verify the synthetic task."})
elif number <= 16:
tool = ("list_dir", {"path": "."})
elif stop_during_checkpoint:
assert number == 17
assert "Handle this independent input" in str(payload["messages"])
text, reason = "Handled independent input.", "content_filter"
elif number == 17:
closing_request.set()
await release_close.wait()
tool = ("update_goal", {"action": "complete", "recap": "Verified."})
else:
assert number == 18 and not payload.get("tools")
text, reason = "Verified.", "stop"
message: dict = {"role": "assistant", "content": text}
if tool is not None:
message["tool_calls"] = [{
"id": f"call-{len(requests)}", "type": "function",
"function": {"name": tool[0], "arguments": json.dumps(tool[1])},
}]
usage = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
if not payload.get("stream"):
return web.json_response({
"id": "synthetic", "object": "chat.completion", "created": 1,
"model": "smoke-model", "choices": [{"index": 0, "message": message, "finish_reason": reason}],
"usage": usage,
})
delta: dict = {"role": "assistant"}
if text is not None:
delta["content"] = text
if tool is not None:
delta["tool_calls"] = [{"index": 0, **message["tool_calls"][0]}]
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
await response.prepare(request)
for choice in (
{"index": 0, "delta": delta, "finish_reason": None},
{"index": 0, "delta": {}, "finish_reason": reason},
):
chunk = {"id": "synthetic", "object": "chat.completion.chunk", "created": 1,
"model": "smoke-model", "choices": [choice], "usage": usage}
await response.write(f"data: {json.dumps(chunk)}\n\n".encode())
await response.write(b"data: [DONE]\n\n")
return response
app = web.Application()
app.router.add_get("/barrier", barrier)
app.router.add_post("/v1/chat/completions", model)
server = web.AppRunner(app)
await server.setup()
site = web.TCPSite(server, "127.0.0.1", 0)
await site.start()
assert site._server is not None and site._server.sockets # noqa: SLF001
model_port = site._server.sockets[0].getsockname()[1] # noqa: SLF001
ws_port, gateway_port = _free_port(), _free_port()
home, workspace = tmp_path / "home", tmp_path / "workspace"
home.mkdir()
workspace.mkdir()
config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log"
_write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port)
config = json.loads(config_path.read_text(encoding="utf-8"))
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
config_path.write_text(json.dumps(config), encoding="utf-8")
launcher = """
import asyncio, sys, urllib.request
from nanobot.session.state import SessionState
original = SessionState.checkpoint_view
barrier_url = sys.argv[3]
held = False
async def checkpoint(self, session, payload):
global held
await original(self, session, payload)
results = payload.get('completed_tool_results', [])
if barrier_url and not held and results and results[-1].get('tool_call_id') == 'call-16':
held = True
def signal():
with urllib.request.urlopen(barrier_url) as response:
response.read()
await asyncio.to_thread(signal)
await asyncio.Event().wait()
SessionState.checkpoint_view = checkpoint
home, config = sys.argv[1:3]
sys.argv = ['nanobot', '--home', home, 'gateway', '--config', config]
from nanobot.cli.entry import main
main()
"""
env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_")}
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
process = None
try:
with log_path.open("wb") as log:
process = subprocess.Popen(
[sys.executable, "-c", launcher, str(home), str(config_path),
f"http://127.0.0.1:{model_port}/barrier" if stop_during_checkpoint else ""],
cwd=Path(__file__).resolve().parents[2], env=env, stdout=log,
stderr=subprocess.STDOUT, creationflags=creationflags,
)
bootstrap = await asyncio.to_thread(
_wait_for_bootstrap, f"http://127.0.0.1:{ws_port}", process, log_path,
)
async with websockets.connect(bootstrap["ws_url"] + "?token=" + bootstrap["token"] + "&client_id=goal-e2e") as ws:
await _recv_until(ws, "ready")
await ws.send(json.dumps({"type": "new_chat"}))
chat_id = (await _recv_until(ws, "attached"))["chat_id"]
await _recv_until(ws, "session_updated")
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
"content": "/goal Verify the synthetic task",
"webui": True, "turn_id": "goal-e2e"}))
events: list[dict] = []
async def receive_until(predicate):
async with asyncio.timeout(20):
while True:
event = json.loads(await ws.recv())
events.append(event)
if predicate(event):
return event
if stop_during_checkpoint:
await asyncio.wait_for(checkpoint_waiting.wait(), 20)
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
"content": "/stop", "webui": True}))
end = await receive_until(lambda event: event.get("event") == "turn_end")
assert end.get("outcome") == "cancelled"
assert end["goal_state"]["status"] == "active"
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "idle")
assert len(requests) == 16
running = [event for event in events if event.get("event") == "goal_status" and event.get("status") == "running"]
# Submitting Stop hydrates the current status before cancellation.
assert {event.get("turn_id") for event in running} == {"goal-e2e"}
assert running[0]["started_at"] > 0
assert len({event["started_at"] for event in running}) == 1
assert sum(event.get("event") == "turn_end" for event in events) == 1
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
"content": "Handle this independent input", "webui": True,
"turn_id": "follow-up"}))
followup = await receive_until(lambda event: event.get("event") == "turn_end")
assert followup.get("turn_id") == "follow-up"
assert len(requests) == 17
else:
await asyncio.wait_for(closing_request.wait(), 20)
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "running")
assert not any(event.get("event") == "turn_end" for event in events)
release_close.set()
end = await receive_until(lambda event: event.get("event") == "turn_end")
assert end.get("turn_id") == "goal-e2e"
assert not end["goal_state"]["active"]
assert len(requests) == 18
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "idle")
assert sum(event.get("event") == "goal_status" and event.get("status") == "running" for event in events) == 1
assert sum(event.get("event") == "turn_end" for event in events) == 1
assert any(event.get("event") == "goal_state" and event.get("goal_state", {}).get("active") for event in events)
reconnect_bootstrap = await asyncio.to_thread(_get_bootstrap, f"http://127.0.0.1:{ws_port}/webui/bootstrap")
async with websockets.connect(reconnect_bootstrap["ws_url"] + "?token=" + reconnect_bootstrap["token"] + "&client_id=goal-reconnect") as reconnected:
await _recv_until(reconnected, "ready")
await reconnected.send(json.dumps({"type": "attach", "chat_id": chat_id}))
await _recv_until(reconnected, "attached")
state = await _recv_until(reconnected, "goal_state")
assert state["goal_state"] == {"active": False}
finally:
release_close.set()
if process is not None and process.poll() is None:
if sys.platform == "win32":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
else:
process.terminate()
process.wait(timeout=30)
await server.cleanup()
+130
View File
@@ -0,0 +1,130 @@
import json
import pytest
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import GoalStateSyncEvent, TurnEndEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
from nanobot.session.goal_state import GOAL_STATE_KEY, goal_state_runtime_lines
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import WebuiTurnCoordinator
from nanobot.webui.goal_state import goal_state_ws_blob
from nanobot.webui.session_projection import WebUISessionProjection
def test_goal_state_ws_blob_inactive_when_missing_or_completed():
assert goal_state_ws_blob(None) == {"active": False}
assert goal_state_ws_blob({}) == {"active": False}
assert goal_state_ws_blob({GOAL_STATE_KEY: {"status": "completed", "objective": "x"}}) == {
"active": False,
}
@pytest.mark.parametrize("current_goal", [None, {"status": "completed"}])
def test_goal_state_ws_does_not_revive_superseded_legacy_goal(current_goal):
metadata = {
GOAL_STATE_KEY: current_goal,
"thread_goal": {"status": "active", "objective": "Old goal"},
}
assert goal_state_ws_blob(metadata) == {"active": False}
def test_goal_state_ws_blob_active_shape():
meta = {
GOAL_STATE_KEY: {
"status": "active",
"objective": "Build feature.",
"ui_summary": "feat",
},
}
assert goal_state_ws_blob(meta) == {
"active": True,
"status": "active",
"ui_summary": "feat",
"objective": "Build feature.",
}
def test_goal_state_ws_blob_preserves_blocked_state_for_host_attention():
meta = {
GOAL_STATE_KEY: {
"status": "blocked",
"objective": "Deploy safely.",
"ui_summary": "Approval required",
"recap": "Production access is required.",
},
}
assert goal_state_ws_blob(meta) == {
"active": False,
"status": "blocked",
"ui_summary": "Approval required",
"objective": "Deploy safely.",
"recap": "Production access is required.",
}
def test_goal_state_ws_truncation_is_display_only_for_legacy_json():
objective = "x" * 598 + " " + "finish the objective"
summary = "s" * 130
recap = "r" * 250
legacy_goal = json.dumps({
"status": "active",
"objective": objective,
"ui_summary": summary,
"recap": recap,
})
metadata = {"thread_goal": legacy_goal}
assert goal_state_ws_blob(metadata) == {
"active": True,
"status": "active",
"objective": "x" * 598 + "…",
"ui_summary": summary[:120],
"recap": recap[:240],
}
assert metadata["thread_goal"] == legacy_goal
assert goal_state_runtime_lines(metadata) == [
"Goal (active):", objective, f"Summary: {summary}",
]
async def test_long_goal_uses_same_display_snapshot_for_live_end_and_reconnect(tmp_path):
sessions = SessionManager(tmp_path)
bus = MessageBus()
coordinator = WebuiTurnCoordinator(
bus=bus, sessions=sessions, schedule_background=lambda coro: coro.close(),
)
coordinator.subscribe()
key = "websocket:goal-view"
objective = "x" * 700
metadata = {GOAL_STATE_KEY: {"status": "active", "objective": objective}}
expected = {"active": True, "status": "active", "objective": "x" * 600 + "…"}
try:
await sessions.state.get(key)
await sessions.state.update_metadata(key, metadata)
await bus.publish(GoalStateChanged(
context=RuntimeEventContext(channel="websocket", chat_id="goal-view", session_key=key),
session_metadata=metadata,
))
live_event = bus.outbound.get_nowait().event
assert isinstance(live_event, GoalStateSyncEvent)
assert live_event.goal_state == expected
await coordinator.handle_turn_end(
InboundMessage(channel="websocket", sender_id="user", chat_id="goal-view", content="go"),
session_key=key, latency_ms=None,
)
end_event = bus.outbound.get_nowait().event
assert isinstance(end_event, TurnEndEvent)
assert end_event.goal_state == expected
assert await WebUISessionProjection(sessions).hydration_events(key, "goal-view") == (
{"event": "goal_state", "chat_id": "goal-view", "goal_state": expected},
)
stored = await sessions.state.read_metadata(key)
assert stored is not None
assert stored["metadata"][GOAL_STATE_KEY]["objective"] == objective
finally:
await sessions.state.aclose()
+4 -3
View File
@@ -101,7 +101,7 @@ async def test_hydration_events_restore_goal_and_running_turn(
) )
async def test_hydration_events_are_quiet_without_actionable_state( async def test_hydration_clears_stale_goal_without_an_active_goal(
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
) -> None: ) -> None:
sessions = MagicMock() sessions = MagicMock()
@@ -115,7 +115,7 @@ async def test_hydration_events_are_quiet_without_actionable_state(
assert await WebUISessionProjection(sessions).hydration_events( assert await WebUISessionProjection(sessions).hydration_events(
"websocket:chat-1", "websocket:chat-1",
"chat-1", "chat-1",
) == () ) == ({"event": "goal_state", "chat_id": "chat-1", "goal_state": {"active": False}},)
async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop( async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop(
@@ -157,4 +157,5 @@ async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop
finally: finally:
release.set() release.set()
events = await task events = await task
assert events[0]["status"] == "running" assert events[0]["goal_state"] == {"active": False}
assert events[1]["status"] == "running"