leashgate 0.1.0__tar.gz

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.
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.5
2
+ Name: leashgate
3
+ Version: 0.1.0
4
+ Summary: The firewall for AI agents: check every agent action against your rules before it runs.
5
+ Project-URL: Homepage, https://leashgate.com
6
+ Project-URL: Documentation, https://leashgate.com/docs/
7
+ License: MIT
8
+ Keywords: agents,ai,approval,guardrails,llm,security
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+
12
+ # leashgate
13
+
14
+ The firewall for AI agents. Check every agent action against your rules before it runs.
15
+
16
+ ```bash
17
+ pip install leashgate
18
+ ```
19
+
20
+ ```python
21
+ from leashgate import Leashgate, ApprovalRequired
22
+
23
+ lg = Leashgate(agent="billing-bot") # reads LEASHGATE_API_KEY
24
+
25
+ @lg.guard("refund")
26
+ def refund(amount: float, order: str):
27
+ ...
28
+
29
+ try:
30
+ refund(amount=4800, order="A-2291")
31
+ except ApprovalRequired as e:
32
+ print("Waiting for a human:", e.approval_id)
33
+ ```
34
+
35
+ Wait for the decision instead: `@lg.guard("refund", wait=900)`.
36
+ Just ask: `lg.check("delete_rows", {"table": "customers"})`.
37
+
38
+ Docs: https://leashgate.com/docs/
@@ -0,0 +1,27 @@
1
+ # leashgate
2
+
3
+ The firewall for AI agents. Check every agent action against your rules before it runs.
4
+
5
+ ```bash
6
+ pip install leashgate
7
+ ```
8
+
9
+ ```python
10
+ from leashgate import Leashgate, ApprovalRequired
11
+
12
+ lg = Leashgate(agent="billing-bot") # reads LEASHGATE_API_KEY
13
+
14
+ @lg.guard("refund")
15
+ def refund(amount: float, order: str):
16
+ ...
17
+
18
+ try:
19
+ refund(amount=4800, order="A-2291")
20
+ except ApprovalRequired as e:
21
+ print("Waiting for a human:", e.approval_id)
22
+ ```
23
+
24
+ Wait for the decision instead: `@lg.guard("refund", wait=900)`.
25
+ Just ask: `lg.check("delete_rows", {"table": "customers"})`.
26
+
27
+ Docs: https://leashgate.com/docs/
@@ -0,0 +1,78 @@
1
+ """Leashgate for Python: check every AI agent action against your rules before it runs. No dependencies."""
2
+ from __future__ import annotations
3
+
4
+ import functools
5
+ import json
6
+ import os
7
+ import time
8
+ import urllib.error
9
+ import urllib.request
10
+ from typing import Any, Callable, Dict, Optional
11
+
12
+ __all__ = ["Leashgate", "ActionBlocked", "ApprovalRequired", "LeashgateError"]
13
+ __version__ = "0.1.0"
14
+
15
+
16
+ class LeashgateError(Exception):
17
+ def __init__(self, message: str, result: Dict[str, Any]):
18
+ super().__init__(message)
19
+ self.result = result
20
+
21
+
22
+ class ActionBlocked(LeashgateError):
23
+ pass
24
+
25
+
26
+ class ApprovalRequired(LeashgateError):
27
+ @property
28
+ def approval_id(self) -> Optional[str]:
29
+ return self.result.get("approval_id")
30
+
31
+
32
+ class Leashgate:
33
+ def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, agent: str = "default", timeout: float = 10.0):
34
+ self.api_key = api_key or os.environ.get("LEASHGATE_API_KEY", "")
35
+ self.base_url = (base_url or os.environ.get("LEASHGATE_BASE_URL", "https://gw.leashgate.com/v1")).rstrip("/")
36
+ self.agent = agent
37
+ self.timeout = timeout
38
+ if not self.api_key:
39
+ raise ValueError("Leashgate: pass api_key or set LEASHGATE_API_KEY.")
40
+
41
+ def check(self, action: str, params: Optional[Dict[str, Any]] = None, agent: Optional[str] = None) -> Dict[str, Any]:
42
+ """Asks Leashgate whether an action may run. Returns {decision, rule, reason, approval_id}."""
43
+ agent = agent or self.agent
44
+ body = json.dumps({"agent": agent, "action": action, "params": params or {}}, default=str).encode()
45
+ req = urllib.request.Request(self.base_url + "/actions/check", data=body, method="POST", headers={
46
+ "Authorization": "Bearer " + self.api_key, "Content-Type": "application/json", "x-leash-agent": agent,
47
+ "User-Agent": "leashgate-python/" + __version__,
48
+ })
49
+ try:
50
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
51
+ return json.loads(r.read().decode())
52
+ except urllib.error.HTTPError as e:
53
+ detail = e.read().decode(errors="replace")[:300]
54
+ raise RuntimeError(f"Leashgate {e.code}: {detail}") from None
55
+
56
+ def enforce(self, action: str, params: Optional[Dict[str, Any]] = None, agent: Optional[str] = None, wait: float = 0, poll: float = 10) -> Dict[str, Any]:
57
+ """Raises ActionBlocked or ApprovalRequired unless allowed. With wait (seconds), waits for a human decision."""
58
+ until, poll = time.time() + wait, max(5.0, poll)
59
+ while True:
60
+ r = self.check(action, params, agent)
61
+ if r.get("decision") == "allow":
62
+ return r
63
+ if r.get("decision") != "approval_required":
64
+ raise ActionBlocked(f"Leashgate blocked this action: {r.get('reason') or r.get('rule')}", r)
65
+ if time.time() + poll > until:
66
+ raise ApprovalRequired(f"Leashgate: human approval required ({r.get('approval_id')}): {r.get('reason')}", r)
67
+ time.sleep(poll)
68
+
69
+ def guard(self, action: str, agent: Optional[str] = None, wait: float = 0) -> Callable:
70
+ """Decorator: the function only runs when Leashgate allows it. Keyword arguments are sent as params."""
71
+ def deco(fn: Callable) -> Callable:
72
+ @functools.wraps(fn)
73
+ def run(*args: Any, **kwargs: Any) -> Any:
74
+ params = dict(kwargs) if kwargs else {"args": list(args)}
75
+ self.enforce(action, params, agent, wait)
76
+ return fn(*args, **kwargs)
77
+ return run
78
+ return deco
@@ -0,0 +1,15 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "leashgate"
7
+ version = "0.1.0"
8
+ description = "The firewall for AI agents: check every agent action against your rules before it runs."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ keywords = ["ai", "agents", "guardrails", "llm", "security", "approval"]
13
+ [project.urls]
14
+ Homepage = "https://leashgate.com"
15
+ Documentation = "https://leashgate.com/docs/"