File size: 9,744 Bytes
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
200
201
202
"""Manage owned Automation definitions through the shared confirmation dispatcher."""
import copy

from fastapi import HTTPException
from core import external_tools, perm_scope
from deps import Session, err
import automation_engine as engine
import external_activity


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.")
    session.require("automation")
    if write:
        from routes_external import _assert_write_scope
        _assert_write_scope(session, "automations")
        if not session.runtime.available():
            raise err(503, "store_unavailable", "The tenant store is unavailable. Nothing was saved.")
    return session


def _databases(value):
    if isinstance(value, dict):
        for key, child in value.items():
            if key in {"database", "sourceDatabase", "targetTable", "table", "tableKey"} and child:
                if not isinstance(child, str):
                    raise ValueError("Name each automation database with its key.")
                yield child
            yield from _databases(child)
    elif isinstance(value, list):
        for child in value:
            yield from _databases(child)


def _scope(ctx, definition):
    from routes_external import _assert_database_scope
    inputs = {key: definition.get(key) for key in ("config", "trigger", "flow")}
    for database in sorted(set(_databases(inputs))):
        _assert_database_scope(ctx.session, database)
        ctx.describe_database(database)


def _item(definition):
    # Configuration and run payloads can contain credentials or row values.
    return {key: copy.deepcopy(definition.get(key))
            for key in ("id", "name", "kind", "trigger", "schedule", "createdBy", "created")}


def _owned(ctx, args, action):
    session = _context(ctx, write=True)
    aid = args["id"]
    if aid.startswith(("field:", "system:")):
        raise err(409, "system_agent", "Change this system automation through its own settings.")
    definition = engine.all_definitions(session.runtime).get(aid)
    if not definition:
        raise err(404, "unknown_automation", "There is no automation with that ID.")
    if definition.get("createdBy") != session.uname:
        raise err(403, "automation_not_owned", f"You cannot {action} another user's automation.")
    if definition.get("system"):
        raise err(409, "system_agent", engine.system_agent_refusal(definition["system"]))
    _scope(ctx, definition)
    return definition


def _sync(session, definition):
    # Preview writers must never reconcile the external scheduler.
    if not external_activity._preview(session):
        from routes_automation import _sync_schedule_or_503
        _sync_schedule_or_503(session.tenant, definition)


def create(ctx, args):
    """Preview a once or recurring Automation, then call confirm_change after the user agrees."""
    session = _context(ctx, write=True)
    # Validate normalized references too, including engine defaults and generated flow steps.
    clean, error = engine.clean_definition(args, username=session.uname, rt=session.runtime)
    if error:
        raise err(400, "invalid_automation", error)
    _scope(ctx, clean)
    notes = []
    definition, error = engine.create(session.runtime, args, username=session.uname, notes=notes)
    if error:
        raise err(400, "invalid_automation", error)
    engine.ensure_agent_contract(session.runtime, definition["id"], session.uname, definition["name"])
    _sync(session, definition)
    return {**_item(definition), "warnings": notes}


def list_automations(ctx, args):
    """List your Automations within this connection's current database access."""
    session = _context(ctx)
    items = []
    for definition in engine.all_definitions(session.runtime).values():
        if definition.get("createdBy") != session.uname or definition.get("system"):
            continue
        try:
            _scope(ctx, definition)
        except HTTPException as exc:
            if exc.status_code not in (403, 404):
                raise
            continue
        items.append(_item(definition))
    return sorted(items, key=lambda row: (row["name"].lower(), row["id"]))


def _paused(ctx, args, paused):
    definition = _owned(ctx, args, "pause" if paused else "resume")
    session = ctx.session
    trigger = definition.get("trigger") or {}
    if trigger.get("key") == "once":
        body = {"trigger": {**trigger, "paused": paused, "enabled": not paused}}
    else:
        body = {"schedule": {**definition["schedule"], "enabled": not paused}}
    from routes_automation import _agent_owned_guard
    _agent_owned_guard(session, definition["id"], body)
    updated, error = engine.patch(session.runtime, definition["id"], body, username=session.uname)
    if error:
        raise err(400, "invalid_automation", error)
    engine.ensure_agent_contract(session.runtime, updated["id"], session.uname, updated["name"])
    _sync(session, updated)
    return _item(updated)


def pause(ctx, args):
    """Preview pausing your Automation, then call confirm_change."""
    return _paused(ctx, args, True)


def resume(ctx, args):
    """Preview resuming your Automation, then call confirm_change."""
    return _paused(ctx, args, False)


def delete(ctx, args):
    """Preview deleting your Automation, then confirm with the exact phrase shown."""
    definition = _owned(ctx, args, "delete")
    session = ctx.session
    if engine.running(session.tenant, definition["id"]):
        raise err(409, "automation_running", "It is running. Wait for it to finish.")
    from routes_automation import _agent_marks, _agent_owned_guard, _prune_marks
    _agent_owned_guard(session, definition["id"], {})
    marked = bool(_agent_marks(session.runtime).get(definition["id"]))
    engine.remove(session.runtime, definition["id"])
    if marked:
        _prune_marks(session, definition["id"])
    if not external_activity._preview(session):
        import automation_control
        try:
            automation_control.delete_definition(session.tenant, definition["id"])
        except automation_control.ControlPlaneError as exc:
            raise err(503, "automation_control_unavailable",
                      f"The automation was deleted, but its schedules could not be removed: {exc}")
    return _item(definition)


def _action(handler, properties=None, required=(), *, read=True, destructive=False):
    return {"read": read, "destructive": destructive, "confirm": not read,
            "grants": ("automation",), "handler": handler,
            "schema": {"type": "object", "description": handler.__doc__,
                       "properties": properties or {}, "required": list(required), "additionalProperties": False}}


_TEXT = {"type": "string", "minLength": 1}
_ID = {"id": _TEXT}
GROUP = {
    "name": "automations", "title": "Automations",
    "guide": "Offer to create a reminder or recurring run with automations.create. "
             "Use the Automation builder definition: name, optional kind and config, trigger, schedule and flow.actions. "
             "For once, use trigger={key:'once', at:'<local ISO date and time>', timezone:'<IANA zone>'}. "
             "The time must be in the future. For weekly, use trigger={key:'schedule'} and "
             "schedule={cron:'0 8 * * 1', enabled:true}. Recurring cron uses UTC. "
             "Use supported action kinds and config shapes in flow.actions. "
             "This group cannot configure a Slack destination or test a Slack delivery. "
             "An event-driven Automation can send a status reply only through its separately authorized Slack channel agent. "
             "That status reply is not a conditional SKU alert or a direct message action. "
             "Do not promise delivery until the channel authorization and delivery receipt have been observed. "
             "Create, pause, resume and delete need confirm_change. Delete needs the exact phrase shown. "
             "List returns only your accessible Automations. You can only change your own Automations. "
             "A fired once Automation leaves the list. Its activity and inbox result stay. "
             "Use schedules for saved-query schedules. "
             'Under MCP rule 9, ask "Do you want me to build a one-time reminder or recurring automation in Loopable?".',
    "actions": {
        "create": _action(create, {"name": _TEXT, "kind": _TEXT, "config": {"type": "object"},
                    "trigger": {"type": "object", "properties": {
                        "key": {"enum": ["once", "schedule"]}, "at": _TEXT, "timezone": _TEXT,
                        "enabled": {"type": "boolean"}, "paused": {"type": "boolean"}},
                        "required": ["key"], "additionalProperties": False},
                    "schedule": {"type": "object", "properties": {
                        "cron": _TEXT, "enabled": {"type": "boolean"}}, "additionalProperties": False},
                    "flow": {"type": "object", "properties": {"actions": {"type": "array", "items": {"type": "object"}}},
                             "required": ["actions"], "additionalProperties": False}}, ("name", "trigger"), read=False),
        "list": _action(list_automations),
        "pause": _action(pause, _ID, ("id",), read=False),
        "resume": _action(resume, _ID, ("id",), read=False),
        "delete": _action(delete, _ID, ("id",), read=False, destructive=True),
    },
}