loopable / api /tool_groups /schedules.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
301db09 verified
Raw History Blame
9.53 kB
"""Schedule saved queries and inbox notes through the shared confirmation dispatcher."""
import copy
from fastapi import HTTPException
from core import external_access, external_tools, perm_scope
from deps import Session, err
import schedules as scheduler
from schedule_tools import _cron_from_phrase, _cron_in_words
def _context(ctx, *, write=False):
if not isinstance(ctx, external_tools.ToolContext) or not isinstance(ctx.session, Session):
raise err(403, "tool_context_required", "Use an authenticated AI connection.")
session = ctx.session
if perm_scope.ai_apps_refusal(session.user, session.runtime):
raise err(403, "ai_apps_off", "Your account does not have AI apps access.")
from routes_external import _assert_write_scope
if write:
_assert_write_scope(session, "schedules")
return session
def _database(ctx, database):
from routes_external import _assert_database_scope
_assert_database_scope(ctx.session, database)
ctx.describe_database(database)
def _scope(ctx):
"""Freeze the current account and credential intersection, including an empty scope."""
from routes_external import _key_scope
allowed = _key_scope(ctx.session)[1]
return sorted({row["database"] for row in ctx.list_databases()["databases"]
if row.get("permitted") and external_access.database_allowed(allowed, row["database"])})
def _visible(ctx, database):
if database is None:
return True
try:
_database(ctx, database)
except HTTPException as exc:
if exc.status_code not in (403, 404):
raise
return False
return True
def _item(item):
preview = copy.deepcopy(item.get("preview") or {})
if item.get("trigger") == "sync":
words = preview["inWords"]
cadence = preview["cadence"]
elif item.get("once"):
from loopy_reminders import once_in_words
words, cadence = once_in_words(item["onceAt"], item["tz"]), "once"
else:
words, cadence = _cron_in_words(item["cron"]), "repeat"
action = item["action"]
preview.update(database=action.get("database"),
filters=copy.deepcopy((action.get("payload") or {}).get("filters") or []),
inWords=words, cadence=cadence, timezone=item["tz"], nextRunAt=item["nextRunAt"])
if item.get("trigger") == "sync" and not item.get("syncFallback"):
preview["nextRun"] = "After the next successful sync."
else:
preview["nextRun"] = item["nextRunAt"]
return {**copy.deepcopy(item), "preview": preview, "inWords": words, "timezone": item["tz"]}
def _owned(ctx, args):
session = _context(ctx, write=True)
item = scheduler.get(session.runtime, args["id"])
if not item or item.get("system") or item.get("owner") != session.uname:
raise err(404, "tool_not_found", "There is no schedule with that ID.")
database = item["action"].get("database")
if database is not None:
_database(ctx, database)
return item
def create(ctx, args):
"""Preview a repeat, one-off query or one-off note, or a query after each successful sync."""
session = _context(ctx, write=True)
if sum(key in args for key in ("when", "once_at", "trigger")) != 1:
raise ValueError("Choose one repeat time, one-off time or sync trigger.")
if "text" in args:
if any(key in args for key in ("database", "payload", "words", "change")) or "once_at" not in args:
raise ValueError("Choose a one-off note or a saved query.")
action = {"kind": "reminder", "text": args["text"], "sendWhatsapp": False}
label = args.get("label", args["text"])
else:
if not all(key in args for key in ("database", "payload", "words")):
raise ValueError("A saved query needs its database, query arguments and your request in words.")
_database(ctx, args["database"])
action = {"kind": "query", "database": args["database"], "payload": args["payload"],
"words": args["words"], "scope": _scope(ctx)}
if "change" in args:
action["change"] = scheduler.scheduled_change(args["change"])
label = args.get("label", args["words"])
config = getattr(session.runtime.tenant, "config", None) or {}
zone = args.get("timezone", config.get("timezone") or "UTC")
timing = ({"cron": _cron_from_phrase(args["when"])} if "when" in args else
{"once_at": args["once_at"]} if "once_at" in args else {"trigger": args["trigger"]})
schedule_id = scheduler.create(session.runtime, session.uname, tz=zone, label=label, action=action,
rule=args.get("rule", "notify"), **timing)
result = _item(scheduler.get(session.runtime, schedule_id))
def save_preview(doc):
# The common preview response shows the staged diff rather than the handler result.
doc["items"][schedule_id]["preview"] = copy.deepcopy(result["preview"])
return doc
session.runtime.update(scheduler.STORE_KEY, save_preview, flush="sync")
return result
def list_schedules(ctx, args):
"""List only your non-system schedules within this connection's current database access."""
session = _context(ctx)
return [_item(item) for item in scheduler.list_for(session.runtime, session.uname)
if not item.get("system") and _visible(ctx, item["action"].get("database"))]
def pause(ctx, args):
"""Preview pausing one of your schedules, then use confirm_change."""
_owned(ctx, args)
return _item(scheduler.pause(ctx.session.runtime, args["id"]))
def resume(ctx, args):
"""Preview resuming one of your schedules, then use confirm_change."""
_owned(ctx, args)
return _item(scheduler.resume(ctx.session.runtime, args["id"]))
def delete(ctx, args):
"""Preview deleting your schedule, then confirm with the exact phrase shown."""
item = _owned(ctx, args)
if not scheduler.delete(ctx.session.runtime, args["id"]):
raise err(404, "tool_not_found", "There is no schedule with that ID.")
return _item(item)
def inbox(ctx, args):
"""Read your unread result envelopes and mark only the result IDs explicitly named in shown as read."""
session = _context(ctx)
results = [item for item in scheduler.inbox(session.runtime, session.uname)
if _visible(ctx, item.get("database"))]
shown = args.get("shown", [])
if shown:
_context(ctx, write=True)
visible_ids = {item["id"] for item in results}
acknowledged = [result_id for result_id in shown if result_id in visible_ids]
if acknowledged:
scheduler.inbox(session.runtime, session.uname, shown=acknowledged)
results = [item for item in results if item["id"] not in acknowledged]
return results
def _action(handler, properties=None, required=(), *, read=True, destructive=False):
return {"read": read, "destructive": destructive, "confirm": not read,
"handler": handler, "schema": {"type": "object", "description": handler.__doc__,
"properties": properties or {}, "required": list(required), "additionalProperties": False}}
_TEXT = {"type": "string", "minLength": 1, "maxLength": 4000}
_ID = {"id": {"type": "string", "minLength": 1}}
_QUERY = copy.deepcopy(external_tools.TOOLS["query_database"]["inputSchema"])
_QUERY["properties"].pop("database")
_QUERY["required"] = []
GROUP = {
"name": "schedules", "title": "Schedules",
"guide": "Create previews a saved query with database, payload and words. Choose when for a repeat "
"phrase or five-field cron, once_at for an ISO date and time, or trigger='sync'. "
"A one-off note uses text and once_at. Optional timezone defaults to your workspace. "
"Queries repeat at most once an hour. Query scope comes from your current connection. "
"Optional rule is notify, draft, ask or act and defaults to notify. "
"Draft, ask and act need change with record_id and one field in values. "
"Create, pause, resume and delete need confirm_change. Delete needs the exact phrase shown. "
"List and inbox return only your schedules and unread result envelopes. "
"Inbox marks a result read only when you explicitly name its id in shown. "
"These schedules use no model and send no WhatsApp messages. "
'Under MCP rule 9, ask "Do you want me to build an after-sync schedule in Loopable?".',
"actions": {
"create": _action(create, {"database": {"type": "string", "minLength": 1}, "payload": _QUERY,
"words": _TEXT, "text": _TEXT, "label": _TEXT, "when": _TEXT,
"once_at": _TEXT, "trigger": {"enum": ["sync"]}, "timezone": _TEXT,
"rule": {"enum": ["notify", "draft", "ask", "act"]},
"change": {"type": "object", "properties": {
"record_id": {"type": "string", "minLength": 1}, "values": {"type": "object"}},
"required": ["record_id", "values"], "additionalProperties": False}}, read=False),
"list": _action(list_schedules),
"pause": _action(pause, _ID, ("id",), read=False),
"resume": _action(resume, _ID, ("id",), read=False),
"delete": _action(delete, _ID, ("id",), read=False, destructive=True),
"inbox": _action(inbox, {"shown": {"type": "array", "items": {"type": "string", "minLength": 1}}}),
},
}