From 9a9117967e3c007f394c082fed02c9fe0807ead9 Mon Sep 17 00:00:00 2001 From: david-dev666 <310195620+david-dev666@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:26:01 +0800 Subject: [PATCH] feat(cron): expose recent run history to the agent --- docs/automations.md | 6 ++ nanobot/agent/tools/cron.py | 32 +++++++-- nanobot/skills/cron/SKILL.md | 6 ++ tests/cron/test_cron_tool_history.py | 97 ++++++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 tests/cron/test_cron_tool_history.py diff --git a/docs/automations.md b/docs/automations.md index 5e6c72748..25ee6a24c 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -68,6 +68,12 @@ Ask nanobot to pause a scheduled task instead of removing it. The agent can use 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. +### Inspect Recent Runs + +Ask nanobot, "Show the last five runs of my daily report." The agent can use `cron(action="history", job_id="...", limit=5)` to read the retained execution time, status, duration, and error for that task. Results are newest first, using the task's timezone or the runtime default. The default is five records; `limit` accepts 1–20. + +This also works for disabled tasks and does not change their schedule or state. Only retained execution records are available: deleted jobs and automatically deleted one-time tasks cannot be queried. Run history does not include the generated reply or confirm message delivery. + ### 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. diff --git a/nanobot/agent/tools/cron.py b/nanobot/agent/tools/cron.py index f5b59844a..08139a00f 100644 --- a/nanobot/agent/tools/cron.py +++ b/nanobot/agent/tools/cron.py @@ -22,7 +22,9 @@ 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", "enable", "disable"]), + action=StringSchema( + "Action to perform", enum=["add", "list", "remove", "update", "enable", "disable", "history"] + ), 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. " @@ -43,9 +45,11 @@ _CRON_PARAMETERS = tool_parameters_schema( "Naive values use the tool's default timezone." ), job_id=StringSchema( - "REQUIRED when action='remove', 'update', 'enable', or 'disable'. Job ID (obtain via action='list')." + "REQUIRED when action='remove', 'update', 'enable', 'disable', or 'history'. " + "Job ID (obtain via action='list')." ), include_disabled=BooleanSchema(description="Include disabled jobs when action='list'."), + limit=IntegerSchema(description="Maximum runs for action='history'; defaults to 5.", minimum=1, maximum=20), required=["action"], description=( "add requires exactly one schedule: every_seconds, cron_expr, or at. " @@ -113,7 +117,7 @@ class CronTool(Tool): @property def description(self) -> str: return ( - "Schedule reminders and recurring tasks. Actions: add, list, remove, update, enable, disable. " + "Schedule reminders and recurring tasks. Actions: add, list, remove, update, enable, disable, history. " f"New cron schedules and naive ISO times default to {self._default_timezone}. " "Updates retain the existing cron timezone when tz is omitted." ) @@ -123,7 +127,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", "enable", "disable"} and not str(params.get("job_id") or "").strip(): + if action in {"remove", "update", "enable", "disable", "history"} and not str(params.get("job_id") or "").strip(): errors.append(f"job_id is required when action='{action}'") return errors @@ -138,6 +142,7 @@ class CronTool(Tool): at: str | None = None, job_id: str | None = None, include_disabled: bool = False, + limit: int = 5, ) -> str: if action == "add": request = current_request_context() @@ -152,6 +157,8 @@ class CronTool(Tool): 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") + elif action == "history": + return self._job_history(job_id, limit) return f"Unknown action: {action}" def _add_job( @@ -340,6 +347,23 @@ class CronTool(Tool): self._cron.enable_job(job_id, enabled=enabled) return f"{'Enabled' if enabled else 'Disabled'} job {job_id}" + def _job_history(self, job_id: str | None, limit: int) -> str: + if not job_id: + return ToolResult.error("Error: job_id is required for history") + job = self._cron.get_job(job_id) + if job is None: + return ToolResult.error(f"Error: job {job_id} not found") + if not job.state.run_history: + return f"No recorded runs for job {job_id}." + lines = [f"Recent runs for '{job.name}' (id: {job.id}), newest first:"] + display_tz = self._display_timezone(job.schedule) + for run in reversed(job.state.run_history[-limit:]): + timestamp = self._format_timestamp(run.run_at_ms, display_tz) + lines.append(f"- {timestamp} — {run.status} ({run.duration_ms}ms)") + if run.error: + lines.append(f" Error: {run.error}") + return "\n".join(lines) + def _remove_job(self, job_id: str | None) -> str: if not job_id: return ToolResult.error("Error: job_id is required for remove") diff --git a/nanobot/skills/cron/SKILL.md b/nanobot/skills/cron/SKILL.md index bf617bdca..3fb30d37a 100644 --- a/nanobot/skills/cron/SKILL.md +++ b/nanobot/skills/cron/SKILL.md @@ -76,3 +76,9 @@ Use `tz` with `cron_expr` to schedule in a specific IANA timezone. New tasks use 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. + +## Run History + +Use `cron(action="history", job_id="...", limit=5)` to inspect recent executions, newest first. Each entry includes its time, status, duration in milliseconds, and any error. `job_id` is required; `limit` defaults to 5 and accepts 1–20. Listing jobs still shows only the last run. + +History can be inspected for disabled jobs too. The scheduler retains at most 20 runs per job; deleted jobs, including automatically deleted one-time tasks, cannot be queried. This reads execution records, not task output or delivery receipts. diff --git a/tests/cron/test_cron_tool_history.py b/tests/cron/test_cron_tool_history.py new file mode 100644 index 000000000..5c27574e9 --- /dev/null +++ b/tests/cron/test_cron_tool_history.py @@ -0,0 +1,97 @@ +"""Inspect persisted cron executions through the agent tool.""" + +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import pytest + +from nanobot.agent.tools.cron import CronTool +from nanobot.agent.tools.registry import ToolRegistry +from nanobot.cron import service as cron_service +from nanobot.cron.service import CronJobSkippedError, CronService +from nanobot.cron.types import CronSchedule + + +def _registry(service: CronService) -> ToolRegistry: + registry = ToolRegistry() + registry.register(CronTool(service)) + return registry + + +def _job(service: CronService): + return service.add_job( + name="Daily report", + schedule=CronSchedule(kind="cron", expr="0 9 * * *", tz="America/Denver"), + message="Check open pull requests", + session_key="websocket:chat-1", origin_channel="websocket", origin_chat_id="chat-1", + ) + + +async def test_history_reads_recent_runs_without_changing_job(tmp_path: Path, monkeypatch) -> None: + now = 1773673200000 + monkeypatch.setattr(cron_service, "_now_ms", lambda: now) + outcomes = iter(["ok"] * 5 + ["error", "skipped"]) + + async def run(_job): + nonlocal now + now += 125 + outcome = next(outcomes) + if outcome == "error": + raise RuntimeError("Report failed") + if outcome == "skipped": + raise CronJobSkippedError("Chat busy") + return "Report ready" + + path = tmp_path / "jobs.json" + service = CronService(path, on_job=run) + job = _job(service) + for _ in range(7): + await service.run_job(job.id, force=True) + now += 60_000 + service.enable_job(job.id, enabled=False) + reloaded = CronService(path) + saved_job = reloaded.get_job(job.id) + assert saved_job is not None + before = path.read_bytes() + registry = _registry(reloaded) + + default = await registry.execute("cron", {"action": "history", "job_id": job.id}) + assert len([line for line in default.splitlines() if line.startswith("- ")]) == 5 + limited = await registry.execute("cron", {"action": "history", "job_id": job.id, "limit": 2}) + assert "Report failed" in limited and "Chat busy" in limited + assert "125ms" in limited and "America/Denver" in limited + assert "ok" not in limited + assert limited.index("skipped") < limited.index("error") + latest = saved_job.state.run_history[-1] + timestamp = datetime.fromtimestamp(latest.run_at_ms / 1000, ZoneInfo("America/Denver")).isoformat() + assert timestamp in limited + assert path.read_bytes() == before + + +async def test_history_reports_no_runs_for_existing_job(tmp_path: Path) -> None: + service = CronService(tmp_path / "jobs.json") + job = _job(service) + result = await _registry(service).execute("cron", {"action": "history", "job_id": job.id}) + assert "No recorded runs" in result + assert job.id in result + + +async def test_history_requires_job_id(tmp_path: Path) -> None: + result = await _registry(CronService(tmp_path / "jobs.json")).execute("cron", {"action": "history"}) + assert "job_id is required" in result + + +async def test_history_reports_unknown_job(tmp_path: Path) -> None: + result = await _registry(CronService(tmp_path / "jobs.json")).execute( + "cron", {"action": "history", "job_id": "missing"}, + ) + assert "job missing not found" in result + + +@pytest.mark.parametrize("limit", [0, 21]) +async def test_history_validates_limit(tmp_path: Path, limit: int) -> None: + result = await _registry(CronService(tmp_path / "jobs.json")).execute( + "cron", {"action": "history", "job_id": "test", "limit": limit}, + ) + assert "limit must be" in result