Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
refactor(goal): sustain one ReAct run until the goal closes (#6538)
chengyongru62c2ed4e7edb
diff --git a/README.md b/README.mdindex 0666bff4e..b576de7b3 100644--- a/README.md+++ b/README.md@@ -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.```-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.diff --git a/docs/guides/long-running-ai-agent.md b/docs/guides/long-running-ai-agent.mdindex d75a551db..802678c09 100644--- a/docs/guides/long-running-ai-agent.md+++ b/docs/guides/long-running-ai-agent.md@@ -1,6 +1,6 @@# 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@@ -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.- 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.## Security notesdiff --git a/nanobot/agent/execution_policy.py b/nanobot/agent/execution_policy.pynew file mode 100644index 000000000..ceda2e5bf--- /dev/null+++ b/nanobot/agent/execution_policy.py@@ -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]: ...diff --git a/nanobot/agent/goal_permission.py b/nanobot/agent/goal_permission.pyindex 335fc36d3..f651e3da4 100644--- a/nanobot/agent/goal_permission.py+++ b/nanobot/agent/goal_permission.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom collections.abc import Iterablefrom contextlib import ExitStack, contextmanagerfrom contextvars import ContextVar+from typing import Selffrom nanobot.bus.events import InboundMessagefrom nanobot.session.automation_turns import automation_history_overrides@@ -35,15 +36,9 @@ def goal_mutation_permission(allowed: bool):class GoalInputScope(ExitStack):"""Own goal authorization for fresh inputs consumed during one agent run."""- def __init__(self, initial_message: InboundMessage | None = None) -> None:- super().__init__()- self._initial_message = initial_message-- def __enter__(self) -> GoalInputScope:+ def __enter__(self) -> Self:super().__enter__()self.enter_context(goal_mutation_permission(False))- if self._initial_message is not None:- self.consume_inputs((self._initial_message,))return selfdef consume_inputs(self, messages: Iterable[InboundMessage]) -> None:diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex eed12efdd..2f234078b 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -6,7 +6,7 @@ import osimport timeimport weakreffrom collections.abc import Coroutine, Iterable, Mapping-from contextlib import AbstractContextManager, ExitStack, nullcontext, suppress+from contextlib import AbstractContextManager, AsyncExitStack, ExitStack, nullcontext, suppressfrom copy import deepcopyfrom dataclasses import dataclass, fieldfrom datetime import datetime@@ -22,7 +22,7 @@ from nanobot.agent import model_presets as preset_helpersfrom nanobot.agent.autocompact import AutoCompactfrom nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInputfrom nanobot.agent.cron_turns import CronTurnCoordinator-from nanobot.agent.goal_permission import GoalInputScope+from nanobot.agent.execution_policy import ExecutionControlError, ExecutionPolicy, ExecutionScopefrom nanobot.agent.hook import AgentHook, AgentTurnHookFactoryfrom nanobot.agent.memory import Consolidatorfrom nanobot.agent.model_runtime import ModelRuntimeResolver@@ -56,8 +56,9 @@ from nanobot.bus.outbound_events import (StreamEndEvent,)from nanobot.bus.queue import MessageBus-from nanobot.command import CommandContext, CommandRouter, register_builtin_commands-from nanobot.command.router import command_text+from nanobot.command import CommandContext, CommandRouter+from nanobot.command.builtin import register_core_commands+from nanobot.command.router import CommandExpansion, command_textfrom nanobot.config.network import NetworkConfigfrom nanobot.config.schema import AgentDefaults, ModelPresetConfigfrom nanobot.events import NO_EVENTS, AgentEvent, EventSink@@ -82,7 +83,6 @@ from nanobot.security.workspace_access import ()from nanobot.session import turn_continuationfrom nanobot.session.automation_turns import automation_history_overrides-from nanobot.session.goal_state import goal_state_runtime_lines, sustained_goal_activefrom nanobot.session.history_visibility import HIDDEN_HISTORY_METAfrom nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channelfrom nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager, SessionPolicy@@ -186,11 +186,10 @@ class TurnContext:run_extra_hooks_for_ephemeral: bool = Falsehooks: list[AgentHook] = field(default_factory=list)hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)- turn_scopes: list[AbstractContextManager[Any]] = field(default_factory=list)tools: ToolRegistry | None = Noneturn_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 = Noneusage: LLMUsage | None = None@@ -311,12 +310,14 @@ class AgentLoop:local_trigger_store: LocalTriggerStore | None = None,idle_compact_check_interval_seconds: int = 0,recovery_admission: RecoveryAdmission | None = None,+ builtin_assembly: Callable[[SessionManager, MessageBus, ToolRegistry, CommandRouter], ExecutionPolicy] | None = None,):from nanobot.config.schema import ToolsConfig_tc = tools_config or ToolsConfig()defaults = AgentDefaults()self.bus = bus+ self.execution_policy: ExecutionPolicy | None = Noneself._recovery_admission = recovery_admissionif turn_delivery_factory is not None:if turn_delivery_factory.bus is not bus:@@ -453,9 +454,11 @@ class AgentLoop:self._next_idle_compact_check_at = time.monotonic()if model_preset:self.set_model_preset(model_preset, publish_update=False)- self._register_default_tools(provider_snapshot_loader=provider_snapshot_loader)self.commands = CommandRouter()- register_builtin_commands(self.commands)+ register_core_commands(self.commands)+ if builtin_assembly is not None:+ self.execution_policy = builtin_assembly(self.sessions, self.bus, self.tools, self.commands)+ self._register_default_tools(provider_snapshot_loader=provider_snapshot_loader)@classmethoddef from_config(@@ -830,12 +833,38 @@ class AgentLoop:blocks.append(skill_context)return blocks+ async def _prepare_command_expansion(+ self, ctx: CommandContext, result: CommandExpansion,+ ) -> InboundMessage | OutboundMessage:+ session = ctx.session+ if session is None:+ if ctx.msg.require_existing_session or ctx.msg.session_generation is not None:+ session = await self.sessions.state.read(ctx.key)+ if session is None:+ raise SessionConflictError("command session no longer exists")+ else:+ session = await self.sessions.state.get(ctx.key)+ if ctx.msg.session_generation is not None and session.generation != ctx.msg.session_generation:+ raise SessionConflictError("command belongs to a replaced session")+ if result.temporary_session_error is not None and not session.policy.persist:+ return OutboundMessage(+ channel=ctx.msg.channel,+ chat_id=ctx.msg.chat_id,+ content=result.temporary_session_error,+ metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},+ )+ session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))+ await self.sessions.state.prepare_input(session)+ return result.message+async def _dispatch_command_inline(self,msg: InboundMessage,key: str,raw: str,- dispatch_fn: Callable[[CommandContext], Awaitable[InboundMessage | OutboundMessage | None]],+ dispatch_fn: Callable[+ [CommandContext], Awaitable[CommandExpansion | InboundMessage | OutboundMessage | None],+ ],) -> None:if self.commands.requires_session_queue(raw):await self._enqueue_session_message(msg)@@ -852,6 +881,8 @@ class AgentLoop:),)result = await dispatch_fn(ctx)+ if isinstance(result, CommandExpansion):+ result = await self._prepare_command_expansion(ctx, result)if isinstance(result, InboundMessage):await self._enqueue_session_message(result)elif result is not None:@@ -892,17 +923,13 @@ class AgentLoop:log_content=session.policy.log_content,))workspace_token = bind_workspace_scope(scope)- turn_scope_stack = ExitStack()try:- for turn_scope in ctx.turn_scopes:- turn_scope_stack.enter_context(turn_scope)result = await tool.execute_to_completion(command=ctx.args.strip(),working_dir=str(scope.project_path),)content = str(result)finally:- turn_scope_stack.close()reset_workspace_scope(workspace_token)reset_request_context(request_token)return OutboundMessage(@@ -928,6 +955,9 @@ class AgentLoop:self._active_tasks.pop(key, None)async def _cancel_active_tasks(self, key: str) -> int:+ pending = self._pending_queues.get(key)+ tasks = tuple(self._active_tasks.pop(key, set()))+ cancelled = sum(1 for t in tasks if not t.done() and t.cancel())journal_session = await self.sessions.state.read(key)journaled_followup_ids = (tuple(@@ -941,12 +971,13 @@ class AgentLoop:if journal_session is not Noneelse ())- pending = self._pending_queues.get(key)- tasks = tuple(self._active_tasks.pop(key, set()))- cancelled = sum(1 for t in tasks if not t.done() and t.cancel())for t in tasks:- with suppress(asyncio.CancelledError, Exception):+ try:await t+ except asyncio.CancelledError:+ pass+ except Exception:+ passif tasks and pending is not None and self._pending_queues.get(key) is pending:# A task cancelled before its first step never enters the worker's# cleanup handler. Only reclaim that worker's original inbox.@@ -1035,10 +1066,10 @@ class AgentLoop:run_extra_hooks_for_ephemeral: bool = False,hooks: list[AgentHook] | None = None,hook_factories: list[AgentTurnHookFactory] | None = None,- turn_scopes: list[AbstractContextManager[Any]] | None = None,tools: ToolRegistry | None = None,request_context: RequestContext | None = None,provider_state: ProviderConversationState | None = None,+ initial_message: InboundMessage | None = None,) -> AgentRunResult:self._sync_subagent_runtime_limits()@@ -1162,13 +1193,19 @@ class AgentLoop:consumed = 0try:converted: list[dict[str, Any]] = []+ consumed_inputs: list[InboundMessage] = []for pending_msg in pending_messages:# Independent turns are FIFO barriers. Their worker path# owns completion, command dispatch, and control metadata.if not self._can_inject_message(pending_msg):breakconverted.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 excconsumed = len(converted)return convertedfinally:@@ -1259,24 +1296,17 @@ class AgentLoop:request_token = bind_request_context(request_ctx)workspace_token = bind_workspace_scope(effective_scope)turn_scope_stack = ExitStack()- # Compute lazily because create_goal may create goal metadata during this run.- async def _goal_continue() -> str | None:- current = await self.sessions.state.read_metadata(session.key) if session else None- _goal_lines = goal_state_runtime_lines(current["metadata"] if current else None)- if not _goal_lines:- return None- return (- "You have an active sustained goal:\n\n"- + "\n".join(_goal_lines)- + "\n\nPlease continue working toward the objective using your tools, "- "or call update_goal with action='complete' if the work is truly finished."- )-- session_metadata = session.metadata if session is not None else None+ execution_scope: ExecutionScope | None = Nonetry:- goal_inputs = turn_scope_stack.enter_context(GoalInputScope())- for scope in turn_scopes or ():- turn_scope_stack.enter_context(scope)+ if self.execution_policy is not None:+ execution_scope = turn_scope_stack.enter_context(self.execution_policy.scope(+ active_session_key,+ session.generation if session is not None else request_ctx.session_generation,+ persistent=request_ctx.persist_session,+ ))+ if initial_message is not None:+ execution_scope.consume_inputs((initial_message,))+hook = build_agent_turn_hook(AgentTurnHookSpec(events=events,streaming=streaming,@@ -1327,11 +1357,8 @@ class AgentLoop:),injection_callback=_drain_pending,terminal_injection_callback=_wait_for_pending,- continuation_callback=_goal_continue,- finalize_on_max_iterations=turn_continuation.should_finalize_on_max_iterations(- pending_queue_available=pending_queue is not None and session is not None,- session_metadata=session_metadata,- message_metadata=request_metadata,+ continuation_callback=(+ execution_scope.continuation_prompt if execution_scope is not None else None),provider_state=provider_state,llm_usage_source=source_from_request(@@ -1350,15 +1377,10 @@ class AgentLoop:session.provider_state = result.provider_stateif result.stop_reason == "max_iterations":logger.warning("Max iterations ({}) reached", self.max_iterations)- should_stream = turn_continuation.should_stream_budget_response(- stop_reason=result.stop_reason,- pending_queue_available=pending_queue is not None and session is not None,- session_metadata=session_metadata,- message_metadata=request_metadata,- )+ if result.stop_reason == "max_iterations" or result.pending_stream_content is not None:# Push final content through stream so streaming channels (e.g. Feishu)# update the card instead of leaving it empty.- if events.publish is not None and streaming and should_stream:+ if events.publish is not None and streaming:stream_content = (result.pending_stream_contentif result.pending_stream_content is not None@@ -1421,7 +1443,7 @@ class AgentLoop:with self.bus.admission.activity():try:await self._dispatch_inbound(msg)- except (SessionOperationQueueFullError, SessionConflictError) as exc:+ except (SessionOperationQueueFullError, SessionConflictError, ExecutionControlError) as exc:key = self._effective_session_key(msg)logger.warning("Session input rejected for {}: {}", key, exc)if msg.is_user_input:@@ -1558,14 +1580,14 @@ class AgentLoop:try:while self._pending_queues.get(session_key) is pending:try:- msg = pending.get_nowait()+ item = pending.get_nowait()except asyncio.QueueEmpty:# Idle-only automation follows all accepted user input on# this same worker, including before the bus loop starts.deferred = self._deferred_automation_turns.get(session_key)if not deferred:break- msg = deferred.pop(0)+ item = deferred.pop(0)if not deferred:self._deferred_automation_turns.pop(session_key)session = self.sessions.state.peek_header(session_key)@@ -1573,10 +1595,10 @@ class AgentLoop:session.policy.persist and session.policy.log_content)try:- await self._dispatch_one(msg, pending)+ await self._dispatch_one(item, pending)except asyncio.CancelledError as exc:for coordinator in self._automation_turn_coordinators:- coordinator.complete(msg, error=exc)+ coordinator.complete(item, error=exc)raiseexcept Exception:logger.opt(exception=log_content).error(@@ -1600,14 +1622,11 @@ class AgentLoop:for msg in self._deferred_automation_turns.pop(session_key, []):pending.put_nowait(msg)while not pending.empty():- msg = pending.get_nowait()+ item = pending.get_nowait()for coordinator in self._automation_turn_coordinators:- coordinator.complete(msg, error=error)- if (- msg.channel != "system"- and self.commands.requires_session_queue(command_text(msg))- ):- delivery = self.turn_delivery_factory.unrouted(msg, session_key)+ coordinator.complete(item, error=error)+ if item.channel != "system" and self.commands.requires_session_queue(command_text(item)):+ delivery = self.turn_delivery_factory.unrouted(item, session_key)await delivery.complete(None, publish_completion=True)async def _dispatch_one(@@ -1625,32 +1644,28 @@ class AgentLoop:recovery_task_registered = Falserecovery_admission = self._recovery_admissioncurrent_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)- returnlock = self._get_session_lock(session_key)gate = self._concurrency_gate or nullcontext()delivery = self.turn_delivery_factory.unrouted(msg, session_key)- completion_published = False+ processing = False+ skip_idle = Falsetry:- async with lock, gate:- # A preceding user turn may have completed or blocked the goal- # while its older continuation was still waiting in the inbox.- if turn_continuation.sustained_goal_continuation_inbound(msg.metadata) and not (- sustained_goal_active((await self.sessions.state.get(session_key)).metadata)- ):- return+ async with AsyncExitStack() as execution:try:+ if recovery_admission is not None:+ recovery_id = msg.metadata.get(RECOVERY_INBOUND_METADATA_KEY)+ if isinstance(recovery_id, str) and recovery_id:+ current_task = asyncio.current_task()+ if current_task is not None:+ recovery_admission.register_recovery_task(session_key, current_task)+ recovery_task_registered = True+ if not await recovery_admission.admit(msg):+ logger.info("Skipped stale recovery for session {}", session_key)+ return+ await execution.enter_async_context(lock)+ await execution.enter_async_context(gate)+ processing = Trueawait self.sessions.state.read(session_key)delivery = self.turn_delivery_factory.create(msg,@@ -1662,18 +1677,17 @@ class AgentLoop:pending_queue=pending,delivery=delivery,)- continuing = delivery.continuation_pending- await delivery.complete(- response,- publish_completion=not continuing,- )- completion_published = not continuing+ await delivery.complete(response, publish_completion=True)for coordinator in self._automation_turn_coordinators:coordinator.complete(msg, response=response)- except asyncio.CancelledError:+ except asyncio.CancelledError as exc:logger.info("Task cancelled for session {}", session_key)- # The queued continuation is cancelled with this session worker.- delivery.continuation_pending = False+ if not processing:+ if self.commands.requires_session_queue(command_text(msg)):+ await delivery.complete(None, publish_completion=True)+ raise+ if delivery.completed:+ raise exctry:await delivery.abort_stream()except Exception:@@ -1689,33 +1703,51 @@ class AgentLoop:session_key in self._discarding_sessionsor self._preserve_inflight_turns_on_shutdown):- raise+ raise exc+ key = self._effective_session_key(msg)+ generation = delivery.delivery_message.session_generationtry:- key = self._effective_session_key(msg)- session = await self.sessions.state.get(key)+ session = await self.sessions.state.read(key)+ if session is None or (generation is not None and session.generation != generation):+ self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)+ skip_idle = True+ raise excrestore_runtime_checkpoint(session)await self.sessions.state.finish_turn(session)logger.info("Saved cancelled turn for session {}", key)+ except SessionConflictError:+ current = await self.sessions.state.read_header(key)+ if current is None or (generation is not None and current.generation != generation):+ self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)+ skip_idle = True+ raise asyncio.CancelledError() from None+ logger.opt(exception=log_content).debug(+ "Could not finalize cancelled turn for session {}", session_key,+ )except Exception:logger.opt(exception=log_content).debug("Could not finalize cancelled turn for session {}",session_key,)- raise+ await delivery.cancelled()+ raise excexcept 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+ returnlogger.opt(exception=log_content).error("Error processing message for session {}", session_key,)- await delivery.fail(publish_completion=not delivery.continuation_pending)+ await delivery.fail(publish_completion=True)for coordinator in self._automation_turn_coordinators:coordinator.complete(msg, error=exc)finally:- if not delivery.continuation_pending:+ if (processing or delivery.completed) and not skip_idle:await delivery.idle()- except asyncio.CancelledError:- if not completion_published and self.commands.requires_session_queue(command_text(msg)):- await delivery.complete(None, publish_completion=True)- raisefinally:if (recovery_task_registered@@ -1873,9 +1905,6 @@ class AgentLoop:else msg.content),turn_wall_started_at=t0,- visible_run_started_at=turn_continuation.internal_continuation_run_started_at(- msg.metadata,- ),events=output_events(default=delivery.events,on_progress=on_progress,@@ -2123,15 +2152,15 @@ class AgentLoop:loop=self,runtime=ctx.runtime,is_user_turn=is_user_turn,- turn_scopes=ctx.turn_scopes,)command_matched = self.commands.command_name(raw) is not Noneresult = await self.commands.dispatch(cmd_ctx)+ if isinstance(result, CommandExpansion):+ result = await self._prepare_command_expansion(cmd_ctx, result)if isinstance(result, InboundMessage):ctx.msg = resultresult = Nonecommand_matched = False- ctx.turn_scopes.append(GoalInputScope(ctx.msg))if result is not None:ctx.outbound = resultif cmd_ctx.raw.lower() == "/new":@@ -2270,9 +2299,8 @@ class AgentLoop:async def _run_turn(self, ctx: TurnContext) -> None:runtime = ctx.require_runtime()- if ctx.visible_run_started_at is None:- ctx.visible_run_started_at = time.time()- await ctx.delivery.running(started_at=ctx.visible_run_started_at)+ ctx.run_started_at = time.time()+ await ctx.delivery.running(started_at=ctx.run_started_at)assert ctx.transcript_input is not Nonewith capture_message_deliveries() as message_sends:result = await self._run_agent_loop(@@ -2285,10 +2313,10 @@ class AgentLoop:run_extra_hooks_for_ephemeral=ctx.run_extra_hooks_for_ephemeral,hooks=ctx.hooks,hook_factories=ctx.hook_factories,- turn_scopes=ctx.turn_scopes,tools=ctx.tools,request_context=ctx.request_context,provider_state=ctx.provider_state,+ initial_message=ctx.msg,events=ctx.events,)ctx.final_content = result.final_content@@ -2305,11 +2333,6 @@ class AgentLoop:ctx.suppress_response = Truectx.usage = result.usagectx.delivery.record_usage(result.round_usages)- if ctx.kind is TurnKind.USER:- current = await self.sessions.state.read_metadata(ctx.session_key)- ctx.delivery.continuation_pending = await turn_continuation.maybe_continue_turn(- ctx, session_metadata=current["metadata"] if current else {},- )async def _persist_turn(self, ctx: TurnContext) -> None:session = ctx.require_session()@@ -2322,23 +2345,23 @@ class AgentLoop:ctx.final_content = EMPTY_FINAL_RESPONSE_MESSAGElatency_started_at = (- ctx.visible_run_started_at- if (- ctx.kind is TurnKind.SYSTEM- or turn_continuation.internal_continuation_inbound(ctx.msg.metadata)- )- and ctx.visible_run_started_at is not None+ ctx.run_started_at+ if ctx.kind is TurnKind.SYSTEM or turn_continuation.internal_continuation_inbound(ctx.msg.metadata)else ctx.turn_wall_started_at)ctx.turn_latency_ms = max(0, int((time.time() - latency_started_at) * 1000))ctx.delivery.record_latency(ctx.turn_latency_ms)- turn_continuation.prepare_save_boundary(ctx)+ assert ctx.transcript_input is not None+ ctx.save_skip = turn_continuation.save_skip_for_turn(+ message_metadata=ctx.msg.metadata,+ initial_message_count=ctx.transcript_input.message_count,+ input_persisted_early=ctx.input_persisted_early,+ )if ctx.usage is not None and not ctx.ephemeral:session.metadata["_last_usage"] = ctx.usage.to_dict()if ctx.kind is TurnKind.USER and not ctx.ephemeral:turn_continuation.record_iteration_limit(session.metadata, ctx.stop_reason,- continuation_pending=ctx.delivery.continuation_pending,)self._save_turn(session, ctx.all_messages, ctx.save_skip,@@ -2648,6 +2671,7 @@ class AgentLoop:lock = self._get_session_lock(session_key)with self.bus.admission.activity():temporary_parent = False+ delivery: TurnDelivery | None = Nonetry:async with lock:kwargs: dict[str, Any] = {@@ -2684,6 +2708,8 @@ class AgentLoop:kwargs["on_runtime_admitted"] = on_runtime_admittedif attributes is not None:kwargs["attributes"] = dict(attributes)+ delivery = self.turn_delivery_factory.create(msg, session_key)+ kwargs["delivery"] = deliverytry:return await self._process_message(msg, **kwargs)finally:@@ -2693,7 +2719,8 @@ class AgentLoop:await self.sessions.state.delete(session_key, expected_generation=parent.generation)finally:await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")- self.runtime_event_publisher.clear_turn(session_key)+ if delivery is not None:+ self.runtime_event_publisher.clear_turn(session_key, run_id=delivery.run_id)def _get_session_lock(self, session_key: str) -> asyncio.Lock:lock = self._session_locks.get(session_key)diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.pyindex b1ce652fb..73d4ce133 100644--- a/nanobot/agent/runner.py+++ b/nanobot/agent/runner.py@@ -20,6 +20,7 @@ from nanobot.agent.context_governance import (ProviderCompactionConsolidator,TranscriptBuilder,)+from nanobot.agent.execution_policy import ExecutionControlErrorfrom nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContextfrom nanobot.agent.tools.context import tool_log_content_allowedfrom nanobot.agent.tools.execution import execute_tool_calls@@ -39,7 +40,7 @@ from nanobot.providers.base import (ProviderConversationState,)from nanobot.providers.conversation_state import ProviderConversationStateController-from nanobot.session.history_visibility import is_hidden_history_message+from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_messagefrom nanobot.session.summary import SessionSummaryCheckpointfrom nanobot.utils.helpers import (build_assistant_message,@@ -138,7 +139,7 @@ class AgentRunResult:failure_error_kind: str | None = Nonetool_events: list[dict[str, str]] = field(default_factory=list)had_injections: bool = False- # Terminal tail to emit when the preceding final-content prefix was already streamed.+ # Unstreamed terminal content or tail; excludes any prefix already delivered.pending_stream_content: str | None = Noneprovider_state: ProviderConversationState | None = field(default=None, repr=False)summary_checkpoint: SessionSummaryCheckpoint | None = field(default=None, repr=False)@@ -177,84 +178,33 @@ class AgentRunner:self,spec: AgentRunSpec,messages: list[dict[str, Any]],- assistant_message: dict[str, Any] | None,- injection_cycles: int,*,- conversation_state: ProviderConversationStateController | None = None,- phase: str = "after error",- iteration: int | None = None,- allow_continuation: bool = False,- wait_at_terminal: bool = False,- drain_callback: bool = True,- ) -> tuple[bool, int]:- injections = await self._drain_injections(spec) if drain_callback else []- real_injection = bool(injections)- if not injections and allow_continuation and assistant_message is not None:- continuation = await self._build_continuation_message(spec)- if continuation is not None:- injections = [continuation]- if (- not injections- and wait_at_terminal- and drain_callback- ):- injections = await self._drain_injections(spec, terminal=True)- real_injection = bool(injections)+ phase: str,+ terminal: bool = False,+ ) -> bool:+ injections = await self._drain_injections(spec, terminal=terminal)if not injections:- return False, injection_cycles- if real_injection:- injection_cycles += 1- if assistant_message is not None:- messages.append(assistant_message)- if iteration is not None:- checkpoint: dict[str, Any] = {- "phase": "final_response",- "iteration": iteration,- "model": spec.runtime.model,- "assistant_message": assistant_message,- "completed_tool_results": [],- "pending_tool_calls": [],- }- if conversation_state is not None:- checkpoint["provider_state"] = conversation_state.checkpoint(- messages- )- await self._emit_checkpoint(- spec,- checkpoint,- messages,- )+ return Falseself._append_injected_messages(messages, injections)- if real_injection:- preview = "[content hidden]"- if tool_log_content_allowed():- preview = "\n\n".join(- message["content"] for message in injections- if isinstance(message.get("content"), str)- and not is_hidden_history_message(message)- )- preview = preview[:80] + "..." if len(preview) > 80 else preview- logger.info(- "Injected {} follow-up message(s) {} (snapshot {}): {}",- len(injections), phase, injection_cycles, preview,+ preview = "[content hidden]"+ if tool_log_content_allowed():+ preview = "\n\n".join(+ content for message in injections+ if isinstance(content := message.get("content"), str)+ and not is_hidden_history_message(message))- else:- logger.info("Injected caller-requested continuation {}", phase)- return True, injection_cycles+ preview = preview[:80] + "..." if len(preview) > 80 else preview+ logger.info(+ "Injected {} follow-up message(s) {}: {}",+ len(injections), phase, preview,+ )+ return True@staticmethod- async def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:- callback = spec.continuation_callback- if callback is None:- return None- try:- content = await callback()- except Exception:- logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")- return None- if content is None or not content.strip():- return None- return {"role": "user", "content": content}+ async def _continuation_prompt(spec: AgentRunSpec) -> str | None:+ prompt = await spec.continuation_callback() if spec.continuation_callback is not None else None+ _raise_if_cancelling()+ return promptasync def _drain_injections(self,@@ -271,6 +221,8 @@ class AgentRunner:return []try:items = await callback()+ except ExecutionControlError:+ raiseexcept Exception:logger.opt(exception=tool_log_content_allowed()).error("injection_callback failed")return []@@ -424,7 +376,6 @@ class AgentRunner:length_recovery_parts: list[str] = []pending_length_segment: tuple[AgentHookContext, str] | None = Nonehad_injections = False- injection_cycles = 0pending_stream_content: str | None = Noneconversation_state = ProviderConversationStateController(provider=spec.runtime.provider,@@ -464,19 +415,25 @@ class AgentRunner:segment_context.stream_continues_current_message = not interruptedawait hook.on_stream_end(segment_context, resuming=True)- for iteration in range(spec.max_iterations):+ iteration = -1+ followup_requested = False+ while (+ iteration + 1 < spec.max_iterations+ or followup_requested+ or await self._continuation_prompt(spec) is not None+ ):+ iteration += 1+ # A response boundary already admitted its follow-up request. Do not+ # reread continuation state for that same decision at loop entry.+ followup_requested = False# A resumed iteration must not inherit a previous iteration's failure.stop_reason = "completed"error = None# The session inbox cuts a finite snapshot before every model call.# This includes follow-ups that arrived before the first request and# messages received while the previous request or tools were running.- drained_before_request, injection_cycles = await self._try_drain_injections(- spec,- messages,- None,- injection_cycles,- phase="before model call",+ drained_before_request = await self._try_drain_injections(+ spec, messages, phase="before model call",)if drained_before_request:had_injections = True@@ -722,6 +679,20 @@ class AgentRunner:assistant_message,response,)+ messages.append(assistant_message)+ await self._emit_checkpoint(+ spec,+ {+ "phase": "final_response",+ "iteration": iteration,+ "model": spec.runtime.model,+ "assistant_message": assistant_message,+ "completed_tool_results": [],+ "pending_tool_calls": [],+ "provider_state": conversation_state.checkpoint(messages),+ },+ messages,+ )if response.finish_reason == "error":interrupted_parts = [@@ -743,22 +714,32 @@ class AgentRunner:# Check for mid-turn injections BEFORE signaling stream end.# If injections are found we keep the stream alive (resuming=True)# so streaming channels don't prematurely finalize the card.- can_make_followup_request = iteration + 1 < spec.max_iterations- should_continue, injection_cycles = await self._try_drain_injections(- spec, messages, assistant_message, injection_cycles,- conversation_state=conversation_state,- phase="after final response",- iteration=iteration,- allow_continuation=(- response.finish_reason not in {"refusal", "content_filter"}- ),- wait_at_terminal=(- assistant_message is not None- and response.finish_reason- not in {"error", "length", "refusal", "content_filter"}- ),- drain_callback=can_make_followup_request,+ normal_response = (+ assistant_message is not None+ and response.finish_reason not in {"error", "length", "refusal", "content_filter"}+ )+ ordinary_budget_remaining = iteration + 1 < spec.max_iterations+ continuation_prompt = None+ if normal_response and not ordinary_budget_remaining:+ continuation_prompt = await self._continuation_prompt(spec)+ can_make_followup_request = ordinary_budget_remaining or continuation_prompt is not None+ should_continue = can_make_followup_request and await self._try_drain_injections(+ spec, messages, phase="after final response",)+ if not should_continue and normal_response:+ if ordinary_budget_remaining:+ continuation_prompt = await self._continuation_prompt(spec)+ if continuation_prompt is not None:+ messages.append({+ "role": "user", "content": continuation_prompt,+ HIDDEN_HISTORY_META: {"kind": "internal_continuation"},+ })+ should_continue = True+ logger.info("Injected caller-requested continuation after final response")+ elif can_make_followup_request:+ should_continue = await self._try_drain_injections(+ spec, messages, phase="at terminal response", terminal=True,+ )if should_continue:had_injections = True@@ -766,6 +747,7 @@ class AgentRunner:await hook.on_stream_end(context, resuming=should_continue)if should_continue:+ followup_requested = Truelength_recovery_parts.clear()await hook.after_iteration(context)continue@@ -782,12 +764,9 @@ class AgentRunner:context.error = errorcontext.stop_reason = stop_reasonawait hook.after_iteration(context)- should_continue, injection_cycles = await self._try_drain_injections(- spec, messages, None, injection_cycles,- phase="after LLM error",- drain_callback=can_make_followup_request,- )- if should_continue:+ if can_make_followup_request and await self._try_drain_injections(+ spec, messages, phase="after LLM error",+ ):had_injections = Truelength_recovery_parts.clear()continue@@ -802,41 +781,14 @@ class AgentRunner:context.error = errorcontext.stop_reason = stop_reasonawait hook.after_iteration(context)- should_continue, injection_cycles = await self._try_drain_injections(- spec, messages, None, injection_cycles,- phase="after empty response",- drain_callback=can_make_followup_request,- )- if should_continue:+ if can_make_followup_request and await self._try_drain_injections(+ spec, messages, phase="after empty response",+ ):had_injections = Truelength_recovery_parts.clear()continuebreak- messages.append(- assistant_message- or conversation_state.project_response_message(- build_assistant_message(- clean,- reasoning_content=response.reasoning_content,- thinking_blocks=response.thinking_blocks,- ),- response,- )- )- await self._emit_checkpoint(- spec,- {- "phase": "final_response",- "iteration": iteration,- "model": spec.runtime.model,- "assistant_message": messages[-1],- "completed_tool_results": [],- "pending_tool_calls": [],- "provider_state": conversation_state.checkpoint(messages),- },- messages,- )if length_recovery_parts:final_content = ("".join(length_recovery_parts)@@ -849,20 +801,33 @@ class AgentRunner:await hook.after_iteration(context)breakelse:+ 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_iterationsterminal_content = None- await end_length_segment(interrupted=False)if spec.finalize_on_max_iterations:terminal_content, usage = await self._try_finalize_after_max_iterations(spec,hook,messages,usage,+ iteration=iteration + 1,request_state=request_state,round_usages=round_usages,)+ if terminal_content is not None and goal_overrun:+ stop_reason = "completed"+ pending_stream_content = terminal_contentif terminal_content is None:- terminal_content = self._max_iterations_fallback(spec)+ if goal_overrun and spec.finalize_on_max_iterations:+ terminal_content = EMPTY_FINAL_RESPONSE_MESSAGE+ stop_reason = "empty_final_response"+ error = terminal_content+ pending_stream_content = terminal_content+ else:+ terminal_content = self._max_iterations_fallback(spec)if length_recovery_parts:terminal_tail = f"\n\n{terminal_content.lstrip()}"final_content = (@@ -1169,7 +1134,7 @@ class AgentRunner:# Advancing it after dropping even one call would replay an unmatched# call without a corresponding tool output on the next request.response.provider_state = None- if not valid:+ if not valid and original_finish_reason in ("tool_calls", "function_call"):response.finish_reason = "stop"return (dropped, not valid, original_finish_reason)@@ -1229,12 +1194,17 @@ class AgentRunner:messages: list[dict[str, Any]],usage: LLMUsage | None,*,+ iteration: int,request_state: ModelRequestState,round_usages: list[LLMUsage],) -> tuple[str | None, LLMUsage | None]:compaction = request_state.compactionrequest_messages = await self.prepare_prompt(compaction.request_messages, messages)- retry_messages = self._budget_exhausted_finalization_messages(request_messages)+ retry_messages = (+ self._finalization_retry_messages(request_messages)+ if iteration > spec.max_iterations+ else self._budget_exhausted_finalization_messages(request_messages)+ )try:response = await self._request_no_tools(spec,@@ -1263,7 +1233,7 @@ class AgentRunner:return None, usagecontext = AgentHookContext(- iteration=spec.max_iterations,+ iteration=iteration,messages=messages,response=response,usage=raw_usage,diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.pyindex 4666330e6..2aa9bfcee 100644--- a/nanobot/agent/turn_delivery.py+++ b/nanobot/agent/turn_delivery.py@@ -6,6 +6,7 @@ from collections.abc import Awaitable, Callablefrom copy import deepcopyfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, cast+from uuid import uuid4from nanobot.bus.delivery import DeliveryRequestfrom nanobot.bus.events import InboundMessage, OutboundMessage@@ -33,6 +34,7 @@ from nanobot.session.keys import (is_internal_session,last_channel_from_metadata,)+from nanobot.utils.cancellation import shield_and_drainfrom nanobot.utils.helpers import strip_thinkif TYPE_CHECKING:@@ -205,7 +207,7 @@ class TurnDelivery:route: TurnRouteroute_admission: TurnRouteAdmission | None = Noneenable_stream: bool = False- continuation_pending: bool = field(init=False, default=False)+ run_id: str = field(init=False)delivery_message: InboundMessage = field(init=False)lifecycle_message: InboundMessage = field(init=False)_stream_base_id: str | None = field(init=False, default=None)@@ -213,6 +215,7 @@ class TurnDelivery:_stream_open: bool = field(init=False, default=False)events: EventSink = field(init=False)_routed_events: EventSink = field(init=False)+ completed: bool = field(init=False, default=False)_stop_reason: str | None = field(init=False, default=None)_failure_error_kind: str | None = field(init=False, default=None)_retry_status: RetryStatusEvent | None = field(init=False, default=None)@@ -223,6 +226,7 @@ class TurnDelivery:_stream_source_unknown: bool = field(init=False, default=False)def __post_init__(self) -> None:+ self.run_id = uuid4().hexself._routed_events = _bind_events(self.bus, self.route, self.session_key)self.events = EventSink(self._publish_event, self._routed_events.accepts)self.delivery_message = dataclasses.replace(@@ -299,15 +303,16 @@ class TurnDelivery:self.delivery_message,self.session_key,runtime,+ run_id=self.run_id,)return- self.runtime_event_publisher.record_turn_runtime(self.session_key, runtime)+ self.runtime_event_publisher.record_turn_runtime(self.session_key, runtime, run_id=self.run_id)def record_latency(self, latency_ms: int | None) -> None:- self.runtime_event_publisher.record_turn_latency(self.session_key, latency_ms)+ self.runtime_event_publisher.record_turn_latency(self.session_key, latency_ms, run_id=self.run_id)def record_usage(self, round_usages: list[LLMUsage]) -> None:- self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages)+ self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages, run_id=self.run_id)def record_stop_reason(self,@@ -390,11 +395,9 @@ class TurnDelivery:)if publish_completion:outcome, failure_kind = _turn_outcome(stop_reason)- await self.runtime_event_publisher.turn_completed(+ await self._publish_completion(channel=completed_channel,chat_id=completed_chat_id,- session_key=self.session_key,- metadata=self.lifecycle_message.metadata,outcome=outcome,failure_kind=failure_kind,failure_error_kind=(self._failure_error_kind or (@@ -405,6 +408,9 @@ class TurnDelivery:),)+ async def cancelled(self) -> None:+ await self._publish_completion(outcome="cancelled")+async def fail(self, *, publish_completion: bool) -> None:await self.bus.publish_outbound(OutboundMessage(@@ -415,14 +421,31 @@ class TurnDelivery:))if publish_completion:+ await self._publish_completion(outcome="failed", failure_kind="internal")++ async def _publish_completion(+ self, *, outcome: str, channel: str | None = None, chat_id: str | None = None,+ failure_kind: str | None = None, failure_error_kind: str | None = None,+ failure_attempts: int | None = None,+ ) -> None:+ if self.completed:+ return++ async def publish() -> None:await self.runtime_event_publisher.turn_completed(- channel=self.lifecycle_message.channel,- chat_id=self.lifecycle_message.chat_id,+ channel=channel if channel is not None else self.lifecycle_message.channel,+ chat_id=chat_id if chat_id is not None else self.lifecycle_message.chat_id,session_key=self.session_key,metadata=self.lifecycle_message.metadata,- outcome="failed",- failure_kind="internal",+ outcome=outcome,+ failure_kind=failure_kind,+ failure_error_kind=failure_error_kind,+ failure_attempts=failure_attempts,+ run_id=self.run_id,)+ self.completed = True++ await shield_and_drain(publish())async def idle(self) -> None:await self.runtime_event_publisher.run_status_changed(@@ -430,7 +453,7 @@ class TurnDelivery:self.session_key,"idle",)- self.runtime_event_publisher.clear_turn(self.session_key)+ self.runtime_event_publisher.clear_turn(self.session_key, run_id=self.run_id)def _stream_id(self) -> str:assert self._stream_base_id is not Nonediff --git a/nanobot/bus/runtime_events.py b/nanobot/bus/runtime_events.pyindex 2ecd6bace..6768ac1fa 100644--- a/nanobot/bus/runtime_events.py+++ b/nanobot/bus/runtime_events.py@@ -114,10 +114,10 @@ class RuntimeEventPublisher:def __init__(self, bus: MessageBus) -> None:self.bus = bus- self._turn_latency_ms: dict[str, int] = {}- self._turn_runtime: dict[str, LLMRuntime] = {}- self._turn_usage: dict[str, LLMUsage] = {}- self._turn_round_usages: dict[str, tuple[LLMUsage, ...]] = {}+ self._turn_latency_ms: dict[tuple[str, str | None], int] = {}+ self._turn_runtime: dict[tuple[str, str | None], LLMRuntime] = {}+ self._turn_usage: dict[tuple[str, str | None], LLMUsage] = {}+ self._turn_round_usages: dict[tuple[str, str | None], tuple[LLMUsage, ...]] = {}@staticmethoddef _context(@@ -138,17 +138,22 @@ class RuntimeEventPublisher:attributes=dict(attributes or {}),)- def record_turn_runtime(self, session_key: str, runtime: LLMRuntime) -> None:- self._turn_runtime[session_key] = runtime+ def record_turn_runtime(+ self, session_key: str, runtime: LLMRuntime, *, run_id: str | None = None,+ ) -> None:+ self._turn_runtime[(session_key, run_id)] = runtime- def record_turn_latency(self, session_key: str, latency_ms: int | None) -> None:+ def record_turn_latency(+ self, session_key: str, latency_ms: int | None, *, run_id: str | None = None,+ ) -> None:if latency_ms is not None:- self._turn_latency_ms[session_key] = int(latency_ms)+ self._turn_latency_ms[(session_key, run_id)] = int(latency_ms)def record_turn_usage(self,session_key: str,round_usages: list[LLMUsage],+ *, run_id: str | None = None,) -> None:if not round_usages:return@@ -156,18 +161,16 @@ class RuntimeEventPublisher:usage = round_usages[0]for round_usage in round_usages[1:]:usage += round_usage- previous = self._turn_usage.get(session_key)- self._turn_usage[session_key] = usage if previous is None else previous + usage- self._turn_round_usages[session_key] = (- *self._turn_round_usages.get(session_key, ()),- *round_usages,- )+ key = (session_key, run_id)+ self._turn_usage[key] = usage+ self._turn_round_usages[key] = tuple(round_usages)- def clear_turn(self, session_key: str) -> None:- self._turn_latency_ms.pop(session_key, None)- self._turn_runtime.pop(session_key, None)- self._turn_usage.pop(session_key, None)- self._turn_round_usages.pop(session_key, None)+ def clear_turn(self, session_key: str, *, run_id: str | None = None) -> None:+ key = (session_key, run_id)+ self._turn_latency_ms.pop(key, None)+ self._turn_runtime.pop(key, None)+ self._turn_usage.pop(key, None)+ self._turn_round_usages.pop(key, None)async def user_input_accepted(self,@@ -209,9 +212,10 @@ class RuntimeEventPublisher:msg: InboundMessage,session_key: str,runtime: LLMRuntime,+ *, run_id: str | None = None,) -> None:"""Record and publish the runtime selected for one turn."""- self.record_turn_runtime(session_key, runtime)+ self.record_turn_runtime(session_key, runtime, run_id=run_id)await self.bus.publish(TurnRuntimeAdmitted(context=self._context(@@ -281,7 +285,9 @@ class RuntimeEventPublisher:failure_kind: str | None = None,failure_error_kind: str | None = None,failure_attempts: int | None = None,+ run_id: str | None = None,) -> None:+ key = (session_key, run_id)await self.bus.publish(TurnCompleted(context=self._context(@@ -290,10 +296,10 @@ class RuntimeEventPublisher:session_key=session_key,metadata=metadata,),- latency_ms=self._turn_latency_ms.pop(session_key, None),- runtime=self._turn_runtime.pop(session_key, None),- usage=self._turn_usage.pop(session_key, None),- round_usages=self._turn_round_usages.pop(session_key, ()),+ latency_ms=self._turn_latency_ms.pop(key, None),+ runtime=self._turn_runtime.pop(key, None),+ usage=self._turn_usage.pop(key, None),+ round_usages=self._turn_round_usages.pop(key, ()),outcome=outcome,failure_kind=failure_kind,failure_error_kind=failure_error_kind,diff --git a/nanobot/channels/discord/runtime.py b/nanobot/channels/discord/runtime.pyindex 269f9a3a5..05318441a 100644--- a/nanobot/channels/discord/runtime.py+++ b/nanobot/channels/discord/runtime.py@@ -17,7 +17,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel-from nanobot.command.builtin import build_help_text+from nanobot.command.application import build_help_textfrom nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dirfrom nanobot.config_base import Basediff --git a/nanobot/channels/discord/tests/test_discord_channel.py b/nanobot/channels/discord/tests/test_discord_channel.pyindex 6295af87d..0270baed1 100644--- a/nanobot/channels/discord/tests/test_discord_channel.py+++ b/nanobot/channels/discord/tests/test_discord_channel.py@@ -21,7 +21,7 @@ from nanobot.channels.discord.runtime import (DiscordChannel,DiscordConfig,)-from nanobot.command.builtin import build_help_text+from nanobot.command.application import build_help_textfrom nanobot.config.network import NetworkConfigdiff --git a/nanobot/channels/matrix/runtime.py b/nanobot/channels/matrix/runtime.pyindex dd1e9d37c..7aae13ed3 100644--- a/nanobot/channels/matrix/runtime.py+++ b/nanobot/channels/matrix/runtime.py@@ -63,7 +63,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel-from nanobot.command.builtin import BUILTIN_COMMAND_SPECS+from nanobot.command.application import BUILTIN_COMMAND_SPECSfrom nanobot.command.router import normalize_command_textfrom nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_data_dir, get_media_dirdiff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex 739bf50f9..5fb9ff34c 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -32,7 +32,7 @@ from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import ProgressEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel-from nanobot.command.builtin import build_help_text+from nanobot.command.application import build_help_textfrom nanobot.config.network import NetworkConfigfrom nanobot.config.paths import get_media_dirfrom nanobot.config_base import Basediff --git a/nanobot/cli/agent.py b/nanobot/cli/agent.pyindex ecb764be9..4523bd4e1 100644--- a/nanobot/cli/agent.py+++ b/nanobot/cli/agent.py@@ -179,6 +179,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: strmcp_provider = MCPProvider.from_config(runtime_config, tools)_set_nanobot_logs(logs)+ from nanobot.goal.assembly import install_goaltry:agent_loop = agent_loop_class.from_config(@@ -188,6 +189,7 @@ def _run_classic(runtime_config: Config, *, message: str | None, session_id: strcron_service=cron,hook_factories=[create_file_edit_activity_hook],tool_registry=tools,+ builtin_assembly=install_goal,)except ValueError as exc:_print_agent_start_error(exc)diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.pyindex 2689123b0..463b90951 100644--- a/nanobot/cli/commands.py+++ b/nanobot/cli/commands.py@@ -381,6 +381,8 @@ def serve(build_unconfigured_provider_snapshot(runtime_config, setup_error).providerif setup_error else None)+ from nanobot.goal.assembly import install_goal+try:agent_loop = AgentLoop.from_config(runtime_config, bus,@@ -388,6 +390,7 @@ def serve(session_manager=session_manager,hook_factories=[create_file_edit_activity_hook],tool_registry=tools,+ builtin_assembly=install_goal,)except ValueError as exc:console.print(f"[red]Error: {exc}[/red]")diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.pyindex 377bf1d51..813ad9967 100644--- a/nanobot/cli/gateway_runtime.py+++ b/nanobot/cli/gateway_runtime.py@@ -593,6 +593,8 @@ def _run_claimed_gateway(unified_session=config.agents.defaults.unified_session,)+ from nanobot.goal.assembly import install_goal+agent = AgentLoop.from_config(config, bus,provider=provider_snapshot.provider,@@ -609,7 +611,9 @@ def _run_claimed_gateway(hook_factories=[create_file_edit_activity_hook],tool_registry=tools,recovery_admission=recovery,+ builtin_assembly=install_goal,)+def _schedule_webui_background(awaitable: Awaitable[None]) -> None:agent.schedule_background(cast(Coroutine[Any, Any, None], awaitable))diff --git a/nanobot/command/__init__.py b/nanobot/command/__init__.pyindex 1d45ca6a3..609f68c04 100644--- a/nanobot/command/__init__.py+++ b/nanobot/command/__init__.py@@ -1,4 +1,18 @@-from nanobot.command.builtin import register_builtin_commands+from typing import TYPE_CHECKING, Callable+from nanobot.command.router import CommandContext, CommandRouter+if TYPE_CHECKING:+ from nanobot.command.application import register_builtin_commands+++def __getattr__(name: str) -> Callable[[CommandRouter], None]:+ if name == "register_builtin_commands":+ from nanobot.command.application import register_builtin_commands++ globals()[name] = register_builtin_commands+ return register_builtin_commands+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++__all__ = ["CommandContext", "CommandRouter", "register_builtin_commands"]diff --git a/nanobot/command/application.py b/nanobot/command/application.pynew file mode 100644index 000000000..d7dcd54eb--- /dev/null+++ b/nanobot/command/application.py@@ -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())diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.pyindex 36c2f22d1..8ea6deb2a 100644--- a/nanobot/command/builtin.py+++ b/nanobot/command/builtin.py@@ -4,18 +4,18 @@ import asyncioimport osimport subprocessimport sys-import timefrom contextlib import suppress-from dataclasses import dataclass, replace-from typing import TYPE_CHECKING, Any, Literal, cast+from dataclasses import replace+from typing import TYPE_CHECKING, Any, castfrom loguru import loggerfrom nanobot import __version__-from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage-from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text+from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage+from nanobot.command.router import CommandContext, CommandRouter+from nanobot.command.spec import BuiltinCommandSpec+from nanobot.command.spec import CommandLifecycle as CommandLifecyclefrom nanobot.providers.base import LLMUsage-from nanobot.session.history_visibility import HIDDEN_HISTORY_METAfrom nanobot.utils.cancellation import shield_and_drainfrom nanobot.utils.helpers import build_status_contentfrom nanobot.utils.restart import set_restart_notice_to_env@@ -26,46 +26,10 @@ if TYPE_CHECKING:from nanobot.session.manager import Sessionfrom nanobot.utils.gitstore import CommitInfo-# WebUI protocol contract for how a slash command participates in turn state:-# - side_channel: returns control text without starting or ending an agent turn.-# - finalize_active_turn: side-channel command that also closes the active UI turn.-# - stop_active_turn: cancels the active turn; WebUI may intercept exact submits.-# - agent_turn: always enters the normal agent path.-# - agent_turn_with_args: no args is side-channel usage; args enter the agent path.-CommandLifecycle = Literal[- "side_channel",- "finalize_active_turn",- "stop_active_turn",- "agent_turn",- "agent_turn_with_args",-]-USER_SHELL_COMMAND = "/__shell"-@dataclass(frozen=True)-class BuiltinCommandSpec:- command: str- title: str- description: str- icon: str- arg_hint: str = ""- lifecycle: CommandLifecycle = "side_channel"- accepts_args: bool = False-- def as_dict(self) -> dict[str, str | bool]:- return {- "command": self.command,- "title": self.title,- "description": self.description,- "icon": self.icon,- "arg_hint": self.arg_hint,- "lifecycle": self.lifecycle,- "accepts_args": self.accepts_args,- }---BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (+CORE_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (BuiltinCommandSpec("/new","New chat",@@ -114,15 +78,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = ("[n]",accepts_args=True,),- BuiltinCommandSpec(- "/goal",- "Start long-running goal",- "Tell the agent to treat the request as a long-running goal.",- "activity",- "<goal>",- lifecycle="agent_turn_with_args",- accepts_args=True,- ),BuiltinCommandSpec("/trigger","Create named local trigger",@@ -190,26 +145,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = ()-def builtin_command_palette() -> list[dict[str, str | bool]]:- """Return structured command metadata for UI command palettes."""- return [spec.as_dict() for spec in BUILTIN_COMMAND_SPECS]---def builtin_command_starts_agent_turn(text: str) -> bool:- """Return whether WebUI ingress should expect a normal agent lifecycle."""- normalized = normalize_command_text(text)- command, separator, args = normalized.partition(" ")- spec = next(- (item for item in BUILTIN_COMMAND_SPECS if item.command == command.lower()),- None,- )- if spec is None or (separator and not spec.accepts_args):- return True- if spec.lifecycle == "agent_turn":- return True- return spec.lifecycle == "agent_turn_with_args" and bool(args.strip())--async def cmd_stop(ctx: CommandContext) -> OutboundMessage:"""Cancel all active tasks and subagents for the session."""loop = ctx.loop@@ -894,41 +829,6 @@ async def cmd_history(ctx: CommandContext) -> OutboundMessage:)-async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:- """Expand an explicit goal command into model-only input."""- goal = ctx.args.strip()- if not goal:- return OutboundMessage(- channel=ctx.msg.channel,- chat_id=ctx.msg.chat_id,- content="Usage: /goal <long-running task description>",- metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},- )- if not ctx.is_user_turn:- return OutboundMessage(- channel=ctx.msg.channel,- chat_id=ctx.msg.chat_id,- content="Goal mode can only be started by a user `/goal <task>` command.",- metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},- )-- session = ctx.session or await ctx.loop.sessions.state.get(ctx.key)- session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))- await ctx.loop.sessions.state.prepare_input(session)- return replace(- ctx.msg,- content=goal,- metadata={- **ctx.msg.metadata,- "original_command": "/goal",- "original_content": ctx.msg.content,- "goal_requested": True,- "goal_started_at": time.time(),- HIDDEN_HISTORY_META: {"kind": "goal_request"},- },- )--async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:"""List, approve, deny or revoke pairing requests."""from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command@@ -1019,7 +919,7 @@ async def cmd_help(ctx: CommandContext) -> OutboundMessage:return OutboundMessage(channel=ctx.msg.channel,chat_id=ctx.msg.chat_id,- content=build_help_text(),+ content=build_help_text(ctx.loop.commands.specs),metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},)@@ -1048,10 +948,10 @@ async def cmd_user_shell(ctx: CommandContext) -> OutboundMessage:return await ctx.loop.execute_user_shell_command(ctx)-def build_help_text() -> str:- """Build canonical help text shared across channels."""+def build_help_text(specs: tuple[BuiltinCommandSpec, ...] = CORE_COMMAND_SPECS) -> str:+ """Build help text for the commands registered in one application."""lines = ["🐈 nanobot commands:"]- for spec in BUILTIN_COMMAND_SPECS:+ for spec in specs:command = spec.commandif spec.arg_hint:command = f"{command} {spec.arg_hint}"@@ -1059,8 +959,10 @@ def build_help_text() -> str:return "\n".join(lines)-def register_builtin_commands(router: CommandRouter) -> None:- """Register the default set of slash commands."""+def register_core_commands(router: CommandRouter) -> None:+ """Register slash commands owned by the core runtime."""+ for spec in CORE_COMMAND_SPECS:+ router.add_spec(spec)router.priority("/stop", cmd_stop)router.priority("/restart", cmd_restart)router.priority("/status", cmd_status)@@ -1071,8 +973,6 @@ def register_builtin_commands(router: CommandRouter) -> None:router.prefix("/model ", cmd_model)router.exact("/history", cmd_history)router.prefix("/history ", cmd_history)- router.exact("/goal", cmd_goal)- router.prefix("/goal ", cmd_goal)router.exact("/trigger", cmd_trigger)router.prefix("/trigger ", cmd_trigger)router.exact("/dream", cmd_dream)diff --git a/nanobot/command/router.py b/nanobot/command/router.pyindex 1b959be98..83e24ae98 100644--- a/nanobot/command/router.py+++ b/nanobot/command/router.py@@ -1,21 +1,39 @@from __future__ import annotationsimport re-from contextlib import AbstractContextManagerfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Any, Awaitable, Callable+from typing import TYPE_CHECKING, Awaitable, Callablefrom nanobot.bus.events import InboundMessage, OutboundMessage+from nanobot.command.spec import BuiltinCommandSpecif TYPE_CHECKING:from nanobot.agent.loop import AgentLoopfrom nanobot.session.manager import Sessionfrom nanobot.utils.llm_runtime import LLMRuntime-Handler = Callable[["CommandContext"], Awaitable["InboundMessage | OutboundMessage | None"]]+Handler = Callable[["CommandContext"], Awaitable["CommandExpansion | InboundMessage | OutboundMessage | None"]]+InputHandler = Callable[["CommandInput"], Awaitable["CommandExpansion | OutboundMessage"]]_BOT_SUFFIX_RE = re.compile(r"^[A-Za-z0-9_]+$")+@dataclass(frozen=True, slots=True)+class CommandInput:+ """Inputs available to a command that only transforms a user request."""++ msg: InboundMessage+ args: str+ is_user_turn: bool+++@dataclass(frozen=True, slots=True)+class CommandExpansion:+ """A transformed input whose original command is persisted by the runtime."""++ message: InboundMessage+ temporary_session_error: str | None = None++def command_text(message: InboundMessage) -> str:"""Return routable text; command-generated agent input must not be dispatched again."""return "" if message.metadata.get("original_command") else message.content.strip()@@ -52,7 +70,6 @@ class CommandContext:loop: AgentLoop = field(kw_only=True)runtime: LLMRuntime | None = Noneis_user_turn: bool = False- turn_scopes: list[AbstractContextManager[Any]] = field(default_factory=list)class CommandRouter:@@ -70,6 +87,24 @@ class CommandRouter:self._exact: dict[str, Handler] = {}self._prefix: list[tuple[str, Handler]] = []self._session_commands: set[str] = set()+ self._specs: list[BuiltinCommandSpec] = []++ @property+ def specs(self) -> tuple[BuiltinCommandSpec, ...]:+ return tuple(self._specs)++ def add_spec(self, spec: BuiltinCommandSpec, *, after: str | None = None) -> None:+ self._specs = [item for item in self._specs if item.command != spec.command]+ index = next((i + 1 for i, item in enumerate(self._specs) if item.command == after), len(self._specs))+ self._specs.insert(index, spec)++ def input_command(self, cmd: str, handler: InputHandler) -> None:+ """Register a command that receives only input facts and returns an expansion."""+ async def invoke(ctx: CommandContext) -> CommandExpansion | OutboundMessage:+ return await handler(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))++ self.exact(cmd, invoke)+ self.prefix(f"{cmd} ", invoke)def priority(self, cmd: str, handler: Handler) -> None:self._priority[cmd] = handler@@ -119,7 +154,9 @@ class CommandRouter:return Truereturn self.command_name(text) is not None- async def dispatch_priority(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:+ async def dispatch_priority(+ self, ctx: CommandContext,+ ) -> CommandExpansion | InboundMessage | OutboundMessage | None:"""Dispatch a priority command. Called from run() without the lock."""ctx.raw = normalize_command_text(ctx.raw)handler = self._priority.get(ctx.raw.lower())@@ -127,7 +164,9 @@ class CommandRouter:return await handler(ctx)return None- async def dispatch(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:+ async def dispatch(+ self, ctx: CommandContext,+ ) -> CommandExpansion | InboundMessage | OutboundMessage | None:"""Try exact and prefix handlers, then validate registered commands."""if ctx.msg.metadata.get("original_command"):return Nonediff --git a/nanobot/command/spec.py b/nanobot/command/spec.pynew file mode 100644index 000000000..bf45a1f58--- /dev/null+++ b/nanobot/command/spec.py@@ -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,+ }diff --git a/nanobot/goal/__init__.py b/nanobot/goal/__init__.pynew file mode 100644index 000000000..906b7993b--- /dev/null+++ b/nanobot/goal/__init__.py@@ -0,0 +1 @@+"""Built-in sustained-goal feature."""diff --git a/nanobot/goal/assembly.py b/nanobot/goal/assembly.pynew file mode 100644index 000000000..b3504ede2--- /dev/null+++ b/nanobot/goal/assembly.py@@ -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)diff --git a/nanobot/goal/command.py b/nanobot/goal/command.pynew file mode 100644index 000000000..2cd478807--- /dev/null+++ b/nanobot/goal/command.py@@ -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")diff --git a/nanobot/goal/runtime.py b/nanobot/goal/runtime.pynew file mode 100644index 000000000..e6bea573b--- /dev/null+++ b/nanobot/goal/runtime.py@@ -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)diff --git a/nanobot/agent/tools/long_task.py b/nanobot/goal/tools.pysimilarity index 90%rename from nanobot/agent/tools/long_task.pyrename to nanobot/goal/tools.pyindex 43bd05f94..289360ae4 100644--- a/nanobot/agent/tools/long_task.py+++ b/nanobot/goal/tools.py@@ -11,7 +11,7 @@ from nanobot.agent.goal_permission import (revoke_goal_mutation_permission,)from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters-from nanobot.agent.tools.context import RequestContext, ToolContext, current_request_context+from nanobot.agent.tools.context import RequestContext, current_request_contextfrom nanobot.agent.tools.schema import StringSchema, tool_parameters_schemafrom nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext@@ -26,7 +26,6 @@ from nanobot.session.goal_state import (parse_goal_state,sustained_goal_active,)-from nanobot.session.turn_continuation import reset_goal_continuation_roundsfrom nanobot.utils.cancellation import shield_and_drainfrom nanobot.utils.prompt_templates import render_template@@ -62,12 +61,16 @@ class _GoalToolsMixin:async def _session(self) -> Session | None:request_ctx = current_request_context()- if request_ctx is None:+ if request_ctx is None or not request_ctx.persist_session:return Nonekey = request_ctx.session_key- if not key:+ generation = request_ctx.session_generation+ if not key or not generation:return None- return await self._sessions.state.get_header(key)+ session = await self._sessions.state.read_header(key)+ if session is None or session.generation != generation:+ return None+ return sessiondef _goal_mutation_allowed(self) -> bool:return current_request_context() is not None and goal_mutation_allowed()@@ -77,7 +80,6 @@ class _GoalToolsMixin:sess: Session,blob: dict[str, Any],*,- reset_continuation: bool = False,revoke_permission: bool = False,) -> None:saved = False@@ -87,8 +89,6 @@ class _GoalToolsMixin:def change(metadata: dict[str, Any]) -> None:metadata[GOAL_STATE_KEY] = deepcopy(blob)discard_legacy_goal_state_key(metadata)- if reset_continuation:- reset_goal_continuation_rounds(metadata)_, sess.metadata = await self._sessions.state.mutate_metadata(sess.key, change, expected_generation=sess.generation,)@@ -150,18 +150,8 @@ class CreateGoalTool(Tool, _GoalToolsMixin):_GoalToolsMixin.__init__(self, sessions, bus)@classmethod- def create(cls, ctx: ToolContext) -> Tool:- sess = ctx.sessions- if sess is None:- raise RuntimeError("CreateGoalTool requires an initialized session manager")- return cls(- sessions=sess,- bus=ctx.bus,- )-- @classmethod- def enabled(cls, ctx: ToolContext) -> bool:- return ctx.sessions is not None+ def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:+ return cls(sessions=sessions, bus=bus)@propertydef name(self) -> str:@@ -236,7 +226,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):"ui_summary": summary,"started_at": _iso_now(),}- await self._save_goal_state(sess, blob, reset_continuation=True)+ await self._save_goal_state(sess, blob)extra = f"\nSummary line: {summary}" if summary else ""return ("Goal recorded. Keep working toward the objective using ordinary tools. "@@ -281,18 +271,8 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):_GoalToolsMixin.__init__(self, sessions, bus)@classmethod- def create(cls, ctx: ToolContext) -> Tool:- sess = ctx.sessions- if sess is None:- raise RuntimeError("UpdateGoalTool requires an initialized session manager")- return cls(- sessions=sess,- bus=ctx.bus,- )-- @classmethod- def enabled(cls, ctx: ToolContext) -> bool:- return ctx.sessions is not None+ def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:+ return cls(sessions=sessions, bus=bus)@propertydef name(self) -> str:@@ -350,7 +330,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):"previous_objective": str(prior.get("objective") or ""),"recap": (recap or "").strip(),}- await self._save_goal_state(sess, blob, reset_continuation=True)+ await self._save_goal_state(sess, blob)extra = f"\nSummary line: {summary}" if summary else ""return "Goal replaced. Continue toward the new objective using ordinary tools." + extradiff --git a/nanobot/nanobot.py b/nanobot/nanobot.pyindex c58f60429..9085bf053 100644--- a/nanobot/nanobot.py+++ b/nanobot/nanobot.py@@ -132,10 +132,13 @@ class Nanobot:tools = ToolRegistry()register_image_generation_tool(config, tools, workspace=config.workspace_path)mcp_provider = MCPProvider.from_config(config, tools)+ from nanobot.goal.assembly import install_goal+loop = AgentLoop.from_config(config,hook_factories=[create_file_edit_activity_hook],tool_registry=tools,+ builtin_assembly=install_goal,)return cls(loop, config=config, mcp_provider=mcp_provider)diff --git a/nanobot/session/goal_state.py b/nanobot/session/goal_state.pyindex d7d2b632f..ab8e53f43 100644--- a/nanobot/session/goal_state.py+++ b/nanobot/session/goal_state.py@@ -1,8 +1,7 @@"""Session metadata helpers for explicit sustained goals.Tools set ``metadata[GOAL_STATE_KEY]``. Reads accept the legacy session key ``thread_goal``-for older sessions. Callers use ``goal_state_runtime_lines`` and ``goal_state_ws_blob`` without-importing tool implementations.+for older sessions. Callers can read the goal without importing tool implementations."""from __future__ import annotations@@ -15,7 +14,6 @@ GOAL_COMMAND = "/goal"MAX_GOAL_OBJECTIVE_CHARS = 4000# Older builds stored the same JSON blob under this key._LEGACY_GOAL_STATE_SESSION_KEY = "thread_goal"-_MAX_OBJECTIVE_WS = 600def _session_goal_raw(metadata: Mapping[str, Any] | None) -> Any:@@ -51,15 +49,6 @@ def explicit_goal_requested(message_metadata: Mapping[str, Any] | None) -> bool:return str(message_metadata.get("original_command") or "").strip() == GOAL_COMMAND-def sustained_goal_turn(- metadata: Mapping[str, Any] | None,- *,- message_metadata: Mapping[str, Any] | None = None,-) -> bool:- """True when this turn should use sustained-goal runtime limits."""- return sustained_goal_active(metadata) or explicit_goal_requested(message_metadata)--def parse_goal_state(blob: Any) -> dict[str, Any] | None:if blob is None:return None@@ -91,24 +80,3 @@ def goal_state_runtime_lines(metadata: Mapping[str, Any] | None) -> list[str]:if hint:out.append(f"Summary: {hint}")return out---def goal_state_ws_blob(metadata: Mapping[str, Any] | None) -> dict[str, Any]:- """JSON-safe snapshot for WebSocket ``goal_state`` events (one chat_id per frame)."""- goal = parse_goal_state(_session_goal_raw(metadata)) if metadata else None- if isinstance(goal, dict) and goal.get("status") in {"active", "blocked"}:- status = str(goal.get("status"))- objective = str(goal.get("objective") or "").strip()- if len(objective) > _MAX_OBJECTIVE_WS:- objective = objective[:_MAX_OBJECTIVE_WS].rstrip() + "…"- summary = str(goal.get("ui_summary") or "").strip()[:120]- blob: dict[str, Any] = {"active": status == "active", "status": status}- if summary:- blob["ui_summary"] = summary- if objective:- blob["objective"] = objective- recap = str(goal.get("recap") or "").strip()[:240]- if recap:- blob["recap"] = recap- return blob- return {"active": False}diff --git a/nanobot/session/manager.py b/nanobot/session/manager.pyindex af461a282..b5e95e6bf 100644--- a/nanobot/session/manager.py+++ b/nanobot/session/manager.py@@ -42,13 +42,11 @@ _FORK_VOLATILE_METADATA_KEYS = {"_stopped_at_iteration_limit",PARENT_SESSION_KEY,SESSION_TYPE_KEY,- "goal_state","pending_user_turn","pending_user_followups","runtime_checkpoint","session_handle","webui_recovery",- "thread_goal","title","title_user_edited",}@@ -374,7 +372,10 @@ class SessionInfo(TypedDict):path: str-def fork_session(source: Session, target_key: str, before_user_index: int) -> Session | None:+def fork_session(+ source: Session, target_key: str, before_user_index: int,+ *, exclude_metadata: frozenset[str] = frozenset(),+) -> Session | None:"""Build a portable fork ending before the requested visible user message."""if before_user_index < 0:return None@@ -394,7 +395,7 @@ def fork_session(source: Session, target_key: str, before_user_index: int) -> Sereturn Nonemetadata = deepcopy(source.metadata)- for key in _FORK_VOLATILE_METADATA_KEYS:+ for key in _FORK_VOLATILE_METADATA_KEYS | exclude_metadata:metadata.pop(key, None)last_consolidated = min(source.last_archived, len(copied))@@ -432,15 +433,23 @@ class SessionManager:self._store.initialize()self._delete_observer: Callable[[str], None] | None = Noneself.types = SessionTypes()+ self._generation_exclusions: set[str] = set()self._state: SessionState | None = None+ def exclude_generation_metadata(self, keys: frozenset[str]) -> None:+ """Register feature metadata that cannot cross a fork or reset."""+ self._generation_exclusions.update(keys)+@propertydef state(self) -> SessionState:"""The asynchronous owner of session state transitions."""if self._state is None:from nanobot.session.state import SessionState- self._state = SessionState(self._store, on_delete=self._notify_delete, types=self.types)+ self._state = SessionState(+ self._store, on_delete=self._notify_delete, types=self.types,+ generation_exclusions=self._generation_exclusions,+ )return self._statedef _notify_delete(self, key: str) -> None:@@ -555,7 +564,9 @@ class SessionManager:source = self._store.load(source_key)if source is None:return None- target = fork_session(source, target_key, before_user_index)+ target = fork_session(+ source, target_key, before_user_index, exclude_metadata=frozenset(self._generation_exclusions),+ )if target is not None:self._store.save(target)self._store.copy_history_prefix(source_key, target, before_user_index)diff --git a/nanobot/session/state.py b/nanobot/session/state.pyindex 4f64e35b7..afa10ce3c 100644--- a/nanobot/session/state.py+++ b/nanobot/session/state.py@@ -53,12 +53,16 @@ class SessionState:workers: int = _DEFAULT_WORKERS,on_delete: Callable[[str], None] | None = None,types: SessionTypes | None = None,+ generation_exclusions: set[str] | None = None,) -> None:if capacity < 1:raise ValueError("session operation capacity must be positive")if workers < 1:raise ValueError("session operation worker count must be positive")self._types = types if types is not None else SessionTypes()+ self._generation_exclusions: set[str] = (+ generation_exclusions if generation_exclusions is not None else set()+ )self._store = storeself._on_delete = on_deleteself._snapshots: dict[str, Session] = {}@@ -426,6 +430,15 @@ class SessionState:return self._draft(session)return await self._execute(key, read, write=False)+ async def read_header(self, key: str) -> Session | None:+ """Read committed identity and metadata without creating a session."""+ def read() -> Session | None:+ session = self._load(key, history=False)+ if session is None:+ return None+ return replace(session, messages=[], provider_state=None, _baseline=None)+ return await self._execute(key, read, write=False)+async def get(self, key: str) -> Session:"""Read an existing conversation; create missing state on the writer."""return await self._get(key, history=True)@@ -661,7 +674,7 @@ class SessionState:await self._submit_draft(session)async def finish_turn(self, session: Session) -> None:- """Commit the assembled transcript and clear its recovery markers."""+ """Commit the assembled transcript and clear its recovery checkpoint."""session.metadata.pop(_PENDING_KEY, None)session.metadata.pop(_CHECKPOINT_KEY, None)await self._submit_draft(session)@@ -997,7 +1010,9 @@ class SessionState:source = self._load(source_key)if source is None:return None- target = fork_session(source, target_key, before_user_index)+ target = fork_session(+ source, target_key, before_user_index, exclude_metadata=frozenset(self._generation_exclusions),+ )if target is None:return Noneif title:@@ -1145,6 +1160,8 @@ class SessionState:session.metadata = deepcopy(old.metadata)for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"):session.metadata.pop(name, None)+ for name in self._generation_exclusions:+ session.metadata.pop(name, None)if session.policy.persist:self._store.delete(key, preserve_archive=True)self._commit(session)diff --git a/nanobot/session/turn_continuation.py b/nanobot/session/turn_continuation.pyindex feb7a5ac4..7cdf5ec08 100644--- a/nanobot/session/turn_continuation.py+++ b/nanobot/session/turn_continuation.py@@ -1,51 +1,23 @@-"""Internal turn continuation helpers.--This module keeps budget-boundary continuation policy out of ``AgentLoop``.-The loop calls a small set of helpers; those helpers decide whether an internal-continuation is allowed and, when it is, queue the next turn directly.-"""+"""Bookkeeping for explicit recovery inputs and ordinary iteration-limit stops."""from __future__ import annotations-import dataclassesfrom typing import TYPE_CHECKING, Any, Mapping, MutableMapping-from loguru import logger-from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines-from nanobot.session.goal_state import (- goal_state_runtime_lines,- sustained_goal_active,- sustained_goal_turn,-)-from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEYif TYPE_CHECKING:- from nanobot.agent.loop import TurnContextfrom nanobot.agent.tools.context import RequestContextfrom nanobot.session.state import SessionStateINTERNAL_CONTINUATION_META = "_internal_continuation"-INTERNAL_CONTINUATION_KIND_META = "_internal_continuation_kind"-INTERNAL_CONTINUATION_RUN_STARTED_AT_META = "_internal_continuation_run_started_at"SKIP_USER_PERSIST_META = "_skip_user_persist"_ITERATION_LIMIT_META = "_stopped_at_iteration_limit"-_GOAL_CONTINUATION_KIND = "sustained_goal"-_GOAL_CONTINUATION_SENDER = "system:continuation"-_GOAL_CONTINUATION_ROUNDS_KEY = "_sustained_goal_continuation_rounds"-_MAX_GOAL_CONTINUATION_ROUNDS = 12-_STRIPPED_INBOUND_META_KEYS = {- "goal_requested",- "original_command",-}--def record_iteration_limit(- metadata: MutableMapping[str, Any], stop_reason: str, *, continuation_pending: bool,-) -> None:- """Remember a terminal budget stop, not an internal continuation handoff."""- if stop_reason == "max_iterations" and not continuation_pending:+def record_iteration_limit(metadata: MutableMapping[str, Any], stop_reason: str) -> None:+ """Remember an ordinary execution stopped at its iteration limit."""+ if stop_reason == "max_iterations":metadata[_ITERATION_LIMIT_META] = Trueelse:metadata.pop(_ITERATION_LIMIT_META, None)@@ -73,245 +45,21 @@ async def iteration_limit_context(def internal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool:- """True for an inbound message created by an internal continuation policy."""return bool(metadata and metadata.get(INTERNAL_CONTINUATION_META) is True)-def sustained_goal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool:- """True only for an internal continuation owned by sustained-goal policy."""- return bool(- internal_continuation_inbound(metadata)- and metadata- and metadata.get(INTERNAL_CONTINUATION_KIND_META) == _GOAL_CONTINUATION_KIND- )---def internal_continuation_run_started_at(metadata: Mapping[str, Any] | None) -> float | None:- """Return the user-visible run start propagated across continuation slices."""- if not metadata:- return None- value = metadata.get(INTERNAL_CONTINUATION_RUN_STARTED_AT_META)- if not isinstance(value, int | float):- return None- started_at = float(value)- return started_at if started_at > 0 else None--def should_persist_user_message(metadata: Mapping[str, Any] | None) -> bool:- """Return whether this inbound message should be persisted as user input."""if metadata and metadata.get(SKIP_USER_PERSIST_META) is True:return Falsereturn not internal_continuation_inbound(metadata)-def should_stream_budget_response(- *,- stop_reason: str,- pending_queue_available: bool,- session_metadata: Mapping[str, Any] | None,- message_metadata: Mapping[str, Any] | None = None,-) -> bool:- """Return whether the budget-boundary response should be sent to the user."""- if stop_reason != "max_iterations":- return True- return should_finalize_on_max_iterations(- pending_queue_available=pending_queue_available,- session_metadata=session_metadata,- message_metadata=message_metadata,- )---def should_finalize_on_max_iterations(- *,- pending_queue_available: bool,- session_metadata: Mapping[str, Any] | None,- message_metadata: Mapping[str, Any] | None = None,-) -> bool:- """Return whether a max-iteration boundary should produce a final response.-- When a sustained goal can continue internally, the current runner slice- should stop without spending an extra no-tools finalization call. The next- queued continuation slice owns the eventual user-visible response.- """- return not (- pending_queue_available- and _goal_continuation_available(- session_metadata,- message_metadata=message_metadata,- )- )---async def maybe_continue_turn(- ctx: TurnContext, *, session_metadata: Mapping[str, Any],-) -> bool:- """Queue an internal continuation for *ctx* when policy allows it."""- if ctx.session is None or ctx.pending_queue is None:- return False- if not _continuation_available(- stop_reason=ctx.stop_reason,- pending_queue_available=True,- session_metadata=session_metadata,- message_metadata=ctx.msg.metadata,- ):- return False-- metadata = _internal_continuation_metadata(- ctx.msg.metadata,- run_started_at=ctx.visible_run_started_at,- )- request = ctx.request_context- assert request is not None and request.turn_id is not None- metadata[REQUEST_ORIGIN_METADATA_KEY] = {- "message_id": request.message_id,- "turn_id": request.turn_id,- }- content = _goal_continuation_prompt(session_metadata)- messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)- _increment_goal_continuation_round(ctx.session.metadata)-- logger.info("Turn budget reached; scheduling internal continuation")- ctx.final_content = ""- ctx.all_messages = messages- ctx.suppress_response = True- await ctx.pending_queue.put(- dataclasses.replace(- ctx.msg,- sender_id=_GOAL_CONTINUATION_SENDER,- content=content,- media=[],- metadata=metadata,- session_key_override=ctx.session_key,- )- )- return True---def prepare_save_boundary(ctx: TurnContext) -> None:- """Prepare continuation bookkeeping and the history append boundary."""- if ctx.session is not None:- clear_internal_continuation_state(ctx.session.metadata)-- assert ctx.transcript_input is not None- ctx.save_skip = _save_skip_for_turn(- message_metadata=ctx.msg.metadata,- initial_message_count=ctx.transcript_input.message_count,- input_persisted_early=ctx.input_persisted_early,- )---def _continuation_available(- *,- stop_reason: str,- pending_queue_available: bool,- session_metadata: Mapping[str, Any] | None,- message_metadata: Mapping[str, Any] | None = None,-) -> bool:- if stop_reason != "max_iterations" or not pending_queue_available:- return False- return _goal_continuation_available(- session_metadata,- message_metadata=message_metadata,- )---def clear_internal_continuation_state(metadata: MutableMapping[str, Any]) -> None:- """Reset policy bookkeeping once its owning runtime mode is inactive."""- if not sustained_goal_active(metadata):- reset_goal_continuation_rounds(metadata)---def reset_goal_continuation_rounds(metadata: MutableMapping[str, Any]) -> None:- """Start a newly created or replaced goal with a fresh continuation budget."""- metadata.pop(_GOAL_CONTINUATION_ROUNDS_KEY, None)---def _save_skip_for_turn(- *,- message_metadata: Mapping[str, Any] | None,- initial_message_count: int,- input_persisted_early: bool,+def save_skip_for_turn(+ *, message_metadata: Mapping[str, Any] | None,+ initial_message_count: int, input_persisted_early: bool,) -> int:if message_metadata and message_metadata.get(SKIP_USER_PERSIST_META) is True:return initial_message_countif internal_continuation_inbound(message_metadata):return initial_message_count- if not input_persisted_early:- return initial_message_count - 1- return initial_message_count---def _goal_continuation_available(- session_metadata: Mapping[str, Any] | None,- *,- message_metadata: Mapping[str, Any] | None = None,- max_rounds: int = _MAX_GOAL_CONTINUATION_ROUNDS,-) -> bool:- if not sustained_goal_turn(session_metadata, message_metadata=message_metadata):- return False- if not sustained_goal_active(session_metadata):- return False- try:- rounds = int((session_metadata or {}).get(_GOAL_CONTINUATION_ROUNDS_KEY) or 0)- except (TypeError, ValueError):- rounds = 0- return rounds < max(0, max_rounds)---def _increment_goal_continuation_round(session_metadata: MutableMapping[str, Any]) -> None:- try:- rounds = int(session_metadata.get(_GOAL_CONTINUATION_ROUNDS_KEY) or 0)- except (TypeError, ValueError):- rounds = 0- session_metadata[_GOAL_CONTINUATION_ROUNDS_KEY] = rounds + 1---def _internal_continuation_metadata(- message_metadata: Mapping[str, Any] | None,- *,- run_started_at: float | None = None,-) -> dict[str, Any]:- metadata = dict(message_metadata or {})- metadata[INTERNAL_CONTINUATION_META] = True- metadata[INTERNAL_CONTINUATION_KIND_META] = _GOAL_CONTINUATION_KIND- if run_started_at is not None:- metadata[INTERNAL_CONTINUATION_RUN_STARTED_AT_META] = float(run_started_at)- for key in _STRIPPED_INBOUND_META_KEYS:- metadata.pop(key, None)- return metadata---def _goal_continuation_prompt(metadata: Mapping[str, Any] | None) -> str:- lines = goal_state_runtime_lines(metadata)- if lines:- goal = "\n".join(lines)- return (- "Continue the active sustained goal after the previous turn reached "- "its tool-call budget.\n\n"- f"{goal}\n\n"- "Continue from the saved context. Do not mention the continuation "- "boundary to the user. Use tools as needed, and call update_goal "- "with action='complete' when the objective is truly finished."- )- return (- "Continue the active sustained goal after the previous turn reached "- "its tool-call budget. Continue from the saved context. Do not mention "- "the continuation boundary to the user. Use tools as needed, and call "- "update_goal with action='complete' when the objective is truly finished."- )---def _strip_terminal_assistant(- messages: list[dict[str, Any]],- final_content: str | None,-) -> list[dict[str, Any]]:- if not messages:- return messages- last = messages[-1]- if last.get("role") != "assistant":- return messages- if final_content is None or last.get("content") != final_content:- return messages- if last.get("tool_calls"):- return messages- return messages[:-1]+ return initial_message_count if input_persisted_early else initial_message_count - 1diff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.pyindex f806f3fee..825bf2b90 100644--- a/nanobot/session/webui_turns.py+++ b/nanobot/session/webui_turns.py@@ -40,7 +40,6 @@ from nanobot.providers.base import LLMProvider, LLMUsagefrom nanobot.providers.fallback_provider import FallbackModelObserver, FallbackModelSelectionfrom nanobot.runtime_context import public_history_messagefrom nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY-from nanobot.session.goal_state import goal_state_ws_blobfrom nanobot.session.history_visibility import is_hidden_history_messagefrom nanobot.session.manager import Session, SessionManagerfrom 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 SessionConflictErrorfrom nanobot.utils.helpers import strip_think, truncate_textfrom nanobot.utils.llm_runtime import LLMRuntime+from nanobot.webui.goal_state import goal_state_ws_blobfrom nanobot.webui.metadata import (WEBSOCKET_TURN_OWNER_METADATA_KEY,WEBUI_TURN_METADATA_KEY,diff --git a/nanobot/webui/goal_state.py b/nanobot/webui/goal_state.pynew file mode 100644index 000000000..072b0bc75--- /dev/null+++ b/nanobot/webui/goal_state.py@@ -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}diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.pyindex 88eb996c1..13260705a 100644--- a/nanobot/webui/inbound_commands.py+++ b/nanobot/webui/inbound_commands.py@@ -16,7 +16,8 @@ from websockets.asyncio.server import ServerConnectionfrom nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_USER_SHELLfrom nanobot.channels.websocket.attachment_policy import validate_attachment_batchfrom 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_COMMANDfrom nanobot.runtime_context import (RUNTIME_CONTEXT_INPUT_META,WEBUI_QUOTE_METADATA,diff --git a/nanobot/webui/session_projection.py b/nanobot/webui/session_projection.pyindex d60a38cde..edf22f62f 100644--- a/nanobot/webui/session_projection.py+++ b/nanobot/webui/session_projection.py@@ -6,11 +6,11 @@ from loguru import logger as default_loggerfrom nanobot.agent.subagent import SubagentControlErrorfrom nanobot.providers.base import LLMUsage-from nanobot.session.goal_state import goal_state_ws_blobfrom nanobot.session.model_selection import model_preset_from_metadatafrom nanobot.session.recovery import recovery_state_from_metadatafrom nanobot.session.state import SessionStatefrom nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at+from nanobot.webui.goal_state import goal_state_ws_blobif TYPE_CHECKING:from nanobot.agent.subagent import SubagentManager@@ -98,16 +98,15 @@ class WebUISessionProjection:return tuple(events)async def persisted_goal_state(self, session_key: str) -> dict[str, Any] | None:- """Return an actionable persisted goal state for reconnect hydration."""+ """Return the persisted goal snapshot, including an inactive state on reconnect."""if self._sessions is None:return Nonesnapshot = await self._sessions.state.read_metadata(session_key)- raw_metadata = snapshot.get("metadata") if snapshot is not None else None- metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}- goal_state = goal_state_ws_blob(metadata)- if not goal_state.get("active") and goal_state.get("status") != "blocked":+ if snapshot is None:return None- return goal_state+ raw_metadata = snapshot.get("metadata")+ metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}+ return goal_state_ws_blob(metadata)@staticmethoddef active_turn_status(chat_id: str) -> tuple[float, str | None] | None:diff --git a/nanobot/webui/temporary_chats.py b/nanobot/webui/temporary_chats.pyindex e01b9238c..0fe084e89 100644--- a/nanobot/webui/temporary_chats.py+++ b/nanobot/webui/temporary_chats.py@@ -11,7 +11,7 @@ from nanobot.bus.events import (InboundMessage,)from nanobot.bus.queue import MessageBus-from nanobot.command.builtin import register_builtin_commands+from nanobot.command.application import register_builtin_commandsfrom nanobot.command.router import CommandRouterfrom nanobot.security.workspace_access import WorkspaceScopefrom nanobot.session.manager import SessionManagerdiff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex 984502b1c..324908ebb 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -28,7 +28,7 @@ from websockets.http11 import Responsefrom nanobot.agent.subagent import SubagentControlErrorfrom nanobot.agent.subagent_status import SubagentSessionError-from nanobot.command.builtin import builtin_command_palette+from nanobot.command.application import builtin_command_palettefrom nanobot.cron.binding import CronBindingError, binding_revisionfrom nanobot.cron.session_turns import is_bound_cron_jobfrom nanobot.cron.types import CronJob, CronSchedulediff --git a/tests/agent/test_goal_permission.py b/tests/agent/test_goal_permission.pyindex 28a838339..1c777d101 100644--- a/tests/agent/test_goal_permission.py+++ b/tests/agent/test_goal_permission.py@@ -28,10 +28,10 @@ def goal_message(**overrides):{"metadata": {"goal_requested": True, "_cron_trigger": {"job_id": "job"}}},{"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)with goal_mutation_permission(True):- with GoalInputScope(message) as scope:+ with GoalInputScope() as scope:assert goal_mutation_allowed() is Falsescope.consume_inputs([message])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():- 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 Truerevoke_goal_mutation_permission()scope.consume_inputs([goal_message(content="ok", metadata={})])diff --git a/tests/agent/test_loop_iteration_limit.py b/tests/agent/test_loop_iteration_limit.pyindex ef00cc3ff..5b8561a19 100644--- a/tests/agent/test_loop_iteration_limit.py+++ b/tests/agent/test_loop_iteration_limit.py@@ -2,7 +2,6 @@from __future__ import annotations-import asyncioimport jsonfrom copy import deepcopyfrom typing import Any@@ -11,8 +10,8 @@ from unittest.mock import AsyncMockimport pytestfrom nanobot.agent.loop import AgentLoop-from nanobot.bus.events import InboundMessagefrom nanobot.bus.queue import MessageBus+from nanobot.goal.assembly import install_goalfrom nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequestfrom nanobot.runtime_context import public_history_messagesfrom 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",context_window_tokens=128_000,max_iterations=2,+ builtin_assembly=install_goal,)exec_tool = loop.tools.get("exec")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()-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]]] = []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:await loop.sessions.state.get("cli:goal")await loop.sessions.state.update_metadata("cli:goal", {GOAL_STATE_KEY: {"status": "active", "objective": "run the tests"},})- await loop._process_message(- InboundMessage(channel="cli", sender_id="user", chat_id="goal", content="run the tests"),- pending_queue=pending,- )- continuation = pending.get_nowait()- assert continuation.sender_id == "system:continuation"+ result = await loop.process_direct("run the tests", session_key="cli:goal")+ assert result.content == "done"+ assert len(requests) == 5+ loop.runner.run.assert_awaited_once()+ session = await loop.sessions.state.read("cli:goal")+ 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")- assert _STOP_MARKER not in _last_user_content(requests[next_request])- next_request = len(requests)- await loop._process_message(continuation, pending_queue=pending)- assert _STOP_MARKER not in _last_user_content(requests[next_request])+ assert _STOP_MARKER not in _last_user_content(requests[-1])finally:await loop.aclose()diff --git a/tests/agent/test_loop_progress.py b/tests/agent/test_loop_progress.pyindex 10dfe28cc..330df5cf0 100644--- a/tests/agent/test_loop_progress.py+++ b/tests/agent/test_loop_progress.py@@ -333,12 +333,15 @@ class TestToolEventProgress:provider.chat_stream_with_retry = chat_stream_with_retryprovider.chat_with_retry = AsyncMock()+ from nanobot.goal.assembly import install_goal+loop = AgentLoop(bus=bus,provider=provider,workspace=tmp_path,model="test-model",hook_factories=[create_file_edit_activity_hook],+ builtin_assembly=install_goal,)tool = WriteFileTool(workspace=tmp_path)loop.tools.get_definitions = MagicMock(return_value=[diff --git a/tests/agent/test_loop_runner_integration.py b/tests/agent/test_loop_runner_integration.pyindex 8ab0d5b16..ab0d1d2e9 100644--- a/tests/agent/test_loop_runner_integration.py+++ b/tests/agent/test_loop_runner_integration.py@@ -7,13 +7,14 @@ import pytestfrom agent.session_helpers import mock_session_managerfrom 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_allowedfrom nanobot.agent.tools.context import RequestContextfrom nanobot.bus.events import InboundMessagefrom nanobot.bus.outbound_events import StreamedResponseEventfrom nanobot.bus.queue import MessageBusfrom nanobot.config.schema import AgentDefaultsfrom nanobot.events import RetryStatusEvent+from nanobot.goal.assembly import install_goalfrom nanobot.providers.base import (GenerationSettings,LLMProvider,@@ -98,27 +99,6 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):assert outbound.chat_id == "chat-a"-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.asyncioasync def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):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),])- 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.add_message("user", "Let's agree on the migration implementation.")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),])- 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.add_message("user", "/goal old completed request")session.add_message("assistant", "The old request is complete.")diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.pyindex 078d06b1b..40d1090f4 100644--- a/tests/agent/test_loop_save_turn.py+++ b/tests/agent/test_loop_save_turn.py@@ -1,5 +1,6 @@import asyncioimport json+import threadingfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -21,8 +22,17 @@ from nanobot.bus.outbound_events import (TurnEndEvent,)from nanobot.bus.queue import MessageBus+from nanobot.bus.runtime_events import TurnCompleted, TurnRunStatusChangedfrom 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 ProviderSnapshotfrom nanobot.runtime_context import (RUNTIME_CONTEXT_HISTORY_META,@@ -119,14 +129,16 @@ def _runtime_message(content, blocks: list[RuntimeContextBlock]) -> dict:def _make_full_loop(tmp_path: Path) -> AgentLoop:- provider = MagicMock()+ provider = MagicMock(aclose=AsyncMock())provider.provider_name = "test"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"))bus = MessageBus()loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model",+ builtin_assembly=install_goal,)WebuiTurnCoordinator(bus=loop.bus,@@ -1382,256 +1394,270 @@ async def test_process_message_does_not_duplicate_early_persisted_user_message(t@pytest.mark.asyncio-async def test_internal_continuation_queues_turn_without_fake_user_history(- tmp_path: Path,-) -> None:+async def test_explicit_recovery_continues_without_fake_user_history(tmp_path: Path) -> None:loop = _make_full_loop(tmp_path)- session = loop.sessions.get_or_create("feishu:c-auto")- session.metadata[GOAL_STATE_KEY] = {- "status": "active",- "objective": "Finish the long goal.",- }+ session = loop.sessions.get_or_create("feishu:recovery")+ session.add_message("user", "Inspect the migration")+ session.add_message("assistant", "Evidence collected before interruption.")loop.sessions.save(session)-- 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"},- ]+ loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))+ try:+ 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_internal_continuation_preserves_streaming_route_metadata(- tmp_path: Path,-) -> None:+async def test_same_run_goal_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+ 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[email protected]("content", ["start the goal", "/goal start the goal"])-async def test_websocket_internal_continuation_keeps_single_visible_run(- tmp_path: Path, content: str,-) -> None:+async def test_stop_during_committed_goal_checkpoint_settles_queued_command(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+):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.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 fake_run_agent_loop(transcript_input, **_kwargs):+ async def respond(*args, **kwargs):nonlocal calls- initial_messages = _assembled_messages(loop.context, transcript_input)+ if args and "You write short, neutral chat titles" in str(args[0]):+ return LLMResponse(content="Goal checkpoint")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"}],+ 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+ stop_msg = InboundMessage(+ channel="websocket", sender_id="user", chat_id=msg.chat_id, content="/stop",+ metadata={"message_id": "stop-attempt"},)+ await loop.bus.publish_inbound(stop_msg)+ async with asyncio.timeout(5):+ while not worker.cancelling():+ await asyncio.sleep(0)+ release.set()+ 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 = []+ while loop.bus.outbound_size:+ outbound.append(await loop.bus.consume_outbound())+ stop_responses = [item.content for item in outbound if item.content.startswith("Stopped ")]+ assert stop_responses == ["Stopped 1 task(s)."]+ endings = [item.event for item in outbound if isinstance(item.event, TurnEndEvent)]+ 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",+ ]- 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+ 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[email protected]("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-[email protected]("operation", ["reset", "delete"])+async def test_active_goal_checkpoint_cannot_revive_an_old_generation(tmp_path: Path, operation):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)+ 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 fake_run_agent_loop(transcript_input, **_kwargs):+ async def respond(**kwargs):nonlocal callscalls += 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)+ 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(saving.wait(), timeout=5)- assert loop._pending_queues[msg.session_key].qsize() == 1- stop_msg = InboundMessage(- channel="websocket", sender_id="u1", chat_id=msg.chat_id, content="/stop",- )- result = await cmd_stop(CommandContext(- msg=stop_msg, session=None, key=msg.session_key, raw="/stop", loop=loop,- ))- assert "Stopped 1 task(s)" in result.content+ 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 == 2finally:- await loop._cancel_active_tasks(msg.session_key)-- outbound = []- while loop.bus.outbound_size:- outbound.append(await loop.bus.consume_outbound())- statuses = [m.event.status for m in outbound if isinstance(m.event, GoalStatusEvent)]- assert statuses == ["running", "idle"]- assert calls == 1- assert msg.session_key not in loop._pending_queues+ release.set()+ await loop._cancel_active_tasks(session.key)+ await asyncio.gather(worker, return_exceptions=True)+ await loop.aclose()@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.metadata == {"subagent_task_id": "sub-1"}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"]assert isinstance(initial_messages, list)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 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()diff --git a/tests/agent/test_mid_turn_goal.py b/tests/agent/test_mid_turn_goal.pyindex 0600ffc55..4d18960ea 100644--- a/tests/agent/test_mid_turn_goal.py+++ b/tests/agent/test_mid_turn_goal.py@@ -5,14 +5,27 @@ import pytestfrom agent.session_helpers import stop_loopfrom nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission-from nanobot.agent.loop import AgentLoop+from nanobot.agent.loop import AgentLoop as CoreAgentLoopfrom nanobot.bus.events import InboundMessage+from nanobot.bus.outbound_events import GoalStatusEvent, TurnEndEventfrom 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_messagesfrom nanobot.session.goal_state import GOAL_STATE_KEYfrom nanobot.session.history_visibility import is_hidden_history_messagefrom 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", [@@ -51,7 +64,7 @@ async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, creturn LLMResponse(content="done")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)loop._process_message = processrun = 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",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:await loop._dispatch_command_inline(msg, msg.session_key, msg.content, loop.commands.dispatch)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.generation = GenerationSettings()provider.estimate_prompt_tokens.return_value = (100, "test")- loop = AgentLoop(+ loop = _assembled_loop(bus=MessageBus(), provider=provider, workspace=tmp_path,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):- from nanobot.command.router import CommandContext+ from nanobot.command.router import CommandContext, CommandExpansionfrom nanobot.session.recovery import pending_followupsprovider = MagicMock(aclose=AsyncMock())provider.get_default_model.return_value = "test-model"provider.generation = GenerationSettings()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(channel="websocket", sender_id="user", chat_id="test", content="/goal /stop",)try:- generated = await loop.commands.dispatch(CommandContext(+ context = CommandContext(msg=message, session=None, key=message.session_key,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 await loop.sessions.state.queue_followup(message.session_key, generated)finally: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))recovered, = pending_followups(session)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.generation = GenerationSettings()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(channel="cli", sender_id="automation", chat_id="test", content="Continue working",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 Falsefinally: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()++[email protected]("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()diff --git a/tests/agent/test_runner_core.py b/tests/agent/test_runner_core.pyindex 6ca2fb806..03d9cee57 100644--- a/tests/agent/test_runner_core.py+++ b/tests/agent/test_runner_core.py@@ -864,7 +864,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(model="test-model",max_iterations=3,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,))@@ -1005,6 +1005,7 @@ async def test_runner_length_recovery_preserves_prefix_at_max_iterations():max_iterations_message="limit reached",))+ assert provider.chat_stream_with_retry.await_count == 1assert result.stop_reason == "max_iterations"assert result.final_content == "partial answer\n\nlimit reached"assert result.pending_stream_content == "\n\nlimit reached"diff --git a/tests/agent/test_runner_goal_continue.py b/tests/agent/test_runner_goal_continue.pyindex 61d4f7748..6d6ee7ecd 100644--- a/tests/agent/test_runner_goal_continue.py+++ b/tests/agent/test_runner_goal_continue.py@@ -3,17 +3,27 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom agent.runner_helpers import make_run_spec+from nanobot.agent.hook import AgentHookfrom nanobot.agent.runner import AgentRunnerfrom 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.fixturedef run_spec():provider = MagicMock(spec=LLMProvider)provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done"))+ provider.supports_native_compaction.return_value = Falsetools = MagicMock()tools.get_definitions.return_value = []+ tools.execute = AsyncMock(return_value="tool result")return make_run_spec(provider,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"])async def test_runner_completes_without_a_continuation_request(run_spec, callback):run_spec.continuation_callback = callback+ result = await AgentRunner().run(run_spec)+ assert result.stop_reason == "completed"+ assert result.final_content == "all done"+ assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1+++async def test_continuation_extends_budget_without_reset(run_spec):+ run_spec.max_iterations = 1+ total_rounds = 14+ calls = 0++ 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)assert result.stop_reason == "completed"assert result.final_content == "all done"- assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1+ assert result.had_injections is True+ assert calls == total_rounds+ assert run_spec.continuation_callback.await_count == total_rounds+ assert [+ call.args[0].iteration for call in run_spec.hook.before_iteration.await_args_list+ ] == 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[email protected]("max_iterations,finalize", [(1, True), (3, True), (8, False)])-async def test_continuation_injects_text_without_exceeding_budget(run_spec, max_iterations, finalize):- continuation = "Continue working toward the active sustained goal."- run_spec.max_iterations = max_iterations[email protected]("finalize,finalization_fails", [(True, False), (False, False), (True, True)])+async def test_goal_closing_after_tool_overrun_gets_bounded_finalization(run_spec, finalize, finalization_fails):+ run_spec.max_iterations = 1run_spec.finalize_on_max_iterations = finalize- run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)+ 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 result.stop_reason == "max_iterations"- requests = run_spec.runtime.provider.chat_stream_with_retry.await_args_list- assert len(requests) == max_iterations + int(finalize)- assert {"role": "user", "content": continuation} in result.messages- if max_iterations > 1:- assert {"role": "user", "content": continuation} in requests[1].kwargs["messages"]- if finalize:- assert not requests[-1].kwargs.get("tools")+ 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-async def test_runner_does_not_request_continuation_on_error(run_spec):- run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(- content=None, finish_reason="error",- )[email protected]("finish_reason", ["error", "refusal", "content_filter"])[email protected]("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.")run_spec.continuation_callback = callbackresult = 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- 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):- continuation = None- calls = 0[email protected]("response_kind", ["text", "tool"])+async def test_real_followup_precedes_goal_at_iteration_cap(run_spec, response_kind):+ followup = {"role": "user", "content": "Stop the goal and answer this instead."}+ pending = []+ goal_active = True+ requests = []+ run_spec.max_iterations = 1async def respond(**kwargs):- nonlocal continuation, calls- calls += 1- if calls == 1:- continuation = "Write the article draft."- return LLMResponse(content="The goal is now active.")- assert {"role": "user", "content": continuation} in kwargs["messages"]- continuation = None- return LLMResponse(content="The draft is complete.")+ requests.append(kwargs["messages"])+ if len(requests) == 1:+ pending.append(followup)+ return (+ LLMResponse(content="Goal checkpoint.") if response_kind == "text" else+ LLMResponse(content=None, tool_calls=[+ ToolCallRequest(id="work", name="work", arguments={}),+ ])+ )+ 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.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++[email protected]("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++[email protected]("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 Nonerun_spec.runtime.provider.chat_stream_with_retry.side_effect = respond- run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)+ 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)- assert calls == 2assert 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"]diff --git a/tests/agent/test_runner_injections.py b/tests/agent/test_runner_injections.pyindex bf7cecd60..8fe3188e6 100644--- a/tests/agent/test_runner_injections.py+++ b/tests/agent/test_runner_injections.py@@ -379,7 +379,7 @@ async def test_goal_continuation_precedes_terminal_wait():continuation_checks = 0terminal_waits = 0- async def continue_goal() -> str | None:+ async def continue_goal():nonlocal continuation_checkscontinuation_checks += 1return "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]")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["extra"]["session_key"] == "cli:c"diff --git a/tests/agent/test_session_inbox_controls.py b/tests/agent/test_session_inbox_controls.pyindex b8b2db9b6..10646701a 100644--- a/tests/agent/test_session_inbox_controls.py+++ b/tests/agent/test_session_inbox_controls.py@@ -4,19 +4,22 @@ from unittest.mock import AsyncMock, MagicMockimport pytest-from agent.session_helpers import run_session, stop_loop+from agent.session_helpers import run_session, stop_loop, visible_messagefrom nanobot.agent.automation_turns import AutomationTurnErrorfrom nanobot.agent.loop import AgentLoopfrom nanobot.agent.tools.context import current_request_contextfrom nanobot.agent.tools.cron import CronToolfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.queue import MessageBus+from nanobot.bus.runtime_events import TurnCompletedfrom nanobot.cron.service import CronServicefrom 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, ToolCallRequestfrom nanobot.runtime_context import public_history_messagesfrom nanobot.session.automation_turns import AUTOMATION_HISTORY_METAfrom nanobot.session.goal_state import GOAL_STATE_KEY+from nanobot.session.history_visibility import is_hidden_history_messagefrom nanobot.session.manager import SessionManagerfrom nanobot.session.recovery import (PENDING_FOLLOWUPS_KEY,@@ -36,6 +39,7 @@ async def loop(tmp_path):provider.estimate_prompt_tokens.return_value = (100, "test")agent = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",+ builtin_assembly=install_goal,)agent.tools.get_definitions = MagicMock(return_value=[])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])-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 = 1loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))loop.tools.execute = AsyncMock(return_value="ok")@@ -612,15 +616,14 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, comawait asyncio.sleep(0)elif complete_on_followup or len(requests) == 3: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="working", finish_reason="tool_calls",- tool_calls=[ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={})],- )+ assert len(requests) <= 3+ return LLMResponse(content="One more check is needed.")loop.provider.chat_stream_with_retry = chat+ loop.runner.run = AsyncMock(wraps=loop.runner.run)run_task = asyncio.create_task(loop.run())try:await loop.bus.publish_inbound(InboundMessage(@@ -630,12 +633,15 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, comwhile not requests or "cli:test" in loop._pending_queues:await asyncio.sleep(0.01)assert len(requests) == (2 if complete_on_followup else 3)- continuation_text = "Continue the active sustained goal after the previous turn"- assert continuation_text not in str(requests[1])+ assert visible_message(requests[1][-1])["content"] == "Inspect file B first"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")- 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"] == ["Start the goal", "Inspect file B first",]@@ -644,7 +650,7 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, comawait 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 = Trueloop.max_iterations = 1loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))@@ -654,15 +660,21 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loopsession.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"}loop.sessions.save(session)requests = []+ completed = []+ loop.bus.subscribe(completed.append, TurnCompleted)+ loop.consolidator.compact_idle_session = AsyncMock()+ loop.runner.run = AsyncMock(wraps=loop.runner.run)persisted_origin = Noneasync def chat(**kwargs):nonlocal persisted_origincontext = current_request_context()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: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"},))async with asyncio.timeout(3):@@ -671,12 +683,13 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loopelif len(requests) == 3:persisted = SessionManager(loop.workspace).get_or_create(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(- 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="working", finish_reason="tool_calls", tool_calls=[+ return LLMResponse(content="done", usage=usage)+ return LLMResponse(content="working", finish_reason="tool_calls", usage=usage, tool_calls=[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(loopasync with asyncio.timeout(5):while not requests or key in loop._pending_queues:await asyncio.sleep(0.01)- assert [request[:2] for request in requests] == [- ("chat-a", "message-a"), ("chat-b", "message-b"), ("chat-a", "message-a"),- ]- assert requests[2][2] == requests[0][2]+ assert [request[:2] for request in requests] == [("chat-a", "message-a")] * 3+ assert len({request[2] for request in requests}) == 1+ loop.runner.run.assert_awaited_once()+ loop.consolidator.compact_idle_session.assert_awaited_once()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 = []while not loop.bus.outbound.empty():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")))assert replies == [("chat-a", "message-a")]finally:await stop_loop(loop, worker, timeout=3)++[email protected]("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)diff --git a/tests/agent/test_session_manager_history.py b/tests/agent/test_session_manager_history.pyindex 36c27c820..f65f73655 100644--- a/tests/agent/test_session_manager_history.py+++ b/tests/agent/test_session_manager_history.py@@ -491,11 +491,15 @@ def test_public_history_omits_cli_app_breadcrumb():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.exclude_generation_metadata(GOAL_GENERATION_VOLATILE_KEYS)source = manager.get_or_create("websocket:source")source.metadata["webui"] = Truesource.metadata["title"] = "Old title"source.metadata["goal_state"] = {"status": "active", "objective": "do not inherit"}+ source.metadata["_sustained_goal_continuation_rounds"] = 7source.add_message("user", "round1")source.add_message("assistant", "answer1")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 Trueassert "title" not in forked.metadataassert "goal_state" not in forked.metadata+ assert "_sustained_goal_continuation_rounds" not in forked.metadatasaved = manager.read_session_file("websocket:fork")assert [m["content"] for m in saved["messages"]] == ["round1", "answer1"]diff --git a/tests/agent/test_stop_preserves_context.py b/tests/agent/test_stop_preserves_context.pyindex 8db9a085f..176600a6d 100644--- a/tests/agent/test_stop_preserves_context.py+++ b/tests/agent/test_stop_preserves_context.py@@ -93,6 +93,7 @@ async def test_dispatch_cancellation_restores_checkpoint():)loop.sessions.get_or_create = MagicMock(return_value=session)+ loop.sessions.state.read = AsyncMock(return_value=session)loop.sessions.save = MagicMock()async def _cancel(*_args, **_kwargs):diff --git a/tests/agent/test_unified_session.py b/tests/agent/test_unified_session.pyindex 311f810b8..f0841fbf6 100644--- a/tests/agent/test_unified_session.py+++ b/tests/agent/test_unified_session.py@@ -11,7 +11,8 @@ from nanobot.agent.loop import AgentLoopfrom nanobot.agent.tools.file_state import FileStateStorefrom nanobot.bus.events import InboundMessagefrom 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_newfrom nanobot.command.router import CommandContext, CommandRouterfrom nanobot.config.schema import AgentDefaults, Configfrom nanobot.session.keys import UNIFIED_SESSION_KEYdiff --git a/tests/agent/tools/test_long_task.py b/tests/agent/tools/test_long_task.pyindex 84d3037c8..2346ac167 100644--- a/tests/agent/tools/test_long_task.py+++ b/tests/agent/tools/test_long_task.py@@ -1,27 +1,27 @@from __future__ import annotationsimport asyncio+from dataclasses import replacefrom unittest.mock import AsyncMock, MagicMockimport pytestfrom nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permissionfrom nanobot.agent.loop import AgentLoop+from nanobot.agent.tools.base import Toolfrom nanobot.agent.tools.context import (RequestContext,current_request_context,request_context,)-from nanobot.agent.tools.long_task import (- CreateGoalTool,- UpdateGoalTool,-)from nanobot.agent.tools.registry import ToolRegistryfrom nanobot.bus.outbound_events import GoalStateSyncEventfrom nanobot.bus.queue import MessageBus+from nanobot.goal.assembly import install_goal+from nanobot.goal.runtime import GoalExecutionPolicy+from nanobot.goal.tools import CreateGoalTool, UpdateGoalToolfrom nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARSfrom nanobot.session.manager import SessionManager-from nanobot.session.turn_continuation import should_finalize_on_max_iterationsfrom nanobot.session.webui_turns import WebuiTurnCoordinator@@ -60,7 +60,15 @@ def _tools(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):+ ctx = await _bound_context(tool._sessions, ctx)with request_context(ctx), goal_mutation_permission(allowed):return await tool.execute(**kwargs)@@ -70,7 +78,6 @@ async def test_create_goal_records_goal_metadata(tmp_path):sm = SessionManager(tmp_path)create, _update, ctx = _tools(sm)await sm.state.get("websocket:c1")- await sm.state.update_metadata("websocket:c1", {"_sustained_goal_continuation_rounds": 12})out = await _execute(create,@@ -86,15 +93,9 @@ async def test_create_goal_records_goal_metadata(tmp_path):assert blob["status"] == "active"assert blob["objective"] == "Do the thing"assert blob["ui_summary"] == "thing"- sess = sm.get_or_create("websocket:c1")- assert "_sustained_goal_continuation_rounds" not in sess.metadata- assert "_sustained_goal_continuation_rounds" not in (- SessionManager(tmp_path).get_or_create("websocket:c1").metadata- )- assert not should_finalize_on_max_iterations(- pending_queue_available=True,- session_metadata=sess.metadata,- )+ assert SessionManager(tmp_path).get_or_create(sess.key).metadata[GOAL_STATE_KEY] == blob+ with GoalExecutionPolicy(sm.state).scope(sess.key, sess.generation, persistent=True) as scope:+ assert "Do the thing" in await scope.continuation_prompt()@pytest.mark.asyncio@@ -153,6 +154,7 @@ async def test_update_goal_complete_closes_active_goal(tmp_path):sm = SessionManager(tmp_path)create, update, ctx = _tools(sm)+ ctx = await _bound_context(sm, ctx)with request_context(ctx), goal_mutation_permission(True):await create.execute(objective="X")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_pathcreate, update, ctx = _tools(sm)await _execute(create, ctx, objective="Old")- await sm.state.update_metadata(- "websocket:c1",- {"_sustained_goal_continuation_rounds": 12},- )out = await _execute(update,_request_context(),@@ -193,14 +191,9 @@ async def test_update_goal_replace_keeps_goal_active_with_new_objective(tmp_pathassert blob["previous_objective"] == "Old"assert blob["ui_summary"] == "new"sess = sm.get_or_create("websocket:c1")- assert "_sustained_goal_continuation_rounds" not in sess.metadata- assert "_sustained_goal_continuation_rounds" not in (- SessionManager(tmp_path).get_or_create("websocket:c1").metadata- )- assert not should_finalize_on_max_iterations(- pending_queue_available=True,- session_metadata=sess.metadata,- )+ assert SessionManager(tmp_path).get_or_create(sess.key).metadata[GOAL_STATE_KEY] == blob+ with GoalExecutionPolicy(sm.state).scope(sess.key, sess.generation, persistent=True) as scope:+ assert "New" in await scope.continuation_prompt()@pytest.mark.asyncio@@ -209,7 +202,6 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypacreate, update, _context = _tools(sm)sess = sm.get_or_create("websocket:c1")sess.metadata["marker"] = {"keep": True}- sess.metadata["_sustained_goal_continuation_rounds"] = 12sm.save(sess)original_save = sm._store.replace_metadatacreate_context = _request_context()@@ -221,18 +213,11 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypawith pytest.raises(OSError, match="disk unavailable"):await _execute(create, create_context, objective="Old")- assert sess.metadata == {- "marker": {"keep": True},- "_sustained_goal_continuation_rounds": 12,- }+ assert sess.metadata == {"marker": {"keep": True}}assert GOAL_STATE_KEY not in SessionManager(tmp_path).get_or_create("websocket:c1").metadatamonkeypatch.setattr(sm._store, "replace_metadata", original_save)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")replace_context = _request_context()@@ -241,10 +226,10 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypaawait _execute(update, replace_context, action="replace", objective="New")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").metadataassert 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)assert "Goal replaced" in await _execute(@@ -254,7 +239,7 @@ async def test_goal_state_mutations_roll_back_on_save_failure(tmp_path, monkeypaobjective="New",)sess = sm.get_or_create("websocket:c1")- assert "_sustained_goal_continuation_rounds" not in sess.metadata+ assert sess.metadata["marker"] == {"keep": True}assert (SessionManager(tmp_path).get_or_create("websocket:c1").metadata[GOAL_STATE_KEY]["objective"]== "New"@@ -294,7 +279,7 @@ async def test_active_goal_create_failure_preserves_permission_for_replace(tmp_pcreate, update, initial_context = _tools(sm)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):create_out = await create.execute(objective="New")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 "/goal <task>" in str(unauthorized)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):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(),)+ 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_b = asyncio.create_task(_execute(create, ctx_b, objective="Goal 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_pathsess = sm.get_or_create("websocket:c1")sess.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Old"}sm.save(sess)- ctx = _request_context()+ ctx = await _bound_context(sm, _request_context())with request_context(ctx), goal_mutation_permission(True):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-async def test_goal_tools_registered_in_base_registry(tmp_path):+async def test_goal_tools_registered_by_builtin_assembly(tmp_path):bus = MessageBus()provider = MagicMock()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")update = loop.tools.get("update_goal")@@ -502,3 +490,41 @@ async def test_goal_tools_registered_in_base_registry(tmp_path):).lower()assert "authoriz" not in model_visible_contractassert "/goal" not in model_visible_contract++[email protected]("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()diff --git a/tests/bus/test_runtime_events.py b/tests/bus/test_runtime_events.pyindex 885492325..83bf283f0 100644--- a/tests/bus/test_runtime_events.py+++ b/tests/bus/test_runtime_events.py@@ -206,8 +206,7 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> Npublisher.record_turn_latency("cli:direct", 123)first_round = LLMUsage.reported(input_tokens=40, output_tokens=2)second_round = LLMUsage.reported(input_tokens=60, output_tokens=3)- publisher.record_turn_usage("cli:direct", [first_round])- publisher.record_turn_usage("cli:direct", [second_round])+ publisher.record_turn_usage("cli:direct", [first_round, second_round])await publisher.turn_completed(channel="cli",diff --git a/tests/cli/test_agent_interactive.py b/tests/cli/test_agent_interactive.pyindex 2aad340ea..c843057a4 100644--- a/tests/cli/test_agent_interactive.py+++ b/tests/cli/test_agent_interactive.py@@ -56,8 +56,9 @@ def test_interactive_agent_routes_a_complete_user_turn(channels_config = None@classmethod- def from_config(cls, _config, bus, **_kwargs):+ def from_config(cls, _config, bus, **kwargs):instance = cls(bus)+ seen["builtin_assembly"] = kwargs["builtin_assembly"]seen["loop"] = instancereturn 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.consume_restart_notice_from_env", lambda: None)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.providers.factory.make_provider", lambda *_args: object())monkeypatch.setattr(@@ -136,6 +139,7 @@ def test_interactive_agent_routes_a_complete_user_turn(assert inbound.metadata == {"_wants_stream": True}loop = seen["loop"]assert isinstance(loop, _AgentLoop)+ assert seen["builtin_assembly"] is install_goalassert loop.aclose_calls == 1assert len(renderers) == 1renderer = renderers[0]diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex 47455e602..1e73489bb 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -91,6 +91,11 @@ class _StopGatewayError(RuntimeError):pass+def _patch_fake_agent_loop(monkeypatch, target, fake):+ monkeypatch.setattr(target, fake)+ monkeypatch.setattr("nanobot.goal.assembly.install_goal", MagicMock())++class _GatewayAgentContractStub:"""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(),)+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:config_file = tmp_path / "instance" / "config.json"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: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)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: Pareturn Nonemonkeypatch.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)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 Nonemonkeypatch.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)result = runner.invoke(@@ -1868,7 +1913,7 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(return Nonemonkeypatch.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)@@ -2248,7 +2293,7 @@ def test_heartbeat_empty_response_is_not_evaluated(session_manager=_FakeSessionManager,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.cli.gateway_runtime.ensure_webui_session_archives", AsyncMock(return_value=[]))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,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("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")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.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")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.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"] = kwargsraise _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.triggers.local_runner.run_local_trigger_queue",@@ -4017,7 +4062,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(message_bus=MessageBus,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.cron.service.CronService", _FakeCronService)monkeypatch.setattr("asyncio.start_server", _fake_start_server)@@ -4235,7 +4280,7 @@ def test_gateway_failure_exits_nonzero_after_cleanup(message_bus=MessageBus,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.channels.manager.ChannelManager", _FakeChannelManager)monkeypatch.setattr("nanobot.cron.service.CronService", _FakeCronService)@@ -4404,7 +4449,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(message_bus=MessageBus,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.cron.service.CronService", _FakeCronService)monkeypatch.setattr("asyncio.start_server", _fake_start_server)diff --git a/tests/command/test_builtin_dream.py b/tests/command/test_builtin_dream.pyindex b11fabaa8..af049bb81 100644--- a/tests/command/test_builtin_dream.py+++ b/tests/command/test_builtin_dream.py@@ -7,9 +7,8 @@ import pytestfrom nanobot.agent.memory import MemoryStorefrom nanobot.bus.events import InboundMessage, OutboundMessage+from nanobot.command.application import build_help_text, builtin_command_palettefrom nanobot.command.builtin import (- build_help_text,- builtin_command_palette,cmd_dream,cmd_dream_log,cmd_dream_prompt,diff --git a/tests/command/test_builtin_evaluator_prompt.py b/tests/command/test_builtin_evaluator_prompt.pyindex 01ebd1768..cb3e77c8c 100644--- a/tests/command/test_builtin_evaluator_prompt.py+++ b/tests/command/test_builtin_evaluator_prompt.py@@ -5,11 +5,8 @@ from types import SimpleNamespaceimport pytestfrom nanobot.bus.events import InboundMessage-from nanobot.command.builtin import (- build_help_text,- builtin_command_palette,- cmd_evaluator_prompt,-)+from nanobot.command.application import build_help_text, builtin_command_palette+from nanobot.command.builtin import cmd_evaluator_promptfrom nanobot.command.router import CommandContextfrom nanobot.utils.evaluator import default_evaluator_promptdiff --git a/tests/command/test_goal_imports.py b/tests/command/test_goal_imports.pynew file mode 100644index 000000000..aa647b9ca--- /dev/null+++ b/tests/command/test_goal_imports.py@@ -0,0 +1,21 @@+import subprocess+import sys++import pytest++[email protected]("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)diff --git a/tests/command/test_model_command.py b/tests/command/test_model_command.pyindex 00314eb04..2bbdfaf4a 100644--- a/tests/command/test_model_command.py+++ b/tests/command/test_model_command.py@@ -1,5 +1,5 @@from types import SimpleNamespace-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -7,15 +7,15 @@ from nanobot.agent.goal_permission import goal_mutation_allowedfrom nanobot.agent.loop import AgentLoopfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.queue import MessageBus-from nanobot.command.builtin import (+from nanobot.command.application import (build_help_text,builtin_command_palette,- cmd_goal,- cmd_model,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, CommandRouterfrom nanobot.config.schema import ModelPresetConfig+from nanobot.goal.command import cmd_goal, register_goal_commandfrom nanobot.session.history_visibility import HIDDEN_HISTORY_METAfrom nanobot.session.model_selection import (SESSION_MODEL_PRESET_METADATA_KEY,@@ -241,7 +241,8 @@ def test_model_command_in_help_and_palette() -> None:@pytest.mark.asyncioasync def test_goal_command_shows_usage_without_args(tmp_path) -> None: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 Noneassert out.channel == "cli"assert out.chat_id == "direct"@@ -256,11 +257,18 @@ async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_setask = "检查 /tmp/project\n保留现有文件。"command = f"/goal {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- 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 ctx.msg.content == commandassert 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"] == commandassert out.metadata["goal_requested"] is Trueassert 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_seassert [(row["role"], row["content"]) for row in session.messages] == [("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()register_builtin_commands(router)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.session = await loop.sessions.state.get(ctx.key)out = await router.dispatch(ctx)- assert isinstance(out, InboundMessage)- assert out.content == "ship it"- assert out.metadata["goal_requested"] is True+ assert isinstance(out, CommandExpansion)+ assert out.message.content == "ship it"+ assert out.message.metadata["goal_requested"] is Trueassert goal_mutation_allowed() is False+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++[email protected]("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.asyncioasync def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None: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,)- out = await cmd_goal(ctx)+ out = await cmd_goal(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))assert isinstance(out, OutboundMessage)assert "only be started by a user" in out.content- assert ctx.turn_scopes == []def test_goal_command_in_help_and_palette() -> None:palette = builtin_command_palette()goal = next(item for item in palette if item["command"] == "/goal")- assert goal["arg_hint"] == "<goal>"- assert goal["lifecycle"] == "agent_turn_with_args"- assert goal["accepts_args"] is True+ assert goal == {+ "command": "/goal",+ "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()diff --git a/tests/command/test_router_dispatchable.py b/tests/command/test_router_dispatchable.pyindex 1433c9a4c..22219faa9 100644--- a/tests/command/test_router_dispatchable.py+++ b/tests/command/test_router_dispatchable.py@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMockimport pytest-from nanobot.command.builtin import (+from nanobot.command.application import (builtin_command_starts_agent_turn,register_builtin_commands,)@@ -141,6 +141,7 @@ class TestMidTurnCommandDispatchedDirectly:async def test_help_dispatched_with_session_none(self, router: CommandRouter, fake_loop: MagicMock, fake_msg: MagicMock,) -> None:+ fake_loop.commands = routerctx = CommandContext(msg=fake_msg, session=None,key="test:chat1", raw="/help", loop=fake_loop,@@ -151,6 +152,7 @@ class TestMidTurnCommandDispatchedDirectly:assert result.chat_id == "chat1"assert result.metadata["render_as"] == "text"assert "/new" in result.content+ assert "/goal <goal>" in result.contentassert "/pairing [list|approve <code>|deny <code>|revoke <user_id>]" in result.content@pytest.mark.asynciodiff --git a/tests/command/test_skill_command.py b/tests/command/test_skill_command.pyindex 0d99a6106..2e7a6ab0b 100644--- a/tests/command/test_skill_command.py+++ b/tests/command/test_skill_command.py@@ -7,7 +7,8 @@ from nanobot.agent.loop import AgentLoopfrom nanobot.agent.skills import SkillsLoaderfrom nanobot.bus.events import InboundMessagefrom 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_skillfrom nanobot.command.router import CommandContext, CommandRouterfrom nanobot.config.schema import ModelPresetConfigdiff --git a/tests/command/test_trigger_command.py b/tests/command/test_trigger_command.pyindex 4dd47fac3..6525f91bf 100644--- a/tests/command/test_trigger_command.py+++ b/tests/command/test_trigger_command.py@@ -6,7 +6,7 @@ from types import SimpleNamespaceimport pytestfrom 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_commandsfrom nanobot.command.router import CommandContext, CommandRouterfrom nanobot.session.keys import UNIFIED_SESSION_KEYfrom nanobot.triggers.local_store import LocalTriggerStorediff --git a/tests/session/test_goal_state.py b/tests/session/test_goal_state.pyindex 59b8f70f8..9eafc7079 100644--- a/tests/session/test_goal_state.py+++ b/tests/session/test_goal_state.py@@ -6,7 +6,6 @@ from nanobot.session.goal_state import (discard_legacy_goal_state_key,explicit_goal_requested,goal_state_runtime_lines,- goal_state_ws_blob,parse_goal_state,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():assert sustained_goal_active(None) is Falseassert sustained_goal_active({}) is Falsediff --git a/tests/session/test_turn_continuation.py b/tests/session/test_turn_continuation.pyindex f407fe7c8..a839ed69f 100644--- a/tests/session/test_turn_continuation.py+++ b/tests/session/test_turn_continuation.py@@ -1,163 +1,107 @@from __future__ import annotations-import asyncio-from types import SimpleNamespace-import pytestfrom nanobot.agent.tools.context import RequestContext-from nanobot.bus.events import InboundMessage-from nanobot.session.goal_state import (- GOAL_STATE_KEY,- explicit_goal_requested,- sustained_goal_turn,-)-from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY+from nanobot.goal.runtime import GoalExecutionPolicy+from nanobot.session.goal_state import GOAL_STATE_KEY+from nanobot.session.manager import SessionManagerfrom nanobot.session.turn_continuation import (- INTERNAL_CONTINUATION_KIND_META,INTERNAL_CONTINUATION_META,- INTERNAL_CONTINUATION_RUN_STARTED_AT_META,- _save_skip_for_turn,- internal_continuation_run_started_at,- maybe_continue_turn,- should_finalize_on_max_iterations,- should_stream_budget_response,- sustained_goal_continuation_inbound,+ iteration_limit_context,+ record_iteration_limit,+ save_skip_for_turn,+ should_persist_user_message,)-async def test_maybe_continue_turn_queues_internal_message():- meta = {- GOAL_STATE_KEY: {- "status": "active",- "objective": "Finish the migration.",- "ui_summary": "migration",- },- }- messages = [- {"role": "system", "content": "system"},- {"role": "user", "content": "start"},- {"role": "assistant", "content": "paused"},- ]- pending: asyncio.Queue[InboundMessage] = asyncio.Queue()- ctx = SimpleNamespace(- session=SimpleNamespace(metadata=meta),- msg=InboundMessage(- channel="feishu",- sender_id="u1",- chat_id="c1",- content="start",- 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:- assert sustained_goal_continuation_inbound({INTERNAL_CONTINUATION_META: True}) is False---async def test_internal_continuation_respects_round_limit():- meta = {- GOAL_STATE_KEY: {"status": "active", "objective": "x"},- "_sustained_goal_continuation_rounds": 12,- }- ctx = SimpleNamespace(- session=SimpleNamespace(metadata=meta),- msg=InboundMessage(channel="feishu", sender_id="u1", chat_id="c1", content="start"),- session_key="feishu:c1",- pending_queue=asyncio.Queue(),- stop_reason="max_iterations",- final_content="paused",- all_messages=[],- )-- assert should_stream_budget_response(- stop_reason="max_iterations",- pending_queue_available=True,- session_metadata=meta,- )- assert await maybe_continue_turn(ctx, session_metadata=ctx.session.metadata) is False---def test_internal_continuation_requires_budget_boundary_and_queue():- meta = {GOAL_STATE_KEY: {"status": "active", "objective": "x"}}-- assert should_stream_budget_response(- stop_reason="completed",- pending_queue_available=True,- session_metadata=meta,- )- 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={},- )[email protected]("status", ["completed", "cancelled", "blocked"])+async def test_goal_scope_reads_current_objective_and_closure(tmp_path, status):+ sessions = SessionManager(tmp_path)+ session = await sessions.state.get("feishu:c1")+ try:+ with GoalExecutionPolicy(sessions.state).scope(session.key, session.generation, persistent=True) as scope:+ assert await scope.continuation_prompt() is None+ await sessions.state.update_metadata(session.key, {+ GOAL_STATE_KEY: {"status": "active", "objective": "Finish the migration."},+ })+ assert "Finish the migration." in await scope.continuation_prompt()+ await sessions.state.update_metadata(session.key, {+ GOAL_STATE_KEY: {"status": "active", "objective": "A replacement."},+ })+ prompt = await scope.continuation_prompt()+ assert "A replacement." in prompt and "Finish the migration." not in prompt+ await sessions.state.update_metadata(session.key, {+ GOAL_STATE_KEY: {"status": status, "objective": "A replacement."},+ })+ assert await scope.continuation_prompt() is None+ finally:+ await sessions.state.aclose()++[email protected]("operation", ["reset", "delete"])+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()+++async def test_iteration_limit_guidance_is_for_the_next_user_request_not_recovery(tmp_path):+ sessions = SessionManager(tmp_path)+ session = await sessions.state.get("cli:test")+ request = RequestContext(channel="cli", chat_id="test", session_key=session.key)+ try:+ await sessions.state.mutate_metadata(+ session.key, lambda metadata: record_iteration_limit(metadata, "max_iterations"),+ )+ context = await iteration_limit_context(sessions.state, request)+ assert context is not None and "Follow the current request" in context.content+ recovery = RequestContext(+ channel="cli", chat_id="test", session_key=session.key,+ metadata={INTERNAL_CONTINUATION_META: True},+ )+ assert await iteration_limit_context(sessions.state, recovery) is None+ await sessions.state.mutate_metadata(+ session.key, lambda metadata: record_iteration_limit(metadata, "completed"),+ )+ assert await iteration_limit_context(sessions.state, request) is None+ finally:+ await sessions.state.aclose()+++def test_explicit_recovery_does_not_persist_a_synthetic_user_input():+ metadata = {INTERNAL_CONTINUATION_META: True}+ assert not should_persist_user_message(metadata)+ assert save_skip_for_turn(+ message_metadata=metadata, initial_message_count=3, input_persisted_early=False,+ ) == 3+ assert should_persist_user_message(None)def test_save_skip_unchanged_for_standalone_current_message():- assert _save_skip_for_turn(- message_metadata=None,- initial_message_count=3,- input_persisted_early=True,+ assert save_skip_for_turn(+ message_metadata=None, initial_message_count=3, input_persisted_early=True,) == 3- assert _save_skip_for_turn(- message_metadata=None,- initial_message_count=3,- input_persisted_early=False,+ assert save_skip_for_turn(+ message_metadata=None, initial_message_count=3, input_persisted_early=False,) == 2diff --git a/tests/test_nanobot_facade.py b/tests/test_nanobot_facade.pyindex 305274f17..b9e92b6fc 100644--- a/tests/test_nanobot_facade.py+++ b/tests/test_nanobot_facade.py@@ -506,6 +506,189 @@ async def test_ephemeral_run_does_not_invoke_persisted_turn_callback(tmp_path):assert seen == [][email protected]("existing_session", [False, True])[email protected]("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()+++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()+++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()++[email protected]("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():import nanobotdiff --git a/tests/test_openai_api.py b/tests/test_openai_api.pyindex 7a8d6c8f2..403afba91 100644--- a/tests/test_openai_api.py+++ b/tests/test_openai_api.py@@ -619,17 +619,20 @@ async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:@pytest.mark.asyncioasync def test_process_direct_accepts_media() -> None:from nanobot.agent.loop import AgentLoop+ from nanobot.agent.turn_delivery import TurnDeliveryFactoryfrom nanobot.bus.queue import MessageBus- from nanobot.bus.runtime_events import RuntimeEventPublisherloop = AgentLoop.__new__(AgentLoop)loop._session_locks = {}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_publishercaptured_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_msgcaptured_msg = msgreturn Nonediff --git a/tests/tools/test_private_tool_logging.py b/tests/tools/test_private_tool_logging.pyindex 35e75e695..b86c845bc 100644--- a/tests/tools/test_private_tool_logging.py+++ b/tests/tools/test_private_tool_logging.py@@ -86,7 +86,7 @@ async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kindif kind == "injection":spec.injection_callback = AsyncMock(side_effect=ValueError(_SECRET))elif kind == "continuation":- spec.continuation_callback = MagicMock(side_effect=ValueError(_SECRET))+ spec.continuation_callback = AsyncMock(side_effect=ValueError(_SECRET))elif kind == "finalization":spec.max_iterations = 0provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(_SECRET))@@ -101,11 +101,14 @@ async def test_runner_recovery_diagnostics_obey_private_policy(log_content, kindspec.hook = BrokenFinallyHook()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):await AgentRunner().run(spec)else:await AgentRunner().run(spec)+ if kind == "continuation":+ assert all(_SECRET not in r["message"] for r in diagnostic_records)+ returnerrors = [r for r in diagnostic_records if r["level"].name == "ERROR"]assert errorsassert all((r["exception"] is not None) is log_content for r in errors)diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.pyindex 395b630b5..2a5c46148 100644--- a/tests/webui/test_gateway_webui_smoke.py+++ b/tests/webui/test_gateway_webui_smoke.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport json+import osimport signalimport socketimport subprocess@@ -14,6 +15,7 @@ from urllib.parse import quoteimport httpximport pytestimport websockets+from aiohttp import webfrom nanobot.agent.subagent_sessions import SubagentSessionsfrom 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())finally:_stop_gateway(second)++[email protected]("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()diff --git a/tests/webui/test_goal_state.py b/tests/webui/test_goal_state.pynew file mode 100644index 000000000..05179d0f1--- /dev/null+++ b/tests/webui/test_goal_state.py@@ -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,+ }++[email protected]("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()diff --git a/tests/webui/test_session_projection.py b/tests/webui/test_session_projection.pyindex d74d76227..78b60e597 100644--- a/tests/webui/test_session_projection.py+++ b/tests/webui/test_session_projection.py@@ -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,) -> None:sessions = MagicMock()@@ -115,7 +115,7 @@ async def test_hydration_events_are_quiet_without_actionable_state(assert await WebUISessionProjection(sessions).hydration_events("websocket: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(@@ -157,4 +157,5 @@ async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loopfinally:release.set()events = await task- assert events[0]["status"] == "running"+ assert events[0]["goal_state"] == {"active": False}+ assert events[1]["status"] == "running"