feat(cron): enable and disable jobs from the tool

This commit is contained in:
david-dev666 authored and Xubin Ren committed 2026-10-25 14:08:36 +08:00
1 parent 60fd7c1a64
commit f971712f4f
5 files changed
+163 -9

No files matched your search

+6
View File
@@ -62,6 +62,12 @@ Ask nanobot, "Move my daily report from 9am to 10am." The agent can use `cron(ac
The task keeps its ID, linked chat, execution history, enabled state, and automatic-deletion setting. A paused task stays paused. Changing only the name or instruction preserves the next run time. Existing tasks configured to delete after a one-time run still do so; tasks configured to remain keep that behavior. System-managed tasks remain protected. Invalid updates leave the task unchanged.
### Pause and Resume a Scheduled Task
Ask nanobot to pause a scheduled task instead of removing it. The agent can use `cron(action="disable", job_id="...")`, then `cron(action="enable", job_id="...")` to resume it with the same ID, schedule, chat, and run history. Use `cron(action="list", include_disabled=True)` to find paused tasks; the default list still shows only enabled jobs.
Disabling affects future runs. It does not cancel a running task or recall an already queued result. System-managed heartbeat and Dream jobs remain protected; change their configuration instead.
### Scheduled Result Delivery
The gateway saves final scheduled messages before it accepts them into the outgoing queue. This includes explicit `message` calls in existing tasks. Each recipient has a separate delivery record. Progress, reasoning, and streaming events do not enter this queue. WebUI streaming and saved chat history keep their existing behavior. External channels receive a complete scheduled reply instead of a streamed reply. Ordinary chat streaming is unchanged.
+30 -8
View File
@@ -11,17 +11,18 @@ from typing import Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ToolContext, current_request_context
from nanobot.agent.tools.schema import (
BooleanSchema,
IntegerSchema,
StringSchema,
tool_parameters_schema,
)
from nanobot.cron.service import CronService
from nanobot.cron.session_turns import is_cron_turn
from nanobot.cron.session_turns import is_bound_cron_job, is_cron_turn
from nanobot.cron.types import CronJob, CronJobState, CronSchedule
from nanobot.session.keys import UNIFIED_SESSION_KEY
_CRON_PARAMETERS = tool_parameters_schema(
action=StringSchema("Action to perform", enum=["add", "list", "remove", "update"]),
action=StringSchema("Action to perform", enum=["add", "list", "remove", "update", "enable", "disable"]),
name=StringSchema("Job label; generated from message for add if omitted."),
message=StringSchema(
"REQUIRED when action='add': non-empty instruction to execute when the job triggers. "
@@ -41,7 +42,10 @@ _CRON_PARAMETERS = tool_parameters_schema(
"ISO datetime for one-time execution (e.g. '2026-02-12T10:30:00'). "
"Naive values use the tool's default timezone."
),
job_id=StringSchema("REQUIRED when action='remove' or action='update'. Job ID (obtain via action='list')."),
job_id=StringSchema(
"REQUIRED when action='remove', 'update', 'enable', or 'disable'. Job ID (obtain via action='list')."
),
include_disabled=BooleanSchema(description="Include disabled jobs when action='list'."),
required=["action"],
description=(
"add requires exactly one schedule: every_seconds, cron_expr, or at. "
@@ -109,7 +113,7 @@ class CronTool(Tool):
@property
def description(self) -> str:
return (
"Schedule reminders and recurring tasks. Actions: add, list, remove, update. "
"Schedule reminders and recurring tasks. Actions: add, list, remove, update, enable, disable. "
f"New cron schedules and naive ISO times default to {self._default_timezone}. "
"Updates retain the existing cron timezone when tz is omitted."
)
@@ -119,7 +123,7 @@ class CronTool(Tool):
action = params.get("action")
if action == "add" and not str(params.get("message") or "").strip():
errors.append("message is required when action='add'")
if action in {"remove", "update"} and not str(params.get("job_id") or "").strip():
if action in {"remove", "update", "enable", "disable"} and not str(params.get("job_id") or "").strip():
errors.append(f"job_id is required when action='{action}'")
return errors
@@ -133,6 +137,7 @@ class CronTool(Tool):
tz: str | None = None,
at: str | None = None,
job_id: str | None = None,
include_disabled: bool = False,
) -> str:
if action == "add":
request = current_request_context()
@@ -140,11 +145,13 @@ class CronTool(Tool):
return ToolResult.error("Error: cannot schedule new jobs from within a cron job execution")
return self._add_job(name, message or "", every_seconds, cron_expr, tz, at)
elif action == "list":
return self._list_jobs()
return self._list_jobs(include_disabled=include_disabled)
elif action == "remove":
return self._remove_job(job_id)
elif action == "update":
return self._update_job(job_id, name, message, every_seconds, cron_expr, tz, at)
elif action in {"enable", "disable"}:
return self._set_job_enabled(job_id, enabled=action == "enable")
return f"Unknown action: {action}"
def _add_job(
@@ -303,14 +310,16 @@ class CronTool(Tool):
return "Dream memory consolidation for long-term memory."
return "System-managed internal job."
def _list_jobs(self) -> str:
jobs = self._cron.list_jobs()
def _list_jobs(self, include_disabled: bool = False) -> str:
jobs = self._cron.list_jobs(include_disabled=include_disabled)
if not jobs:
return "No scheduled jobs."
lines: list[str] = []
for j in jobs:
timing = self._format_timing(j.schedule)
parts = [f"- {j.name} (id: {j.id}, {timing})"]
if include_disabled:
parts.append(f" Status: {'enabled' if j.enabled else 'disabled'}")
if j.payload.kind == "system_event":
parts.append(f" Purpose: {self._system_job_purpose(j)}")
parts.append(" Protected: visible for inspection, but cannot be removed.")
@@ -318,6 +327,19 @@ class CronTool(Tool):
lines.append("\n".join(parts))
return "Scheduled jobs:\n" + "\n".join(lines)
def _set_job_enabled(self, job_id: str | None, *, enabled: bool) -> str:
if not job_id:
return ToolResult.error("Error: job_id is required for enable or disable")
job = self._cron.get_job(job_id)
if job is None:
return ToolResult.error(f"Error: job {job_id} not found")
if job.payload.kind == "system_event":
return ToolResult.error("Error: system-managed cron jobs are protected; change their configuration instead")
if enabled and not is_bound_cron_job(job):
return ToolResult.error("Error: job has no linked chat; recreate it from a chat session")
self._cron.enable_job(job_id, enabled=enabled)
return f"{'Enabled' if enabled else 'Disabled'} job {job_id}"
def _remove_job(self, job_id: str | None) -> str:
if not job_id:
return ToolResult.error("Error: job_id is required for remove")
+9
View File
@@ -47,6 +47,15 @@ cron(action="list")
cron(action="remove", job_id="abc123")
```
Pause and resume an existing task without deleting its schedule or run history:
```
cron(action="disable", job_id="abc123")
cron(action="list", include_disabled=True)
cron(action="enable", job_id="abc123")
```
Disabling a task stops future runs; it does not cancel a running task or recall a queued reply. System-managed jobs such as heartbeat and Dream are protected; change their configuration instead.
## Time Expressions
| User says | Parameters |
+117
View File
@@ -0,0 +1,117 @@
"""Agent-facing controls for existing scheduled jobs."""
import json
from dataclasses import asdict
from pathlib import Path
import pytest
from nanobot.agent.tools.cron import CronTool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.cron.service import CronService
from nanobot.cron.types import CronJob, CronPayload, CronSchedule
def _registry(service: CronService) -> ToolRegistry:
registry = ToolRegistry()
registry.register(CronTool(service))
return registry
async def test_pause_resume_preserves_job_and_history(tmp_path: Path) -> None:
store_path = tmp_path / "jobs.json"
async def complete(_job: CronJob) -> str:
return "Report completed"
service = CronService(store_path, on_job=complete)
job = service.add_job(
name="Morning report",
schedule=CronSchedule(kind="every", every_ms=60_000),
message="Summarize open pull requests",
session_key="websocket:chat-1",
origin_channel="websocket",
origin_chat_id="chat-1",
)
await service.run_job(job.id, force=True)
job = service.get_job(job.id)
assert job is not None and job.state.run_history
original = (job.id, asdict(job.schedule), asdict(job.payload), list(job.state.run_history))
registry = _registry(service)
await registry.execute("cron", {"action": "disable", "job_id": job.id})
paused = CronService(store_path).get_job(job.id)
assert paused is not None and not paused.enabled
assert paused.state.next_run_at_ms is None
assert job.name not in await registry.execute("cron", {"action": "list"})
listing = await registry.execute("cron", {"action": "list", "include_disabled": True})
assert job.name in listing and "disabled" in listing
await registry.execute("cron", {"action": "enable", "job_id": job.id})
resumed = CronService(store_path).get_job(job.id)
assert resumed is not None and resumed.enabled
assert resumed.state.next_run_at_ms is not None
assert (resumed.id, asdict(resumed.schedule), asdict(resumed.payload), resumed.state.run_history) == original
async def test_legacy_delivery_job_can_pause_and_resume_after_reload(tmp_path: Path) -> None:
path = tmp_path / "jobs.json"
path.write_text(json.dumps({"version": 1, "jobs": [{
"id": "legacy-1", "name": "Legacy reminder", "enabled": True,
"schedule": {"kind": "every", "everyMs": 60_000},
"payload": {"kind": "agent_turn", "message": "check status", "deliver": True,
"channel": "telegram", "to": "user-1", "channelMeta": {"message_thread_id": 42},
"sessionKey": "telegram:user-1:topic:42"},
"state": {}, "createdAtMs": 1, "updatedAtMs": 1,
}]}), encoding="utf-8")
for action, enabled in (("disable", False), ("enable", True)):
registry = _registry(CronService(path))
schema = json.dumps(registry.get_definitions(), sort_keys=True)
result = await registry.execute("cron", {"action": action, "job_id": "legacy-1"})
assert result.startswith("Enabled" if enabled else "Disabled")
assert json.dumps(registry.get_definitions(), sort_keys=True) == schema
listing = await registry.execute("cron", {"action": "list", "include_disabled": True})
assert "legacy-1" in listing
saved = CronService(path).get_job("legacy-1")
assert saved is not None and saved.enabled is enabled
assert saved.payload.session_key == "telegram:user-1:topic:42"
assert saved.payload.origin_channel == "telegram"
assert saved.payload.origin_chat_id == "user-1"
assert saved.payload.origin_metadata == {"message_thread_id": 42}
@pytest.mark.parametrize("action", ["enable", "disable"])
async def test_tool_cannot_toggle_system_job(tmp_path: Path, action: str) -> None:
service = CronService(tmp_path / "jobs.json")
job = service.register_system_job(CronJob(
id="dream",
name="dream",
schedule=CronSchedule(kind="every", every_ms=60_000),
payload=CronPayload(kind="system_event", message="dream"),
))
result = await _registry(service).execute("cron", {"action": action, "job_id": job.id})
assert "protected" in result
assert job.enabled
async def test_tool_cannot_enable_job_without_linked_chat(tmp_path: Path) -> None:
service = CronService(tmp_path / "jobs.json")
job = service.add_job(
name="Legacy job", schedule=CronSchedule(kind="every", every_ms=60_000), message="report",
)
result = await _registry(service).execute("cron", {"action": "enable", "job_id": job.id})
assert "linked chat" in result
assert not job.enabled
@pytest.mark.parametrize("action", ["enable", "disable"])
async def test_toggle_requires_job_id(tmp_path: Path, action: str) -> None:
registry = _registry(CronService(tmp_path / "jobs.json"))
result = await registry.execute("cron", {"action": action})
assert "job_id" in result and "required" in result
@pytest.mark.parametrize("action", ["enable", "disable"])
async def test_toggle_reports_missing_job(tmp_path: Path, action: str) -> None:
registry = _registry(CronService(tmp_path / "jobs.json"))
result = await registry.execute("cron", {"action": action, "job_id": "missing"})
assert "not found" in result
+1 -1
View File
@@ -21,7 +21,7 @@ from nanobot.agent.tools.registry import ToolRegistry
class _SvcStub:
"""Minimal CronService stand-in; we only exercise schema/dispatch paths."""
def list_jobs(self):
def list_jobs(self, include_disabled=False):
return []
def get_job(self, _job_id):