"""schedule: reminders and scheduled tasks of the person asking (v2). Contract: schedule.spec.md.""" from __future__ import annotations import re import time from datetime import datetime from typing import Any, Dict, Optional from ..base import Tool, ToolContext from ..types import ToolExecutionResult from ...debug import debug_log _ACTIONS = ("add", "list", "delete") _KINDS = ("remind", "task") _REPEATS = ("none", "daily", "weekdays", "weekly") _FORMATS = ("%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S") MAX_TEXT_CHARS = 500 def _fail(text: str) -> ToolExecutionResult: return ToolExecutionResult(success=False, reply_text=f"Error: {text}", error_message=text) def _ok(text: str) -> ToolExecutionResult: return ToolExecutionResult(success=True, reply_text=text) def _word(raw: Any, words: tuple) -> str: """The first known word, also from planner forms like "add_reminder" or "delete schedule".""" return next((w for w in re.findall(r"[a-z]+", str(raw or "").lower()) if w in words), "") def _local(ts: float) -> str: return time.strftime("%Y-%m-%d %H:%M (%a)", time.localtime(ts)) def _when(args: dict, now: float) -> Optional[float]: """The first time as a Unix time: ``in_minutes`` from now, or ``at`` in this PC's local time.""" minutes = args.get("in_minutes") if minutes not in (None, ""): try: m = float(minutes) except (TypeError, ValueError): return None return now + m * 60 if m > 0 else None at = str(args.get("at") or "").strip() for fmt in _FORMATS: try: return datetime.strptime(at, fmt).timestamp() except ValueError: continue return None def _line(item: dict) -> str: repeat = item.get("repeat") or "none" return (f"- id {item.get('id')}: {item.get('kind')} at {_local(float(item.get('next') or 0))}" f"{'' if repeat == 'none' else f', repeats {repeat}'}: {item.get('text')}") class ScheduleTool(Tool): @property def name(self) -> str: return "schedule" @property def description(self) -> str: return ( "Reminders, timers and scheduled tasks of the person asking. Call it whenever they ask to be " "reminded or told something later, to set a timer or alarm, to have something checked at a " "time or regularly (e.g. every morning), or to see or cancel what they scheduled. " "kind='remind' delivers a fixed message at that time; when what they want to hear then " "changes over time (weather, news, prices, a web search), use kind='task': text is looked " "up at that time and they hear the result. When they ask for it more than once, set repeat " "to match exactly (weekdays is Monday to Friday only). Write text in the language the " "person speaks. " "Never say something was scheduled unless this tool said so." ) @property def inputSchema(self) -> Dict[str, Any]: return { "type": "object", "properties": { "action": {"type": "string", "enum": list(_ACTIONS)}, "kind": {"type": "string", "enum": list(_KINDS), "description": "remind: a fixed message; task: look something up at that time"}, "text": {"type": "string", "description": "remind: the message to tell them; task: what to look up and tell"}, "at": {"type": "string", "description": "Local time YYYY-MM-DD HH:MM"}, "in_minutes": {"type": "number", "description": "Minutes from now, instead of at"}, "repeat": {"type": "string", "enum": list(_REPEATS), "description": "daily: every day; weekdays: Monday to Friday; weekly: once a week"}, "id": {"type": "string", "description": "delete: the id from list"}, }, "required": ["action"], } def run(self, args: Optional[Dict[str, Any]], context: ToolContext) -> ToolExecutionResult: from ...reply.turn_state import get_schedule backend = get_schedule() if backend is None: return _fail("scheduling is not available here") args = args if isinstance(args, dict) else {} action = _word(args.get("action"), _ACTIONS) if not action: return _fail(f"action must be one of {', '.join(_ACTIONS)}") debug_log(f"schedule {action}", "tools") if action == "list": result = backend.act("list") or {} if not result.get("ok"): return _fail(str(result.get("error") or "the list could not be read")) items = result.get("items") or [] return _ok(("Scheduled for this person:\n" + "\n".join(_line(i) for i in items)) if items else "Nothing is scheduled for this person.") if action == "delete": sid = str(args.get("id") or "").strip() if not sid: return _fail("delete needs id (call action='list' first)") result = backend.act("delete", schedule=sid) or {} if not result.get("ok"): return _fail(str(result.get("error") or "not deleted")) return _ok(f"Deleted: {_line(result['item'])}" if result.get("item") else "Deleted.") text = " ".join(str(args.get("text") or "").split()) if not text: return _fail("add needs text") if len(text) > MAX_TEXT_CHARS: return _fail(f"text must be at most {MAX_TEXT_CHARS} characters") kind = _word(args.get("kind"), _KINDS) or "remind" repeat = _word(args.get("repeat"), _REPEATS) or "none" now = time.time() at = _when(args, now) if at is None: return _fail("add needs at (local time YYYY-MM-DD HH:MM) or in_minutes above 0") if repeat == "none" and at <= now: return _fail(f"{_local(at)} has already passed (now {_local(now)})") result = backend.act("add", kind=kind, text=text, at=at, repeat=repeat) or {} if not result.get("ok"): return _fail(str(result.get("error") or "not scheduled")) return _ok(f"Scheduled: {_line(result['item'])}")