feat: reminders and scheduled tasks (schedule tool, app store and delivery)
The brain gets a schedule tool (add, list, delete the asker's own reminders, timers and tasks) offered only with a schedule backend. The voice worker asks the app through schedule_action and runs fired tasks as reply via task with read-only tools, no MCP and a fresh short-term memory. The app keeps the schedules in config/schedules.json, fires them every 5 s, speaks them when the person is in Jarvis's voice channel and otherwise posts in the chat channel they asked in (or schedule.chatChannel for voice). A feature switch and a 예약 screen list and delete everyone's schedules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
145
src/jarvis/tools/builtin/schedule.py
Normal file
145
src/jarvis/tools/builtin/schedule.py
Normal file
@@ -0,0 +1,145 @@
|
||||
"""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'])}")
|
||||
49
src/jarvis/tools/builtin/schedule.spec.md
Normal file
49
src/jarvis/tools/builtin/schedule.spec.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# schedule tool spec (v2)
|
||||
|
||||
Reminders, timers and scheduled tasks of the person asking. Product rules: `docs/v2/proactive.md`
|
||||
(제안 1). The app keeps the schedules, fires them and delivers them (`app/src/admin.spec.md`,
|
||||
"Schedules"); this tool only asks it to add, list or delete.
|
||||
|
||||
## Principles
|
||||
|
||||
- **Only in v2, only the asker's own.** The tool exists for a turn only when the v2 voice worker's
|
||||
brain put a schedule backend in the turn state (`turn_state.set_schedule`). Without one (v1, evals
|
||||
without a backend, and scheduled tasks themselves) it is not offered and refuses. The backend acts
|
||||
for the person asking only: they list and delete only what they scheduled themselves.
|
||||
- **Never claimed without the tool.** The description tells the model to call it for reminders,
|
||||
timers, alarms and things to check at a time or regularly, and never to say something was
|
||||
scheduled unless the tool said so (the "5분 타이머" confabulation, `docs/v2/decisions.md`).
|
||||
- **Tasks only look things up.** A `task` runs at its time with nobody there to ask, so it gets the
|
||||
read-only tools only (voice worker `TASK_TOOLS`: weather, web search, reading a page, the asker's
|
||||
meals, the tool search) and no MCP tools. It cannot send, delete, schedule or operate anything.
|
||||
- **Raw data.** The tool returns plain text for the reply model; no LLM call inside.
|
||||
|
||||
## Schema
|
||||
|
||||
| action | needs | does |
|
||||
|---|---|---|
|
||||
| `add` | `text`, `at` or `in_minutes` (`kind`, `repeat`) | schedules it; returns its id, kind, next time and repeat |
|
||||
| `list` | | the asker's schedules, soonest first |
|
||||
| `delete` | `id` | deletes one of the asker's schedules |
|
||||
|
||||
- `kind`: `remind` (default) tells `text` at the time; `task` does `text` at the time and tells the
|
||||
result.
|
||||
- `at`: local time of this PC, `YYYY-MM-DD HH:MM` (a `T` between and seconds are accepted).
|
||||
`in_minutes`: minutes from now (above 0), used instead of `at` when given; it spares the model
|
||||
the arithmetic for timers.
|
||||
- `repeat`: `none` (default), `daily`, `weekdays` (Monday to Friday), `weekly` (the weekday of `at`).
|
||||
A time that has passed is refused unless it repeats (the app then takes the next one).
|
||||
- `text`: whitespace collapsed, 1-500 characters.
|
||||
- `action`, `kind` and `repeat` are read as their first known word, so planner forms like
|
||||
`add_reminder` work. A refused add never reaches the app.
|
||||
- Lines: `- id <id>: <kind> at YYYY-MM-DD HH:MM (<weekday>)[, repeats <repeat>]: <text>`.
|
||||
|
||||
## Backend
|
||||
|
||||
`turn_state.get_schedule()` returns an object with `act(action, **fields) -> dict` (add: `kind`,
|
||||
`text`, `at`, `repeat`; delete: `schedule`, the schedule's id): `{"ok": true,
|
||||
"item": {...}}` for add and delete, `{"ok": true, "items": [...]}` for list, `{"ok": false, "error":
|
||||
"..."}` on failure. Items carry `id`, `kind`, `text`, `next` (Unix time) and `repeat`. The voice
|
||||
worker implements it (`voice_worker/schedule_bridge.py`): each action goes to the app as
|
||||
`schedule_action` with the asker and where they asked (voice_worker.spec.md, "Schedules").
|
||||
Failures come back as `Error: ...` text with `success=False`.
|
||||
@@ -17,6 +17,7 @@ from .builtin.nutrition.log_meal import LogMealTool
|
||||
from .builtin.nutrition.fetch_meals import FetchMealsTool
|
||||
from .builtin.nutrition.delete_meal import DeleteMealTool
|
||||
from .builtin.chat_channels import ChatChannelsTool
|
||||
from .builtin.schedule import ScheduleTool
|
||||
from .builtin.bot_browser import BotBrowserTool, CDP_ENV
|
||||
from .builtin.refresh_mcp_tools import RefreshMCPToolsTool
|
||||
from .builtin.weather import WeatherTool
|
||||
@@ -48,6 +49,7 @@ BUILTIN_TOOLS = {
|
||||
"controlBrowser": ControlBrowserTool(),
|
||||
"setBroadcast": SetBroadcastTool(),
|
||||
"chatChannels": ChatChannelsTool(),
|
||||
"schedule": ScheduleTool(),
|
||||
"botBrowser": BotBrowserTool(),
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user