riskbound 0.1.1__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.
riskbound/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """Riskbound SDK for Python. Ask before an AI agent acts, then carry out the answer."""
2
+
3
+ from ._client import AsyncGuard, AsyncRiskbound, Guard, Riskbound
4
+ from ._errors import (
5
+ RiskboundApprovalTimeoutError,
6
+ RiskboundBlockedError,
7
+ RiskboundError,
8
+ RiskboundRequestError,
9
+ RiskboundUnavailableError,
10
+ )
11
+ from ._transport import Transport, TransportError, urllib_transport
12
+ from ._types import (
13
+ Decision,
14
+ DecisionStatus,
15
+ FailMode,
16
+ GuardResult,
17
+ Outcome,
18
+ ReportResultMode,
19
+ )
20
+
21
+ __all__ = [
22
+ "AsyncGuard",
23
+ "AsyncRiskbound",
24
+ "Decision",
25
+ "DecisionStatus",
26
+ "FailMode",
27
+ "Guard",
28
+ "GuardResult",
29
+ "Outcome",
30
+ "ReportResultMode",
31
+ "Riskbound",
32
+ "RiskboundApprovalTimeoutError",
33
+ "RiskboundBlockedError",
34
+ "RiskboundError",
35
+ "RiskboundRequestError",
36
+ "RiskboundUnavailableError",
37
+ "Transport",
38
+ "TransportError",
39
+ "urllib_transport",
40
+ ]
riskbound/_client.py ADDED
@@ -0,0 +1,456 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import contextlib
5
+ import inspect
6
+ import json
7
+ import threading
8
+ import time
9
+ from collections.abc import Awaitable, Mapping
10
+ from typing import Any, Callable, Optional, TypeVar, Union, cast, overload
11
+
12
+ from ._errors import (
13
+ RiskboundApprovalTimeoutError,
14
+ RiskboundBlockedError,
15
+ RiskboundRequestError,
16
+ RiskboundUnavailableError,
17
+ )
18
+ from ._transport import Transport, TransportError, urllib_transport
19
+ from ._types import Decision, FailMode, GuardResult, ReportResultMode
20
+
21
+ # The SDK never decides anything. It asks the backend, then carries out the
22
+ # answer: run, wait for a person, dry run, or stop. It mirrors the
23
+ # TypeScript SDK in ../sdk, and both speak the same wire contract.
24
+
25
+ T = TypeVar("T")
26
+ D = TypeVar("D")
27
+ Params = Mapping[str, Any]
28
+ OnError = Callable[[BaseException], None]
29
+
30
+ DEFAULT_TIMEOUT = 3.0
31
+ DEFAULT_POLL_INTERVAL = 2.0
32
+ DEFAULT_APPROVAL_TIMEOUT = 15 * 60.0
33
+
34
+
35
+ class _Core:
36
+ """Settings and the parts that do not care about sync or async."""
37
+
38
+ def __init__(
39
+ self,
40
+ api_key: str,
41
+ base_url: str,
42
+ *,
43
+ timeout: float,
44
+ fail_mode: FailMode,
45
+ approval_poll_interval: float,
46
+ approval_timeout: float,
47
+ report_result: ReportResultMode,
48
+ on_error: Optional[OnError],
49
+ transport: Optional[Transport],
50
+ clock: Optional[Callable[[], float]],
51
+ ) -> None:
52
+ if not api_key:
53
+ raise ValueError("Riskbound: api_key is required")
54
+ if not base_url:
55
+ raise ValueError("Riskbound: base_url is required")
56
+ if fail_mode not in ("closed", "open"):
57
+ raise ValueError("Riskbound: fail_mode must be 'closed' or 'open'")
58
+ if report_result not in ("await", "background"):
59
+ raise ValueError("Riskbound: report_result must be 'await' or 'background'")
60
+ self.api_key = api_key
61
+ self.base_url = base_url.rstrip("/")
62
+ self.timeout = timeout
63
+ self.fail_mode: FailMode = fail_mode
64
+ self.poll_interval = approval_poll_interval
65
+ self.approval_timeout = approval_timeout
66
+ self.report_result: ReportResultMode = report_result
67
+ self.transport: Transport = transport or urllib_transport
68
+ self.clock = clock or time.monotonic
69
+ self._on_error = on_error
70
+
71
+ def on_error(self, err: BaseException) -> None:
72
+ # A throwing on_error must not change what the caller sees.
73
+ if self._on_error is None:
74
+ return
75
+ with contextlib.suppress(Exception):
76
+ self._on_error(err)
77
+
78
+ # One request to the backend. Network failures, timeouts and 5xx answers
79
+ # mean "unavailable". A 4xx means the request is wrong.
80
+ def send(self, method: str, path: str, body: Optional[Any] = None) -> Any:
81
+ headers = {"authorization": f"Bearer {self.api_key}", "accept": "application/json"}
82
+ data: Optional[bytes] = None
83
+ if body is not None:
84
+ headers["content-type"] = "application/json"
85
+ data = json.dumps(body).encode("utf-8")
86
+ try:
87
+ status, raw = self.transport(
88
+ method, f"{self.base_url}{path}", headers, data, self.timeout
89
+ )
90
+ except TransportError as err:
91
+ raise RiskboundUnavailableError(f"the request did not complete: {err}") from err
92
+ if status >= 500:
93
+ raise RiskboundUnavailableError(f"the backend answered {status}")
94
+ try:
95
+ parsed: Any = json.loads(raw.decode("utf-8")) if raw else None
96
+ except (ValueError, UnicodeDecodeError):
97
+ parsed = None
98
+ if status < 200 or status >= 300:
99
+ raise RiskboundRequestError(status, parsed)
100
+ return parsed
101
+
102
+ def decision_body(
103
+ self,
104
+ agent: str,
105
+ tool: str,
106
+ params: Params,
107
+ dry_run_supported: bool,
108
+ idempotency_key: Optional[str],
109
+ ) -> dict[str, Any]:
110
+ body: dict[str, Any] = {
111
+ "agent": agent,
112
+ "tool": tool,
113
+ "params": dict(params),
114
+ "dry_run_supported": dry_run_supported,
115
+ "via": "sdk",
116
+ }
117
+ if idempotency_key is not None:
118
+ body["idempotency_key"] = idempotency_key
119
+ return body
120
+
121
+
122
+ def _check_guard(agent: str, fail_mode: Optional[FailMode], core: _Core) -> FailMode:
123
+ if not agent:
124
+ raise ValueError("guard: agent is required")
125
+ mode = fail_mode or core.fail_mode
126
+ if mode not in ("closed", "open"):
127
+ raise ValueError("guard: fail_mode must be 'closed' or 'open'")
128
+ return mode
129
+
130
+
131
+ def _describe(err: BaseException) -> str:
132
+ return str(err) or type(err).__name__
133
+
134
+
135
+ class Riskbound:
136
+ """The synchronous client.
137
+
138
+ rb = Riskbound(api_key=..., base_url="https://...")
139
+ refund = rb.guard("refund", agent="support-bot")
140
+ result = refund({"amount_minor": 4800, "currency": "USD"}, lambda: pay(...))
141
+ """
142
+
143
+ def __init__(
144
+ self,
145
+ api_key: str,
146
+ base_url: str,
147
+ *,
148
+ timeout: float = DEFAULT_TIMEOUT,
149
+ fail_mode: FailMode = "closed",
150
+ approval_poll_interval: float = DEFAULT_POLL_INTERVAL,
151
+ approval_timeout: float = DEFAULT_APPROVAL_TIMEOUT,
152
+ report_result: ReportResultMode = "await",
153
+ on_error: Optional[OnError] = None,
154
+ transport: Optional[Transport] = None,
155
+ sleep: Optional[Callable[[float], None]] = None,
156
+ clock: Optional[Callable[[], float]] = None,
157
+ ) -> None:
158
+ self._core = _Core(
159
+ api_key,
160
+ base_url,
161
+ timeout=timeout,
162
+ fail_mode=fail_mode,
163
+ approval_poll_interval=approval_poll_interval,
164
+ approval_timeout=approval_timeout,
165
+ report_result=report_result,
166
+ on_error=on_error,
167
+ transport=transport,
168
+ clock=clock,
169
+ )
170
+ self._sleep = sleep or time.sleep
171
+
172
+ def guard(self, tool: str, *, agent: str, fail_mode: Optional[FailMode] = None) -> Guard:
173
+ """Returns a function that asks Riskbound before running an action."""
174
+ return Guard(self, tool, agent, _check_guard(agent, fail_mode, self._core))
175
+
176
+ def _wait_for_approval(self, decision: Decision) -> Decision:
177
+ core = self._core
178
+ deadline = core.clock() + core.approval_timeout
179
+ current = decision
180
+ while current["status"] == "pending_approval":
181
+ if core.clock() >= deadline:
182
+ raise RiskboundApprovalTimeoutError(decision["id"])
183
+ self._sleep(core.poll_interval)
184
+ current = cast(Decision, core.send("GET", f"/v1/decisions/{decision['id']}"))
185
+ return current
186
+
187
+ # The action already ran or failed, so a reporting problem must not
188
+ # change what the caller sees. It goes to on_error instead.
189
+ def _report(self, decision_id: str, status: str, detail: Optional[str] = None) -> None:
190
+ core = self._core
191
+ body: dict[str, Any] = {"status": status}
192
+ if detail is not None:
193
+ body["detail"] = detail
194
+
195
+ def send() -> None:
196
+ try:
197
+ core.send("POST", f"/v1/decisions/{decision_id}/result", body)
198
+ except Exception as err:
199
+ core.on_error(err)
200
+
201
+ if core.report_result == "await":
202
+ send()
203
+ else:
204
+ threading.Thread(target=send, name="riskbound-report", daemon=True).start()
205
+
206
+ def _run(self, decision_id: str, action: Callable[[], T]) -> T:
207
+ try:
208
+ value = action()
209
+ except BaseException as err:
210
+ self._report(decision_id, "failed", _describe(err))
211
+ raise
212
+ self._report(decision_id, "executed")
213
+ return value
214
+
215
+
216
+ class Guard:
217
+ """One guarded tool for one agent. Call it with the params and the action."""
218
+
219
+ def __init__(self, client: Riskbound, tool: str, agent: str, fail_mode: FailMode) -> None:
220
+ self._client = client
221
+ self.tool = tool
222
+ self.agent = agent
223
+ self.fail_mode: FailMode = fail_mode
224
+
225
+ def __call__(
226
+ self,
227
+ params: Params,
228
+ action: Callable[[], T],
229
+ *,
230
+ dry_run: Optional[Callable[[], D]] = None,
231
+ idempotency_key: Optional[str] = None,
232
+ ) -> GuardResult[Union[T, D]]:
233
+ client = self._client
234
+ core = client._core
235
+ try:
236
+ decision = cast(
237
+ Decision,
238
+ core.send(
239
+ "POST",
240
+ "/v1/decisions",
241
+ core.decision_body(
242
+ self.agent, self.tool, params, dry_run is not None, idempotency_key
243
+ ),
244
+ ),
245
+ )
246
+ except RiskboundUnavailableError as err:
247
+ if self.fail_mode == "open":
248
+ core.on_error(err)
249
+ return GuardResult(True, "fail_open", None, action())
250
+ raise
251
+
252
+ outcome = decision["outcome"]
253
+ if outcome == "allow":
254
+ return GuardResult(True, "allow", decision["id"], client._run(decision["id"], action))
255
+ if outcome == "ask_human":
256
+ # Once a person has been asked, an unreachable backend never falls
257
+ # back to running the action, whatever the fail mode.
258
+ resolved = client._wait_for_approval(decision)
259
+ if resolved["status"] != "approved":
260
+ raise RiskboundBlockedError([f"approval_{resolved['status']}"], decision["id"])
261
+ return GuardResult(
262
+ True, "ask_human", decision["id"], client._run(decision["id"], action)
263
+ )
264
+ if outcome == "dry_run":
265
+ if dry_run is None:
266
+ raise RiskboundBlockedError(["dry_run_unsupported"], decision["id"])
267
+ return GuardResult(False, "dry_run", decision["id"], dry_run())
268
+ raise RiskboundBlockedError(list(decision.get("reasons") or []), decision["id"])
269
+
270
+
271
+ # ---- The async client. Same behaviour; HTTP runs in a worker thread so the
272
+ # event loop is never blocked, and actions may be sync or async.
273
+
274
+ AsyncAction = Callable[[], Union[Awaitable[T], T]]
275
+
276
+
277
+ async def _call(fn: Callable[[], Union[Awaitable[T], T]]) -> T:
278
+ result = fn()
279
+ if inspect.isawaitable(result):
280
+ return cast(T, await result)
281
+ return result
282
+
283
+
284
+ class AsyncRiskbound:
285
+ """The asyncio client.
286
+
287
+ rb = AsyncRiskbound(api_key=..., base_url="https://...")
288
+ refund = rb.guard("refund", agent="support-bot")
289
+ result = await refund({"amount_minor": 4800}, lambda: pay_async(...))
290
+ """
291
+
292
+ def __init__(
293
+ self,
294
+ api_key: str,
295
+ base_url: str,
296
+ *,
297
+ timeout: float = DEFAULT_TIMEOUT,
298
+ fail_mode: FailMode = "closed",
299
+ approval_poll_interval: float = DEFAULT_POLL_INTERVAL,
300
+ approval_timeout: float = DEFAULT_APPROVAL_TIMEOUT,
301
+ report_result: ReportResultMode = "await",
302
+ on_error: Optional[OnError] = None,
303
+ transport: Optional[Transport] = None,
304
+ sleep: Optional[Callable[[float], Awaitable[None]]] = None,
305
+ clock: Optional[Callable[[], float]] = None,
306
+ ) -> None:
307
+ self._core = _Core(
308
+ api_key,
309
+ base_url,
310
+ timeout=timeout,
311
+ fail_mode=fail_mode,
312
+ approval_poll_interval=approval_poll_interval,
313
+ approval_timeout=approval_timeout,
314
+ report_result=report_result,
315
+ on_error=on_error,
316
+ transport=transport,
317
+ clock=clock,
318
+ )
319
+ self._sleep = sleep or asyncio.sleep
320
+ # Background reports, kept so they are not collected before they finish.
321
+ self._pending: set[asyncio.Task[None]] = set()
322
+
323
+ def guard(self, tool: str, *, agent: str, fail_mode: Optional[FailMode] = None) -> AsyncGuard:
324
+ return AsyncGuard(self, tool, agent, _check_guard(agent, fail_mode, self._core))
325
+
326
+ async def _send(self, method: str, path: str, body: Optional[Any] = None) -> Any:
327
+ return await asyncio.to_thread(self._core.send, method, path, body)
328
+
329
+ async def _wait_for_approval(self, decision: Decision) -> Decision:
330
+ core = self._core
331
+ deadline = core.clock() + core.approval_timeout
332
+ current = decision
333
+ while current["status"] == "pending_approval":
334
+ if core.clock() >= deadline:
335
+ raise RiskboundApprovalTimeoutError(decision["id"])
336
+ await self._sleep(core.poll_interval)
337
+ current = cast(Decision, await self._send("GET", f"/v1/decisions/{decision['id']}"))
338
+ return current
339
+
340
+ async def _report(self, decision_id: str, status: str, detail: Optional[str] = None) -> None:
341
+ core = self._core
342
+ body: dict[str, Any] = {"status": status}
343
+ if detail is not None:
344
+ body["detail"] = detail
345
+
346
+ async def send() -> None:
347
+ try:
348
+ await self._send("POST", f"/v1/decisions/{decision_id}/result", body)
349
+ except Exception as err:
350
+ core.on_error(err)
351
+
352
+ if core.report_result == "await":
353
+ await send()
354
+ else:
355
+ task = asyncio.ensure_future(send())
356
+ self._pending.add(task)
357
+ task.add_done_callback(self._pending.discard)
358
+
359
+ async def drain(self) -> None:
360
+ """Waits for background result reports. Call before the program exits."""
361
+ if self._pending:
362
+ await asyncio.gather(*self._pending, return_exceptions=True)
363
+
364
+ async def _run(self, decision_id: str, action: AsyncAction[T]) -> T:
365
+ try:
366
+ value = await _call(action)
367
+ except BaseException as err:
368
+ await self._report(decision_id, "failed", _describe(err))
369
+ raise
370
+ await self._report(decision_id, "executed")
371
+ return value
372
+
373
+
374
+ class AsyncGuard:
375
+ """One guarded tool for one agent, for asyncio code."""
376
+
377
+ def __init__(self, client: AsyncRiskbound, tool: str, agent: str, fail_mode: FailMode) -> None:
378
+ self._client = client
379
+ self.tool = tool
380
+ self.agent = agent
381
+ self.fail_mode: FailMode = fail_mode
382
+
383
+ # An action may be async or plain. The overloads let a type checker see
384
+ # what an awaited action returns.
385
+ @overload
386
+ async def __call__(
387
+ self,
388
+ params: Params,
389
+ action: Callable[[], Awaitable[T]],
390
+ *,
391
+ dry_run: None = None,
392
+ idempotency_key: Optional[str] = None,
393
+ ) -> GuardResult[T]: ...
394
+
395
+ @overload
396
+ async def __call__(
397
+ self,
398
+ params: Params,
399
+ action: Callable[[], T],
400
+ *,
401
+ dry_run: None = None,
402
+ idempotency_key: Optional[str] = None,
403
+ ) -> GuardResult[T]: ...
404
+
405
+ @overload
406
+ async def __call__(
407
+ self,
408
+ params: Params,
409
+ action: AsyncAction[Any],
410
+ *,
411
+ dry_run: AsyncAction[Any],
412
+ idempotency_key: Optional[str] = None,
413
+ ) -> GuardResult[Any]: ...
414
+
415
+ async def __call__(
416
+ self,
417
+ params: Params,
418
+ action: AsyncAction[Any],
419
+ *,
420
+ dry_run: Optional[AsyncAction[Any]] = None,
421
+ idempotency_key: Optional[str] = None,
422
+ ) -> GuardResult[Any]:
423
+ client = self._client
424
+ core = client._core
425
+ try:
426
+ decision = cast(
427
+ Decision,
428
+ await client._send(
429
+ "POST",
430
+ "/v1/decisions",
431
+ core.decision_body(
432
+ self.agent, self.tool, params, dry_run is not None, idempotency_key
433
+ ),
434
+ ),
435
+ )
436
+ except RiskboundUnavailableError as err:
437
+ if self.fail_mode == "open":
438
+ core.on_error(err)
439
+ return GuardResult(True, "fail_open", None, await _call(action))
440
+ raise
441
+
442
+ outcome = decision["outcome"]
443
+ if outcome == "allow":
444
+ value = await client._run(decision["id"], action)
445
+ return GuardResult(True, "allow", decision["id"], value)
446
+ if outcome == "ask_human":
447
+ resolved = await client._wait_for_approval(decision)
448
+ if resolved["status"] != "approved":
449
+ raise RiskboundBlockedError([f"approval_{resolved['status']}"], decision["id"])
450
+ value = await client._run(decision["id"], action)
451
+ return GuardResult(True, "ask_human", decision["id"], value)
452
+ if outcome == "dry_run":
453
+ if dry_run is None:
454
+ raise RiskboundBlockedError(["dry_run_unsupported"], decision["id"])
455
+ return GuardResult(False, "dry_run", decision["id"], await _call(dry_run))
456
+ raise RiskboundBlockedError(list(decision.get("reasons") or []), decision["id"])
riskbound/_errors.py ADDED
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class RiskboundError(Exception):
7
+ """Base class for every error the SDK raises."""
8
+
9
+
10
+ class RiskboundBlockedError(RiskboundError):
11
+ """Policy, a limit, a stop control or a person said no. The action did not run."""
12
+
13
+ def __init__(self, reasons: list[str], decision_id: str | None) -> None:
14
+ super().__init__(f"Action blocked by Riskbound: {', '.join(reasons)}")
15
+ self.reasons = reasons
16
+ self.decision_id = decision_id
17
+
18
+
19
+ class RiskboundUnavailableError(RiskboundError):
20
+ """Riskbound could not be reached and the guard fails closed. The action did not run."""
21
+
22
+ def __init__(self, message: str) -> None:
23
+ super().__init__(f"Riskbound is unavailable, so the action was not run: {message}")
24
+
25
+
26
+ class RiskboundApprovalTimeoutError(RiskboundError):
27
+ """Nobody answered the approval in time. The action did not run."""
28
+
29
+ def __init__(self, decision_id: str) -> None:
30
+ super().__init__("No one answered the approval request in time, so the action was not run")
31
+ self.decision_id = decision_id
32
+
33
+
34
+ class RiskboundRequestError(RiskboundError):
35
+ """The request itself is wrong: a bad key, a missing agent name, bad params.
36
+
37
+ Never treated as "unavailable", so fail-open does not apply.
38
+ """
39
+
40
+ def __init__(self, status: int, body: Any) -> None:
41
+ super().__init__(f"Riskbound rejected the request ({status}): {_describe(body)}")
42
+ self.status = status
43
+ self.body = body
44
+
45
+
46
+ def _describe(body: Any) -> str:
47
+ if isinstance(body, dict) and "message" in body:
48
+ return str(body["message"])
49
+ return body if isinstance(body, str) else "no details"
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ import http.client
4
+ import urllib.error
5
+ import urllib.request
6
+ from collections.abc import Mapping
7
+ from typing import Optional, Protocol
8
+
9
+
10
+ class TransportError(Exception):
11
+ """The request did not complete: no connection, a timeout, a reset."""
12
+
13
+
14
+ class Transport(Protocol):
15
+ """Sends one HTTP request and returns the status and body.
16
+
17
+ Raises TransportError when the request did not complete. Any HTTP status,
18
+ 4xx and 5xx included, is a completed request and is returned.
19
+ """
20
+
21
+ def __call__(
22
+ self,
23
+ method: str,
24
+ url: str,
25
+ headers: Mapping[str, str],
26
+ body: Optional[bytes],
27
+ timeout: float,
28
+ ) -> tuple[int, bytes]: ...
29
+
30
+
31
+ def urllib_transport(
32
+ method: str,
33
+ url: str,
34
+ headers: Mapping[str, str],
35
+ body: Optional[bytes],
36
+ timeout: float,
37
+ ) -> tuple[int, bytes]:
38
+ """The default transport, from the standard library."""
39
+ request = urllib.request.Request(url, data=body, method=method, headers=dict(headers))
40
+ try:
41
+ with urllib.request.urlopen(request, timeout=timeout) as res: # noqa: S310
42
+ return int(res.status), bytes(res.read())
43
+ except urllib.error.HTTPError as err:
44
+ return int(err.code), bytes(err.read() or b"")
45
+ except (
46
+ urllib.error.URLError,
47
+ http.client.HTTPException,
48
+ TimeoutError,
49
+ OSError,
50
+ ValueError,
51
+ ) as err:
52
+ raise TransportError(str(err)) from err
riskbound/_types.py ADDED
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Generic, Literal, Optional, TypedDict, TypeVar
5
+
6
+ # The wire contract is the backend's /v1/decisions routes, in
7
+ # ../src/modules/decisions, and matches the TypeScript SDK (../sdk/src/types.ts).
8
+
9
+ Outcome = Literal["allow", "ask_human", "dry_run", "block"]
10
+
11
+ DecisionStatus = Literal[
12
+ "allowed",
13
+ "pending_approval",
14
+ "approved",
15
+ "rejected",
16
+ "expired",
17
+ "dry_run",
18
+ "blocked",
19
+ "executed",
20
+ "failed",
21
+ ]
22
+
23
+ # closed: if Riskbound cannot be reached, the action does not run. The default.
24
+ # open: if Riskbound cannot be reached, the action runs unchecked.
25
+ FailMode = Literal["closed", "open"]
26
+
27
+ # await: the guard returns once the result report is sent. The default.
28
+ # background: the guard returns as soon as the action does; the report is
29
+ # sent after, on a daemon thread (or a task, for the async client).
30
+ ReportResultMode = Literal["await", "background"]
31
+
32
+
33
+ class Approval(TypedDict):
34
+ id: str
35
+ status: str
36
+ expiresAt: str
37
+
38
+
39
+ class Decision(TypedDict):
40
+ """What the backend returns for a decision."""
41
+
42
+ id: str
43
+ outcome: Outcome
44
+ status: DecisionStatus
45
+ reasons: list[str]
46
+ agent: str
47
+ tool: str
48
+ policyVersion: Optional[int]
49
+ approval: Optional[Approval]
50
+ createdAt: str
51
+
52
+
53
+ T = TypeVar("T")
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class GuardResult(Generic[T]):
58
+ """What happened.
59
+
60
+ ran: True if the real action ran.
61
+ outcome: "allow" or "ask_human" when it ran after a check, "dry_run" when
62
+ only the dry-run handler ran, "fail_open" when Riskbound was unreachable and
63
+ the guard is set to fail open.
64
+ decision_id: None only for fail_open.
65
+ value: what the action (or the dry-run handler) returned.
66
+ """
67
+
68
+ ran: bool
69
+ outcome: Literal["allow", "ask_human", "dry_run", "fail_open"]
70
+ decision_id: Optional[str]
71
+ value: T
riskbound/py.typed ADDED
File without changes
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: riskbound
3
+ Version: 0.1.1
4
+ Summary: Ask Riskbound before an AI agent acts, then carry out the answer.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://riskbound.ai
7
+ Project-URL: Documentation, https://docs.riskbound.ai
8
+ Project-URL: Source, https://github.com/riskboundhq/riskbound
9
+ Keywords: ai-agents,agent-security,ai-governance,guardrails,mcp,human-in-the-loop
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8; extra == "dev"
20
+ Requires-Dist: mypy>=1.11; extra == "dev"
21
+ Requires-Dist: ruff>=0.6; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # Riskbound SDK (Python)
25
+
26
+ The Python SDK. It asks Riskbound before an AI agent acts, then carries out
27
+ the answer. It matches the TypeScript SDK in `../sdk` in behaviour and on the
28
+ wire. It has no runtime dependencies, needs Python 3.10 or later, and is not
29
+ published yet.
30
+
31
+ ```python
32
+ import os
33
+ from riskbound import Riskbound, RiskboundBlockedError
34
+
35
+ rb = Riskbound(api_key=os.environ["RISKBOUND_API_KEY"], base_url="http://localhost:8200")
36
+ refund = rb.guard("refund", agent="support-bot")
37
+
38
+ try:
39
+ result = refund(
40
+ {"order_id": "ord_2291", "amount_minor": 48000, "currency": "USD"},
41
+ lambda: payments.refund("ord_2291", 48000),
42
+ )
43
+ # result.outcome is "allow" or "ask_human"; result.value is what the action returned.
44
+ except RiskboundBlockedError as err:
45
+ # err.reasons says why: a policy id, "spend_cap", "kill_switch", ...
46
+ ...
47
+ ```
48
+
49
+ For asyncio code, use `AsyncRiskbound`. Actions may be `async` or plain
50
+ functions. HTTP runs in a worker thread, so the event loop is not blocked.
51
+
52
+ ```python
53
+ from riskbound import AsyncRiskbound
54
+
55
+ rb = AsyncRiskbound(api_key=..., base_url=...)
56
+ refund = rb.guard("refund", agent="support-bot")
57
+ result = await refund({"amount_minor": 48000, "currency": "USD"}, do_refund_async)
58
+ ```
59
+
60
+ ## What happens for each outcome
61
+
62
+ | Outcome | What the SDK does |
63
+ |---|---|
64
+ | `allow` | Runs the action and reports the result |
65
+ | `ask_human` | Waits for a person, polling every `approval_poll_interval` seconds. Runs on approval; raises `RiskboundBlockedError` on rejection or expiry, `RiskboundApprovalTimeoutError` after `approval_timeout` seconds |
66
+ | `dry_run` | Runs the `dry_run=` handler you passed, never the real action. Without a handler, policy never offers a dry run, and if it does anyway the call is blocked |
67
+ | `block` | Raises `RiskboundBlockedError`. The action does not run |
68
+
69
+ ## When Riskbound cannot be reached
70
+
71
+ By default the guard fails closed: it raises `RiskboundUnavailableError` and
72
+ the action does not run. That covers no connection, a timeout (`timeout=`,
73
+ 3 seconds by default) and any 5xx answer. Pass `fail_mode="open"` to a guard
74
+ to run the action unchecked instead; the result says `outcome="fail_open"`
75
+ and the error goes to `on_error`. Fail-open never applies to a rejected
76
+ request (4xx, `RiskboundRequestError`), and never once a person has been asked.
77
+
78
+ ## Reporting the result
79
+
80
+ After the action runs, the SDK tells Riskbound whether it worked. A raised
81
+ exception is reported as failed, with its message, and raised again
82
+ unchanged. By default the guard waits for the report. Pass
83
+ `report_result="background"` to send it after: on a daemon thread for
84
+ `Riskbound`, as a task for `AsyncRiskbound` (call `await rb.drain()` before the
85
+ program exits). A failed report goes to `on_error` and never changes the
86
+ result.
87
+
88
+ ## Other options
89
+
90
+ - `idempotency_key=` on a call: send the same key again to get the same
91
+ answer instead of a new decision.
92
+ - Requests carry `via: "sdk"`, which the risk score uses
93
+ (`../docs/adr/0010-risk-score.md`).
94
+ - `transport=`, `sleep=` and `clock=` are for tests.
95
+
96
+ ## Amounts
97
+
98
+ Send amounts as whole numbers in minor units (`amount_minor: 48000` for
99
+ $480.00). Floats are rejected by the backend.
100
+
101
+ ## Develop
102
+
103
+ ```bash
104
+ uv venv .venv && uv pip install -e '.[dev]'
105
+ .venv/bin/ruff check . && .venv/bin/ruff format --check . && .venv/bin/mypy && .venv/bin/pytest
106
+ ```
107
+
108
+ Tests run the SDK against a stand-in Riskbound API on a real local HTTP
109
+ server (`tests/fake_server.py`), so the real transport is used.
@@ -0,0 +1,11 @@
1
+ riskbound/__init__.py,sha256=fgf7irzw0bWFoY-p1KnfmRnnlX7wc-8BYzMijF88eVw,922
2
+ riskbound/_client.py,sha256=xSh_11UaTplnxA4mBu50k8Dt5y8j1ABs36M5vU2_l4I,16588
3
+ riskbound/_errors.py,sha256=6XgfXDxw26LaFA_x8U0CmxwV5GUE_q5zJDJI0Qlql8E,1694
4
+ riskbound/_transport.py,sha256=BqPwNOUVvntQ8zwH_AnNSbBZYqfO5ISUWpZaQT3dOQw,1474
5
+ riskbound/_types.py,sha256=KqGdbsr2686fYxnCZr-zMqzd3nHLTxqwZRoxKlG5hmA,1890
6
+ riskbound/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ riskbound-0.1.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ riskbound-0.1.1.dist-info/METADATA,sha256=39ba00JrzheNHggrcQB6r4qo0L5uYKkfc6xNpQcsUh0,4345
9
+ riskbound-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ riskbound-0.1.1.dist-info/top_level.txt,sha256=SAiWpgs99qaria0WYblG6tlZAXMiMGInvXyEl3XrupU,10
11
+ riskbound-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ riskbound