- Schedules web UI (/settings/crons): list, add, edit, pause/resume, delete jobs - cron task type: full orchestrator tool loop on a schedule, result → notification channel - parse_schedule: monthly/yearly formats (monthly:DD:HH:MM, yearly:MM:DD:HH:MM) - HA inbound webhook tools toggle: orchestrator loop vs. direct LLM, configurable in UI - ae_db_query/describe/show_view: SELECT-only Aether MariaDB access (admin, per-user creds) - /settings/integrations: admin-only page for Aether DB credentials - Schedules nav link added to all settings pages - pymysql added to requirements - Docs updated: HELP.md, MASTER.md, CLAUDE.md Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
269 lines
9.6 KiB
Python
269 lines
9.6 KiB
Python
"""
|
|
Cron job management tools for Inara.
|
|
|
|
Jobs are stored in inara/CRONS.json and registered with the live APScheduler
|
|
instance so they survive restarts and take effect immediately without a restart.
|
|
|
|
Tools:
|
|
cron_list — show all scheduled jobs
|
|
cron_add — create a job and register it immediately
|
|
cron_remove — delete a job and unschedule it
|
|
cron_toggle — pause or resume a job without deleting it
|
|
reminders_clear — erase inara/REMINDERS.md (dismiss all pending reminders)
|
|
"""
|
|
|
|
import asyncio
|
|
import secrets
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from google.genai import types
|
|
from persona import persona_path, get_user, get_persona
|
|
from cron_runner import load_crons, save_crons, parse_schedule
|
|
|
|
|
|
def _now() -> str:
|
|
return datetime.now(timezone.utc).isoformat()
|
|
|
|
|
|
def _short_id() -> str:
|
|
return "c_" + secrets.token_urlsafe(6)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Sync implementations
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _cron_list() -> str:
|
|
crons = load_crons(get_user(), get_persona())
|
|
if not crons:
|
|
return "No crons scheduled."
|
|
|
|
lines = [f"Crons ({len(crons)}):\n"]
|
|
for c in crons:
|
|
status = "enabled" if c.get("enabled", True) else "PAUSED "
|
|
last = c.get("last_run")
|
|
last_str = last[:10] if last else "never"
|
|
lines.append(
|
|
f" {c['id']} [{status}] {c['schedule']:<18} "
|
|
f"{c['type']:<7} {c['label']} (last: {last_str})"
|
|
)
|
|
return "\n".join(lines)
|
|
|
|
|
|
def _cron_add(label: str, schedule: str, job_type: str, payload: str) -> str:
|
|
# Validate schedule first — raises ValueError with a clear message on bad input
|
|
try:
|
|
sched_kwargs = parse_schedule(schedule)
|
|
except ValueError as e:
|
|
return f"Bad schedule: {e}"
|
|
|
|
_VALID_TYPES = ("remind", "note", "message", "brief", "task")
|
|
if job_type not in _VALID_TYPES:
|
|
return f"Bad type: must be one of {', '.join(_VALID_TYPES)}."
|
|
|
|
current_user = get_user()
|
|
current_persona = get_persona()
|
|
crons = load_crons(current_user, current_persona)
|
|
job = {
|
|
"id": _short_id(),
|
|
"user": current_user,
|
|
"persona": current_persona,
|
|
"label": label,
|
|
"schedule": schedule,
|
|
"type": job_type,
|
|
"payload": payload,
|
|
"enabled": True,
|
|
"created_at": _now(),
|
|
"last_run": None,
|
|
}
|
|
crons.append(job)
|
|
save_crons(crons, current_user, current_persona)
|
|
|
|
# Register with the live scheduler
|
|
_scheduler_add(job, sched_kwargs)
|
|
|
|
return f"Created and scheduled: {job['id']} {schedule} [{job_type}] {label} (user: {current_user}, persona: {current_persona})"
|
|
|
|
|
|
def _cron_remove(cron_id: str) -> str:
|
|
user = get_user()
|
|
persona = get_persona()
|
|
crons = load_crons(user, persona)
|
|
before = len(crons)
|
|
crons = [c for c in crons if c["id"] != cron_id]
|
|
if len(crons) == before:
|
|
return f"Not found: {cron_id}"
|
|
save_crons(crons, user, persona)
|
|
_scheduler_remove(f"{user}:{persona}:{cron_id}")
|
|
return f"Removed: {cron_id}"
|
|
|
|
|
|
def _cron_toggle(cron_id: str) -> str:
|
|
user = get_user()
|
|
persona = get_persona()
|
|
crons = load_crons(user, persona)
|
|
for c in crons:
|
|
if c["id"] == cron_id:
|
|
c["enabled"] = not c.get("enabled", True)
|
|
save_crons(crons, user, persona)
|
|
action = "resumed" if c["enabled"] else "paused"
|
|
sched_id = f"{user}:{persona}:{cron_id}"
|
|
_scheduler_resume(sched_id) if c["enabled"] else _scheduler_pause(sched_id)
|
|
return f"{action.capitalize()}: {cron_id} {c['label']}"
|
|
return f"Not found: {cron_id}"
|
|
|
|
|
|
def _reminders_clear() -> str:
|
|
p = persona_path() / "REMINDERS.md"
|
|
p.write_text("")
|
|
return "Reminders cleared."
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Scheduler bridge — thin wrappers so the tool layer never touches APScheduler
|
|
# directly, keeping it swappable
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _scheduler_add(job: dict, sched_kwargs: dict) -> None:
|
|
try:
|
|
import scheduler as sched_module
|
|
from cron_runner import run_job
|
|
s = sched_module.get_scheduler()
|
|
if s and s.running:
|
|
sched_id = f"{job.get('user', 'scott')}:{job.get('persona', 'inara')}:{job['id']}"
|
|
s.add_job(
|
|
lambda j=job: asyncio.ensure_future(run_job(j)),
|
|
"cron",
|
|
id=sched_id,
|
|
replace_existing=True,
|
|
**sched_kwargs,
|
|
)
|
|
except Exception as e:
|
|
import logging
|
|
logging.getLogger(__name__).warning("scheduler_add failed: %s", e)
|
|
|
|
|
|
def _scheduler_remove(job_id: str) -> None:
|
|
try:
|
|
import scheduler as sched_module
|
|
s = sched_module.get_scheduler()
|
|
if s and s.running:
|
|
s.remove_job(job_id)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _scheduler_pause(job_id: str) -> None:
|
|
try:
|
|
import scheduler as sched_module
|
|
s = sched_module.get_scheduler()
|
|
if s and s.running:
|
|
s.pause_job(job_id)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _scheduler_resume(job_id: str) -> None:
|
|
try:
|
|
import scheduler as sched_module
|
|
s = sched_module.get_scheduler()
|
|
if s and s.running:
|
|
s.resume_job(job_id)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Async wrappers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
async def cron_list() -> str:
|
|
return await asyncio.to_thread(_cron_list)
|
|
|
|
|
|
async def cron_add(label: str, schedule: str, job_type: str, payload: str) -> str:
|
|
return await asyncio.to_thread(_cron_add, label, schedule, job_type, payload)
|
|
|
|
|
|
async def cron_remove(cron_id: str) -> str:
|
|
return await asyncio.to_thread(_cron_remove, cron_id)
|
|
|
|
|
|
async def cron_toggle(cron_id: str) -> str:
|
|
return await asyncio.to_thread(_cron_toggle, cron_id)
|
|
|
|
|
|
async def reminders_clear() -> str:
|
|
return await asyncio.to_thread(_reminders_clear)
|
|
|
|
|
|
DECLARATIONS = [
|
|
types.FunctionDeclaration(
|
|
name="cron_list",
|
|
description=(
|
|
"List all scheduled cron jobs — their ID, label, schedule, type, and last run time. "
|
|
"Use this to see what's scheduled before adding or removing jobs."
|
|
),
|
|
parameters=types.Schema(type=types.Type.OBJECT, properties={}),
|
|
),
|
|
types.FunctionDeclaration(
|
|
name="cron_add",
|
|
description=(
|
|
"Create a new scheduled cron job and register it immediately (no restart needed). "
|
|
"Job types: "
|
|
"'remind' — appends to REMINDERS.md, auto-surfaced in chat context at tier 2+; "
|
|
"'note' — appends to SCRATCH.md, read on demand; "
|
|
"'message' — sends payload text directly to the user's notification channel; "
|
|
"'brief' — calls the LLM (no tools) with payload as the prompt, sends the response; "
|
|
"'task' — runs the full orchestrator tool loop with payload as the request, sends "
|
|
"Claude's response to the notification channel (use for agentic scheduled work: "
|
|
"research, checks, file updates, summaries that need tool access). "
|
|
"Schedule formats: 'hourly' | 'daily' | 'daily:HH:MM' | 'weekly:DOW' | 'weekly:DOW:HH:MM' | "
|
|
"'monthly' | 'monthly:DD' | 'monthly:DD:HH:MM' | 'yearly:MM:DD' | 'yearly:MM:DD:HH:MM'. "
|
|
"Examples: schedule='weekly:mon:08:00' for Monday briefings; "
|
|
"schedule='monthly:1:09:00' for a first-of-month review; "
|
|
"schedule='yearly:03:15' for a March 15 birthday reminder."
|
|
),
|
|
parameters=types.Schema(
|
|
type=types.Type.OBJECT,
|
|
properties={
|
|
"label": types.Schema(type=types.Type.STRING, description="Short human-readable name for this job (e.g. 'Monday task summary')"),
|
|
"schedule": types.Schema(type=types.Type.STRING, description="When to run: hourly | daily | daily:HH:MM | weekly:DOW | weekly:DOW:HH:MM | monthly | monthly:DD | monthly:DD:HH:MM | yearly:MM:DD | yearly:MM:DD:HH:MM"),
|
|
"job_type": types.Schema(type=types.Type.STRING, description="remind | note | message | brief | task"),
|
|
"payload": types.Schema(type=types.Type.STRING, description="The text/prompt to use when the job fires"),
|
|
},
|
|
required=["label", "schedule", "job_type", "payload"],
|
|
),
|
|
),
|
|
types.FunctionDeclaration(
|
|
name="cron_remove",
|
|
description=(
|
|
"Permanently delete a scheduled cron job. Use cron_list first to get the ID. "
|
|
"To temporarily disable without deleting, use cron_toggle instead."
|
|
),
|
|
parameters=types.Schema(
|
|
type=types.Type.OBJECT,
|
|
properties={
|
|
"cron_id": types.Schema(type=types.Type.STRING, description="Job ID (e.g. c_abc123) — get from cron_list"),
|
|
},
|
|
required=["cron_id"],
|
|
),
|
|
),
|
|
types.FunctionDeclaration(
|
|
name="cron_toggle",
|
|
description=(
|
|
"Pause a running cron job, or resume a paused one. "
|
|
"The job stays in the list and can be re-enabled later. "
|
|
"Use cron_list to see current enabled/paused state."
|
|
),
|
|
parameters=types.Schema(
|
|
type=types.Type.OBJECT,
|
|
properties={
|
|
"cron_id": types.Schema(type=types.Type.STRING, description="Job ID (e.g. c_abc123) — get from cron_list"),
|
|
},
|
|
required=["cron_id"],
|
|
),
|
|
),
|
|
]
|