File size: 9,528 Bytes
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301db09
c72f0a1
 
 
 
 
 
 
 
 
301db09
 
c72f0a1
 
 
 
 
301db09
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301db09
 
c72f0a1
 
 
81a8217
 
c72f0a1
 
 
301db09
 
 
 
 
c72f0a1
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""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}}}),
    },
}