refactor(goal): sustain one ReAct run until the goal closes (#6538)
* refactor(goal): sustain one ReAct run until the goal closes Keep active goals in the same runner beyond the ordinary iteration limit, with a final answer after successful closure. Remove cross-turn goal handoffs, continuation allowances and rollback bookkeeping while preserving input authorization, recovery, cancellation and terminal lifecycle ownership. Contributes to NAN-392 Co-authored-by: chengyongru <chengyongru.ai@gmail.com> * test(goal): consolidate sustained-run regression coverage Retain lifecycle, history, usage, provider-state privacy and checkpoint cancellation assertions in the existing long-run scenarios. Remove duplicate smoke cases and parameter combinations that do not exercise distinct behavior; keep real Gateway, authorization and generation regressions.
This commit is contained in:
1 parent
3545539128
commit
62c2ed4e7e
68 files changed
+2683
-1421
No files matched your search
@@ -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"]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The standard application's composed command registrations and display catalog."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from nanobot.command.builtin import build_help_text as build_registered_help_text
|
||||
from nanobot.command.builtin import register_core_commands
|
||||
from nanobot.command.router import CommandRouter, normalize_command_text
|
||||
from nanobot.command.spec import BuiltinCommandSpec
|
||||
from nanobot.goal.command import register_goal_command
|
||||
|
||||
|
||||
def register_builtin_commands(router: CommandRouter) -> None:
|
||||
"""Register the standard application commands."""
|
||||
register_core_commands(router)
|
||||
register_goal_command(router)
|
||||
|
||||
|
||||
def _builtin_specs() -> tuple[BuiltinCommandSpec, ...]:
|
||||
router = CommandRouter()
|
||||
register_builtin_commands(router)
|
||||
return router.specs
|
||||
|
||||
|
||||
BUILTIN_COMMAND_SPECS = _builtin_specs()
|
||||
|
||||
|
||||
def build_help_text() -> str:
|
||||
return build_registered_help_text(BUILTIN_COMMAND_SPECS)
|
||||
|
||||
|
||||
def builtin_command_palette() -> list[dict[str, str | bool]]:
|
||||
"""Return structured command metadata for UI command palettes."""
|
||||
return [spec.as_dict() for spec in BUILTIN_COMMAND_SPECS]
|
||||
|
||||
|
||||
def builtin_command_starts_agent_turn(text: str) -> bool:
|
||||
"""Return whether WebUI ingress should expect a normal agent lifecycle."""
|
||||
normalized = normalize_command_text(text)
|
||||
command, separator, args = normalized.partition(" ")
|
||||
spec = next(
|
||||
(item for item in BUILTIN_COMMAND_SPECS if item.command == command.lower()),
|
||||
None,
|
||||
)
|
||||
if spec is None or (separator and not spec.accepts_args):
|
||||
return True
|
||||
if spec.lifecycle == "agent_turn":
|
||||
return True
|
||||
return spec.lifecycle == "agent_turn_with_args" and bool(args.strip())
|
||||
+15
-115
@@ -4,18 +4,18 @@ import asyncio
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import TYPE_CHECKING, Any, Literal, cast
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
|
||||
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
|
||||
from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage
|
||||
from nanobot.command.router import CommandContext, CommandRouter
|
||||
from nanobot.command.spec import BuiltinCommandSpec
|
||||
from nanobot.command.spec import CommandLifecycle as CommandLifecycle
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
from nanobot.utils.helpers import build_status_content
|
||||
from nanobot.utils.restart import set_restart_notice_to_env
|
||||
@@ -26,46 +26,10 @@ if TYPE_CHECKING:
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.utils.gitstore import CommitInfo
|
||||
|
||||
# WebUI protocol contract for how a slash command participates in turn state:
|
||||
# - side_channel: returns control text without starting or ending an agent turn.
|
||||
# - finalize_active_turn: side-channel command that also closes the active UI turn.
|
||||
# - stop_active_turn: cancels the active turn; WebUI may intercept exact submits.
|
||||
# - agent_turn: always enters the normal agent path.
|
||||
# - agent_turn_with_args: no args is side-channel usage; args enter the agent path.
|
||||
CommandLifecycle = Literal[
|
||||
"side_channel",
|
||||
"finalize_active_turn",
|
||||
"stop_active_turn",
|
||||
"agent_turn",
|
||||
"agent_turn_with_args",
|
||||
]
|
||||
|
||||
USER_SHELL_COMMAND = "/__shell"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BuiltinCommandSpec:
|
||||
command: str
|
||||
title: str
|
||||
description: str
|
||||
icon: str
|
||||
arg_hint: str = ""
|
||||
lifecycle: CommandLifecycle = "side_channel"
|
||||
accepts_args: bool = False
|
||||
|
||||
def as_dict(self) -> dict[str, str | bool]:
|
||||
return {
|
||||
"command": self.command,
|
||||
"title": self.title,
|
||||
"description": self.description,
|
||||
"icon": self.icon,
|
||||
"arg_hint": self.arg_hint,
|
||||
"lifecycle": self.lifecycle,
|
||||
"accepts_args": self.accepts_args,
|
||||
}
|
||||
|
||||
|
||||
BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
|
||||
CORE_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
|
||||
BuiltinCommandSpec(
|
||||
"/new",
|
||||
"New chat",
|
||||
@@ -114,15 +78,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
|
||||
"[n]",
|
||||
accepts_args=True,
|
||||
),
|
||||
BuiltinCommandSpec(
|
||||
"/goal",
|
||||
"Start long-running goal",
|
||||
"Tell the agent to treat the request as a long-running goal.",
|
||||
"activity",
|
||||
"<goal>",
|
||||
lifecycle="agent_turn_with_args",
|
||||
accepts_args=True,
|
||||
),
|
||||
BuiltinCommandSpec(
|
||||
"/trigger",
|
||||
"Create named local trigger",
|
||||
@@ -190,26 +145,6 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
|
||||
)
|
||||
|
||||
|
||||
def builtin_command_palette() -> list[dict[str, str | bool]]:
|
||||
"""Return structured command metadata for UI command palettes."""
|
||||
return [spec.as_dict() for spec in BUILTIN_COMMAND_SPECS]
|
||||
|
||||
|
||||
def builtin_command_starts_agent_turn(text: str) -> bool:
|
||||
"""Return whether WebUI ingress should expect a normal agent lifecycle."""
|
||||
normalized = normalize_command_text(text)
|
||||
command, separator, args = normalized.partition(" ")
|
||||
spec = next(
|
||||
(item for item in BUILTIN_COMMAND_SPECS if item.command == command.lower()),
|
||||
None,
|
||||
)
|
||||
if spec is None or (separator and not spec.accepts_args):
|
||||
return True
|
||||
if spec.lifecycle == "agent_turn":
|
||||
return True
|
||||
return spec.lifecycle == "agent_turn_with_args" and bool(args.strip())
|
||||
|
||||
|
||||
async def cmd_stop(ctx: CommandContext) -> OutboundMessage:
|
||||
"""Cancel all active tasks and subagents for the session."""
|
||||
loop = ctx.loop
|
||||
@@ -894,41 +829,6 @@ async def cmd_history(ctx: CommandContext) -> OutboundMessage:
|
||||
)
|
||||
|
||||
|
||||
async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:
|
||||
"""Expand an explicit goal command into model-only input."""
|
||||
goal = ctx.args.strip()
|
||||
if not goal:
|
||||
return OutboundMessage(
|
||||
channel=ctx.msg.channel,
|
||||
chat_id=ctx.msg.chat_id,
|
||||
content="Usage: /goal <long-running task description>",
|
||||
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
||||
)
|
||||
if not ctx.is_user_turn:
|
||||
return OutboundMessage(
|
||||
channel=ctx.msg.channel,
|
||||
chat_id=ctx.msg.chat_id,
|
||||
content="Goal mode can only be started by a user `/goal <task>` command.",
|
||||
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
||||
)
|
||||
|
||||
session = ctx.session or await ctx.loop.sessions.state.get(ctx.key)
|
||||
session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))
|
||||
await ctx.loop.sessions.state.prepare_input(session)
|
||||
return replace(
|
||||
ctx.msg,
|
||||
content=goal,
|
||||
metadata={
|
||||
**ctx.msg.metadata,
|
||||
"original_command": "/goal",
|
||||
"original_content": ctx.msg.content,
|
||||
"goal_requested": True,
|
||||
"goal_started_at": time.time(),
|
||||
HIDDEN_HISTORY_META: {"kind": "goal_request"},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
|
||||
"""List, approve, deny or revoke pairing requests."""
|
||||
from nanobot.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_command
|
||||
@@ -1019,7 +919,7 @@ async def cmd_help(ctx: CommandContext) -> OutboundMessage:
|
||||
return OutboundMessage(
|
||||
channel=ctx.msg.channel,
|
||||
chat_id=ctx.msg.chat_id,
|
||||
content=build_help_text(),
|
||||
content=build_help_text(ctx.loop.commands.specs),
|
||||
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
||||
)
|
||||
|
||||
@@ -1048,10 +948,10 @@ async def cmd_user_shell(ctx: CommandContext) -> OutboundMessage:
|
||||
return await ctx.loop.execute_user_shell_command(ctx)
|
||||
|
||||
|
||||
def build_help_text() -> str:
|
||||
"""Build canonical help text shared across channels."""
|
||||
def build_help_text(specs: tuple[BuiltinCommandSpec, ...] = CORE_COMMAND_SPECS) -> str:
|
||||
"""Build help text for the commands registered in one application."""
|
||||
lines = ["🐈 nanobot commands:"]
|
||||
for spec in BUILTIN_COMMAND_SPECS:
|
||||
for spec in specs:
|
||||
command = spec.command
|
||||
if spec.arg_hint:
|
||||
command = f"{command} {spec.arg_hint}"
|
||||
@@ -1059,8 +959,10 @@ def build_help_text() -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def register_builtin_commands(router: CommandRouter) -> None:
|
||||
"""Register the default set of slash commands."""
|
||||
def register_core_commands(router: CommandRouter) -> None:
|
||||
"""Register slash commands owned by the core runtime."""
|
||||
for spec in CORE_COMMAND_SPECS:
|
||||
router.add_spec(spec)
|
||||
router.priority("/stop", cmd_stop)
|
||||
router.priority("/restart", cmd_restart)
|
||||
router.priority("/status", cmd_status)
|
||||
@@ -1071,8 +973,6 @@ def register_builtin_commands(router: CommandRouter) -> None:
|
||||
router.prefix("/model ", cmd_model)
|
||||
router.exact("/history", cmd_history)
|
||||
router.prefix("/history ", cmd_history)
|
||||
router.exact("/goal", cmd_goal)
|
||||
router.prefix("/goal ", cmd_goal)
|
||||
router.exact("/trigger", cmd_trigger)
|
||||
router.prefix("/trigger ", cmd_trigger)
|
||||
router.exact("/dream", cmd_dream)
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from contextlib import AbstractContextManager
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, Awaitable, Callable
|
||||
from typing import TYPE_CHECKING, Awaitable, Callable
|
||||
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.command.spec import BuiltinCommandSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
Handler = Callable[["CommandContext"], Awaitable["InboundMessage | OutboundMessage | None"]]
|
||||
Handler = Callable[["CommandContext"], Awaitable["CommandExpansion | InboundMessage | OutboundMessage | None"]]
|
||||
InputHandler = Callable[["CommandInput"], Awaitable["CommandExpansion | OutboundMessage"]]
|
||||
_BOT_SUFFIX_RE = re.compile(r"^[A-Za-z0-9_]+$")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CommandInput:
|
||||
"""Inputs available to a command that only transforms a user request."""
|
||||
|
||||
msg: InboundMessage
|
||||
args: str
|
||||
is_user_turn: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CommandExpansion:
|
||||
"""A transformed input whose original command is persisted by the runtime."""
|
||||
|
||||
message: InboundMessage
|
||||
temporary_session_error: str | None = None
|
||||
|
||||
|
||||
def command_text(message: InboundMessage) -> str:
|
||||
"""Return routable text; command-generated agent input must not be dispatched again."""
|
||||
return "" if message.metadata.get("original_command") else message.content.strip()
|
||||
@@ -52,7 +70,6 @@ class CommandContext:
|
||||
loop: AgentLoop = field(kw_only=True)
|
||||
runtime: LLMRuntime | None = None
|
||||
is_user_turn: bool = False
|
||||
turn_scopes: list[AbstractContextManager[Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
class CommandRouter:
|
||||
@@ -70,6 +87,24 @@ class CommandRouter:
|
||||
self._exact: dict[str, Handler] = {}
|
||||
self._prefix: list[tuple[str, Handler]] = []
|
||||
self._session_commands: set[str] = set()
|
||||
self._specs: list[BuiltinCommandSpec] = []
|
||||
|
||||
@property
|
||||
def specs(self) -> tuple[BuiltinCommandSpec, ...]:
|
||||
return tuple(self._specs)
|
||||
|
||||
def add_spec(self, spec: BuiltinCommandSpec, *, after: str | None = None) -> None:
|
||||
self._specs = [item for item in self._specs if item.command != spec.command]
|
||||
index = next((i + 1 for i, item in enumerate(self._specs) if item.command == after), len(self._specs))
|
||||
self._specs.insert(index, spec)
|
||||
|
||||
def input_command(self, cmd: str, handler: InputHandler) -> None:
|
||||
"""Register a command that receives only input facts and returns an expansion."""
|
||||
async def invoke(ctx: CommandContext) -> CommandExpansion | OutboundMessage:
|
||||
return await handler(CommandInput(ctx.msg, ctx.args, ctx.is_user_turn))
|
||||
|
||||
self.exact(cmd, invoke)
|
||||
self.prefix(f"{cmd} ", invoke)
|
||||
|
||||
def priority(self, cmd: str, handler: Handler) -> None:
|
||||
self._priority[cmd] = handler
|
||||
@@ -119,7 +154,9 @@ class CommandRouter:
|
||||
return True
|
||||
return self.command_name(text) is not None
|
||||
|
||||
async def dispatch_priority(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
|
||||
async def dispatch_priority(
|
||||
self, ctx: CommandContext,
|
||||
) -> CommandExpansion | InboundMessage | OutboundMessage | None:
|
||||
"""Dispatch a priority command. Called from run() without the lock."""
|
||||
ctx.raw = normalize_command_text(ctx.raw)
|
||||
handler = self._priority.get(ctx.raw.lower())
|
||||
@@ -127,7 +164,9 @@ class CommandRouter:
|
||||
return await handler(ctx)
|
||||
return None
|
||||
|
||||
async def dispatch(self, ctx: CommandContext) -> InboundMessage | OutboundMessage | None:
|
||||
async def dispatch(
|
||||
self, ctx: CommandContext,
|
||||
) -> CommandExpansion | InboundMessage | OutboundMessage | None:
|
||||
"""Try exact and prefix handlers, then validate registered commands."""
|
||||
if ctx.msg.metadata.get("original_command"):
|
||||
return None
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
Reference in new issue
Block a user