fix(tui): accept goal requests during active turns (#5981)

* fix(tui): accept goal requests during active turns

* fix(goal): reuse live input routing and remove busy guards

* test(goal): cover followup streams across iteration budgets

* refactor(goal): expand slash commands into hidden agent input

* fix(goal): keep generated input permission scoped to users

* refactor(agent): encapsulate goal input permission scope

* refactor(goal): preserve task text without prompt wrapper

* test(goal): consolidate coverage and exercise restart recovery

* test(goal): wait for recovery reply without task registry race
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-30 13:08:13 +08:00
1 parent b46d4dfd7d
commit 99ba062a97
15 files changed
+613 -360

No files matched your search

+39 -1
View File
@@ -2,9 +2,14 @@
from __future__ import annotations
from contextlib import contextmanager
from collections.abc import Iterable
from contextlib import ExitStack, contextmanager
from contextvars import ContextVar
from nanobot.bus.events import InboundMessage
from nanobot.session.automation_turns import automation_history_overrides
from nanobot.session.turn_continuation import internal_continuation_inbound
_GOAL_MUTATION_ALLOWED: ContextVar[bool] = ContextVar(
"nanobot_goal_mutation_allowed",
default=False,
@@ -27,3 +32,36 @@ def goal_mutation_permission(allowed: bool):
yield
finally:
_GOAL_MUTATION_ALLOWED.reset(token)
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:
super().__enter__()
self.enter_context(goal_mutation_permission(False))
if self._initial_message is not None:
self.consume_inputs((self._initial_message,))
return self
def consume_inputs(self, messages: Iterable[InboundMessage]) -> None:
"""Authorize consumed user requests, never queued or replayed history."""
if any(self._authorizes(message) for message in messages):
self.enter_context(goal_mutation_permission(True))
@staticmethod
def _authorizes(message: InboundMessage) -> bool:
if (
not message.is_user_input
or message.channel == "system"
or message.sender_id == "subagent"
or internal_continuation_inbound(message.metadata)
or message.metadata.get("goal_requested") is not True
):
return False
_, automation_metadata = automation_history_overrides(message.metadata)
return not automation_metadata
+28 -9
View File
@@ -25,6 +25,7 @@ from nanobot.agent import model_presets as preset_helpers
from nanobot.agent.autocompact import AutoCompact
from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput
from nanobot.agent.cron_turns import CronTurnCoordinator
from nanobot.agent.goal_permission import GoalInputScope
from nanobot.agent.hook import AgentHook, AgentTurnHookFactory
from nanobot.agent.memory import Consolidator
from nanobot.agent.model_runtime import ModelRuntimeResolver
@@ -50,7 +51,7 @@ from nanobot.bus.outbound_events import (
)
from nanobot.bus.queue import MessageBus
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
from nanobot.command.router import normalize_command_text
from nanobot.command.router import command_text, normalize_command_text
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
from nanobot.llm_usage.context import source_from_request
@@ -682,6 +683,8 @@ class AgentLoop:
if has_text or media_paths or runtime_context_blocks:
extra: dict[str, Any] = ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
extra.update(kwargs)
if HIDDEN_HISTORY_META in msg.metadata:
extra[HIDDEN_HISTORY_META] = msg.metadata[HIDDEN_HISTORY_META]
text = content_value if isinstance(content_value, str) else ""
text_override, automation_extra = automation_history_overrides(msg.metadata)
if text_override is not None:
@@ -768,7 +771,7 @@ class AgentLoop:
msg: InboundMessage,
key: str,
raw: str,
dispatch_fn: Callable[[CommandContext], Awaitable[OutboundMessage | None]],
dispatch_fn: Callable[[CommandContext], Awaitable[InboundMessage | OutboundMessage | None]],
) -> None:
"""Dispatch a command directly from the run() loop and publish the result."""
if normalize_command_text(raw).lower() == "/compact":
@@ -777,9 +780,19 @@ class AgentLoop:
return
async def dispatch_and_publish() -> None:
ctx = CommandContext(msg=msg, session=None, key=key, raw=raw, loop=self)
_, automation_metadata = automation_history_overrides(msg.metadata)
ctx = CommandContext(
msg=msg, session=None, key=key, raw=raw, loop=self,
is_user_turn=(
msg.is_user_input and msg.channel != "system"
and msg.sender_id != "subagent" and not automation_metadata
and not turn_continuation.internal_continuation_inbound(msg.metadata)
),
)
result = await dispatch_fn(ctx)
if result:
if isinstance(result, InboundMessage):
self._enqueue_session_message(result)
elif result:
await self.bus.publish_outbound(result)
else:
logger.warning("Command '{}' matched but dispatch returned None", raw)
@@ -921,7 +934,7 @@ class AgentLoop:
):
return False
return msg.channel == "system" or not self.commands.is_dispatchable_command(
msg.content.strip()
command_text(msg)
)
def _idle_events(
@@ -1038,6 +1051,8 @@ class AgentLoop:
image_paths=image_paths,
)
row: dict[str, Any] = {"role": "user", "content": user_content}
if HIDDEN_HISTORY_META in pending_msg.metadata:
row[HIDDEN_HISTORY_META] = pending_msg.metadata[HIDDEN_HISTORY_META]
metadata_value = cast(object, pending_msg.metadata)
metadata = (
pending_msg.metadata
@@ -1101,6 +1116,7 @@ class AgentLoop:
if not self._can_inject_message(pending_msg):
break
converted.append(await _to_user_message(pending_msg))
goal_inputs.consume_inputs(pending_messages[:len(converted)])
consumed = len(converted)
return converted
finally:
@@ -1196,6 +1212,7 @@ class AgentLoop:
session_metadata = session.metadata if session is not None else None
try:
goal_inputs = turn_scope_stack.enter_context(GoalInputScope())
for scope in turn_scopes or ():
turn_scope_stack.enter_context(scope)
hook = build_agent_turn_hook(AgentTurnHookSpec(
@@ -1332,7 +1349,7 @@ class AgentLoop:
logger.warning("Error consuming inbound message: {}, continuing...", e)
continue
raw = msg.content.strip()
raw = command_text(msg)
effective_key = self._effective_session_key(msg)
if await agent_context.handle_runtime_control(self, msg, self.tools):
continue
@@ -1370,8 +1387,6 @@ class AgentLoop:
# is processing this session), route the message there for mid-turn
# injection instead of creating a competing task.
if effective_key in self._pending_queues:
# Non-priority commands must not be queued for injection;
# dispatch them directly (same pattern as priority commands).
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
@@ -1976,7 +1991,7 @@ class AgentLoop:
if ctx.kind is TurnKind.SYSTEM or ctx.msg.channel == "system":
return False
session = ctx.require_session()
raw = ctx.msg.content.strip()
raw = command_text(ctx.msg)
_, automation_metadata = automation_history_overrides(ctx.msg.metadata)
is_user_turn = (
ctx.original_user_text is not None
@@ -1995,6 +2010,10 @@ class AgentLoop:
turn_scopes=ctx.turn_scopes,
)
result = await self.commands.dispatch(cmd_ctx)
if isinstance(result, InboundMessage):
ctx.msg = result
result = None
ctx.turn_scopes.append(GoalInputScope(ctx.msg))
if cmd_ctx.raw.lower() == "/compact":
# Compaction reports through events, not an archiveable command reply.
return True
+2 -21
View File
@@ -684,10 +684,7 @@ 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
or spec.finalize_on_max_iterations
)
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,
@@ -794,22 +791,8 @@ class AgentRunner:
else:
stop_reason = "max_iterations"
terminal_content = None
await end_length_segment(interrupted=False)
if spec.finalize_on_max_iterations:
# The no-tools finalization is a real model boundary, so include
# exactly the inputs waiting before that request. Without this
# request, leave them in the session inbox for its worker.
drained_after_max_iterations, injection_cycles = (
await self._try_drain_injections(
spec,
messages,
None,
injection_cycles,
phase="before max-iterations finalization",
)
)
if drained_after_max_iterations:
had_injections = True
await end_length_segment(interrupted=drained_after_max_iterations)
terminal_content, usage = await self._try_finalize_after_max_iterations(
spec,
hook,
@@ -818,8 +801,6 @@ class AgentRunner:
request_state=request_state,
round_usages=round_usages,
)
else:
await end_length_segment(interrupted=False)
if terminal_content is None:
terminal_content = self._max_iterations_fallback(spec)
if length_recovery_parts:
+19 -25
View File
@@ -14,9 +14,10 @@ from typing import TYPE_CHECKING, Any, Literal, cast
from loguru import logger
from nanobot import __version__
from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
from nanobot.providers.base import LLMUsage
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.utils.helpers import build_status_content
from nanobot.utils.restart import set_restart_notice_to_env
from nanobot.utils.workspace_prompts import initialize_workspace_prompt
@@ -901,10 +902,8 @@ async def cmd_history(ctx: CommandContext) -> OutboundMessage:
)
async def cmd_goal(ctx: CommandContext) -> OutboundMessage | None:
"""Mark this turn as an explicit sustained-goal request."""
from nanobot.agent.goal_permission import goal_mutation_permission
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(
@@ -913,16 +912,6 @@ async def cmd_goal(ctx: CommandContext) -> OutboundMessage | None:
content="Usage: /goal <long-running task description>",
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
if ctx.session is None:
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content=(
"A task is already running for this chat. "
"Use `/stop` first, then send `/goal <long-running task description>` again."
),
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
if not ctx.is_user_turn:
return OutboundMessage(
channel=ctx.msg.channel,
@@ -931,16 +920,21 @@ async def cmd_goal(ctx: CommandContext) -> OutboundMessage | None:
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
ctx.turn_scopes.append(goal_mutation_permission(True))
ctx.msg.metadata = {
**dict(ctx.msg.metadata or {}),
"original_command": "/goal",
"original_content": ctx.raw,
"goal_requested": True,
"goal_started_at": time.time(),
}
ctx.msg.content = ctx.raw
return None
session = ctx.session or ctx.loop.sessions.get_or_create(ctx.key)
session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))
ctx.loop.sessions.save(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:
+11 -5
View File
@@ -8,18 +8,22 @@ from dataclasses import dataclass, field
from difflib import get_close_matches
from typing import TYPE_CHECKING, Any, Awaitable, Callable
from nanobot.bus.events import OutboundMessage
from nanobot.bus.events import InboundMessage, OutboundMessage
if TYPE_CHECKING:
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.session.manager import Session
from nanobot.utils.llm_runtime import LLMRuntime
Handler = Callable[["CommandContext"], Awaitable["OutboundMessage | None"]]
Handler = Callable[["CommandContext"], Awaitable["InboundMessage | OutboundMessage | None"]]
_BOT_SUFFIX_RE = re.compile(r"^[A-Za-z0-9_]+$")
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()
def normalize_command_text(text: str) -> str:
"""Normalize slash-command transport variants before routing.
@@ -99,7 +103,7 @@ class CommandRouter:
return True
return cmd.startswith("/")
async def dispatch_priority(self, ctx: CommandContext) -> OutboundMessage | None:
async def dispatch_priority(self, ctx: CommandContext) -> 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())
@@ -107,8 +111,10 @@ class CommandRouter:
return await handler(ctx)
return None
async def dispatch(self, ctx: CommandContext) -> OutboundMessage | None:
async def dispatch(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
"""Try exact and prefix handlers, then reject invalid slash commands."""
if ctx.msg.metadata.get("original_command"):
return None
ctx.raw = normalize_command_text(ctx.raw)
cmd = ctx.raw.lower()