variantgate 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
variantgate/errors.py ADDED
@@ -0,0 +1,169 @@
1
+ """What can go wrong. Every one of these means: do not act."""
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from .cancel_window import (
6
+ describe_window,
7
+ describe_withdrawn,
8
+ in_cancel_window,
9
+ withdrawn_from_window,
10
+ )
11
+
12
+ if TYPE_CHECKING:
13
+ from .types import Decision
14
+
15
+
16
+ class VariantGateError(Exception):
17
+ """Anything that stops an action. Catch this to handle every refusal."""
18
+
19
+
20
+ class ConfigurationError(VariantGateError):
21
+ """The client was set up wrongly, such as without a key."""
22
+
23
+
24
+ class ApprovalApiError(VariantGateError):
25
+ """The API refused a call, or could not be reached.
26
+
27
+ ``code`` is the error code the API sent, such as ``rate_limited``, or
28
+ ``network`` when there was no answer. ``status`` is the HTTP status, or
29
+ 0 when there was no response.
30
+ """
31
+
32
+ def __init__(self, message: str, code: str, status: int) -> None:
33
+ super().__init__(message)
34
+ self.code = code
35
+ self.status = status
36
+
37
+
38
+ class OutOfScopeError(ApprovalApiError):
39
+ """This agent key may not ask about the action.
40
+
41
+ A workspace owner limited the key to other actions, and the message says
42
+ which. Nothing was stored and nobody was told. Asking again will not
43
+ help: an owner has to widen the key's scope, or the agent has to use
44
+ another key. ``code`` is ``action_out_of_scope`` and ``status`` is 403.
45
+ """
46
+
47
+ CODE = "action_out_of_scope"
48
+ """The code the API sends for an action outside the key's scope."""
49
+
50
+ def __init__(self, message: str, status: int) -> None:
51
+ super().__init__(message, self.CODE, status)
52
+
53
+
54
+ class OnBehalfLockedError(ApprovalApiError):
55
+ """The run already says whom it works for, and that cannot be changed.
56
+
57
+ Nothing was changed: the first lock stands, and anything that names
58
+ someone else waits for a person. ``code`` is ``on_behalf_locked`` and
59
+ ``status`` is 409.
60
+ """
61
+
62
+ CODE = "on_behalf_locked"
63
+ """The code the API sends for a second, different lock."""
64
+
65
+ def __init__(self, message: str, status: int) -> None:
66
+ super().__init__(message, self.CODE, status)
67
+
68
+
69
+ class PlanLockedError(ApprovalApiError):
70
+ """The run already has a different plan, and a plan cannot be changed.
71
+
72
+ Nothing was changed: the first plan stands, and anything off it waits
73
+ for a person. ``code`` is ``plan_locked`` and ``status`` is 409.
74
+ """
75
+
76
+ CODE = "plan_locked"
77
+ """The code the API sends for a second, different plan."""
78
+
79
+ def __init__(self, message: str, status: int) -> None:
80
+ super().__init__(message, self.CODE, status)
81
+
82
+
83
+ class RunLinkedError(ApprovalApiError):
84
+ """The run is already a sub-agent of another run; a link cannot change.
85
+
86
+ Nothing was changed: the first link stands. ``code`` is ``run_linked``
87
+ and ``status`` is 409.
88
+ """
89
+
90
+ CODE = "run_linked"
91
+ """The code the API sends for a second, different parent."""
92
+
93
+ def __init__(self, message: str, status: int) -> None:
94
+ super().__init__(message, self.CODE, status)
95
+
96
+
97
+ class RunStoppedError(ApprovalApiError):
98
+ """A person stopped the run this request belongs to. Nothing was stored.
99
+
100
+ The agent must not act, and should stop asking in this run: the API
101
+ refuses everything the run asks from now on. ``code`` is
102
+ ``run_stopped`` and ``status`` is 409.
103
+ """
104
+
105
+ CODE = "run_stopped"
106
+ """The code the API sends for a request in a stopped run."""
107
+
108
+ def __init__(self, message: str, status: int) -> None:
109
+ super().__init__(message, self.CODE, status)
110
+
111
+
112
+ class NotApprovedError(VariantGateError):
113
+ """A request ended without permission to act.
114
+
115
+ ``decision`` is the request as it last stood.
116
+ """
117
+
118
+ def __init__(self, decision: "Decision") -> None:
119
+ lead = "Not allowed yet" if in_cancel_window(decision) else "Not approved"
120
+ super().__init__(f"{lead}: the request is {describe(decision)}.")
121
+ self.decision = decision
122
+
123
+
124
+ class ChangedApprovalError(NotApprovedError):
125
+ """A person approved only a changed version, so nothing was done.
126
+
127
+ ``decision`` holds what was approved: ``approved_summary`` and
128
+ ``approved_amount``. Pass ``accept_changes=True`` to act on it instead.
129
+ """
130
+
131
+ def __init__(self, decision: "Decision") -> None:
132
+ super().__init__(decision)
133
+ self.args = (
134
+ f"Approved only with changes, so nothing was done: {approved_version(decision)}.",
135
+ )
136
+
137
+
138
+ def approved_version(decision: "Decision") -> str:
139
+ """The version a person approved: its wording, and its amount if any."""
140
+ wording = f'"{decision.get("approved_summary") or decision.get("summary")}"'
141
+ amount, currency = decision.get("approved_amount"), decision.get("currency")
142
+ return f"{wording}, for at most {amount} {currency}" if amount and currency else wording
143
+
144
+
145
+ def describe(decision: "Decision") -> str:
146
+ """Where a request stands, in a few words."""
147
+ status = str(decision.get("status", "unknown"))
148
+ if decision.get("pause") == "run":
149
+ return f"{status}, but a person stopped this run"
150
+ if decision.get("pause") == "contained":
151
+ return (
152
+ f"{status}, but this agent was contained after it asked, "
153
+ "so this approval is void for good"
154
+ )
155
+ if status == "approved" and decision.get("paused"):
156
+ if decision.get("pause") == "agent":
157
+ return "approved, but this agent is paused"
158
+ return "approved, but every agent is paused"
159
+ if in_cancel_window(decision):
160
+ return describe_window(decision)
161
+ if withdrawn_from_window(decision):
162
+ return describe_withdrawn(decision)
163
+ cancelled_by = decision.get("cancelled_by")
164
+ if status == "denied" and cancelled_by:
165
+ return f"cancelled by {cancelled_by} during its cancel window"
166
+ note = decision.get("decision_note")
167
+ if status == "denied" and note:
168
+ return f"denied ({note})"
169
+ return status
variantgate/guard.py ADDED
@@ -0,0 +1,132 @@
1
+ """``require_approval``: code that runs only after a person says yes.
2
+
3
+ It works as a decorator, on plain and ``async`` functions, and as a ``with``
4
+ block. Any field may be a function of the decorated function's arguments,
5
+ so the summary can name the real values::
6
+
7
+ @require_approval(
8
+ "payment.refund",
9
+ lambda order: f"Refund {order.total} EUR to {order.email}",
10
+ amount=lambda order: order.total,
11
+ currency="EUR",
12
+ )
13
+ def refund(order): ...
14
+ """
15
+
16
+ import asyncio
17
+ import functools
18
+ import inspect
19
+ import threading
20
+ from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, cast
21
+
22
+ from .types import Decision
23
+
24
+ if TYPE_CHECKING:
25
+ from types import TracebackType
26
+
27
+ from .client import ApprovalClient
28
+
29
+ F = TypeVar("F", bound=Callable[..., Any])
30
+
31
+
32
+ class Approved:
33
+ """An approval being acted on inside a ``with`` block.
34
+
35
+ Set ``note`` to say, for the record, what was done.
36
+ """
37
+
38
+ def __init__(self, decision: Decision) -> None:
39
+ self.decision = decision
40
+ self.id = decision["id"]
41
+ self.note: Optional[str] = None
42
+
43
+
44
+ class RequireApproval:
45
+ """Asks before the code it wraps runs. Made by ``require_approval``."""
46
+
47
+ def __init__(
48
+ self,
49
+ client: "Callable[[], ApprovalClient]",
50
+ action: Any,
51
+ summary: Any,
52
+ *,
53
+ timeout: Optional[float] = None,
54
+ accept_changes: bool = False,
55
+ **request: Any,
56
+ ) -> None:
57
+ self._client = client
58
+ self._fields: dict[str, Any] = {"action": action, "summary": summary, **request}
59
+ self._timeout = timeout
60
+ # Only a ``with`` block can see what was approved, so only it can act
61
+ # on a changed version; a decorated function always does what it asked.
62
+ self._accept_changes = accept_changes
63
+ self._open = threading.local()
64
+
65
+ def __call__(self, func: F) -> F:
66
+ if self._accept_changes:
67
+ raise TypeError(
68
+ "accept_changes works only in a `with` block, which can read what was approved"
69
+ )
70
+ if inspect.iscoroutinefunction(func):
71
+ return cast("F", self._wrap_async(func))
72
+
73
+ @functools.wraps(func)
74
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
75
+ client = self._client()
76
+ fields = self._resolve(args, kwargs)
77
+ return client.guard(lambda: func(*args, **kwargs), timeout=self._timeout, **fields)
78
+
79
+ return cast("F", wrapper)
80
+
81
+ def _wrap_async(self, func: Callable[..., Any]) -> Callable[..., Any]:
82
+ @functools.wraps(func)
83
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
84
+ client = self._client()
85
+ fields = self._resolve(args, kwargs)
86
+ decision = await asyncio.to_thread(
87
+ client.wait_for_approval, timeout=self._timeout, **fields
88
+ )
89
+ try:
90
+ result = await func(*args, **kwargs)
91
+ except BaseException as error:
92
+ await asyncio.to_thread(client.report_failure, decision["id"], error)
93
+ raise
94
+ note = result if isinstance(result, str) else None
95
+ await asyncio.to_thread(client.report_outcome, decision["id"], "succeeded", note)
96
+ return result
97
+
98
+ return wrapper
99
+
100
+ def __enter__(self) -> Approved:
101
+ client = self._client()
102
+ decision = client.wait_for_approval(
103
+ timeout=self._timeout, accept_changes=self._accept_changes, **self._resolve((), {})
104
+ )
105
+ approved = Approved(decision)
106
+ self._stack().append((client, approved))
107
+ return approved
108
+
109
+ def __exit__(
110
+ self,
111
+ kind: "Optional[type[BaseException]]",
112
+ error: Optional[BaseException],
113
+ trace: "Optional[TracebackType]",
114
+ ) -> None:
115
+ client, approved = self._stack().pop()
116
+ if error is None:
117
+ client.report_outcome(approved.id, "succeeded", approved.note)
118
+ else:
119
+ client.report_failure(approved.id, error)
120
+
121
+ def _stack(self) -> "list[Any]":
122
+ if not hasattr(self._open, "stack"):
123
+ self._open.stack = []
124
+ stack: list[Any] = self._open.stack
125
+ return stack
126
+
127
+ def _resolve(self, args: Any, kwargs: dict[str, Any]) -> dict[str, Any]:
128
+ """The request, with every field that is a function called on the arguments."""
129
+ return {
130
+ name: value(*args, **kwargs) if callable(value) else value
131
+ for name, value in self._fields.items()
132
+ }
variantgate/mandate.py ADDED
@@ -0,0 +1,80 @@
1
+ """Mandates: ask once, up front, for a bounded run of one action.
2
+
3
+ "Up to 10 refunds, each at most EUR 40, EUR 200 in all, for the next hour,
4
+ in this run." Only a workspace owner can grant it. The request that asks
5
+ never has ``allowed`` true: each step is still asked for with ``ask`` or
6
+ ``guard``, in the same run, and the grant answers it until its uses, total
7
+ or time run out. After that, steps wait for a person as usual.
8
+ """
9
+
10
+ from dataclasses import dataclass
11
+ from typing import TYPE_CHECKING, Any, Optional, Union
12
+
13
+ from .types import Decision
14
+
15
+ if TYPE_CHECKING:
16
+ from .client import ApprovalClient
17
+
18
+ HOLD_SECONDS = 30
19
+ """The longest one call is held open while waiting, as the API allows."""
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class MandateAnswer:
24
+ """How an owner answered a mandate."""
25
+
26
+ granted: bool
27
+ """True only when an owner granted it; a denial, expiry or withdrawal is False."""
28
+ request: Decision
29
+ """The request that asked, as it ended. Its ``allowed`` is always False."""
30
+
31
+
32
+ def mandate_terms(
33
+ uses: int,
34
+ minutes: int,
35
+ total: Optional[Union[int, float, str]] = None,
36
+ currency: Optional[str] = None,
37
+ ) -> dict[str, Any]:
38
+ """The ``mandate`` field of a request: the bounds, with a total only when given."""
39
+ terms: dict[str, Any] = {"uses": uses, "minutes": minutes}
40
+ if total is not None:
41
+ terms["total"] = total
42
+ terms["currency"] = currency
43
+ return terms
44
+
45
+
46
+ def is_granted(decision: Decision) -> bool:
47
+ """Whether a mandate request was granted by an owner."""
48
+ mandate = decision.get("mandate")
49
+ granted = mandate is not None and mandate.get("granted") is True
50
+ return decision.get("status") == "approved" and granted
51
+
52
+
53
+ def request_mandate(
54
+ client: "ApprovalClient",
55
+ action: str,
56
+ summary: str,
57
+ *,
58
+ uses: int,
59
+ minutes: int,
60
+ total: Optional[Union[int, float, str]] = None,
61
+ total_currency: Optional[str] = None,
62
+ timeout: Optional[float] = None,
63
+ **step: Any,
64
+ ) -> MandateAnswer:
65
+ """Asks for a mandate and waits until an owner decides or ``timeout`` is up.
66
+
67
+ ``step`` takes what ``ask`` takes (``run``, ``amount``, ``currency``,
68
+ ``details``...); ``amount`` is the most one step may move. ``total`` is
69
+ in ``total_currency``, or else in ``currency``. A request still pending
70
+ at the end is withdrawn. The API refuses a mandate with no run, with a
71
+ ``*`` in its action, or with a total below one step's amount.
72
+ """
73
+ for taken in ("mandate", "wait_seconds"):
74
+ if taken in step:
75
+ raise TypeError(f"request_mandate sets {taken} itself")
76
+ currency = total_currency or step.get("currency")
77
+ terms = mandate_terms(uses, minutes, total, currency)
78
+ asked = client.ask(action, summary, mandate=terms, wait_seconds=HOLD_SECONDS, **step)
79
+ decided = client.wait(asked, timeout)
80
+ return MandateAnswer(granted=is_granted(decided), request=decided)
@@ -0,0 +1,57 @@
1
+ """On-behalf-of locks: a run says at its start whom it works for.
2
+
3
+ The parties are that one person's or account's email addresses, phone
4
+ numbers, IBANs, account numbers and ids, such as ``cus_8812``. The lock is
5
+ fixed once declared, so text the agent reads later cannot change it.
6
+ Anything the run asks whose details name someone else waits for a person
7
+ whatever the rules say. A lock never approves anything.
8
+ """
9
+
10
+ from collections.abc import Sequence
11
+ from typing import TYPE_CHECKING, Any, Optional
12
+ from urllib.parse import quote
13
+
14
+ from . import _http
15
+ from .errors import ApprovalApiError
16
+ from .plans import or_none
17
+ from .runs import run_id
18
+
19
+ if TYPE_CHECKING:
20
+ from .client import ApprovalClient
21
+
22
+
23
+ def _path(client: "ApprovalClient", run: Optional[str]) -> str:
24
+ chosen = run_id(run) or client.run
25
+ if chosen is None:
26
+ raise ApprovalApiError(
27
+ "an on-behalf-of lock belongs to a run: pass run=, or give the client one",
28
+ "invalid_request",
29
+ 0,
30
+ )
31
+ return f"{client.api_url}/v1/runs/{quote(chosen, safe='')}/on-behalf-of"
32
+
33
+
34
+ def declare_on_behalf(
35
+ client: "ApprovalClient",
36
+ parties: Sequence[str],
37
+ label: str = "",
38
+ run: Optional[str] = None,
39
+ ) -> Optional[dict[str, Any]]:
40
+ """Declares whom the run (``run``, or the client's) works for.
41
+
42
+ Raises ``OnBehalfLockedError`` when the run already has a different
43
+ lock; the same lock again changes nothing. Returns None when the server
44
+ is older than these locks (404): the run then goes on under the
45
+ workspace's rules alone, which is no less cautious than before.
46
+ """
47
+ if isinstance(parties, str):
48
+ raise ApprovalApiError("parties is a list of strings, not one string", "invalid_request", 0)
49
+ body = {"label": label, "parties": list(parties)}
50
+ url = _path(client, run)
51
+ return or_none(lambda: _http.call_object(url, client._key, "PUT", body, client.timeout))
52
+
53
+
54
+ def get_on_behalf(client: "ApprovalClient", run: Optional[str] = None) -> Optional[dict[str, Any]]:
55
+ """Whom the run works for, or None when it declared nobody."""
56
+ url = _path(client, run)
57
+ return or_none(lambda: _http.call_object(url, client._key, "GET", None, client.timeout))
variantgate/plans.py ADDED
@@ -0,0 +1,78 @@
1
+ """Run plans: a run says at its start which actions it will take.
2
+
3
+ Each step is an action such as ``email.send`` or a family such as ``kb.*``,
4
+ at most so many times when it says. The plan is locked once declared, so
5
+ text the agent reads later cannot widen it. Anything the run asks that is
6
+ off the plan waits for a person whatever the rules say. A plan never
7
+ approves anything.
8
+ """
9
+
10
+ from collections.abc import Callable, Mapping, Sequence
11
+ from typing import TYPE_CHECKING, Any, Optional, Union
12
+ from urllib.parse import quote
13
+
14
+ from . import _http
15
+ from .errors import ApprovalApiError
16
+ from .runs import run_id
17
+
18
+ if TYPE_CHECKING:
19
+ from .client import ApprovalClient
20
+
21
+ Step = Union[str, tuple[str, Optional[int]], Mapping[str, Any]]
22
+ """One step: ``"crm.read"``, ``("email.send", 1)`` or ``{"action": ..., "max": ...}``."""
23
+
24
+ NOT_FOUND = 404
25
+
26
+
27
+ def plan_steps(steps: Sequence[Step]) -> list[dict[str, Any]]:
28
+ """The steps as the API takes them, with ``max`` only when given."""
29
+ shaped: list[dict[str, Any]] = []
30
+ for step in steps:
31
+ if isinstance(step, str):
32
+ action, most = step, None
33
+ elif isinstance(step, tuple):
34
+ action, most = step
35
+ else:
36
+ action, most = step["action"], step.get("max")
37
+ shaped.append({"action": action} if most is None else {"action": action, "max": most})
38
+ return shaped
39
+
40
+
41
+ def _path(client: "ApprovalClient", run: Optional[str]) -> str:
42
+ chosen = run_id(run) or client.run
43
+ if chosen is None:
44
+ raise ApprovalApiError(
45
+ "a plan belongs to a run: pass run=, or give the client one", "invalid_request", 0
46
+ )
47
+ return f"{client.api_url}/v1/runs/{quote(chosen, safe='')}/plan"
48
+
49
+
50
+ def declare_plan(
51
+ client: "ApprovalClient", goal: str, steps: Sequence[Step], run: Optional[str] = None
52
+ ) -> Optional[dict[str, Any]]:
53
+ """Declares what the run (``run``, or the client's) will do.
54
+
55
+ Raises ``PlanLockedError`` when the run already has a different plan;
56
+ the same plan again changes nothing. Returns None when the server is
57
+ older than run plans (404): the run then goes on under the workspace's
58
+ rules alone, which is no less cautious than before.
59
+ """
60
+ body = {"goal": goal, "steps": plan_steps(steps)}
61
+ url = _path(client, run)
62
+ return or_none(lambda: _http.call_object(url, client._key, "PUT", body, client.timeout))
63
+
64
+
65
+ def or_none(read: Callable[[], dict[str, Any]]) -> Optional[dict[str, Any]]:
66
+ """What ``read`` answers, or None when the API answers 404."""
67
+ try:
68
+ return read()
69
+ except ApprovalApiError as error:
70
+ if error.status == NOT_FOUND:
71
+ return None
72
+ raise
73
+
74
+
75
+ def get_plan(client: "ApprovalClient", run: Optional[str] = None) -> Optional[dict[str, Any]]:
76
+ """The run's plan with how much of each step is used, or None."""
77
+ url = _path(client, run)
78
+ return or_none(lambda: _http.call_object(url, client._key, "GET", None, client.timeout))