feat(cron): update scheduled tasks in place

This commit is contained in:
david-dev666 authored and Xubin Ren committed 2026-10-25 13:42:15 +08:00
1 parent 9650f4fd5b
commit 60fd7c1a64
4 files changed
+229 -30

No files matched your search

+6
View File
@@ -56,6 +56,12 @@ Repetition alone does not select heartbeat. "Every day at 8am, remind me to drin
An upgrade does not overwrite your workspace's `AGENTS.md` or convert existing heartbeat entries into cron jobs. The current scheduling rules are included in the system prompt. If an old workspace rule directs all recurring tasks to heartbeat, update that rule too. To correct an existing reminder, remove its old heartbeat entry and create the cron task once. Check the task list to avoid duplicates.
### Change a Scheduled Task
Ask nanobot, "Move my daily report from 9am to 10am." The agent can use `cron(action="update", job_id="...", cron_expr="0 10 * * *")` without deleting and recreating the task. It can also update `name` or `message` independently. Supply one complete schedule when changing its timing; omitted fields keep their values. Cron edits retain the existing timezone unless another `tz` is supplied with the expression. Naive `at` values use the runtime default timezone.
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.
### 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.
+71 -29
View File
@@ -21,8 +21,8 @@ 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"]),
name=StringSchema("Job label; generated from message if omitted."),
action=StringSchema("Action to perform", enum=["add", "list", "remove", "update"]),
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. "
"The final reply goes to the task's saved chat automatically. "
@@ -34,16 +34,18 @@ _CRON_PARAMETERS = tool_parameters_schema(
),
cron_expr=StringSchema("Cron expression like '0 9 * * *' (for scheduled tasks)"),
tz=StringSchema(
"IANA timezone for cron_expr only, e.g. 'America/Vancouver'."
"IANA timezone for cron_expr only, e.g. 'America/Vancouver'. "
"For update, omitting tz retains the existing cron timezone."
),
at=StringSchema(
"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'. Job ID to remove (obtain via action='list')."),
job_id=StringSchema("REQUIRED when action='remove' or action='update'. Job ID (obtain via action='list')."),
required=["action"],
description=(
"add requires exactly one schedule: every_seconds, cron_expr, or at."
"add requires exactly one schedule: every_seconds, cron_expr, or at. "
"update changes only supplied fields and requires name, message, or one schedule."
),
)
@@ -107,8 +109,9 @@ class CronTool(Tool):
@property
def description(self) -> str:
return (
"Schedule reminders and recurring tasks. Actions: add, list, remove. "
f"If tz is omitted, cron expressions and naive ISO times default to {self._default_timezone}."
"Schedule reminders and recurring tasks. Actions: add, list, remove, update. "
f"New cron schedules and naive ISO times default to {self._default_timezone}. "
"Updates retain the existing cron timezone when tz is omitted."
)
def validate_params(self, params: dict[str, Any]) -> list[str]:
@@ -116,15 +119,15 @@ 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 == "remove" and not str(params.get("job_id") or "").strip():
errors.append("job_id is required when action='remove'")
if action in {"remove", "update"} and not str(params.get("job_id") or "").strip():
errors.append(f"job_id is required when action='{action}'")
return errors
async def execute(
self,
action: str,
name: str | None = None,
message: str = "",
message: str | None = None,
every_seconds: int | None = None,
cron_expr: str | None = None,
tz: str | None = None,
@@ -135,11 +138,13 @@ class CronTool(Tool):
request = current_request_context()
if request is not None and is_cron_turn(request.metadata):
return ToolResult.error("Error: cannot schedule new jobs from within a cron job execution")
return self._add_job(name, message, every_seconds, cron_expr, tz, at)
return self._add_job(name, message or "", every_seconds, cron_expr, tz, at)
elif action == "list":
return self._list_jobs()
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)
return f"Unknown action: {action}"
def _add_job(
@@ -162,6 +167,28 @@ class CronTool(Tool):
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
if not origin_channel or not origin_chat_id:
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
if cron_expr and not tz:
tz = self._default_timezone
schedule = self._parse_schedule(every_seconds, cron_expr, tz, at)
if isinstance(schedule, str):
return schedule
job = self._cron.add_job(
name=name or message[:30],
schedule=schedule,
message=message,
delete_after_run=schedule.kind == "at",
session_key=session_key,
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
origin_metadata=origin_metadata,
)
return f"Created job '{job.name}' (id: {job.id})"
def _parse_schedule(
self, every_seconds: int | None, cron_expr: str | None,
tz: str | None, at: str | None,
) -> CronSchedule | str:
if tz and not cron_expr:
return ToolResult.error("Error: tz can only be used with cron_expr")
if tz:
@@ -176,17 +203,12 @@ class CronTool(Tool):
"Error: exactly one of every_seconds, cron_expr, or at is required"
)
# Build schedule
delete_after = False
if every_seconds is not None:
if every_seconds <= 0:
return ToolResult.error("Error: every_seconds must be a positive integer")
schedule = CronSchedule(kind="every", every_ms=every_seconds * 1000)
elif cron_expr:
effective_tz = tz or self._default_timezone
if err := self._validate_timezone(effective_tz):
return err
schedule = CronSchedule(kind="cron", expr=cron_expr, tz=effective_tz)
schedule = CronSchedule(kind="cron", expr=cron_expr, tz=tz)
elif at:
from zoneinfo import ZoneInfo
@@ -205,21 +227,41 @@ class CronTool(Tool):
"Retry with a future ISO datetime computed from the current time."
)
schedule = CronSchedule(kind="at", at_ms=at_ms)
delete_after = True
else:
return ToolResult.error("Error: either every_seconds, cron_expr, or at is required")
job = self._cron.add_job(
name=name or message[:30],
schedule=schedule,
message=message,
delete_after_run=delete_after,
session_key=session_key,
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
origin_metadata=origin_metadata,
)
return f"Created job '{job.name}' (id: {job.id})"
return schedule
def _update_job(
self, job_id: str | None, name: str | None, message: str | None,
every_seconds: int | None, cron_expr: str | None, tz: str | None, at: str | None,
) -> str:
if not job_id:
return ToolResult.error("Error: job_id is required for update")
if all(value is None for value in (name, message, every_seconds, cron_expr, tz, at)):
return ToolResult.error("Error: update requires at least one changed field")
for field, value in (("name", name), ("message", message)):
if value is not None and not value.strip():
return ToolResult.error(f"Error: {field} must not be empty")
job = self._cron.get_job(job_id)
if job is None:
return ToolResult.error(f"Error: job {job_id} not found")
schedule = None
if any(value is not None for value in (every_seconds, cron_expr, tz, at)):
if cron_expr and not tz:
tz = job.schedule.tz if job.schedule.kind == "cron" else self._default_timezone
schedule = self._parse_schedule(every_seconds, cron_expr, tz, at)
if isinstance(schedule, str):
return schedule
try:
result = self._cron.update_job(job_id, name=name, message=message, schedule=schedule)
except ValueError as exc:
return ToolResult.error(f"Error: {exc}")
if result == "protected":
return ToolResult.error("Error: system-managed cron jobs are protected")
if result == "not_found":
return ToolResult.error(f"Error: job {job_id} not found")
return f"Updated job '{result.name}' (id: {result.id})"
def _format_timing(self, schedule: CronSchedule) -> str:
"""Format schedule as a human-readable timing string."""
+7 -1
View File
@@ -60,4 +60,10 @@ cron(action="remove", job_id="abc123")
## Timezone
Use `tz` with `cron_expr` to schedule in a specific IANA timezone. Without `tz`, the server's local timezone is used.
Use `tz` with `cron_expr` to schedule in a specific IANA timezone. New tasks use the runtime default timezone when `tz` is omitted. Updates retain the task's existing cron timezone.
## Update a Task
Use `cron(action="update", job_id="...", cron_expr="0 10 * * *")` to change an existing task. Supply only the fields to change: `name`, `message`, or exactly one of `every_seconds`, `cron_expr`, and `at`. Omitted fields keep their values; empty names and instructions are rejected. A cron edit retains the existing timezone unless `tz` is supplied with `cron_expr`. Naive `at` values use the runtime default timezone.
Updates preserve the task ID, linked chat, history, enabled state, and automatic-deletion setting. Changing only the name or instruction does not move the next run. System-managed tasks cannot be edited.
+145
View File
@@ -0,0 +1,145 @@
"""Update scheduled tasks through the public tool boundary."""
from dataclasses import asdict
from datetime import datetime, timezone
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):
tools = ToolRegistry()
tools.register(CronTool(service, default_timezone="UTC"))
return tools
def _job(service, *, delete_after_run=False):
schedule = CronSchedule(kind="cron", expr="0 9 * * *", tz="America/Denver")
if delete_after_run:
schedule = CronSchedule(kind="at", at_ms=int(datetime(2099, 1, 2, tzinfo=timezone.utc).timestamp() * 1000))
return service.add_job(
name="Daily report", message="Check open issues",
schedule=schedule,
session_key="websocket:reports", origin_channel="websocket", origin_chat_id="reports",
delete_after_run=delete_after_run,
)
async def test_update_text_keeps_schedule_routing_and_history(tmp_path: Path):
async def run(_job):
return "Report ready"
path = tmp_path / "jobs.json"
service = CronService(path, on_job=run)
job = _job(service)
await service.run_job(job.id, force=True)
before = service.get_job(job.id)
identity = (before.id, asdict(before.schedule), before.state.next_run_at_ms, list(before.state.run_history))
route = (before.payload.session_key, before.payload.origin_channel, before.payload.origin_chat_id)
result = await _registry(service).execute("cron", {
"action": "update", "job_id": job.id, "name": "Issue report", "message": "Check only assigned issues",
})
assert "Updated" in result
saved = CronService(path).get_job(job.id)
assert saved.name == "Issue report" and saved.payload.message == "Check only assigned issues"
assert (saved.id, asdict(saved.schedule), saved.state.next_run_at_ms, saved.state.run_history) == identity
assert (saved.payload.session_key, saved.payload.origin_channel, saved.payload.origin_chat_id) == route
@pytest.mark.parametrize("tz, supplied_tz, expected", [
("America/Denver", None, "America/Denver"),
(None, None, None),
("America/Denver", "UTC", "UTC"),
])
async def test_update_cron_uses_supplied_or_existing_timezone(tmp_path: Path, tz, supplied_tz, expected):
service = CronService(tmp_path / "jobs.json")
job = _job(service)
service.update_job(job.id, schedule=CronSchedule(kind="cron", expr="0 9 * * *", tz=tz))
before = service.get_job(job.id)
next_run = before.state.next_run_at_ms
params = {"action": "update", "job_id": job.id, "cron_expr": "0 10 * * *"}
if supplied_tz is not None:
params["tz"] = supplied_tz
result = await _registry(service).execute("cron", params)
assert "Updated" in result
saved = service.get_job(job.id)
assert saved.schedule.expr == "0 10 * * *"
assert saved.schedule.tz == expected
assert saved.state.next_run_at_ms != next_run
assert saved.payload.message == "Check open issues"
async def test_update_keeps_disabled_task_disabled(tmp_path: Path):
service = CronService(tmp_path / "jobs.json")
job = _job(service)
service.enable_job(job.id, False)
result = await _registry(service).execute("cron", {
"action": "update", "job_id": job.id, "every_seconds": 120,
})
assert "Updated" in result
saved = service.get_job(job.id)
assert saved.schedule.kind == "every" and saved.schedule.every_ms == 120_000
assert not saved.enabled and saved.state.next_run_at_ms is None
@pytest.mark.parametrize("delete_after_run", [False, True])
async def test_update_preserves_existing_one_time_deletion_policy(tmp_path: Path, delete_after_run):
service = CronService(tmp_path / "jobs.json")
job = _job(service, delete_after_run=delete_after_run)
result = await _registry(service).execute("cron", {
"action": "update", "job_id": job.id, "at": "2099-01-01T09:00:00+00:00",
})
assert "Updated" in result
assert service.get_job(job.id).delete_after_run == delete_after_run
await service.run_job(job.id, force=True)
saved = service.get_job(job.id)
if delete_after_run:
assert saved is None
else:
assert saved is not None and not saved.enabled
assert len(saved.state.run_history) == 1
@pytest.mark.parametrize("changes, error", [
({}, "at least one"),
({"name": " "}, "name must not be empty"),
({"message": " "}, "message must not be empty"),
({"every_seconds": 30, "cron_expr": "0 10 * * *"}, "exactly one"),
({"name": "Renamed", "message": "New instruction", "cron_expr": "not a cron"}, "invalid cron expression"),
({"cron_expr": "0 10 * * *", "tz": "Bad/Zone"}, "unknown timezone"),
({"tz": "UTC"}, "tz can only"),
({"at": "2000-01-01T00:00:00+00:00"}, "not in the future"),
])
async def test_invalid_update_keeps_task_unchanged(tmp_path: Path, changes, error):
service = CronService(tmp_path / "jobs.json")
job = _job(service)
before = asdict(service.get_job(job.id))
result = await _registry(service).execute("cron", {"action": "update", "job_id": job.id, **changes})
assert error in result
assert asdict(service.get_job(job.id)) == before
async def test_update_requires_job_id(tmp_path: Path):
result = await _registry(CronService(tmp_path / "jobs.json")).execute("cron", {"action": "update", "name": "Renamed"})
assert "job_id is required" in result
async def test_update_reports_missing_task(tmp_path: Path):
result = await _registry(CronService(tmp_path / "jobs.json")).execute("cron", {"action": "update", "job_id": "missing", "name": "Renamed"})
assert "job missing not found" in result
async def test_update_protects_system_task(tmp_path: Path):
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"),
))
result = await _registry(service).execute("cron", {"action": "update", "job_id": job.id, "name": "Renamed"})
assert "protected" in result
assert service.get_job(job.id).name == "dream"