nrtvix 0.2.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.
nrtvix-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NorthViax LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
nrtvix-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: nrtvix
3
+ Version: 0.2.0
4
+ Summary: NrtVix Guardian: ask before your AI agent acts. Allowed, waits for you, or blocked.
5
+ Author-email: NorthViax LLC <hello@nrtvix.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://www.nrtvix.com/developers/
8
+ Project-URL: Documentation, https://www.nrtvix.com/developers/#sdk
9
+ Keywords: ai agents,guardrails,approvals,nrtvix,guardian,llm
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # NrtVix Guardian for Python
21
+
22
+ Ask Guardian before your AI agent acts. Guardian answers: **allowed**, **waits for you**, or **blocked**, using the
23
+ rules you set in [NrtVix](https://app.nrtvix.com/rules).
24
+
25
+ ```bash
26
+ pip install nrtvix
27
+ ```
28
+
29
+ ## Quick start
30
+
31
+ 1. In NrtVix, open **Connected agents**, choose your agent and press **Create a key**.
32
+ 2. Keep the key on your server, for example in an environment variable `NRTVIX_API_KEY`. Never put it in a browser or an app.
33
+
34
+ ```python
35
+ from nrtvix import Guardian, NotPermitted
36
+
37
+ guardian = Guardian() # reads NRTVIX_API_KEY
38
+
39
+ try:
40
+ with guardian.guard("refund_order", "ORDER-1042", amount=40, details="Damaged item"):
41
+ issue_refund("ORDER-1042", 40) # runs only if Guardian allows it
42
+ except NotPermitted as e:
43
+ print("Not done:", e) # blocked, rejected by you, or expired
44
+ ```
45
+
46
+ `guard()` asks Guardian, waits while you approve or reject (if your rules say so), runs your block only when it is
47
+ allowed, and then tells Guardian the action was done (or failed, if your block raised an error).
48
+
49
+ ## Step by step
50
+
51
+ ```python
52
+ d = guardian.ask("view_customer_record", "jane@example.com")
53
+ if d.waiting:
54
+ d = guardian.wait(d, timeout=600) # raises nrtvix.Timeout if nobody decides in time
55
+ if d.allowed:
56
+ look_up_customer("jane@example.com")
57
+ guardian.done(d) # Live mode: report it (each permission can be used once)
58
+ ```
59
+
60
+ | Answer | Meaning |
61
+ | --- | --- |
62
+ | `allow` | Go ahead. |
63
+ | `pending` | Waits for you (the owner). `wait()` checks until you decide. |
64
+ | `approved` | You approved it. Go ahead. |
65
+ | `rejected` | You rejected it. Do not do it. |
66
+ | `blocked` | Your rules (or Guardian's safety checks) block it. Do not do it. |
67
+ | `reviewable` | Blocked by default (for example a delete). Your agent may `request_exception(d, reason)`. |
68
+ | `expired` / `revoked` | Nobody decided in time, or the permission was cancelled. |
69
+
70
+ ## Actions
71
+
72
+ `refund_order` (with `amount`), `view_customer_record`, `send_support_reply` (text in `details`),
73
+ `export_customer_data` and `send_campaign` (how many records or people in `units`), `delete_database_record`.
74
+
75
+ Agents start in **Test** mode, where Guardian accepts only names that start with `DEMO-`
76
+ (for example `DEMO-ORDER-1001`). Switch the agent to **Live** on the Connect page when you are ready.
77
+ In Test mode, use `guard(..., report=False)`.
78
+
79
+ ## Errors
80
+
81
+ `AuthError` (wrong or revoked key), `RateLimited`, `Blocked`, `Rejected`, `Expired`, `Timeout`, `APIError`;
82
+ all inherit from `GuardianError`. Network errors and server errors are retried twice with backoff.
83
+
84
+ ## Settings
85
+
86
+ ```python
87
+ Guardian(api_key="nvx_live_…", base_url="https://app.nrtvix.com/api/saas", timeout=10, retries=2)
88
+ ```
89
+
90
+ ## Webhooks
91
+
92
+ Let NrtVix tell your server when something happens (add the address under **Webhooks** in the app):
93
+
94
+ ```python
95
+ from nrtvix import verify_webhook, challenge_response, InvalidSignature
96
+
97
+ @app.post("/nrtvix/webhook") # Flask, FastAPI, Django: pass the raw body
98
+ def hook():
99
+ try:
100
+ event = verify_webhook(request.get_data(), request.headers["NrtVix-Signature"], os.environ["NRTVIX_WEBHOOK_SECRET"])
101
+ except InvalidSignature:
102
+ return "", 400
103
+ if event["type"] == "webhook.verify":
104
+ return challenge_response(event) # proves the address is yours; switches the webhook on
105
+ if event["type"] == "request.waiting":
106
+ notify_my_team(event["data"])
107
+ return "", 200
108
+ ```
109
+
110
+ Events: `request.allowed`, `request.waiting`, `request.approved`, `request.rejected`, `request.blocked`,
111
+ `request.expired`, `action.done`, `action.failed`, `agent.paused` (and `webhook.test` from the Send a test button).
112
+
113
+ No third-party dependencies. Python 3.9 or newer. MIT licence.
nrtvix-0.2.0/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # NrtVix Guardian for Python
2
+
3
+ Ask Guardian before your AI agent acts. Guardian answers: **allowed**, **waits for you**, or **blocked**, using the
4
+ rules you set in [NrtVix](https://app.nrtvix.com/rules).
5
+
6
+ ```bash
7
+ pip install nrtvix
8
+ ```
9
+
10
+ ## Quick start
11
+
12
+ 1. In NrtVix, open **Connected agents**, choose your agent and press **Create a key**.
13
+ 2. Keep the key on your server, for example in an environment variable `NRTVIX_API_KEY`. Never put it in a browser or an app.
14
+
15
+ ```python
16
+ from nrtvix import Guardian, NotPermitted
17
+
18
+ guardian = Guardian() # reads NRTVIX_API_KEY
19
+
20
+ try:
21
+ with guardian.guard("refund_order", "ORDER-1042", amount=40, details="Damaged item"):
22
+ issue_refund("ORDER-1042", 40) # runs only if Guardian allows it
23
+ except NotPermitted as e:
24
+ print("Not done:", e) # blocked, rejected by you, or expired
25
+ ```
26
+
27
+ `guard()` asks Guardian, waits while you approve or reject (if your rules say so), runs your block only when it is
28
+ allowed, and then tells Guardian the action was done (or failed, if your block raised an error).
29
+
30
+ ## Step by step
31
+
32
+ ```python
33
+ d = guardian.ask("view_customer_record", "jane@example.com")
34
+ if d.waiting:
35
+ d = guardian.wait(d, timeout=600) # raises nrtvix.Timeout if nobody decides in time
36
+ if d.allowed:
37
+ look_up_customer("jane@example.com")
38
+ guardian.done(d) # Live mode: report it (each permission can be used once)
39
+ ```
40
+
41
+ | Answer | Meaning |
42
+ | --- | --- |
43
+ | `allow` | Go ahead. |
44
+ | `pending` | Waits for you (the owner). `wait()` checks until you decide. |
45
+ | `approved` | You approved it. Go ahead. |
46
+ | `rejected` | You rejected it. Do not do it. |
47
+ | `blocked` | Your rules (or Guardian's safety checks) block it. Do not do it. |
48
+ | `reviewable` | Blocked by default (for example a delete). Your agent may `request_exception(d, reason)`. |
49
+ | `expired` / `revoked` | Nobody decided in time, or the permission was cancelled. |
50
+
51
+ ## Actions
52
+
53
+ `refund_order` (with `amount`), `view_customer_record`, `send_support_reply` (text in `details`),
54
+ `export_customer_data` and `send_campaign` (how many records or people in `units`), `delete_database_record`.
55
+
56
+ Agents start in **Test** mode, where Guardian accepts only names that start with `DEMO-`
57
+ (for example `DEMO-ORDER-1001`). Switch the agent to **Live** on the Connect page when you are ready.
58
+ In Test mode, use `guard(..., report=False)`.
59
+
60
+ ## Errors
61
+
62
+ `AuthError` (wrong or revoked key), `RateLimited`, `Blocked`, `Rejected`, `Expired`, `Timeout`, `APIError`;
63
+ all inherit from `GuardianError`. Network errors and server errors are retried twice with backoff.
64
+
65
+ ## Settings
66
+
67
+ ```python
68
+ Guardian(api_key="nvx_live_…", base_url="https://app.nrtvix.com/api/saas", timeout=10, retries=2)
69
+ ```
70
+
71
+ ## Webhooks
72
+
73
+ Let NrtVix tell your server when something happens (add the address under **Webhooks** in the app):
74
+
75
+ ```python
76
+ from nrtvix import verify_webhook, challenge_response, InvalidSignature
77
+
78
+ @app.post("/nrtvix/webhook") # Flask, FastAPI, Django: pass the raw body
79
+ def hook():
80
+ try:
81
+ event = verify_webhook(request.get_data(), request.headers["NrtVix-Signature"], os.environ["NRTVIX_WEBHOOK_SECRET"])
82
+ except InvalidSignature:
83
+ return "", 400
84
+ if event["type"] == "webhook.verify":
85
+ return challenge_response(event) # proves the address is yours; switches the webhook on
86
+ if event["type"] == "request.waiting":
87
+ notify_my_team(event["data"])
88
+ return "", 200
89
+ ```
90
+
91
+ Events: `request.allowed`, `request.waiting`, `request.approved`, `request.rejected`, `request.blocked`,
92
+ `request.expired`, `action.done`, `action.failed`, `agent.paused` (and `webhook.test` from the Send a test button).
93
+
94
+ No third-party dependencies. Python 3.9 or newer. MIT licence.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nrtvix"
7
+ version = "0.2.0"
8
+ description = "NrtVix Guardian: ask before your AI agent acts. Allowed, waits for you, or blocked."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "NorthViax LLC", email = "hello@nrtvix.com" }]
13
+ keywords = ["ai agents", "guardrails", "approvals", "nrtvix", "guardian", "llm"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Developers",
19
+ "Topic :: Security",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://www.nrtvix.com/developers/"
25
+ Documentation = "https://www.nrtvix.com/developers/#sdk"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+
30
+ [tool.setuptools.package-data]
31
+ nrtvix = ["py.typed"]
nrtvix-0.2.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ """NrtVix Guardian for Python.
2
+
3
+ Ask Guardian before your agent acts. Guardian answers: allowed, waits for you, or blocked.
4
+
5
+ from nrtvix import Guardian
6
+
7
+ guardian = Guardian(api_key=os.environ["NRTVIX_API_KEY"])
8
+
9
+ with guardian.guard("refund_order", "ORDER-1042", amount=40) as action:
10
+ issue_refund("ORDER-1042", 40) # runs only if Guardian allows it
11
+ # leaving the block reports the action as done (or failed, if your code raised)
12
+
13
+ No third-party dependencies. Python 3.9+.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from .client import (Decision, Guardian, GuardianError, Blocked, Rejected, Expired, Timeout, AuthError,
18
+ RateLimited, NotPermitted, APIError)
19
+
20
+ from .webhooks import verify as verify_webhook, challenge_response, InvalidSignature
21
+
22
+ __all__ = ['verify_webhook', 'challenge_response', 'InvalidSignature', 'Guardian', 'Decision', 'GuardianError', 'Blocked', 'Rejected', 'Expired', 'Timeout', 'AuthError',
23
+ 'RateLimited', 'NotPermitted', 'APIError']
24
+ __version__ = '0.2.0'
@@ -0,0 +1,246 @@
1
+ """The NrtVix Guardian client. Standard library only."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import random
7
+ import time
8
+ import urllib.error
9
+ import urllib.request
10
+ from contextlib import contextmanager
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Iterator, Optional
13
+
14
+ DEFAULT_BASE_URL = 'https://app.nrtvix.com/api/saas'
15
+ USER_AGENT = 'nrtvix-python/0.2.0'
16
+
17
+ ALLOWED = ('allow', 'approved')
18
+ WAITING = ('pending', 'reviewable', 'exception_pending')
19
+
20
+
21
+ class GuardianError(Exception):
22
+ """Base class for every error this package raises."""
23
+
24
+
25
+ class APIError(GuardianError):
26
+ def __init__(self, status: int, message: str):
27
+ super().__init__(f'NrtVix answered {status}: {message}')
28
+ self.status, self.message = status, message
29
+
30
+
31
+ class AuthError(APIError):
32
+ """The key is missing, wrong, revoked, or the agent is switched off."""
33
+
34
+
35
+ class RateLimited(APIError):
36
+ """Too many requests from this agent in a minute."""
37
+
38
+
39
+ class NotPermitted(GuardianError):
40
+ """Raised by guard() when Guardian did not allow the action."""
41
+
42
+ def __init__(self, decision: 'Decision'):
43
+ super().__init__(f'{decision.action} on {decision.target}: {decision.status}. ' + ' '.join(decision.reasons))
44
+ self.decision = decision
45
+
46
+
47
+ class Blocked(NotPermitted):
48
+ """Guardian blocked the action. Do not do it."""
49
+
50
+
51
+ class Rejected(NotPermitted):
52
+ """You (the owner) rejected the action."""
53
+
54
+
55
+ class Expired(NotPermitted):
56
+ """Nobody decided in time, or the permission was cancelled (rules or mode changed, key revoked)."""
57
+
58
+
59
+ class Timeout(GuardianError):
60
+ """wait() gave up before the owner decided. The request is still waiting; you can wait again later."""
61
+
62
+ def __init__(self, decision: 'Decision'):
63
+ super().__init__(f'Still waiting for approval of {decision.action} on {decision.target} (id {decision.id}).')
64
+ self.decision = decision
65
+
66
+
67
+ @dataclass
68
+ class Decision:
69
+ """Guardian's answer to one request."""
70
+ id: str
71
+ status: str # allow, pending, reviewable, exception_pending, approved, blocked, rejected, expired, revoked
72
+ action: str = ''
73
+ target: str = ''
74
+ amount: float = 0.0
75
+ risk: Optional[int] = None
76
+ reasons: list = field(default_factory=list)
77
+ raw: dict = field(default_factory=dict, repr=False)
78
+
79
+ @property
80
+ def allowed(self) -> bool:
81
+ """True if your agent may carry the action out now."""
82
+ return self.status in ALLOWED
83
+
84
+ @property
85
+ def waiting(self) -> bool:
86
+ """True while the owner has not decided yet."""
87
+ return self.status in WAITING
88
+
89
+ @property
90
+ def blocked(self) -> bool:
91
+ return self.status == 'blocked'
92
+
93
+ @classmethod
94
+ def from_json(cls, data: dict, fallback: Optional['Decision'] = None) -> 'Decision':
95
+ base = fallback or cls(id=str(data.get('id', '')), status='')
96
+ return cls(id=str(data.get('id', base.id)), status=str(data.get('decision', '')),
97
+ action=str(data.get('action', base.action)), target=str(data.get('target', base.target)),
98
+ amount=float(data.get('amount', base.amount) or 0), risk=data.get('risk', base.risk),
99
+ reasons=list(data.get('reasons', base.reasons) or []), raw=data)
100
+
101
+
102
+ class Guardian:
103
+ """A client for one agent key.
104
+
105
+ api_key: the agent key from the Connect page (starts with nvx_live_). Defaults to $NRTVIX_API_KEY.
106
+ base_url: defaults to https://app.nrtvix.com/api/saas (or $NRTVIX_BASE_URL).
107
+ timeout: seconds for each HTTP request.
108
+ retries: extra tries on network errors and 5xx answers (with backoff). Never retried: 4xx answers.
109
+ """
110
+
111
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, timeout: float = 10.0,
112
+ retries: int = 2):
113
+ key = api_key or os.environ.get('NRTVIX_API_KEY', '')
114
+ if not key or not isinstance(key, str):
115
+ raise AuthError(401, 'No API key. Pass api_key=... or set NRTVIX_API_KEY.')
116
+ if not (40 <= len(key) <= 200) or any(ch.isspace() for ch in key):
117
+ raise AuthError(401, 'That does not look like an NrtVix agent key.')
118
+ self._key = key
119
+ self.base_url = (base_url or os.environ.get('NRTVIX_BASE_URL') or DEFAULT_BASE_URL).rstrip('/')
120
+ if not (self.base_url.startswith('https://') or self.base_url.startswith(('http://localhost', 'http://127.0.0.1'))):
121
+ raise GuardianError('base_url must use https:// (http:// only for localhost).')
122
+ self.timeout, self.retries = float(timeout), max(0, int(retries))
123
+
124
+ def __repr__(self) -> str: # never print the key
125
+ return f'Guardian(base_url={self.base_url!r}, key=…{self._key[-4:]})'
126
+
127
+ # ---------------- low level ----------------
128
+ def _request(self, method: str, path: str, body: Optional[dict] = None) -> dict:
129
+ data = json.dumps(body).encode('utf-8') if body is not None else None
130
+ headers = {'Authorization': 'Bearer ' + self._key, 'Accept': 'application/json', 'User-Agent': USER_AGENT}
131
+ if data is not None:
132
+ headers['Content-Type'] = 'application/json'
133
+ attempt = 0
134
+ while True:
135
+ req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
136
+ try:
137
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
138
+ raw = resp.read()
139
+ return json.loads(raw.decode('utf-8')) if raw else {}
140
+ except urllib.error.HTTPError as err:
141
+ message = _detail(err)
142
+ if err.code >= 500 and attempt < self.retries:
143
+ attempt += 1; time.sleep(_backoff(attempt)); continue
144
+ if err.code in (401, 403):
145
+ raise AuthError(err.code, message) from None
146
+ if err.code == 429:
147
+ raise RateLimited(err.code, message) from None
148
+ raise APIError(err.code, message) from None
149
+ except (urllib.error.URLError, TimeoutError, ConnectionError) as err:
150
+ if attempt < self.retries:
151
+ attempt += 1; time.sleep(_backoff(attempt)); continue
152
+ raise GuardianError(f'Could not reach NrtVix: {getattr(err, "reason", err)}') from None
153
+
154
+ # ---------------- the three calls ----------------
155
+ def ask(self, action: str, target: str, amount: float = 0, *, details: str = '', units: int = 1,
156
+ estimated_cost: float = 0.03) -> Decision:
157
+ """Ask before acting. Returns Guardian's first answer (it may be 'pending': see wait())."""
158
+ payload = {'action': action, 'target': target, 'amount': amount, 'details': details, 'units': units,
159
+ 'estimated_cost': estimated_cost}
160
+ data = self._request('POST', '/agent/propose', payload)
161
+ d = Decision.from_json(data)
162
+ return Decision(id=d.id, status=d.status, action=action, target=target, amount=float(amount),
163
+ risk=d.risk, reasons=d.reasons, raw=data)
164
+
165
+ def status(self, request_id: str) -> Decision:
166
+ """Guardian's current answer for a request."""
167
+ data = self._request('GET', '/agent/status/' + _safe_id(request_id))
168
+ return Decision.from_json(data, Decision(id=request_id, status=''))
169
+
170
+ def wait(self, decision: Decision, *, timeout: float = 600, interval: float = 5) -> Decision:
171
+ """Wait while the owner decides. Returns the final answer, or raises Timeout."""
172
+ deadline = time.monotonic() + max(0.0, timeout)
173
+ current = decision
174
+ while current.waiting:
175
+ if time.monotonic() >= deadline:
176
+ raise Timeout(current)
177
+ time.sleep(min(max(0.5, interval), max(0.0, deadline - time.monotonic())) or 0.5)
178
+ fresh = self.status(current.id)
179
+ current = Decision(id=current.id, status=fresh.status, action=current.action, target=current.target,
180
+ amount=current.amount, risk=current.risk, reasons=current.reasons, raw=fresh.raw)
181
+ return current
182
+
183
+ def done(self, decision_or_id: Any, ok: bool = True) -> dict:
184
+ """Tell Guardian the action was carried out (ok=True) or failed (ok=False). Live mode only; once per permission."""
185
+ rid = decision_or_id.id if isinstance(decision_or_id, Decision) else str(decision_or_id)
186
+ return self._request('POST', '/agent/done', {'event_id': _safe_id(rid), 'ok': bool(ok)})
187
+
188
+ def request_exception(self, decision: Decision, reason: str) -> Decision:
189
+ """For an action Guardian marked 'reviewable' (for example a delete): ask the owner for a one-time exception."""
190
+ data = self._request('POST', '/agent/request-exception', {'event_id': _safe_id(decision.id), 'reason': reason})
191
+ return Decision.from_json(data, decision)
192
+
193
+ # ---------------- the easy way ----------------
194
+ def check(self, action: str, target: str, amount: float = 0, *, details: str = '', units: int = 1,
195
+ wait: bool = True, timeout: float = 600) -> Decision:
196
+ """ask() and, if needed, wait(). Returns the final answer without raising for blocked or rejected."""
197
+ d = self.ask(action, target, amount, details=details, units=units)
198
+ return self.wait(d, timeout=timeout) if (wait and d.waiting and d.status != 'reviewable') else d
199
+
200
+ @contextmanager
201
+ def guard(self, action: str, target: str, amount: float = 0, *, details: str = '', units: int = 1,
202
+ timeout: float = 600, report: bool = True) -> Iterator[Decision]:
203
+ """Run a block only if Guardian allows the action; then report it done (or failed, if the block raised).
204
+
205
+ Raises Blocked, Rejected or Expired instead of entering the block. Raises Timeout if nobody decided in time.
206
+ report=False skips the done report (for agents still in Test mode)."""
207
+ d = self.check(action, target, amount, details=details, units=units, timeout=timeout)
208
+ if not d.allowed:
209
+ raise {'blocked': Blocked, 'rejected': Rejected}.get(d.status, Expired)(d)
210
+ try:
211
+ yield d
212
+ except BaseException:
213
+ if report:
214
+ _quiet(lambda: self.done(d, ok=False))
215
+ raise
216
+ if report:
217
+ self.done(d, ok=True)
218
+
219
+
220
+ def _detail(err: urllib.error.HTTPError) -> str:
221
+ try:
222
+ body = json.loads(err.read().decode('utf-8'))
223
+ detail = body.get('detail')
224
+ if isinstance(detail, list) and detail and isinstance(detail[0], dict):
225
+ return str(detail[0].get('msg', detail[0]))
226
+ return str(detail) if detail else err.reason
227
+ except Exception:
228
+ return str(err.reason)
229
+
230
+
231
+ def _backoff(attempt: int) -> float:
232
+ return min(8.0, 0.5 * 2 ** (attempt - 1)) + random.uniform(0, 0.25)
233
+
234
+
235
+ def _safe_id(value: str) -> str:
236
+ value = str(value)
237
+ if len(value) != 24 or any(c not in '0123456789abcdef' for c in value):
238
+ raise GuardianError('Not a valid request id.')
239
+ return value
240
+
241
+
242
+ def _quiet(fn) -> None:
243
+ try:
244
+ fn()
245
+ except Exception:
246
+ pass
File without changes
@@ -0,0 +1,55 @@
1
+ """Receive NrtVix webhooks safely.
2
+
3
+ from nrtvix.webhooks import verify, InvalidSignature
4
+
5
+ @app.post("/nrtvix/webhook")
6
+ def hook(request):
7
+ try:
8
+ event = verify(request.body, request.headers["NrtVix-Signature"], os.environ["NRTVIX_WEBHOOK_SECRET"])
9
+ except InvalidSignature:
10
+ return 400
11
+ if event["type"] == "webhook.verify":
12
+ return {"challenge": event["data"]["challenge"]} # proves the address is yours
13
+ ... # handle event["type"] / event["data"]
14
+ return 200
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import hmac
20
+ import json
21
+ import time
22
+ from typing import Union
23
+
24
+
25
+ class InvalidSignature(Exception):
26
+ """The message is not from NrtVix, was changed on the way, or is too old."""
27
+
28
+
29
+ def verify(body: Union[bytes, str], signature_header: str, secret: str, *, tolerance: int = 300) -> dict:
30
+ """Check the NrtVix-Signature header and return the event as a dict.
31
+
32
+ body: the raw request body exactly as received (bytes or str), before any JSON parsing.
33
+ tolerance: seconds a message may be old (protects against replays). 0 turns the age check off."""
34
+ raw = body.encode('utf-8') if isinstance(body, str) else bytes(body)
35
+ if not secret or not signature_header:
36
+ raise InvalidSignature('Missing secret or NrtVix-Signature header.')
37
+ parts = dict(p.split('=', 1) for p in signature_header.split(',') if '=' in p)
38
+ try:
39
+ ts = int(parts.get('t', ''))
40
+ except ValueError:
41
+ raise InvalidSignature('Bad timestamp in the signature header.') from None
42
+ expected = hmac.new(secret.encode('utf-8'), str(ts).encode() + b'.' + raw, hashlib.sha256).hexdigest()
43
+ if not hmac.compare_digest(expected, parts.get('v1', '')):
44
+ raise InvalidSignature('Signature does not match.')
45
+ if tolerance and abs(time.time() - ts) > tolerance:
46
+ raise InvalidSignature('Message is too old.')
47
+ try:
48
+ return json.loads(raw.decode('utf-8'))
49
+ except ValueError:
50
+ raise InvalidSignature('Body is not JSON.') from None
51
+
52
+
53
+ def challenge_response(event: dict) -> dict:
54
+ """For a webhook.verify event: the answer that switches your webhook on."""
55
+ return {'challenge': event.get('data', {}).get('challenge', '')}
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: nrtvix
3
+ Version: 0.2.0
4
+ Summary: NrtVix Guardian: ask before your AI agent acts. Allowed, waits for you, or blocked.
5
+ Author-email: NorthViax LLC <hello@nrtvix.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://www.nrtvix.com/developers/
8
+ Project-URL: Documentation, https://www.nrtvix.com/developers/#sdk
9
+ Keywords: ai agents,guardrails,approvals,nrtvix,guardian,llm
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # NrtVix Guardian for Python
21
+
22
+ Ask Guardian before your AI agent acts. Guardian answers: **allowed**, **waits for you**, or **blocked**, using the
23
+ rules you set in [NrtVix](https://app.nrtvix.com/rules).
24
+
25
+ ```bash
26
+ pip install nrtvix
27
+ ```
28
+
29
+ ## Quick start
30
+
31
+ 1. In NrtVix, open **Connected agents**, choose your agent and press **Create a key**.
32
+ 2. Keep the key on your server, for example in an environment variable `NRTVIX_API_KEY`. Never put it in a browser or an app.
33
+
34
+ ```python
35
+ from nrtvix import Guardian, NotPermitted
36
+
37
+ guardian = Guardian() # reads NRTVIX_API_KEY
38
+
39
+ try:
40
+ with guardian.guard("refund_order", "ORDER-1042", amount=40, details="Damaged item"):
41
+ issue_refund("ORDER-1042", 40) # runs only if Guardian allows it
42
+ except NotPermitted as e:
43
+ print("Not done:", e) # blocked, rejected by you, or expired
44
+ ```
45
+
46
+ `guard()` asks Guardian, waits while you approve or reject (if your rules say so), runs your block only when it is
47
+ allowed, and then tells Guardian the action was done (or failed, if your block raised an error).
48
+
49
+ ## Step by step
50
+
51
+ ```python
52
+ d = guardian.ask("view_customer_record", "jane@example.com")
53
+ if d.waiting:
54
+ d = guardian.wait(d, timeout=600) # raises nrtvix.Timeout if nobody decides in time
55
+ if d.allowed:
56
+ look_up_customer("jane@example.com")
57
+ guardian.done(d) # Live mode: report it (each permission can be used once)
58
+ ```
59
+
60
+ | Answer | Meaning |
61
+ | --- | --- |
62
+ | `allow` | Go ahead. |
63
+ | `pending` | Waits for you (the owner). `wait()` checks until you decide. |
64
+ | `approved` | You approved it. Go ahead. |
65
+ | `rejected` | You rejected it. Do not do it. |
66
+ | `blocked` | Your rules (or Guardian's safety checks) block it. Do not do it. |
67
+ | `reviewable` | Blocked by default (for example a delete). Your agent may `request_exception(d, reason)`. |
68
+ | `expired` / `revoked` | Nobody decided in time, or the permission was cancelled. |
69
+
70
+ ## Actions
71
+
72
+ `refund_order` (with `amount`), `view_customer_record`, `send_support_reply` (text in `details`),
73
+ `export_customer_data` and `send_campaign` (how many records or people in `units`), `delete_database_record`.
74
+
75
+ Agents start in **Test** mode, where Guardian accepts only names that start with `DEMO-`
76
+ (for example `DEMO-ORDER-1001`). Switch the agent to **Live** on the Connect page when you are ready.
77
+ In Test mode, use `guard(..., report=False)`.
78
+
79
+ ## Errors
80
+
81
+ `AuthError` (wrong or revoked key), `RateLimited`, `Blocked`, `Rejected`, `Expired`, `Timeout`, `APIError`;
82
+ all inherit from `GuardianError`. Network errors and server errors are retried twice with backoff.
83
+
84
+ ## Settings
85
+
86
+ ```python
87
+ Guardian(api_key="nvx_live_…", base_url="https://app.nrtvix.com/api/saas", timeout=10, retries=2)
88
+ ```
89
+
90
+ ## Webhooks
91
+
92
+ Let NrtVix tell your server when something happens (add the address under **Webhooks** in the app):
93
+
94
+ ```python
95
+ from nrtvix import verify_webhook, challenge_response, InvalidSignature
96
+
97
+ @app.post("/nrtvix/webhook") # Flask, FastAPI, Django: pass the raw body
98
+ def hook():
99
+ try:
100
+ event = verify_webhook(request.get_data(), request.headers["NrtVix-Signature"], os.environ["NRTVIX_WEBHOOK_SECRET"])
101
+ except InvalidSignature:
102
+ return "", 400
103
+ if event["type"] == "webhook.verify":
104
+ return challenge_response(event) # proves the address is yours; switches the webhook on
105
+ if event["type"] == "request.waiting":
106
+ notify_my_team(event["data"])
107
+ return "", 200
108
+ ```
109
+
110
+ Events: `request.allowed`, `request.waiting`, `request.approved`, `request.rejected`, `request.blocked`,
111
+ `request.expired`, `action.done`, `action.failed`, `agent.paused` (and `webhook.test` from the Send a test button).
112
+
113
+ No third-party dependencies. Python 3.9 or newer. MIT licence.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/nrtvix/__init__.py
5
+ src/nrtvix/client.py
6
+ src/nrtvix/py.typed
7
+ src/nrtvix/webhooks.py
8
+ src/nrtvix.egg-info/PKG-INFO
9
+ src/nrtvix.egg-info/SOURCES.txt
10
+ src/nrtvix.egg-info/dependency_links.txt
11
+ src/nrtvix.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ nrtvix