fix(goal): make cancellation a user-only control (#6667)
This commit is contained in:
1 parent
c927808aff
commit
12a86eaa86
33 files changed
+641
-63
No files matched your search
+77
-4
@@ -1,14 +1,27 @@
|
||||
"""Command adapter for explicitly starting a sustained goal."""
|
||||
"""User commands for starting and cancelling a sustained goal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from dataclasses import replace
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.command.router import CommandExpansion, CommandInput, CommandRouter
|
||||
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
|
||||
from nanobot.command.builtin import cmd_stop
|
||||
from nanobot.command.router import CommandContext, CommandExpansion, CommandInput, CommandRouter
|
||||
from nanobot.command.spec import BuiltinCommandSpec
|
||||
from nanobot.session.goal_state import GOAL_COMMAND
|
||||
from nanobot.session.goal_state import (
|
||||
GOAL_COMMAND,
|
||||
GOAL_STATE_KEY,
|
||||
discard_legacy_goal_state_key,
|
||||
goal_state_raw,
|
||||
parse_goal_state,
|
||||
)
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.session.sqlite_store import SessionConflictError
|
||||
from nanobot.utils.cancellation import shield_and_drain
|
||||
|
||||
GOAL_COMMAND_SPEC = BuiltinCommandSpec(
|
||||
GOAL_COMMAND,
|
||||
@@ -55,7 +68,67 @@ async def cmd_goal(ctx: CommandInput) -> CommandExpansion | OutboundMessage:
|
||||
)
|
||||
|
||||
|
||||
async def cmd_cancel_goal(ctx: CommandContext) -> OutboundMessage:
|
||||
"""Cancel a user's saved goal, stopping active goal work before committing."""
|
||||
def reply(content: str) -> OutboundMessage:
|
||||
return OutboundMessage(
|
||||
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id, content=content,
|
||||
metadata={**ctx.msg.metadata, "render_as": "text"},
|
||||
)
|
||||
|
||||
if not ctx.is_user_turn:
|
||||
return reply("Goals can only be cancelled by a user `/cancel_goal` command.")
|
||||
session = await ctx.loop.sessions.state.read_header(ctx.key)
|
||||
if session is None or not session.policy.persist:
|
||||
return reply("No goal to cancel.")
|
||||
if ctx.msg.session_generation is not None and ctx.msg.session_generation != session.generation:
|
||||
return reply("The session changed. Try /cancel_goal again.")
|
||||
goal = parse_goal_state(goal_state_raw(session.metadata))
|
||||
if goal is None or goal.get("status") not in {"active", "blocked"}:
|
||||
return reply("No goal to cancel.")
|
||||
|
||||
if goal.get("status") == "active":
|
||||
await cmd_stop(ctx)
|
||||
|
||||
async def cancel_and_publish() -> bool:
|
||||
def cancel(metadata: dict[str, Any]) -> bool:
|
||||
current = parse_goal_state(goal_state_raw(metadata))
|
||||
if current is None or current.get("status") not in {"active", "blocked"}:
|
||||
return False
|
||||
metadata[GOAL_STATE_KEY] = {
|
||||
**current, "status": "cancelled", "ended_at": datetime.now().isoformat(),
|
||||
"recap": "Cancelled by user.",
|
||||
}
|
||||
discard_legacy_goal_state_key(metadata)
|
||||
return True
|
||||
|
||||
changed, metadata = await ctx.loop.sessions.state.mutate_metadata(
|
||||
ctx.key, cancel, expected_generation=session.generation,
|
||||
)
|
||||
await ctx.loop.bus.publish(GoalStateChanged(
|
||||
context=RuntimeEventContext(
|
||||
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id,
|
||||
session_key=ctx.key, metadata=dict(ctx.msg.metadata),
|
||||
),
|
||||
session_metadata=metadata,
|
||||
))
|
||||
return changed
|
||||
|
||||
try:
|
||||
changed = await shield_and_drain(cancel_and_publish())
|
||||
except SessionConflictError:
|
||||
return reply("The session changed. Try /cancel_goal again.")
|
||||
except (OSError, sqlite3.Error):
|
||||
return reply("Could not save the goal cancellation. Try /cancel_goal again.")
|
||||
return reply("Goal cancelled." if changed else "No goal to cancel.")
|
||||
|
||||
|
||||
def register_goal_command(router: CommandRouter) -> None:
|
||||
"""Register the exact usage and task-bearing forms of /goal."""
|
||||
"""Register goal input and user-only cancellation."""
|
||||
router.input_command(GOAL_COMMAND, cmd_goal)
|
||||
router.add_spec(GOAL_COMMAND_SPEC, after="/model")
|
||||
router.priority("/cancel_goal", cmd_cancel_goal)
|
||||
router.exact("/cancel_goal", cmd_cancel_goal)
|
||||
router.add_spec(BuiltinCommandSpec(
|
||||
"/cancel_goal", "Cancel goal", "Cancel the saved goal and stop active goal work.", "circle-x",
|
||||
), after=GOAL_COMMAND)
|
||||
+15
-23
@@ -33,7 +33,7 @@ if TYPE_CHECKING:
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
|
||||
_GOAL_ACTIONS = ("complete", "block", "replace")
|
||||
_CREATE_UNAVAILABLE_ERROR = (
|
||||
"Error: create_goal is unavailable for this turn. Ask the user to submit the complete "
|
||||
"objective as `/goal <task>`."
|
||||
@@ -179,7 +179,9 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
|
||||
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:
|
||||
goal = parse_goal_state(goal_state_raw(metadata))
|
||||
goal_blocked = isinstance(goal, dict) and goal.get("status") == "blocked"
|
||||
if not goal_start_requested and not goal_active and not goal_blocked:
|
||||
return None
|
||||
|
||||
guidance = render_template(
|
||||
@@ -187,6 +189,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
|
||||
strip=True,
|
||||
goal_start_requested=goal_start_requested,
|
||||
goal_active=goal_active,
|
||||
goal_blocked=goal_blocked,
|
||||
)
|
||||
state = wrap_runtime_context_lines(goal_state_runtime_lines(metadata))
|
||||
content = "\n\n".join(part for part in (guidance, state) if part)
|
||||
@@ -242,7 +245,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
|
||||
enum=_GOAL_ACTIONS,
|
||||
),
|
||||
recap=StringSchema(
|
||||
"Brief honest recap for the user. Required in practice for complete, cancel, and block.",
|
||||
"Brief honest recap for the user. Required in practice for complete and block.",
|
||||
max_length=8000,
|
||||
nullable=True,
|
||||
),
|
||||
@@ -261,7 +264,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
|
||||
)
|
||||
)
|
||||
class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
"""Complete, cancel, block, or replace the active sustained goal."""
|
||||
"""Complete, block, or replace an active goal."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -282,9 +285,9 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
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."
|
||||
"is actually achieved and verified, action='block' when progress is genuinely blocked "
|
||||
"or the user asks to stop, and action='replace' only when the requested objective changes. "
|
||||
"Only the user can cancel a goal, using /cancel_goal or the WebUI button."
|
||||
)
|
||||
|
||||
async def execute(
|
||||
@@ -299,14 +302,11 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
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."
|
||||
)
|
||||
return ToolResult.error("Error: action must be one of complete, block, or replace.")
|
||||
if not isinstance(prior, dict) or prior.get("status") != "active":
|
||||
return "No active goal to update."
|
||||
|
||||
if normalized == "replace":
|
||||
if not self._goal_mutation_allowed():
|
||||
@@ -335,11 +335,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
|
||||
|
||||
ended = _iso_now()
|
||||
status = {
|
||||
"complete": "completed",
|
||||
"cancel": "cancelled",
|
||||
"block": "blocked",
|
||||
}[normalized]
|
||||
status = {"complete": "completed", "block": "blocked"}[normalized]
|
||||
blob = {
|
||||
**prior,
|
||||
"status": status,
|
||||
@@ -351,11 +347,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
await self._save_goal_state(sess, blob, revoke_permission=True)
|
||||
|
||||
tail = (recap or "").strip()
|
||||
label = {
|
||||
"complete": "complete",
|
||||
"cancel": "cancelled",
|
||||
"block": "blocked",
|
||||
}[normalized]
|
||||
label = {"complete": "complete", "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