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:
1 parent
b46d4dfd7d
commit
99ba062a97
15 files changed
+613
-360
No files matched your search
@@ -2,9 +2,14 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from contextlib import contextmanager
|
from collections.abc import Iterable
|
||||||
|
from contextlib import ExitStack, contextmanager
|
||||||
from contextvars import ContextVar
|
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(
|
_GOAL_MUTATION_ALLOWED: ContextVar[bool] = ContextVar(
|
||||||
"nanobot_goal_mutation_allowed",
|
"nanobot_goal_mutation_allowed",
|
||||||
default=False,
|
default=False,
|
||||||
@@ -27,3 +32,36 @@ def goal_mutation_permission(allowed: bool):
|
|||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
_GOAL_MUTATION_ALLOWED.reset(token)
|
_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
@@ -25,6 +25,7 @@ from nanobot.agent import model_presets as preset_helpers
|
|||||||
from nanobot.agent.autocompact import AutoCompact
|
from nanobot.agent.autocompact import AutoCompact
|
||||||
from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput
|
from nanobot.agent.context import ContextBuilder, PersistedPromptContextResolver, TranscriptInput
|
||||||
from nanobot.agent.cron_turns import CronTurnCoordinator
|
from nanobot.agent.cron_turns import CronTurnCoordinator
|
||||||
|
from nanobot.agent.goal_permission import GoalInputScope
|
||||||
from nanobot.agent.hook import AgentHook, AgentTurnHookFactory
|
from nanobot.agent.hook import AgentHook, AgentTurnHookFactory
|
||||||
from nanobot.agent.memory import Consolidator
|
from nanobot.agent.memory import Consolidator
|
||||||
from nanobot.agent.model_runtime import ModelRuntimeResolver
|
from nanobot.agent.model_runtime import ModelRuntimeResolver
|
||||||
@@ -50,7 +51,7 @@ from nanobot.bus.outbound_events import (
|
|||||||
)
|
)
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
|
from nanobot.command import CommandContext, CommandRouter, 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.config.schema import AgentDefaults, ModelPresetConfig
|
||||||
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
|
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
|
||||||
from nanobot.llm_usage.context import source_from_request
|
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:
|
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: dict[str, Any] = ({"media": list(media_paths)} if media_paths else {}) | agent_context.session_extra(msg.metadata)
|
||||||
extra.update(kwargs)
|
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 = content_value if isinstance(content_value, str) else ""
|
||||||
text_override, automation_extra = automation_history_overrides(msg.metadata)
|
text_override, automation_extra = automation_history_overrides(msg.metadata)
|
||||||
if text_override is not None:
|
if text_override is not None:
|
||||||
@@ -768,7 +771,7 @@ class AgentLoop:
|
|||||||
msg: InboundMessage,
|
msg: InboundMessage,
|
||||||
key: str,
|
key: str,
|
||||||
raw: str,
|
raw: str,
|
||||||
dispatch_fn: Callable[[CommandContext], Awaitable[OutboundMessage | None]],
|
dispatch_fn: Callable[[CommandContext], Awaitable[InboundMessage | OutboundMessage | None]],
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Dispatch a command directly from the run() loop and publish the result."""
|
"""Dispatch a command directly from the run() loop and publish the result."""
|
||||||
if normalize_command_text(raw).lower() == "/compact":
|
if normalize_command_text(raw).lower() == "/compact":
|
||||||
@@ -777,9 +780,19 @@ class AgentLoop:
|
|||||||
return
|
return
|
||||||
|
|
||||||
async def dispatch_and_publish() -> None:
|
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)
|
result = await dispatch_fn(ctx)
|
||||||
if result:
|
if isinstance(result, InboundMessage):
|
||||||
|
self._enqueue_session_message(result)
|
||||||
|
elif result:
|
||||||
await self.bus.publish_outbound(result)
|
await self.bus.publish_outbound(result)
|
||||||
else:
|
else:
|
||||||
logger.warning("Command '{}' matched but dispatch returned None", raw)
|
logger.warning("Command '{}' matched but dispatch returned None", raw)
|
||||||
@@ -921,7 +934,7 @@ class AgentLoop:
|
|||||||
):
|
):
|
||||||
return False
|
return False
|
||||||
return msg.channel == "system" or not self.commands.is_dispatchable_command(
|
return msg.channel == "system" or not self.commands.is_dispatchable_command(
|
||||||
msg.content.strip()
|
command_text(msg)
|
||||||
)
|
)
|
||||||
|
|
||||||
def _idle_events(
|
def _idle_events(
|
||||||
@@ -1038,6 +1051,8 @@ class AgentLoop:
|
|||||||
image_paths=image_paths,
|
image_paths=image_paths,
|
||||||
)
|
)
|
||||||
row: dict[str, Any] = {"role": "user", "content": user_content}
|
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_value = cast(object, pending_msg.metadata)
|
||||||
metadata = (
|
metadata = (
|
||||||
pending_msg.metadata
|
pending_msg.metadata
|
||||||
@@ -1101,6 +1116,7 @@ class AgentLoop:
|
|||||||
if not self._can_inject_message(pending_msg):
|
if not self._can_inject_message(pending_msg):
|
||||||
break
|
break
|
||||||
converted.append(await _to_user_message(pending_msg))
|
converted.append(await _to_user_message(pending_msg))
|
||||||
|
goal_inputs.consume_inputs(pending_messages[:len(converted)])
|
||||||
consumed = len(converted)
|
consumed = len(converted)
|
||||||
return converted
|
return converted
|
||||||
finally:
|
finally:
|
||||||
@@ -1196,6 +1212,7 @@ class AgentLoop:
|
|||||||
|
|
||||||
session_metadata = session.metadata if session is not None else None
|
session_metadata = session.metadata if session is not None else None
|
||||||
try:
|
try:
|
||||||
|
goal_inputs = turn_scope_stack.enter_context(GoalInputScope())
|
||||||
for scope in turn_scopes or ():
|
for scope in turn_scopes or ():
|
||||||
turn_scope_stack.enter_context(scope)
|
turn_scope_stack.enter_context(scope)
|
||||||
hook = build_agent_turn_hook(AgentTurnHookSpec(
|
hook = build_agent_turn_hook(AgentTurnHookSpec(
|
||||||
@@ -1332,7 +1349,7 @@ class AgentLoop:
|
|||||||
logger.warning("Error consuming inbound message: {}, continuing...", e)
|
logger.warning("Error consuming inbound message: {}, continuing...", e)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
raw = msg.content.strip()
|
raw = command_text(msg)
|
||||||
effective_key = self._effective_session_key(msg)
|
effective_key = self._effective_session_key(msg)
|
||||||
if await agent_context.handle_runtime_control(self, msg, self.tools):
|
if await agent_context.handle_runtime_control(self, msg, self.tools):
|
||||||
continue
|
continue
|
||||||
@@ -1370,8 +1387,6 @@ class AgentLoop:
|
|||||||
# is processing this session), route the message there for mid-turn
|
# is processing this session), route the message there for mid-turn
|
||||||
# injection instead of creating a competing task.
|
# injection instead of creating a competing task.
|
||||||
if effective_key in self._pending_queues:
|
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):
|
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
|
||||||
await self._dispatch_command_inline(
|
await self._dispatch_command_inline(
|
||||||
msg, effective_key, raw,
|
msg, effective_key, raw,
|
||||||
@@ -1976,7 +1991,7 @@ class AgentLoop:
|
|||||||
if ctx.kind is TurnKind.SYSTEM or ctx.msg.channel == "system":
|
if ctx.kind is TurnKind.SYSTEM or ctx.msg.channel == "system":
|
||||||
return False
|
return False
|
||||||
session = ctx.require_session()
|
session = ctx.require_session()
|
||||||
raw = ctx.msg.content.strip()
|
raw = command_text(ctx.msg)
|
||||||
_, automation_metadata = automation_history_overrides(ctx.msg.metadata)
|
_, automation_metadata = automation_history_overrides(ctx.msg.metadata)
|
||||||
is_user_turn = (
|
is_user_turn = (
|
||||||
ctx.original_user_text is not None
|
ctx.original_user_text is not None
|
||||||
@@ -1995,6 +2010,10 @@ class AgentLoop:
|
|||||||
turn_scopes=ctx.turn_scopes,
|
turn_scopes=ctx.turn_scopes,
|
||||||
)
|
)
|
||||||
result = await self.commands.dispatch(cmd_ctx)
|
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":
|
if cmd_ctx.raw.lower() == "/compact":
|
||||||
# Compaction reports through events, not an archiveable command reply.
|
# Compaction reports through events, not an archiveable command reply.
|
||||||
return True
|
return True
|
||||||
|
|||||||
+2
-21
@@ -684,10 +684,7 @@ class AgentRunner:
|
|||||||
# Check for mid-turn injections BEFORE signaling stream end.
|
# Check for mid-turn injections BEFORE signaling stream end.
|
||||||
# If injections are found we keep the stream alive (resuming=True)
|
# If injections are found we keep the stream alive (resuming=True)
|
||||||
# so streaming channels don't prematurely finalize the card.
|
# so streaming channels don't prematurely finalize the card.
|
||||||
can_make_followup_request = (
|
can_make_followup_request = iteration + 1 < spec.max_iterations
|
||||||
iteration + 1 < spec.max_iterations
|
|
||||||
or spec.finalize_on_max_iterations
|
|
||||||
)
|
|
||||||
should_continue, injection_cycles = await self._try_drain_injections(
|
should_continue, injection_cycles = await self._try_drain_injections(
|
||||||
spec, messages, assistant_message, injection_cycles,
|
spec, messages, assistant_message, injection_cycles,
|
||||||
conversation_state=conversation_state,
|
conversation_state=conversation_state,
|
||||||
@@ -794,22 +791,8 @@ class AgentRunner:
|
|||||||
else:
|
else:
|
||||||
stop_reason = "max_iterations"
|
stop_reason = "max_iterations"
|
||||||
terminal_content = None
|
terminal_content = None
|
||||||
|
await end_length_segment(interrupted=False)
|
||||||
if spec.finalize_on_max_iterations:
|
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(
|
terminal_content, usage = await self._try_finalize_after_max_iterations(
|
||||||
spec,
|
spec,
|
||||||
hook,
|
hook,
|
||||||
@@ -818,8 +801,6 @@ class AgentRunner:
|
|||||||
request_state=request_state,
|
request_state=request_state,
|
||||||
round_usages=round_usages,
|
round_usages=round_usages,
|
||||||
)
|
)
|
||||||
else:
|
|
||||||
await end_length_segment(interrupted=False)
|
|
||||||
if terminal_content is None:
|
if terminal_content is None:
|
||||||
terminal_content = self._max_iterations_fallback(spec)
|
terminal_content = self._max_iterations_fallback(spec)
|
||||||
if length_recovery_parts:
|
if length_recovery_parts:
|
||||||
|
|||||||
+19
-25
@@ -14,9 +14,10 @@ from typing import TYPE_CHECKING, Any, Literal, cast
|
|||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
from nanobot import __version__
|
from nanobot import __version__
|
||||||
from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage
|
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
|
||||||
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
|
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
|
||||||
from nanobot.providers.base import LLMUsage
|
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.helpers import build_status_content
|
||||||
from nanobot.utils.restart import set_restart_notice_to_env
|
from nanobot.utils.restart import set_restart_notice_to_env
|
||||||
from nanobot.utils.workspace_prompts import initialize_workspace_prompt
|
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:
|
async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:
|
||||||
"""Mark this turn as an explicit sustained-goal request."""
|
"""Expand an explicit goal command into model-only input."""
|
||||||
from nanobot.agent.goal_permission import goal_mutation_permission
|
|
||||||
|
|
||||||
goal = ctx.args.strip()
|
goal = ctx.args.strip()
|
||||||
if not goal:
|
if not goal:
|
||||||
return OutboundMessage(
|
return OutboundMessage(
|
||||||
@@ -913,16 +912,6 @@ async def cmd_goal(ctx: CommandContext) -> OutboundMessage | None:
|
|||||||
content="Usage: /goal <long-running task description>",
|
content="Usage: /goal <long-running task description>",
|
||||||
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
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:
|
if not ctx.is_user_turn:
|
||||||
return OutboundMessage(
|
return OutboundMessage(
|
||||||
channel=ctx.msg.channel,
|
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"},
|
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
||||||
)
|
)
|
||||||
|
|
||||||
ctx.turn_scopes.append(goal_mutation_permission(True))
|
session = ctx.session or ctx.loop.sessions.get_or_create(ctx.key)
|
||||||
ctx.msg.metadata = {
|
session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))
|
||||||
**dict(ctx.msg.metadata or {}),
|
ctx.loop.sessions.save(session)
|
||||||
"original_command": "/goal",
|
return replace(
|
||||||
"original_content": ctx.raw,
|
ctx.msg,
|
||||||
"goal_requested": True,
|
content=goal,
|
||||||
"goal_started_at": time.time(),
|
metadata={
|
||||||
}
|
**ctx.msg.metadata,
|
||||||
ctx.msg.content = ctx.raw
|
"original_command": "/goal",
|
||||||
return None
|
"original_content": ctx.msg.content,
|
||||||
|
"goal_requested": True,
|
||||||
|
"goal_started_at": time.time(),
|
||||||
|
HIDDEN_HISTORY_META: {"kind": "goal_request"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
|
async def cmd_pairing(ctx: CommandContext) -> OutboundMessage:
|
||||||
|
|||||||
@@ -8,18 +8,22 @@ from dataclasses import dataclass, field
|
|||||||
from difflib import get_close_matches
|
from difflib import get_close_matches
|
||||||
from typing import TYPE_CHECKING, Any, Awaitable, Callable
|
from typing import TYPE_CHECKING, Any, Awaitable, Callable
|
||||||
|
|
||||||
from nanobot.bus.events import OutboundMessage
|
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
from nanobot.bus.events import InboundMessage
|
|
||||||
from nanobot.session.manager import Session
|
from nanobot.session.manager import Session
|
||||||
from nanobot.utils.llm_runtime import LLMRuntime
|
from nanobot.utils.llm_runtime import LLMRuntime
|
||||||
|
|
||||||
Handler = Callable[["CommandContext"], Awaitable["OutboundMessage | None"]]
|
Handler = Callable[["CommandContext"], Awaitable["InboundMessage | OutboundMessage | None"]]
|
||||||
_BOT_SUFFIX_RE = re.compile(r"^[A-Za-z0-9_]+$")
|
_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:
|
def normalize_command_text(text: str) -> str:
|
||||||
"""Normalize slash-command transport variants before routing.
|
"""Normalize slash-command transport variants before routing.
|
||||||
|
|
||||||
@@ -99,7 +103,7 @@ class CommandRouter:
|
|||||||
return True
|
return True
|
||||||
return cmd.startswith("/")
|
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."""
|
"""Dispatch a priority command. Called from run() without the lock."""
|
||||||
ctx.raw = normalize_command_text(ctx.raw)
|
ctx.raw = normalize_command_text(ctx.raw)
|
||||||
handler = self._priority.get(ctx.raw.lower())
|
handler = self._priority.get(ctx.raw.lower())
|
||||||
@@ -107,8 +111,10 @@ class CommandRouter:
|
|||||||
return await handler(ctx)
|
return await handler(ctx)
|
||||||
return None
|
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."""
|
"""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)
|
ctx.raw = normalize_command_text(ctx.raw)
|
||||||
cmd = ctx.raw.lower()
|
cmd = ctx.raw.lower()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import asyncio
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.agent.goal_permission import (
|
||||||
|
GoalInputScope,
|
||||||
|
goal_mutation_allowed,
|
||||||
|
goal_mutation_permission,
|
||||||
|
revoke_goal_mutation_permission,
|
||||||
|
)
|
||||||
|
from nanobot.bus.events import InboundMessage
|
||||||
|
|
||||||
|
|
||||||
|
def goal_message(**overrides):
|
||||||
|
fields = dict(
|
||||||
|
channel="websocket", sender_id="user", chat_id="test", content="Execute the plan",
|
||||||
|
metadata={"goal_requested": True},
|
||||||
|
)
|
||||||
|
fields.update(overrides)
|
||||||
|
return InboundMessage(**fields)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("overrides", [
|
||||||
|
{"channel": "system", "input_role": "user"},
|
||||||
|
{"sender_id": "subagent"},
|
||||||
|
{"input_role": "system"},
|
||||||
|
{"metadata": {"goal_requested": True, "_internal_continuation": True}},
|
||||||
|
{"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):
|
||||||
|
message = goal_message(**overrides)
|
||||||
|
with goal_mutation_permission(True):
|
||||||
|
with GoalInputScope(message) as scope:
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
scope.consume_inputs([message])
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
assert goal_mutation_allowed() is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_revoked_permission_requires_a_new_explicit_request_to_reauthorize():
|
||||||
|
with GoalInputScope(goal_message()) as scope:
|
||||||
|
assert goal_mutation_allowed() is True
|
||||||
|
revoke_goal_mutation_permission()
|
||||||
|
scope.consume_inputs([goal_message(content="ok", metadata={})])
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
scope.consume_inputs([goal_message(content="Execute another plan")])
|
||||||
|
assert goal_mutation_allowed() is True
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("error", [RuntimeError, asyncio.CancelledError])
|
||||||
|
def test_injected_permission_is_cleared_on_abnormal_exit(error):
|
||||||
|
with pytest.raises(error):
|
||||||
|
with GoalInputScope() as scope:
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
scope.consume_inputs([goal_message()])
|
||||||
|
assert goal_mutation_allowed() is True
|
||||||
|
raise error()
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
@@ -581,11 +581,12 @@ class TestToolEventProgress:
|
|||||||
assert {event.stream_id for event in [*deltas, *endings]} == {deltas[0].stream_id}
|
assert {event.stream_id for event in [*deltas, *endings]} == {deltas[0].stream_id}
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize("max_iterations", [1, 2])
|
||||||
async def test_followup_after_truncation_starts_a_new_stream(
|
async def test_followup_after_truncation_starts_a_new_stream(
|
||||||
self, tmp_path: Path,
|
self, tmp_path: Path, max_iterations: int,
|
||||||
) -> None:
|
) -> None:
|
||||||
loop = _make_loop(tmp_path)
|
loop = _make_loop(tmp_path)
|
||||||
loop.max_iterations = 1
|
loop.max_iterations = max_iterations
|
||||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||||
_attach_webui_runtime_events(loop, loop.bus)
|
_attach_webui_runtime_events(loop, loop.bus)
|
||||||
calls = 0
|
calls = 0
|
||||||
@@ -597,11 +598,17 @@ class TestToolEventProgress:
|
|||||||
await on_content_delta("old partial")
|
await on_content_delta("old partial")
|
||||||
loop._enqueue_session_message(InboundMessage(
|
loop._enqueue_session_message(InboundMessage(
|
||||||
channel="websocket", sender_id="u", chat_id="test", content="new question",
|
channel="websocket", sender_id="u", chat_id="test", content="new question",
|
||||||
|
metadata={"_wants_stream": True},
|
||||||
))
|
))
|
||||||
return LLMResponse(content="old partial", finish_reason="length")
|
return LLMResponse(content="old partial", finish_reason="length")
|
||||||
|
has_followup = any(
|
||||||
|
"new question" in str(message.get("content", ""))
|
||||||
|
for message in kwargs["messages"]
|
||||||
|
)
|
||||||
|
answer = "new answer" if has_followup else "old ending"
|
||||||
if on_content_delta is not None:
|
if on_content_delta is not None:
|
||||||
await on_content_delta("new answer")
|
await on_content_delta(answer)
|
||||||
return LLMResponse(content="new answer", finish_reason="stop")
|
return LLMResponse(content=answer, finish_reason="stop")
|
||||||
|
|
||||||
loop.provider.chat_stream_with_retry = chat
|
loop.provider.chat_stream_with_retry = chat
|
||||||
try:
|
try:
|
||||||
@@ -616,15 +623,25 @@ class TestToolEventProgress:
|
|||||||
endings = [
|
endings = [
|
||||||
message.event for message in outbound if isinstance(message.event, StreamEndEvent)
|
message.event for message in outbound if isinstance(message.event, StreamEndEvent)
|
||||||
]
|
]
|
||||||
assert [event.content for event in deltas] == ["old partial", "new answer"]
|
if max_iterations == 1:
|
||||||
assert deltas[0].stream_id != deltas[1].stream_id
|
assert calls == 3
|
||||||
assert [(event.resuming, event.merge_next) for event in endings] == [
|
assert [event.content for event in deltas] == [
|
||||||
(True, False), (False, False),
|
"old partial", "\n\nold ending", "new answer",
|
||||||
]
|
]
|
||||||
|
assert [(event.resuming, event.merge_next) for event in endings] == [
|
||||||
|
(True, True), (False, False), (False, False),
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
assert calls == 2
|
||||||
|
assert [event.content for event in deltas] == ["old partial", "new answer"]
|
||||||
|
assert [(event.resuming, event.merge_next) for event in endings] == [
|
||||||
|
(True, False), (False, False),
|
||||||
|
]
|
||||||
|
assert deltas[0].stream_id != deltas[-1].stream_id
|
||||||
assert [
|
assert [
|
||||||
message.content for message in outbound
|
message.content for message in outbound
|
||||||
if isinstance(message.event, StreamedResponseEvent)
|
if isinstance(message.event, StreamedResponseEvent)
|
||||||
] == ["new answer"]
|
] == (["old partial\n\nold ending", "new answer"] if max_iterations == 1 else ["new answer"])
|
||||||
finally:
|
finally:
|
||||||
await loop.aclose()
|
await loop.aclose()
|
||||||
|
|
||||||
|
|||||||
@@ -153,17 +153,6 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
|
|||||||
],
|
],
|
||||||
usage=None,
|
usage=None,
|
||||||
),
|
),
|
||||||
LLMResponse(
|
|
||||||
content="trying to start another goal",
|
|
||||||
tool_calls=[
|
|
||||||
ToolCallRequest(
|
|
||||||
id="call_create_again",
|
|
||||||
name="create_goal",
|
|
||||||
arguments={"objective": "Start an unrelated follow-up."},
|
|
||||||
)
|
|
||||||
],
|
|
||||||
usage=None,
|
|
||||||
),
|
|
||||||
LLMResponse(content="done", tool_calls=[], usage=None),
|
LLMResponse(content="done", tool_calls=[], usage=None),
|
||||||
])
|
])
|
||||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||||
@@ -186,14 +175,11 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
|
|||||||
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||||
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
|
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
|
||||||
assert "staged migration plan" in str(first_request)
|
assert "staged migration plan" in str(first_request)
|
||||||
assert "/goal implement the plan above" in str(first_request)
|
assert "implement the plan above" in str(first_request)
|
||||||
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(first_request)
|
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(first_request)
|
||||||
final_request = provider.chat_stream_with_retry.await_args_list[-1].kwargs["messages"]
|
assert session.messages[2]["content"] == "/goal implement the plan above"
|
||||||
assert "create_goal is unavailable for this turn" in str(final_request)
|
assert session.messages[3]["_hidden_history"] == {"kind": "goal_request"}
|
||||||
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(session.messages[2]["content"])
|
assert _GOAL_RUNTIME_GUIDANCE_TAG in str(session.messages[3]["content"])
|
||||||
assert _GOAL_RUNTIME_GUIDANCE_TAG not in str(
|
|
||||||
public_history_message(session.messages[2])["content"]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
"""Explicit goal requests can steer a running session without restarting it."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
|
||||||
|
from nanobot.agent.loop import AgentLoop
|
||||||
|
from nanobot.bus.events import InboundMessage
|
||||||
|
from nanobot.bus.queue import MessageBus
|
||||||
|
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||||
|
from nanobot.runtime_context import public_history_messages
|
||||||
|
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||||
|
from nanobot.session.history_visibility import is_hidden_history_message
|
||||||
|
from nanobot.session.manager import SessionManager
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("command", [
|
||||||
|
"/goal execute the agreed plan",
|
||||||
|
"/GOAL@nanobot execute the agreed plan",
|
||||||
|
"/goal /tmp/project: execute the agreed plan",
|
||||||
|
])
|
||||||
|
async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, command):
|
||||||
|
task = command.split(" ", 1)[1]
|
||||||
|
first_call = asyncio.Event()
|
||||||
|
release = asyncio.Event()
|
||||||
|
calls = []
|
||||||
|
permissions = []
|
||||||
|
provider = MagicMock()
|
||||||
|
provider.get_default_model.return_value = "test-model"
|
||||||
|
provider.generation = GenerationSettings()
|
||||||
|
provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||||
|
|
||||||
|
async def respond(**kwargs):
|
||||||
|
calls.append(str(kwargs["messages"]))
|
||||||
|
permissions.append(goal_mutation_allowed())
|
||||||
|
if len(calls) == 1:
|
||||||
|
first_call.set()
|
||||||
|
await release.wait()
|
||||||
|
return LLMResponse(content="The plan is to verify the migration.")
|
||||||
|
if len(calls) == 2:
|
||||||
|
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="create", name="create_goal",
|
||||||
|
arguments={"objective": "Verify the migration as agreed in this conversation."},
|
||||||
|
)])
|
||||||
|
if len(calls) == 3:
|
||||||
|
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="complete", name="update_goal",
|
||||||
|
arguments={"action": "complete", "recap": "Migration verified."},
|
||||||
|
)])
|
||||||
|
return LLMResponse(content="done")
|
||||||
|
|
||||||
|
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||||
|
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||||
|
process = AsyncMock(wraps=loop._process_message)
|
||||||
|
loop._process_message = process
|
||||||
|
run = asyncio.create_task(loop.run())
|
||||||
|
try:
|
||||||
|
await loop.bus.publish_inbound(InboundMessage(
|
||||||
|
channel="cli", sender_id="user", chat_id="test", content="Discuss the migration.",
|
||||||
|
))
|
||||||
|
await asyncio.wait_for(first_call.wait(), 3)
|
||||||
|
await loop.bus.publish_inbound(InboundMessage(
|
||||||
|
channel="cli", sender_id="user", chat_id="test", content=command,
|
||||||
|
))
|
||||||
|
async with asyncio.timeout(3):
|
||||||
|
while loop._pending_queues["cli:test"].empty():
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
assert len(calls) == 1
|
||||||
|
release.set()
|
||||||
|
await asyncio.wait_for(asyncio.gather(*loop._active_tasks["cli:test"]), 5)
|
||||||
|
session = loop.sessions.get_or_create("cli:test")
|
||||||
|
assert process.await_count == 1
|
||||||
|
assert permissions[:3] == [False, True, True]
|
||||||
|
assert "Discuss the migration" in calls[1]
|
||||||
|
assert task in calls[1]
|
||||||
|
assert "Goal Runtime Guidance" in calls[1]
|
||||||
|
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||||
|
assert "Verify the migration" in session.metadata[GOAL_STATE_KEY]["objective"]
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
persisted = SessionManager(tmp_path).get_or_create("cli:test").messages
|
||||||
|
visible = public_history_messages([
|
||||||
|
row for row in persisted if not is_hidden_history_message(row)
|
||||||
|
])
|
||||||
|
assert sum(row.get("content") == command for row in visible) == 1
|
||||||
|
hidden = [row for row in persisted if is_hidden_history_message(row)]
|
||||||
|
assert len(hidden) == 1
|
||||||
|
assert public_history_messages(hidden)[0]["content"] == task
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
loop.stop()
|
||||||
|
await asyncio.wait_for(run, 5)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
|
||||||
|
msg = InboundMessage(
|
||||||
|
channel="cli", sender_id="user", chat_id="test", content="/goal execute",
|
||||||
|
metadata={"_cron_trigger": {"job_id": "job"}},
|
||||||
|
)
|
||||||
|
loop = AgentLoop(bus=MessageBus(), provider=MagicMock(), 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()
|
||||||
|
assert "only be started by a user" in response.content
|
||||||
|
assert loop._pending_queues == {}
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
assert loop.sessions.get_or_create(msg.session_key).messages == []
|
||||||
|
finally:
|
||||||
|
await loop.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("boundary", ["text", "tool", "error", "empty"])
|
||||||
|
async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_path, boundary):
|
||||||
|
from agent.session_helpers import run_session
|
||||||
|
|
||||||
|
provider = MagicMock()
|
||||||
|
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", max_iterations=1,
|
||||||
|
)
|
||||||
|
calls = []
|
||||||
|
goal = InboundMessage(
|
||||||
|
channel="cli", sender_id="user", chat_id="test", content="/goal verify the migration",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def respond(**kwargs):
|
||||||
|
calls.append(str(kwargs["messages"]))
|
||||||
|
if len(calls) == 1:
|
||||||
|
await loop._dispatch_command_inline(
|
||||||
|
goal, goal.session_key, goal.content, loop.commands.dispatch,
|
||||||
|
)
|
||||||
|
if boundary == "tool":
|
||||||
|
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="list", name="list_dir", arguments={"path": "."},
|
||||||
|
)])
|
||||||
|
if boundary == "error":
|
||||||
|
return LLMResponse(content="Temporary model error", finish_reason="error")
|
||||||
|
if boundary == "empty":
|
||||||
|
return LLMResponse(content="")
|
||||||
|
return LLMResponse(content="The migration plan is ready.")
|
||||||
|
if kwargs.get("tools") and GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata:
|
||||||
|
assert goal_mutation_allowed() is True
|
||||||
|
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="create", name="create_goal",
|
||||||
|
arguments={"objective": "Verify the migration."},
|
||||||
|
)])
|
||||||
|
if kwargs.get("tools"):
|
||||||
|
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="complete", name="update_goal",
|
||||||
|
arguments={"action": "complete", "recap": "Verified."},
|
||||||
|
)])
|
||||||
|
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="test", content="Discuss the migration.",
|
||||||
|
))
|
||||||
|
session = loop.sessions.get_or_create("cli:test")
|
||||||
|
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||||
|
goal_calls = [call for call in calls if "Goal Runtime Guidance" in call]
|
||||||
|
assert goal_calls
|
||||||
|
assert "Discuss the migration" in goal_calls[0]
|
||||||
|
assert "verify the migration" in goal_calls[0]
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
finally:
|
||||||
|
await loop.aclose()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
|
||||||
|
from nanobot.command.router import CommandContext
|
||||||
|
from nanobot.session.recovery import pending_followups, record_pending_followup
|
||||||
|
|
||||||
|
provider = MagicMock()
|
||||||
|
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")
|
||||||
|
message = InboundMessage(
|
||||||
|
channel="websocket", sender_id="user", chat_id="test", content="/goal /stop",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
generated = await loop.commands.dispatch(CommandContext(
|
||||||
|
msg=message, session=None, key=message.session_key,
|
||||||
|
raw=message.content, loop=loop, is_user_turn=True,
|
||||||
|
))
|
||||||
|
assert isinstance(generated, InboundMessage)
|
||||||
|
session = loop.sessions.get_or_create(message.session_key)
|
||||||
|
assert record_pending_followup(session, generated)
|
||||||
|
loop.sessions.save(session)
|
||||||
|
finally:
|
||||||
|
await loop.aclose()
|
||||||
|
|
||||||
|
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
|
||||||
|
session = loop.sessions.get_or_create(message.session_key)
|
||||||
|
recovered, = pending_followups(session)
|
||||||
|
responses = iter([
|
||||||
|
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="create", name="create_goal", arguments={"objective": "Verify the migration."},
|
||||||
|
)]),
|
||||||
|
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="complete", name="update_goal", arguments={"action": "complete", "recap": "Verified."},
|
||||||
|
)]),
|
||||||
|
LLMResponse(content="done"),
|
||||||
|
])
|
||||||
|
|
||||||
|
async def respond(**kwargs):
|
||||||
|
assert any(
|
||||||
|
row.get("role") == "user" and row.get("content", "").startswith("/stop")
|
||||||
|
for row in kwargs["messages"]
|
||||||
|
)
|
||||||
|
return next(responses)
|
||||||
|
|
||||||
|
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||||
|
run = asyncio.create_task(loop.run())
|
||||||
|
try:
|
||||||
|
assert recovered.content == "/stop"
|
||||||
|
assert recovered.metadata["goal_requested"] is True
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
await loop.bus.publish_inbound(recovered)
|
||||||
|
async with asyncio.timeout(5):
|
||||||
|
while (await loop.bus.consume_outbound()).content != "done":
|
||||||
|
pass
|
||||||
|
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
|
||||||
|
assert pending_followups(session) == []
|
||||||
|
assert sum(row.get("content") == message.content for row in session.messages) == 1
|
||||||
|
assert sum(is_hidden_history_message(row) for row in session.messages) == 1
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
finally:
|
||||||
|
loop.stop()
|
||||||
|
await asyncio.wait_for(run, 5)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
|
||||||
|
provider = MagicMock()
|
||||||
|
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")
|
||||||
|
message = InboundMessage(
|
||||||
|
channel="cli", sender_id="automation", chat_id="test", content="Continue working",
|
||||||
|
metadata={"goal_requested": True, "_internal_continuation": True},
|
||||||
|
)
|
||||||
|
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||||
|
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||||
|
id="create", name="create_goal", arguments={"objective": "An unauthorized goal."},
|
||||||
|
)]),
|
||||||
|
LLMResponse(content="done"),
|
||||||
|
])
|
||||||
|
try:
|
||||||
|
with goal_mutation_permission(True):
|
||||||
|
await loop._process_message(message, session_key="cli:test")
|
||||||
|
assert goal_mutation_allowed() is True
|
||||||
|
assert GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata
|
||||||
|
final_request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
|
||||||
|
assert "create_goal is unavailable for this turn" in str(final_request)
|
||||||
|
assert goal_mutation_allowed() is False
|
||||||
|
finally:
|
||||||
|
await loop.aclose()
|
||||||
@@ -1,249 +1,94 @@
|
|||||||
"""Tests for caller-controlled continuation in AgentRunner.
|
"""Caller-controlled continuation respects live state and the runner budget."""
|
||||||
|
|
||||||
When the continuation callback returns a message, the runner must not exit with
|
|
||||||
stop_reason="completed" after a plain-text final response. Instead it injects
|
|
||||||
that message and keeps looping, similar to a mid-turn injection.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from agent.runner_helpers import make_run_spec
|
from agent.runner_helpers import make_run_spec
|
||||||
|
from nanobot.agent.runner import AgentRunner
|
||||||
from nanobot.config.schema import AgentDefaults
|
from nanobot.config.schema import AgentDefaults
|
||||||
from nanobot.providers.base import LLMProvider, LLMResponse
|
from nanobot.providers.base import LLMProvider, LLMResponse
|
||||||
|
|
||||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
|
||||||
|
|
||||||
|
|
||||||
def _continue_goal() -> str:
|
|
||||||
return "Continue working toward the active sustained goal."
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_runner_exits_normally_without_continuation_callback():
|
|
||||||
"""Without a continuation request, final text completes the run."""
|
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def run_spec():
|
||||||
provider = MagicMock(spec=LLMProvider)
|
provider = MagicMock(spec=LLMProvider)
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="all done"))
|
||||||
content="all done", tool_calls=[], usage=None,
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
tools = MagicMock()
|
||||||
tools.get_definitions.return_value = []
|
tools.get_definitions.return_value = []
|
||||||
|
return make_run_spec(
|
||||||
runner = AgentRunner()
|
provider,
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=2,
|
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
|
||||||
))
|
|
||||||
|
|
||||||
assert result.stop_reason == "completed"
|
|
||||||
assert result.final_content == "all done"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_runner_exits_normally_when_continuation_callback_returns_none():
|
|
||||||
"""A callback returning None leaves the final response terminal."""
|
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
|
||||||
content="all done", tool_calls=[], usage=None,
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
|
||||||
tools.get_definitions.return_value = []
|
|
||||||
|
|
||||||
runner = AgentRunner()
|
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=2,
|
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
|
||||||
continuation_callback=lambda: None,
|
|
||||||
))
|
|
||||||
|
|
||||||
assert result.stop_reason == "completed"
|
|
||||||
assert result.final_content == "all done"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_runner_continues_when_callback_returns_message():
|
|
||||||
"""A callback result after final text is injected for the next iteration.
|
|
||||||
|
|
||||||
We set max_iterations=3 and let the provider return final text every time.
|
|
||||||
Without the fix this would exit on the first iteration with stop_reason
|
|
||||||
"completed". With the fix the runner is forced to continue until
|
|
||||||
max_iterations is hit.
|
|
||||||
"""
|
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
|
||||||
content="still working", tool_calls=[], usage=None,
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
|
||||||
tools.get_definitions.return_value = []
|
|
||||||
|
|
||||||
runner = AgentRunner()
|
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
initial_messages=[{"role": "user", "content": "do task"}],
|
||||||
tools=tools,
|
tools=tools,
|
||||||
model="test-model",
|
model="test-model",
|
||||||
max_iterations=3,
|
max_iterations=3,
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
max_tool_result_chars=AgentDefaults().max_tool_result_chars,
|
||||||
continuation_callback=_continue_goal,
|
)
|
||||||
))
|
|
||||||
|
|
||||||
# Because the callback keeps returning a message, the runner should never
|
|
||||||
# naturally complete. It loops until max_iterations is exhausted.
|
|
||||||
assert result.stop_reason == "max_iterations"
|
|
||||||
# The injected continuation message should be present in the message list.
|
|
||||||
user_msgs = [m for m in result.messages if m.get("role") == "user"]
|
|
||||||
assert any("active sustained goal" in str(m.get("content", "")) for m in user_msgs)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.parametrize("callback", [None, lambda: None], ids=["absent", "no-request"])
|
||||||
async def test_runner_respects_max_iterations_with_continuation():
|
async def test_runner_completes_without_a_continuation_request(run_spec, callback):
|
||||||
"""A continuation request after one iteration still hits max_iterations."""
|
run_spec.continuation_callback = callback
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
result = await AgentRunner().run(run_spec)
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
|
||||||
content="still working", tool_calls=[], usage=None,
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
|
||||||
tools.get_definitions.return_value = []
|
|
||||||
|
|
||||||
runner = AgentRunner()
|
assert result.stop_reason == "completed"
|
||||||
result = await runner.run(make_run_spec(provider,
|
assert result.final_content == "all done"
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=1,
|
@pytest.mark.parametrize("max_iterations,finalize", [(1, True), (3, True), (8, False)])
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
async def test_continuation_injects_text_without_exceeding_budget(run_spec, max_iterations, finalize):
|
||||||
continuation_callback=_continue_goal,
|
continuation = "Continue working toward the active sustained goal."
|
||||||
))
|
run_spec.max_iterations = max_iterations
|
||||||
|
run_spec.finalize_on_max_iterations = finalize
|
||||||
|
run_spec.continuation_callback = lambda: continuation
|
||||||
|
|
||||||
|
result = await AgentRunner().run(run_spec)
|
||||||
|
|
||||||
assert result.stop_reason == "max_iterations"
|
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")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
async def test_runner_does_not_request_continuation_on_error(run_spec):
|
||||||
async def test_runner_continuation_is_governed_by_max_iterations():
|
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
|
||||||
"""Caller-requested continuation is governed by max_iterations."""
|
content=None, finish_reason="error",
|
||||||
from nanobot.agent.runner import AgentRunner
|
)
|
||||||
|
callback = MagicMock(return_value="Continue working.")
|
||||||
|
run_spec.continuation_callback = callback
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
result = await AgentRunner().run(run_spec)
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
|
||||||
content="still working", tool_calls=[], usage=None,
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
|
||||||
tools.get_definitions.return_value = []
|
|
||||||
max_iterations = 8
|
|
||||||
|
|
||||||
runner = AgentRunner()
|
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=max_iterations,
|
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
|
||||||
continuation_callback=_continue_goal,
|
|
||||||
finalize_on_max_iterations=False,
|
|
||||||
))
|
|
||||||
|
|
||||||
assert result.stop_reason == "max_iterations"
|
|
||||||
assert provider.chat_stream_with_retry.await_count == max_iterations
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_runner_does_not_continue_on_error():
|
|
||||||
"""An LLM error remains terminal even when continuation is available."""
|
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
|
||||||
content=None, tool_calls=[], usage=None,
|
|
||||||
finish_reason="error",
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
|
||||||
tools.get_definitions.return_value = []
|
|
||||||
|
|
||||||
runner = AgentRunner()
|
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=2,
|
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
|
||||||
continuation_callback=_continue_goal,
|
|
||||||
))
|
|
||||||
|
|
||||||
assert result.stop_reason == "error"
|
assert result.stop_reason == "error"
|
||||||
|
assert run_spec.runtime.provider.chat_stream_with_retry.await_count == 1
|
||||||
|
callback.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
async def test_runner_reads_continuation_state_after_each_response(run_spec):
|
||||||
async def test_runner_injects_continuation_callback_message():
|
continuation = None
|
||||||
"""The callback result becomes the injected user message."""
|
calls = 0
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
async def respond(**kwargs):
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
nonlocal continuation, calls
|
||||||
content="still working", tool_calls=[], usage=None,
|
calls += 1
|
||||||
))
|
if calls == 1:
|
||||||
tools = MagicMock()
|
continuation = "Write the article draft."
|
||||||
tools.get_definitions.return_value = []
|
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.")
|
||||||
|
|
||||||
custom_msg = "CUSTOM_CONTINUE_PLEASE"
|
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
|
||||||
|
run_spec.continuation_callback = lambda: continuation
|
||||||
|
|
||||||
runner = AgentRunner()
|
result = await AgentRunner().run(run_spec)
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=2,
|
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
|
||||||
continuation_callback=lambda: custom_msg,
|
|
||||||
))
|
|
||||||
|
|
||||||
user_msgs = [m for m in result.messages if m.get("role") == "user"]
|
assert calls == 2
|
||||||
assert any(custom_msg in str(m.get("content", "")) for m in user_msgs)
|
assert result.stop_reason == "completed"
|
||||||
|
assert result.final_content == "The draft is complete."
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_runner_resolves_continuation_callback_lazily():
|
|
||||||
"""The continuation text can depend on goal metadata created during the run."""
|
|
||||||
from nanobot.agent.runner import AgentRunner
|
|
||||||
|
|
||||||
provider = MagicMock(spec=LLMProvider)
|
|
||||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(
|
|
||||||
content="still working", tool_calls=[], usage=None,
|
|
||||||
))
|
|
||||||
tools = MagicMock()
|
|
||||||
tools.get_definitions.return_value = []
|
|
||||||
calls = {"n": 0}
|
|
||||||
|
|
||||||
def dynamic_msg() -> str:
|
|
||||||
calls["n"] += 1
|
|
||||||
return "Goal (active):\nWrite the article draft."
|
|
||||||
|
|
||||||
runner = AgentRunner()
|
|
||||||
result = await runner.run(make_run_spec(provider,
|
|
||||||
initial_messages=[{"role": "user", "content": "do task"}],
|
|
||||||
tools=tools,
|
|
||||||
model="test-model",
|
|
||||||
max_iterations=1,
|
|
||||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
|
||||||
continuation_callback=dynamic_msg,
|
|
||||||
finalize_on_max_iterations=False,
|
|
||||||
))
|
|
||||||
|
|
||||||
user_msgs = [m for m in result.messages if m.get("role") == "user"]
|
|
||||||
assert calls["n"] == 1
|
|
||||||
assert any("Write the article draft." in str(m.get("content", "")) for m in user_msgs)
|
|
||||||
@@ -532,7 +532,7 @@ async def test_injected_followup_starts_new_length_recovery_chain():
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@pytest.mark.parametrize("max_iterations", [1, 3])
|
@pytest.mark.parametrize("max_iterations", [1, 3])
|
||||||
async def test_followup_interrupts_truncated_answer_before_next_request(max_iterations):
|
async def test_truncated_answer_followup_requires_remaining_iteration(max_iterations):
|
||||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||||
from nanobot.agent.runner import AgentRunner
|
from nanobot.agent.runner import AgentRunner
|
||||||
|
|
||||||
@@ -571,12 +571,20 @@ async def test_followup_interrupts_truncated_answer_before_next_request(max_iter
|
|||||||
injection_callback=_make_injection_callback(queue),
|
injection_callback=_make_injection_callback(queue),
|
||||||
))
|
))
|
||||||
|
|
||||||
assert result.final_content == "4"
|
|
||||||
assert len(requests) == 2
|
assert len(requests) == 2
|
||||||
assert endings[0] == (True, False)
|
|
||||||
second_request = "\n".join(str(message.get("content", "")) for message in requests[1])
|
second_request = "\n".join(str(message.get("content", "")) for message in requests[1])
|
||||||
assert "Never mind. What is 2+2?" in second_request
|
if max_iterations == 1:
|
||||||
assert "Continue the same response from its exact endpoint" not in second_request
|
assert "Never mind. What is 2+2?" not in second_request
|
||||||
|
assert queue.get_nowait()["content"] == "Never mind. What is 2+2?"
|
||||||
|
assert result.had_injections is False
|
||||||
|
assert result.final_content == "Unfinished old answer:\n\n4"
|
||||||
|
assert "Continue the same response from its exact endpoint" in second_request
|
||||||
|
else:
|
||||||
|
assert result.final_content == "4"
|
||||||
|
assert endings[0] == (True, False)
|
||||||
|
assert "Never mind. What is 2+2?" in second_request
|
||||||
|
assert queue.empty()
|
||||||
|
assert "Continue the same response from its exact endpoint" not in second_request
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -1880,8 +1888,8 @@ async def test_max_iterations_without_finalization_keeps_late_injection_queued()
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_max_iterations_finalization_consumes_late_injection():
|
async def test_max_iterations_finalization_keeps_late_injection_queued():
|
||||||
"""The finalization model request receives the snapshot after the last iteration."""
|
"""New input waits for a turn with tools instead of entering no-tools finalization."""
|
||||||
from nanobot.agent.hook import AgentHook
|
from nanobot.agent.hook import AgentHook
|
||||||
from nanobot.agent.runner import AgentRunner
|
from nanobot.agent.runner import AgentRunner
|
||||||
from nanobot.bus.events import InboundMessage
|
from nanobot.bus.events import InboundMessage
|
||||||
@@ -1935,18 +1943,18 @@ async def test_max_iterations_finalization_consumes_late_injection():
|
|||||||
))
|
))
|
||||||
|
|
||||||
assert result.stop_reason == "max_iterations"
|
assert result.stop_reason == "max_iterations"
|
||||||
assert result.had_injections is True
|
assert result.had_injections is False
|
||||||
assert injection_queue.empty()
|
assert injection_queue.get_nowait().content == "late follow-up after max iters"
|
||||||
assert call_count["n"] == 3
|
assert call_count["n"] == 3
|
||||||
finalization_request = "\n".join(
|
finalization_request = "\n".join(
|
||||||
str(message.get("content", "")) for message in captured_messages[-1]
|
str(message.get("content", "")) for message in captured_messages[-1]
|
||||||
)
|
)
|
||||||
assert "late follow-up after max iters" in finalization_request
|
assert "late follow-up after max iters" not in finalization_request
|
||||||
injected = [
|
injected = [
|
||||||
m for m in result.messages
|
m for m in result.messages
|
||||||
if m.get("role") == "user" and m.get("content") == "late follow-up after max iters"
|
if m.get("role") == "user" and m.get("content") == "late follow-up after max iters"
|
||||||
]
|
]
|
||||||
assert len(injected) == 1
|
assert injected == []
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import pytest
|
|||||||
|
|
||||||
from nanobot.agent.goal_permission import goal_mutation_allowed
|
from nanobot.agent.goal_permission import goal_mutation_allowed
|
||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
from nanobot.bus.events import InboundMessage
|
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.command.builtin import (
|
from nanobot.command.builtin import (
|
||||||
build_help_text,
|
build_help_text,
|
||||||
@@ -16,6 +16,7 @@ from nanobot.command.builtin import (
|
|||||||
)
|
)
|
||||||
from nanobot.command.router import CommandContext, CommandRouter
|
from nanobot.command.router import CommandContext, CommandRouter
|
||||||
from nanobot.config.schema import ModelPresetConfig
|
from nanobot.config.schema import ModelPresetConfig
|
||||||
|
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||||
from nanobot.session.model_selection import (
|
from nanobot.session.model_selection import (
|
||||||
SESSION_MODEL_PRESET_METADATA_KEY,
|
SESSION_MODEL_PRESET_METADATA_KEY,
|
||||||
model_preset_from_metadata,
|
model_preset_from_metadata,
|
||||||
@@ -64,7 +65,8 @@ def _ctx(loop: AgentLoop, raw: str, args: str = "") -> CommandContext:
|
|||||||
def _ctx_session(loop: AgentLoop, raw: str, args: str = "") -> CommandContext:
|
def _ctx_session(loop: AgentLoop, raw: str, args: str = "") -> CommandContext:
|
||||||
msg = InboundMessage(channel="cli", sender_id="user", chat_id="direct", content=raw)
|
msg = InboundMessage(channel="cli", sender_id="user", chat_id="direct", content=raw)
|
||||||
return CommandContext(
|
return CommandContext(
|
||||||
msg=msg, session=MagicMock(), key=msg.session_key, raw=raw, args=args, loop=loop,
|
msg=msg, session=loop.sessions.get_or_create(msg.session_key),
|
||||||
|
key=msg.session_key, raw=raw, args=args, loop=loop,
|
||||||
is_user_turn=True,
|
is_user_turn=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -256,34 +258,27 @@ async def test_goal_command_shows_usage_without_args(tmp_path) -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_goal_command_rejects_mid_turn_without_session(tmp_path) -> None:
|
@pytest.mark.parametrize("with_session", [False, True])
|
||||||
|
async def test_goal_command_preserves_task_and_visible_command(tmp_path, with_session) -> None:
|
||||||
loop = _make_loop(tmp_path)
|
loop = _make_loop(tmp_path)
|
||||||
out = await cmd_goal(_ctx(loop, "/goal do work", args="do work"))
|
task = "检查 /tmp/project\n保留现有文件。"
|
||||||
assert out is not None
|
command = f"/goal {task}"
|
||||||
assert out.channel == "cli"
|
ctx = _ctx_session(loop, command, args=task)
|
||||||
assert out.chat_id == "direct"
|
if not with_session:
|
||||||
assert out.metadata == {"render_as": "text"}
|
ctx.session = None
|
||||||
assert out.content == (
|
|
||||||
"A task is already running for this chat. "
|
|
||||||
"Use `/stop` first, then send `/goal <long-running task description>` again."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_goal_command_marks_turn_and_preserves_explicit_request(tmp_path) -> None:
|
|
||||||
loop = _make_loop(tmp_path)
|
|
||||||
ctx = _ctx_session(loop, "/goal audit the repo", args="audit the repo")
|
|
||||||
out = await cmd_goal(ctx)
|
out = await cmd_goal(ctx)
|
||||||
assert out is None
|
assert isinstance(out, InboundMessage)
|
||||||
assert ctx.msg.content == "/goal audit the repo"
|
assert ctx.msg.content == command
|
||||||
assert ctx.msg.metadata.get("original_command") == "/goal"
|
assert out.content == task
|
||||||
assert ctx.msg.metadata.get("original_content") == "/goal audit the repo"
|
assert out.metadata["original_content"] == command
|
||||||
assert ctx.msg.metadata.get("goal_requested") is True
|
assert out.metadata["goal_requested"] is True
|
||||||
assert isinstance(ctx.msg.metadata.get("goal_started_at"), int | float)
|
assert out.metadata[HIDDEN_HISTORY_META] == {"kind": "goal_request"}
|
||||||
assert len(ctx.turn_scopes) == 1
|
|
||||||
with ctx.turn_scopes[0]:
|
|
||||||
assert goal_mutation_allowed() is True
|
|
||||||
assert goal_mutation_allowed() is False
|
assert goal_mutation_allowed() is False
|
||||||
|
session = loop.sessions.get_or_create(ctx.key)
|
||||||
|
assert [(row["role"], row["content"]) for row in session.messages] == [
|
||||||
|
("user", command),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -293,14 +288,13 @@ async def test_goal_command_registered_on_router(tmp_path) -> None:
|
|||||||
loop = _make_loop(tmp_path)
|
loop = _make_loop(tmp_path)
|
||||||
ctx = _ctx_session(loop, "/goal ship it", args="ship it")
|
ctx = _ctx_session(loop, "/goal ship it", args="ship it")
|
||||||
out = await router.dispatch(ctx)
|
out = await router.dispatch(ctx)
|
||||||
assert out is None
|
assert isinstance(out, InboundMessage)
|
||||||
assert "ship it" in ctx.msg.content
|
assert out.content == "ship it"
|
||||||
assert len(ctx.turn_scopes) == 1
|
assert out.metadata["goal_requested"] is True
|
||||||
with ctx.turn_scopes[0]:
|
|
||||||
assert goal_mutation_allowed() is True
|
|
||||||
assert goal_mutation_allowed() is False
|
assert goal_mutation_allowed() is False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
|
async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
|
||||||
loop = _make_loop(tmp_path)
|
loop = _make_loop(tmp_path)
|
||||||
@@ -321,7 +315,7 @@ async def test_goal_command_does_not_allow_internal_turn(tmp_path) -> None:
|
|||||||
|
|
||||||
out = await cmd_goal(ctx)
|
out = await cmd_goal(ctx)
|
||||||
|
|
||||||
assert out is not None
|
assert isinstance(out, OutboundMessage)
|
||||||
assert "only be started by a user" in out.content
|
assert "only be started by a user" in out.content
|
||||||
assert ctx.turn_scopes == []
|
assert ctx.turn_scopes == []
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -59,7 +59,8 @@ Type `@` to complete installed CLI apps, configured MCP servers, or saved sessio
|
|||||||
same gateway metadata used by the WebUI. While nanobot is working, `Enter` sends immediately,
|
same gateway metadata used by the WebUI. While nanobot is working, `Enter` sends immediately,
|
||||||
`Tab` waits until the current response is finished, and `Option+Up` on macOS (`Alt+Up` on
|
`Tab` waits until the current response is finished, and `Option+Up` on macOS (`Alt+Up` on
|
||||||
Windows/Linux) returns the latest waiting message to the composer for editing. Waiting messages
|
Windows/Linux) returns the latest waiting message to the composer for editing. Waiting messages
|
||||||
stay visible above the composer.
|
stay visible above the composer. `/goal <task>` follows the same keys: `Enter` sends the goal
|
||||||
|
into the running conversation, while `Tab` waits for the current response to finish.
|
||||||
Use `Shift+Enter` for a newline; `Ctrl+J` is the universal fallback when a terminal cannot
|
Use `Shift+Enter` for a newline; `Ctrl+J` is the universal fallback when a terminal cannot
|
||||||
distinguish modified Enter keys. `Alt+Enter` and `Ctrl+Enter` are also accepted when distinguishable.
|
distinguish modified Enter keys. `Alt+Enter` and `Ctrl+Enter` are also accepted when distinguishable.
|
||||||
Unsent prompts return to the composer if the turn stops or fails.
|
Unsent prompts return to the composer if the turn stops or fails.
|
||||||
|
|||||||
+3
-11
@@ -2227,8 +2227,8 @@ export class NanobotTui {
|
|||||||
this.markSubmitUnsent()
|
this.markSubmitUnsent()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (this.activeTurn && lifecycle === "agent_turn") {
|
if (lifecycle === "agent_turn") {
|
||||||
this.status.content = "A turn is already running · Ctrl+C to stop"
|
this.sendPrompt({ content, options }, this.activeTurn)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
let turnId: string
|
let turnId: string
|
||||||
@@ -2247,15 +2247,7 @@ export class NanobotTui {
|
|||||||
if (!silent && lifecycle !== "stop_active_turn") this.transcript.user(content)
|
if (!silent && lifecycle !== "stop_active_turn") this.transcript.user(content)
|
||||||
if (!silent) this.recordPrompt(content)
|
if (!silent) this.recordPrompt(content)
|
||||||
|
|
||||||
if (lifecycle === "agent_turn") {
|
if (lifecycle === "finalize_active_turn") {
|
||||||
this.host.reportTitle(content)
|
|
||||||
this.activeTurnId = turnId
|
|
||||||
this.finalMessage = ""
|
|
||||||
this.turnHadAnswer = false
|
|
||||||
this.activeLabel = "Thinking"
|
|
||||||
this.currentFileEdits = []
|
|
||||||
this.setActive(true)
|
|
||||||
} else if (lifecycle === "finalize_active_turn") {
|
|
||||||
this.activeTurnId = null
|
this.activeTurnId = null
|
||||||
this.transcript.finishStream(this.turnHadAnswer ? "" : this.finalMessage)
|
this.transcript.finishStream(this.turnHadAnswer ? "" : this.finalMessage)
|
||||||
this.transcript.finishActivity()
|
this.transcript.finishActivity()
|
||||||
|
|||||||
@@ -407,6 +407,55 @@ describe("NanobotTui composer", () => {
|
|||||||
expect(disposed).toBeTrue()
|
expect(disposed).toBeTrue()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test.each(["enter", "tab"])("submits a running goal with %s", async (key) => {
|
||||||
|
const sent: string[] = []
|
||||||
|
setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })
|
||||||
|
const transport = client(sent)
|
||||||
|
transport.send = (content) => {
|
||||||
|
sent.push(content)
|
||||||
|
return sent.length === 1 ? "active" : "followup"
|
||||||
|
}
|
||||||
|
const app = NanobotTui.mount(
|
||||||
|
setup.renderer, options, transport,
|
||||||
|
new MockTreeSitterClient({ autoResolveTimeout: 0 }),
|
||||||
|
)
|
||||||
|
app.accept({ event: "attached", chat_id: "chat" })
|
||||||
|
const ui = app as unknown as {
|
||||||
|
ready: boolean
|
||||||
|
activeTurnId: string | null
|
||||||
|
composer: TextareaRenderable
|
||||||
|
commandMenu: { setCommands(commands: SlashCommand[]): void }
|
||||||
|
queuePreview: { root: { visible: boolean } }
|
||||||
|
}
|
||||||
|
await waitUntil(() => ui.ready)
|
||||||
|
ui.commandMenu.setCommands([{
|
||||||
|
command: "/goal",
|
||||||
|
title: "Goal",
|
||||||
|
description: "Start sustained work",
|
||||||
|
argHint: "<goal>",
|
||||||
|
lifecycle: "agent_turn_with_args",
|
||||||
|
acceptsArgs: true,
|
||||||
|
}])
|
||||||
|
ui.composer.setText("Discuss the migration plan")
|
||||||
|
setup.mockInput.pressEnter()
|
||||||
|
await waitUntil(() => sent.length === 1)
|
||||||
|
await waitUntil(() => ui.activeTurnId === "active")
|
||||||
|
|
||||||
|
const goal = "/goal implement the plan we discussed"
|
||||||
|
ui.composer.setText(goal)
|
||||||
|
if (key === "enter") setup.mockInput.pressEnter()
|
||||||
|
else setup.mockInput.pressTab()
|
||||||
|
await waitUntil(() => ui.composer.plainText === "")
|
||||||
|
|
||||||
|
expect(sent).toEqual(key === "enter" ? ["Discuss the migration plan", goal] : ["Discuss the migration plan"])
|
||||||
|
expect(ui.activeTurnId).toBe("active")
|
||||||
|
expect(ui.queuePreview.root.visible).toBe(key === "tab")
|
||||||
|
app.accept({ event: "turn_end", chat_id: "chat", turn_id: "active" })
|
||||||
|
await waitUntil(() => sent.length === 2)
|
||||||
|
expect(sent).toEqual(["Discuss the migration plan", goal])
|
||||||
|
expect(ui.queuePreview.root.visible).toBeFalse()
|
||||||
|
})
|
||||||
|
|
||||||
test("steers with Enter, queues with Tab, and restores queued text with Alt+Up", async () => {
|
test("steers with Enter, queues with Tab, and restores queued text with Alt+Up", async () => {
|
||||||
const sent: string[] = []
|
const sent: string[] = []
|
||||||
const sentOptions: MessageOptions[] = []
|
const sentOptions: MessageOptions[] = []
|
||||||
|
|||||||
Reference in new issue
Block a user