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
@@ -0,0 +1 @@
|
||||
"""Built-in sustained-goal feature."""
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Assemble the built-in sustained-goal feature at application entrypoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from nanobot.goal.command import register_goal_command
|
||||
from nanobot.goal.runtime import GOAL_GENERATION_VOLATILE_KEYS, GoalExecutionPolicy
|
||||
from nanobot.goal.tools import CreateGoalTool, UpdateGoalTool
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command.router import CommandRouter
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
def install_goal(
|
||||
sessions: SessionManager, bus: MessageBus, tools: ToolRegistry, commands: CommandRouter,
|
||||
) -> GoalExecutionPolicy:
|
||||
register_goal_command(commands)
|
||||
sessions.exclude_generation_metadata(GOAL_GENERATION_VOLATILE_KEYS)
|
||||
for tool in (CreateGoalTool.bind(sessions, bus), UpdateGoalTool.bind(sessions, bus)):
|
||||
if not tools.has(tool.name):
|
||||
tools.register(tool)
|
||||
return GoalExecutionPolicy(sessions.state)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Command adapter for explicitly starting a sustained goal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.command.router import CommandExpansion, CommandInput, CommandRouter
|
||||
from nanobot.command.spec import BuiltinCommandSpec
|
||||
from nanobot.session.goal_state import GOAL_COMMAND
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
|
||||
GOAL_COMMAND_SPEC = BuiltinCommandSpec(
|
||||
GOAL_COMMAND,
|
||||
"Start long-running goal",
|
||||
"Tell the agent to treat the request as a long-running goal.",
|
||||
"activity",
|
||||
"<goal>",
|
||||
lifecycle="agent_turn_with_args",
|
||||
accepts_args=True,
|
||||
)
|
||||
|
||||
|
||||
async def cmd_goal(ctx: CommandInput) -> CommandExpansion | OutboundMessage:
|
||||
"""Expand an explicit goal command into model-only input."""
|
||||
goal = ctx.args.strip()
|
||||
if not goal:
|
||||
return OutboundMessage(
|
||||
channel=ctx.msg.channel,
|
||||
chat_id=ctx.msg.chat_id,
|
||||
content="Usage: /goal <long-running task description>",
|
||||
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
||||
)
|
||||
if not ctx.is_user_turn:
|
||||
return OutboundMessage(
|
||||
channel=ctx.msg.channel,
|
||||
chat_id=ctx.msg.chat_id,
|
||||
content="Goal mode can only be started by a user `/goal <task>` command.",
|
||||
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
|
||||
)
|
||||
|
||||
return CommandExpansion(
|
||||
message=replace(
|
||||
ctx.msg,
|
||||
content=goal,
|
||||
metadata={
|
||||
**ctx.msg.metadata,
|
||||
"original_command": GOAL_COMMAND,
|
||||
"original_content": ctx.msg.content,
|
||||
"goal_requested": True,
|
||||
HIDDEN_HISTORY_META: {"kind": "goal_request"},
|
||||
},
|
||||
),
|
||||
temporary_session_error="Goals can't start in a temporary session. Use a persistent session for `/goal`.",
|
||||
)
|
||||
|
||||
|
||||
def register_goal_command(router: CommandRouter) -> None:
|
||||
"""Register the exact usage and task-bearing forms of /goal."""
|
||||
router.input_command(GOAL_COMMAND, cmd_goal)
|
||||
router.add_spec(GOAL_COMMAND_SPEC, after="/history")
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Authorization and in-run guidance for sustained goals."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from nanobot.agent.goal_permission import GoalInputScope
|
||||
from nanobot.session.goal_state import goal_state_runtime_lines, sustained_goal_active
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.session.state import SessionState
|
||||
|
||||
GOAL_GENERATION_VOLATILE_KEYS = frozenset({
|
||||
"goal_state", "thread_goal", "_sustained_goal_continuation_rounds",
|
||||
})
|
||||
|
||||
|
||||
class GoalExecutionScope(GoalInputScope):
|
||||
def __init__(
|
||||
self, state: SessionState, session_key: str | None, generation: str | None,
|
||||
*, persistent: bool,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._state = state
|
||||
self._session_key = session_key
|
||||
self._generation = generation
|
||||
self._persistent = persistent
|
||||
|
||||
async def continuation_prompt(self) -> str | None:
|
||||
key = self._session_key
|
||||
current = await self._state.read_header(key) if key and self._persistent else None
|
||||
if current is None or current.generation != self._generation:
|
||||
return None
|
||||
if not sustained_goal_active(current.metadata):
|
||||
return None
|
||||
lines = "\n".join(goal_state_runtime_lines(current.metadata))
|
||||
return (
|
||||
f"You have an active sustained goal:\n\n{lines}\n\n"
|
||||
"Please continue working toward the objective using your tools, or call update_goal "
|
||||
"with action='complete' if the work is truly finished. "
|
||||
"If required conditions are unavailable, use action='block' with an honest recap."
|
||||
)
|
||||
|
||||
|
||||
class GoalExecutionPolicy:
|
||||
def __init__(self, state: SessionState) -> None:
|
||||
self._state = state
|
||||
|
||||
def scope(
|
||||
self, session_key: str | None, generation: str | None, *, persistent: bool,
|
||||
) -> GoalExecutionScope:
|
||||
return GoalExecutionScope(self._state, session_key, generation, persistent=persistent)
|
||||
@@ -0,0 +1,361 @@
|
||||
# pyright: reportIncompatibleMethodOverride=false
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from nanobot.agent.goal_permission import (
|
||||
goal_mutation_allowed,
|
||||
revoke_goal_mutation_permission,
|
||||
)
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import RequestContext, current_request_context
|
||||
from nanobot.agent.tools.schema import StringSchema, tool_parameters_schema
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
|
||||
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
|
||||
from nanobot.session.goal_state import (
|
||||
GOAL_STATE_KEY,
|
||||
MAX_GOAL_OBJECTIVE_CHARS,
|
||||
discard_legacy_goal_state_key,
|
||||
explicit_goal_requested,
|
||||
goal_state_raw,
|
||||
goal_state_runtime_lines,
|
||||
parse_goal_state,
|
||||
sustained_goal_active,
|
||||
)
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
|
||||
_CREATE_UNAVAILABLE_ERROR = (
|
||||
"Error: create_goal is unavailable for this turn. Ask the user to submit the complete "
|
||||
"objective as `/goal <task>`."
|
||||
)
|
||||
_REPLACE_UNAVAILABLE_ERROR = (
|
||||
"Error: replacing the goal is unavailable for this turn. Ask the user to submit the "
|
||||
"replacement objective as `/goal <task>`."
|
||||
)
|
||||
|
||||
|
||||
def _iso_now() -> str:
|
||||
return datetime.now().isoformat()
|
||||
|
||||
|
||||
class _GoalToolsMixin:
|
||||
"""Shared routing context and session lookup."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sessions: SessionManager,
|
||||
bus: MessageBus | None = None,
|
||||
) -> None:
|
||||
self._sessions = sessions
|
||||
self._bus = bus
|
||||
|
||||
async def _session(self) -> Session | None:
|
||||
request_ctx = current_request_context()
|
||||
if request_ctx is None or not request_ctx.persist_session:
|
||||
return None
|
||||
key = request_ctx.session_key
|
||||
generation = request_ctx.session_generation
|
||||
if not key or not generation:
|
||||
return None
|
||||
session = await self._sessions.state.read_header(key)
|
||||
if session is None or session.generation != generation:
|
||||
return None
|
||||
return session
|
||||
|
||||
def _goal_mutation_allowed(self) -> bool:
|
||||
return current_request_context() is not None and goal_mutation_allowed()
|
||||
|
||||
async def _save_goal_state(
|
||||
self,
|
||||
sess: Session,
|
||||
blob: dict[str, Any],
|
||||
*,
|
||||
revoke_permission: bool = False,
|
||||
) -> None:
|
||||
saved = False
|
||||
|
||||
async def save_and_publish() -> None:
|
||||
nonlocal saved
|
||||
def change(metadata: dict[str, Any]) -> None:
|
||||
metadata[GOAL_STATE_KEY] = deepcopy(blob)
|
||||
discard_legacy_goal_state_key(metadata)
|
||||
_, sess.metadata = await self._sessions.state.mutate_metadata(
|
||||
sess.key, change, expected_generation=sess.generation,
|
||||
)
|
||||
saved = True
|
||||
await self._publish_goal_state_changed(sess.metadata)
|
||||
|
||||
try:
|
||||
await shield_and_drain(save_and_publish())
|
||||
finally:
|
||||
# This ContextVar belongs to the caller task, not the settlement task.
|
||||
if revoke_permission and saved:
|
||||
revoke_goal_mutation_permission()
|
||||
|
||||
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
|
||||
bus = self._bus
|
||||
rc = current_request_context()
|
||||
if bus is None or rc is None:
|
||||
return
|
||||
cid = (rc.chat_id or "").strip()
|
||||
if not cid:
|
||||
return
|
||||
await bus.publish(
|
||||
GoalStateChanged(
|
||||
context=RuntimeEventContext(
|
||||
channel=rc.channel,
|
||||
chat_id=cid,
|
||||
session_key=rc.session_key or f"{rc.channel}:{cid}",
|
||||
metadata=dict(rc.metadata or {}),
|
||||
),
|
||||
session_metadata=dict(metadata),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@tool_parameters(
|
||||
tool_parameters_schema(
|
||||
objective=StringSchema(
|
||||
"Self-contained goal with explicit completion criteria, bounded and safe to repeat. "
|
||||
"May incorporate prior discussion.",
|
||||
min_length=1,
|
||||
max_length=MAX_GOAL_OBJECTIVE_CHARS,
|
||||
),
|
||||
ui_summary=StringSchema(
|
||||
"One-line display label for session lists and logs; objective defines the goal.",
|
||||
max_length=120,
|
||||
nullable=True,
|
||||
),
|
||||
required=["objective"],
|
||||
)
|
||||
)
|
||||
class CreateGoalTool(Tool, _GoalToolsMixin):
|
||||
"""Create one explicit sustained objective for the current session."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sessions: SessionManager,
|
||||
bus: MessageBus | None = None,
|
||||
) -> None:
|
||||
_GoalToolsMixin.__init__(self, sessions, bus)
|
||||
|
||||
@classmethod
|
||||
def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:
|
||||
return cls(sessions=sessions, bus=bus)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "create_goal"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"Create one sustained goal for the current session only when Goal Runtime Guidance "
|
||||
"asks you to record it. Do not retry after successful creation."
|
||||
)
|
||||
|
||||
def runtime_context_provider(self):
|
||||
return self._provide_runtime_context
|
||||
|
||||
async def _provide_runtime_context(
|
||||
self,
|
||||
request: RequestContext,
|
||||
) -> RuntimeContextBlock | None:
|
||||
if not request.session_key or not request.persist_session:
|
||||
return None
|
||||
payload = await self._sessions.state.read_metadata(request.session_key)
|
||||
if payload is None:
|
||||
return None
|
||||
metadata = payload["metadata"]
|
||||
goal_start_requested = explicit_goal_requested(request.metadata)
|
||||
goal_active = sustained_goal_active(metadata)
|
||||
if not goal_start_requested and not goal_active:
|
||||
return None
|
||||
|
||||
guidance = render_template(
|
||||
"agent/goal_runtime.md",
|
||||
strip=True,
|
||||
goal_start_requested=goal_start_requested,
|
||||
goal_active=goal_active,
|
||||
)
|
||||
state = wrap_runtime_context_lines(goal_state_runtime_lines(metadata))
|
||||
content = "\n\n".join(part for part in (guidance, state) if part)
|
||||
return RuntimeContextBlock(source="goal", content=content)
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
objective: str,
|
||||
ui_summary: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
sess = await self._session()
|
||||
if sess is None:
|
||||
return ToolResult.error(
|
||||
"Error: create_goal requires an active chat session (missing routing context)."
|
||||
)
|
||||
if not self._goal_mutation_allowed():
|
||||
return ToolResult.error(_CREATE_UNAVAILABLE_ERROR)
|
||||
prior = parse_goal_state(goal_state_raw(sess.metadata))
|
||||
if isinstance(prior, dict) and prior.get("status") == "active":
|
||||
return ToolResult.error(
|
||||
"Error: a sustained goal is already active. Use update_goal with "
|
||||
"action='replace' only if the user explicitly changes the objective."
|
||||
)
|
||||
|
||||
objective_text = objective.strip()
|
||||
if not objective_text:
|
||||
return ToolResult.error("Error: objective must not be empty.")
|
||||
if len(objective_text) > MAX_GOAL_OBJECTIVE_CHARS:
|
||||
return ToolResult.error(
|
||||
f"Error: objective must not exceed {MAX_GOAL_OBJECTIVE_CHARS} characters."
|
||||
)
|
||||
summary = (ui_summary or "").strip()[:120]
|
||||
blob = {
|
||||
"status": "active",
|
||||
"objective": objective_text,
|
||||
"ui_summary": summary,
|
||||
"started_at": _iso_now(),
|
||||
}
|
||||
await self._save_goal_state(sess, blob)
|
||||
extra = f"\nSummary line: {summary}" if summary else ""
|
||||
return (
|
||||
"Goal recorded. Keep working toward the objective using ordinary tools. "
|
||||
"When fully done and verified, call update_goal with action='complete'."
|
||||
f"{extra}"
|
||||
)
|
||||
|
||||
|
||||
@tool_parameters(
|
||||
tool_parameters_schema(
|
||||
action=StringSchema(
|
||||
"How to update the active goal.",
|
||||
enum=_GOAL_ACTIONS,
|
||||
),
|
||||
recap=StringSchema(
|
||||
"Brief honest recap for the user. Required in practice for complete, cancel, and block.",
|
||||
max_length=8000,
|
||||
nullable=True,
|
||||
),
|
||||
objective=StringSchema(
|
||||
"Replacement objective. Required only when action is 'replace'; make it durable, "
|
||||
"self-contained, bounded, and explicit about done-ness.",
|
||||
max_length=MAX_GOAL_OBJECTIVE_CHARS,
|
||||
nullable=True,
|
||||
),
|
||||
ui_summary=StringSchema(
|
||||
"Optional one-line display label for a replacement goal.",
|
||||
max_length=120,
|
||||
nullable=True,
|
||||
),
|
||||
required=["action"],
|
||||
)
|
||||
)
|
||||
class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
"""Complete, cancel, block, or replace the active sustained goal."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sessions: SessionManager,
|
||||
bus: MessageBus | None = None,
|
||||
) -> None:
|
||||
_GoalToolsMixin.__init__(self, sessions, bus)
|
||||
|
||||
@classmethod
|
||||
def bind(cls, sessions: SessionManager, bus: MessageBus | None) -> Tool:
|
||||
return cls(sessions=sessions, bus=bus)
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "update_goal"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"Update the active sustained goal. Use action='complete' only after the objective "
|
||||
"is actually achieved and verified. Use action='cancel' when the user cancels, "
|
||||
"action='block' when progress is genuinely blocked, and action='replace' only when "
|
||||
"the requested objective changes."
|
||||
)
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
action: str,
|
||||
recap: str | None = None,
|
||||
objective: str | None = None,
|
||||
ui_summary: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
sess = await self._session()
|
||||
if sess is None:
|
||||
return ToolResult.error("Error: update_goal requires an active chat session.")
|
||||
prior = parse_goal_state(goal_state_raw(sess.metadata))
|
||||
if not isinstance(prior, dict) or prior.get("status") != "active":
|
||||
return "No active goal to update."
|
||||
|
||||
normalized = (action or "").strip().lower()
|
||||
if normalized not in _GOAL_ACTIONS:
|
||||
return ToolResult.error(
|
||||
"Error: action must be one of complete, cancel, block, or replace."
|
||||
)
|
||||
|
||||
if normalized == "replace":
|
||||
if not self._goal_mutation_allowed():
|
||||
return ToolResult.error(_REPLACE_UNAVAILABLE_ERROR)
|
||||
objective_text = (objective or "").strip()
|
||||
if not objective_text:
|
||||
return ToolResult.error(
|
||||
"Error: update_goal action='replace' requires a replacement objective."
|
||||
)
|
||||
if len(objective_text) > MAX_GOAL_OBJECTIVE_CHARS:
|
||||
return ToolResult.error(
|
||||
f"Error: objective must not exceed {MAX_GOAL_OBJECTIVE_CHARS} characters."
|
||||
)
|
||||
summary = (ui_summary or "").strip()[:120]
|
||||
blob = {
|
||||
"status": "active",
|
||||
"objective": objective_text,
|
||||
"ui_summary": summary,
|
||||
"started_at": _iso_now(),
|
||||
"replaced_at": _iso_now(),
|
||||
"previous_objective": str(prior.get("objective") or ""),
|
||||
"recap": (recap or "").strip(),
|
||||
}
|
||||
await self._save_goal_state(sess, blob)
|
||||
extra = f"\nSummary line: {summary}" if summary else ""
|
||||
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
|
||||
|
||||
ended = _iso_now()
|
||||
status = {
|
||||
"complete": "completed",
|
||||
"cancel": "cancelled",
|
||||
"block": "blocked",
|
||||
}[normalized]
|
||||
blob = {
|
||||
**prior,
|
||||
"status": status,
|
||||
"ended_at": ended,
|
||||
"recap": (recap or "").strip(),
|
||||
}
|
||||
if normalized == "complete":
|
||||
blob["completed_at"] = ended
|
||||
await self._save_goal_state(sess, blob, revoke_permission=True)
|
||||
|
||||
tail = (recap or "").strip()
|
||||
label = {
|
||||
"complete": "complete",
|
||||
"cancel": "cancelled",
|
||||
"block": "blocked",
|
||||
}[normalized]
|
||||
if tail:
|
||||
return f"Goal marked {label} ({ended}). Recap:\n{tail}"
|
||||
return f"Goal marked {label} ({ended})."
|
||||
Reference in new issue
Block a user