Spaces:
Running

File size: 1,667 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Undo windows on approved sends (Phase 7).



A T2 send queues its message with ``send_after = now + undo window``. When such a call ran

on a human approval, the tool result tells the gateway how to undo it::



    {"send_after": "<iso>", "undo_url": "/packs/.../cancel",

     "undo": {"tool": "<pack>.cancel_message", "args": {...}}}



and the gateway copies those onto the approval row, so the inbox shows a countdown and an

Undo button. Undo is itself a gateway call (``undo.tool``), executed as the operator.

"""

from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any

from sqlalchemy import update
from sqlalchemy.ext.asyncio import AsyncSession

from core.approvals.models import Approval


def _when(v: Any) -> datetime | None:
    if isinstance(v, datetime):
        return v
    if isinstance(v, str):
        try:
            return datetime.fromisoformat(v)
        except ValueError:
            return None
    return None


async def attach_undo(s: AsyncSession, approval_id: uuid.UUID, data: dict[str, Any]) -> bool:
    when = _when(data.get("send_after"))
    undo = data.get("undo")
    if when is None or not isinstance(undo, dict) or not isinstance(undo.get("tool"), str):
        return False
    url = data.get("undo_url")
    await s.execute(
        update(Approval)
        .where(Approval.id == approval_id)
        .values(
            send_after=when,
            undo={"tool": undo["tool"], "args": dict(undo.get("args") or {})},
            undo_url=url if isinstance(url, str) and len(url) <= 300 else None,
        )
    )
    return True