haltstate-sdk 0.6.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.
haltstate/__init__.py ADDED
@@ -0,0 +1,66 @@
1
+ # HaltState SDK - re-exports from janus for new branding
2
+ # Backward compatible: both `from haltstate import HaltStateClient` and
3
+ # `from janus import JanusClient` continue to work.
4
+
5
+ from janus.client import JanusClient as HaltStateClient, Permit
6
+ from janus.async_client import AsyncJanusClient as AsyncHaltStateClient
7
+ from janus.models import CheckResult, Decision, ApprovalDecision, ApprovalStatus
8
+ from janus.decorators import janus_guard as haltstate_guard, openai_guard
9
+ from janus.exceptions import (
10
+ JanusError as HaltStateError,
11
+ JanusConnectionError as HaltStateConnectionError,
12
+ JanusAuthError as HaltStateAuthError,
13
+ JanusRateLimitError as HaltStateRateLimitError,
14
+ JanusApprovalTimeoutError as HaltStateApprovalTimeoutError,
15
+ ApprovalPending,
16
+ ActionDenied,
17
+ ActionExpired,
18
+ KillSwitchTriggered,
19
+ )
20
+
21
+ # Keep Janus names as aliases for full backward compatibility
22
+ from janus import (
23
+ JanusClient,
24
+ AsyncJanusClient,
25
+ janus_guard,
26
+ JanusError,
27
+ JanusConnectionError,
28
+ JanusAuthError,
29
+ JanusRateLimitError,
30
+ JanusApprovalTimeoutError,
31
+ )
32
+
33
+ __all__ = [
34
+ # HaltState branded names (new)
35
+ "HaltStateClient",
36
+ "AsyncHaltStateClient",
37
+ "haltstate_guard",
38
+ "HaltStateError",
39
+ "HaltStateConnectionError",
40
+ "HaltStateAuthError",
41
+ "HaltStateRateLimitError",
42
+ "HaltStateApprovalTimeoutError",
43
+ # Janus names (backward compatible)
44
+ "JanusClient",
45
+ "AsyncJanusClient",
46
+ "janus_guard",
47
+ "JanusError",
48
+ "JanusConnectionError",
49
+ "JanusAuthError",
50
+ "JanusRateLimitError",
51
+ "JanusApprovalTimeoutError",
52
+ # Shared models
53
+ "CheckResult",
54
+ "Decision",
55
+ "ApprovalDecision",
56
+ "ApprovalStatus",
57
+ "Permit",
58
+ "openai_guard",
59
+ # Control flow exceptions
60
+ "ApprovalPending",
61
+ "ActionDenied",
62
+ "ActionExpired",
63
+ "KillSwitchTriggered",
64
+ ]
65
+
66
+ __version__ = "0.5.0"
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.4
2
+ Name: haltstate-sdk
3
+ Version: 0.6.0
4
+ Summary: HaltState Sentinel Python SDK - Compliance & Policy Checks for AI Agents
5
+ Author-email: Krystal Unity <support@krystalunity.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Krystal Unity
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://haltstate.ai
29
+ Project-URL: Repository, https://github.com/StartKrystal/krystal-unity-core
30
+ Project-URL: Issues, https://github.com/StartKrystal/krystal-unity-core/issues
31
+ Project-URL: Documentation, https://haltstate.ai/docs
32
+ Keywords: haltstate,janus,sentinel,ai,compliance,policy,sdk,safety
33
+ Classifier: Development Status :: 4 - Beta
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
42
+ Classifier: Topic :: Security
43
+ Requires-Python: >=3.9
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: httpx>=0.24
47
+ Dynamic: license-file
48
+
49
+ # HaltState Sentinel SDK
50
+
51
+ [![PyPI](https://img.shields.io/pypi/v/haltstate-sdk.svg)](https://pypi.org/project/haltstate-sdk/)
52
+
53
+ Compliance & policy checks for AI agents. Perform pre-action checks, approvals, and post-action reporting with minimal code.
54
+
55
+ ## Installation
56
+ ```bash
57
+ pip install haltstate-sdk
58
+ ```
59
+
60
+ ## Quickstart (sync)
61
+ ```python
62
+ from haltstate import HaltStateClient
63
+
64
+ client = HaltStateClient(tenant_id="your_tenant_id", api_key="janus_xyz", fail_open=False)
65
+
66
+ decision = client.check(
67
+ action="payment.process",
68
+ params={"amount": 5000, "currency": "USD"},
69
+ agent_id="payment-bot-01",
70
+ )
71
+
72
+ if decision.allowed:
73
+ process_payment(...)
74
+ client.report(decision, status="success", result={"transaction_id": "tx_123"}, action="payment.process", agent_id="payment-bot-01")
75
+ elif decision.requires_approval:
76
+ print(f"Approval required: {decision.reason}")
77
+ else:
78
+ print(f"Action denied: {decision.reason}")
79
+ ```
80
+
81
+ ### Backward Compatibility
82
+
83
+ Existing code using `janus` imports continues to work:
84
+
85
+ ```python
86
+ from janus import JanusClient # Still works!
87
+ ```
88
+
89
+ ## Guard Pattern (SDK 0.5.0+)
90
+
91
+ For actions requiring human approval, use the idempotent guard pattern:
92
+
93
+ ```python
94
+ from haltstate import AsyncHaltStateClient, ActionPending, ActionRejected
95
+
96
+ async def process_high_value_payment(invoice_id: str, amount: float):
97
+ client = AsyncHaltStateClient(tenant_id="acme", api_key="janus_xxx")
98
+
99
+ try:
100
+ async with client.guard(
101
+ action="payment.process",
102
+ agent_id="payment-bot",
103
+ params={"invoice_id": invoice_id, "amount": amount},
104
+ idempotency_key=f"payment-{invoice_id}", # Retry-safe
105
+ timeout_seconds=300
106
+ ) as permit:
107
+ # Only executes after human approval
108
+ result = await execute_payment(amount)
109
+ print(f"Approved by {permit.approver} at {permit.approved_at}")
110
+ return result
111
+
112
+ except ActionPending:
113
+ print("Awaiting human approval...")
114
+ return {"status": "pending"}
115
+
116
+ except ActionRejected as e:
117
+ print(f"Rejected by {e.rejected_by}: {e.reason}")
118
+ raise
119
+ ```
120
+
121
+ Key features:
122
+ - **Idempotency keys**: Same key = same approval request, safe for retries
123
+ - **Process restart safety**: Approved actions can be executed after restart
124
+ - **Audit trail**: Full record of who approved and when
125
+
126
+ ## Decorators
127
+ ```python
128
+ from haltstate import HaltStateClient, haltstate_guard
129
+
130
+ client = HaltStateClient(tenant_id="acme", api_key="janus_xxx")
131
+
132
+ @haltstate_guard(client, action="email.send", agent_id="email-bot")
133
+ def send_email(to, subject, body):
134
+ return mailer.send(to, subject, body)
135
+ ```
136
+
137
+ ## Async
138
+ ```python
139
+ from haltstate import AsyncHaltStateClient
140
+
141
+ async def main():
142
+ async with AsyncHaltStateClient(tenant_id="acme", api_key="janus_xxx") as client:
143
+ res = await client.check("database.drop", params={"table": "users"})
144
+ if res.allowed:
145
+ await client.report(res, status="success", action="database.drop", agent_id="ops-bot")
146
+ ```
147
+
148
+ ## Exceptions
149
+
150
+ ```python
151
+ from haltstate import (
152
+ HaltStateError, # Base error
153
+ HaltStateAuthError, # Invalid API key
154
+ HaltStateConnectionError, # Network/timeout
155
+ ActionPending, # Awaiting approval (guard pattern)
156
+ ActionRejected, # Human rejected (guard pattern)
157
+ ActionTimeout, # Approval expired (guard pattern)
158
+ )
159
+ ```
160
+
161
+ ## Docs
162
+
163
+ Full documentation at [haltstate.ai/docs](https://haltstate.ai/docs):
164
+ - Quickstart - 5-minute setup
165
+ - Guard Pattern - HITL approval flow
166
+ - API Reference - All methods
167
+ - Error Handling - Exception handling
168
+ - SB-53 Compliance - Regulatory mapping
169
+
170
+ ## Migration from janus-sdk
171
+
172
+ If upgrading from `janus-sdk`:
173
+
174
+ ```python
175
+ # Old (still works)
176
+ from janus import JanusClient, janus_guard
177
+
178
+ # New
179
+ from haltstate import HaltStateClient, haltstate_guard
180
+ ```
181
+
182
+ Both import styles work - no code changes required for existing users.
183
+
184
+ ## License
185
+ MIT
@@ -0,0 +1,12 @@
1
+ haltstate/__init__.py,sha256=uVWzd77ZKnGRFkwHAVAPqJpZU43J22mxmMo60zEg448,1876
2
+ haltstate_sdk-0.6.0.dist-info/licenses/LICENSE,sha256=l9IQitroqvw1jSejXkOrkZWESb0CcxhYm-H4jd8sMOA,1070
3
+ janus/__init__.py,sha256=trWgl6pQjvys1KDg67xPEtO-e0WkKpZVNfjRc20dvKM,1029
4
+ janus/async_client.py,sha256=YAz0L8Tb--V1t5B0nGvJl372e9S4uASHefSDhI7qlgo,13360
5
+ janus/client.py,sha256=r6VgC7NKGHtSD3WpYtOn7pDJICX3Qn5SK8YnfZl31do,29515
6
+ janus/decorators.py,sha256=yYpbPa-n3IpMSv_Bbq1GclixeLSzktJnvXYE-PJHw-8,3436
7
+ janus/exceptions.py,sha256=_RXIyzr4dFF1XtQduI-yQvSR5EIdudHUAliv04wC4io,2112
8
+ janus/models.py,sha256=K8ZcZ-hFhPfJunwgUXpi91r7qPnjpzzWWbeG8HSFhbI,1940
9
+ haltstate_sdk-0.6.0.dist-info/METADATA,sha256=wqJjIqIdlFxlQ1zqsnnyk6sgSYTd6d_8bW-DbS7W5-o,6341
10
+ haltstate_sdk-0.6.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ haltstate_sdk-0.6.0.dist-info/top_level.txt,sha256=pAzUdHCySp2XktDm8a5wjdtPWXTvbCzjO-p-J-29Pr0,16
12
+ haltstate_sdk-0.6.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Krystal Unity
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.
@@ -0,0 +1,2 @@
1
+ haltstate
2
+ janus
janus/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ from .client import JanusClient, Permit
2
+ from .async_client import AsyncJanusClient
3
+ from .models import CheckResult, Decision, ApprovalDecision, ApprovalStatus
4
+ from .decorators import janus_guard, openai_guard
5
+ from .exceptions import (
6
+ JanusError,
7
+ JanusConnectionError,
8
+ JanusAuthError,
9
+ JanusRateLimitError,
10
+ JanusApprovalTimeoutError,
11
+ ApprovalPending,
12
+ ActionDenied,
13
+ ActionExpired,
14
+ KillSwitchTriggered,
15
+ )
16
+
17
+ __all__ = [
18
+ # Clients
19
+ "JanusClient",
20
+ "AsyncJanusClient",
21
+ # Models
22
+ "CheckResult",
23
+ "Decision",
24
+ "ApprovalDecision",
25
+ "ApprovalStatus",
26
+ "Permit",
27
+ # Decorators
28
+ "janus_guard",
29
+ "openai_guard",
30
+ # Exceptions
31
+ "JanusError",
32
+ "JanusConnectionError",
33
+ "JanusAuthError",
34
+ "JanusRateLimitError",
35
+ "JanusApprovalTimeoutError",
36
+ # Guard pattern exceptions (control flow)
37
+ "ApprovalPending",
38
+ "ActionDenied",
39
+ "ActionExpired",
40
+ "KillSwitchTriggered",
41
+ ]
42
+
43
+ __version__ = "0.5.0" # Idempotent Guard pattern for autonomous agents
janus/async_client.py ADDED
@@ -0,0 +1,340 @@
1
+ import uuid
2
+ import json
3
+ from datetime import datetime
4
+ from typing import Dict, Any, Optional, List, AsyncIterator, Callable
5
+
6
+ import httpx
7
+
8
+ from .models import CheckResult, Decision, ApprovalDecision, ApprovalStatus
9
+ from .exceptions import JanusError, JanusConnectionError, JanusAuthError, JanusRateLimitError, JanusApprovalTimeoutError
10
+
11
+
12
+ class AsyncJanusClient:
13
+ """Asynchronous Janus SDK client."""
14
+
15
+ DEFAULT_BASE_URL = "https://krystalunity.com"
16
+ DEFAULT_TIMEOUT = 5.0
17
+
18
+ def __init__(
19
+ self,
20
+ tenant_id: str,
21
+ api_key: str,
22
+ base_url: Optional[str] = None,
23
+ timeout: Optional[float] = None,
24
+ fail_open: bool = False,
25
+ retry_count: int = 2,
26
+ ):
27
+ self.tenant_id = tenant_id
28
+ self.api_key = api_key
29
+ self.base_url = (base_url or self.DEFAULT_BASE_URL).rstrip("/")
30
+ self.timeout = timeout or self.DEFAULT_TIMEOUT
31
+ self.fail_open = fail_open
32
+ self.retry_count = retry_count
33
+
34
+ self._client = httpx.AsyncClient(
35
+ timeout=self.timeout,
36
+ headers={
37
+ "Content-Type": "application/json",
38
+ "X-Tenant-Id": self.tenant_id,
39
+ "X-API-Key": self.api_key,
40
+ "X-Admin-Token": self.api_key, # Also send as admin token for approval endpoints
41
+ },
42
+ )
43
+
44
+ async def check(self, action: str, params: Dict[str, Any], agent_id: str = "default") -> CheckResult:
45
+ request_id = str(uuid.uuid4())
46
+
47
+ for attempt in range(self.retry_count + 1):
48
+ try:
49
+ response = await self._client.post(
50
+ f"{self.base_url}/api/sentinel/action/check",
51
+ json={"agent_id": agent_id, "action": action, "params": params},
52
+ )
53
+
54
+ if response.status_code == 401:
55
+ raise JanusAuthError("Invalid API key")
56
+ if response.status_code == 429:
57
+ if attempt < self.retry_count:
58
+ continue
59
+ raise JanusRateLimitError("Rate limit exceeded")
60
+ if response.status_code >= 400:
61
+ raise JanusError(f"API error: {response.text}")
62
+
63
+ data = response.json()
64
+ decision = Decision(data["decision"])
65
+ approval_id = data.get("approval_id") or data.get("request_id")
66
+
67
+ return CheckResult(
68
+ decision=decision,
69
+ reason=data.get("reason", ""),
70
+ policy_id=data.get("policy_id"),
71
+ latency_ms=data.get("latency_ms", 0),
72
+ request_id=request_id,
73
+ approval_id=approval_id if decision == Decision.APPROVAL_REQUIRED else None,
74
+ )
75
+
76
+ except httpx.RequestError as exc:
77
+ if attempt < self.retry_count:
78
+ continue
79
+ if self.fail_open:
80
+ return CheckResult(
81
+ decision=Decision.ALLOW,
82
+ reason="Fail-open: connection error",
83
+ policy_id=None,
84
+ latency_ms=0,
85
+ request_id=request_id,
86
+ )
87
+ raise JanusConnectionError(f"Connection failed: {exc}")
88
+
89
+ raise JanusError("Unknown error")
90
+
91
+ async def report(
92
+ self,
93
+ check_result: CheckResult,
94
+ status: str,
95
+ result: Optional[Dict[str, Any]] = None,
96
+ agent_id: str = "default",
97
+ action: Optional[str] = None,
98
+ ) -> None:
99
+ payload = {
100
+ "request_id": check_result.request_id,
101
+ "agent_id": agent_id,
102
+ "action": action or "",
103
+ "status": status,
104
+ "decision": check_result.decision.value,
105
+ "policy_id": check_result.policy_id,
106
+ "result": result,
107
+ }
108
+ try:
109
+ await self._client.post(f"{self.base_url}/api/sentinel/action/report", json=payload)
110
+ except Exception:
111
+ return
112
+
113
+ async def close(self) -> None:
114
+ await self._client.aclose()
115
+
116
+ async def __aenter__(self):
117
+ return self
118
+
119
+ async def __aexit__(self, *args):
120
+ await self.close()
121
+
122
+ # =========================================================================
123
+ # Approval Notifications - SSE Stream & Catch-up
124
+ # =========================================================================
125
+
126
+ async def get_approvals_since(
127
+ self,
128
+ since: str,
129
+ limit: int = 100,
130
+ ) -> List[ApprovalDecision]:
131
+ """
132
+ Fetch approval decisions since a given timestamp.
133
+ Use this for catch-up when reconnecting or for polling-based integrations.
134
+
135
+ Args:
136
+ since: ISO timestamp (e.g., "2025-01-01T00:00:00Z")
137
+ limit: Maximum number of decisions to return (1-500)
138
+
139
+ Returns:
140
+ List of ApprovalDecision objects ordered by decided_at ascending
141
+ """
142
+ try:
143
+ response = await self._client.get(
144
+ f"{self.base_url}/api/sentinel/approvals/since",
145
+ params={"tenant_id": self.tenant_id, "since": since, "limit": limit},
146
+ )
147
+
148
+ if response.status_code == 401:
149
+ raise JanusAuthError("Invalid API key")
150
+ if response.status_code >= 400:
151
+ raise JanusError(f"API error: {response.text}")
152
+
153
+ data = response.json()
154
+ decisions = []
155
+ for d in data.get("decisions", []):
156
+ decisions.append(ApprovalDecision(
157
+ request_id=d["request_id"],
158
+ status=ApprovalStatus(d["status"]),
159
+ approver=d.get("approver"),
160
+ reason=d.get("reason"),
161
+ agent_id=d.get("agent_id"),
162
+ action=d.get("action"),
163
+ timestamp=d.get("decided_at"),
164
+ is_catchup=True,
165
+ ))
166
+ return decisions
167
+
168
+ except httpx.RequestError as exc:
169
+ raise JanusConnectionError(f"Connection failed: {exc}")
170
+
171
+ async def subscribe_approvals(
172
+ self,
173
+ last_seen: Optional[str] = None,
174
+ on_connected: Optional[Callable[[], None]] = None,
175
+ ) -> AsyncIterator[ApprovalDecision]:
176
+ """
177
+ Subscribe to real-time approval decision notifications via SSE.
178
+
179
+ This is an async generator that yields ApprovalDecision objects as they arrive.
180
+ The connection is kept alive with heartbeats from the server.
181
+
182
+ Args:
183
+ last_seen: Optional ISO timestamp for catch-up. If provided, any decisions
184
+ made after this timestamp will be sent first before real-time events.
185
+ on_connected: Optional callback invoked when SSE connection is established.
186
+
187
+ Yields:
188
+ ApprovalDecision objects as they arrive
189
+
190
+ Example:
191
+ async for decision in client.subscribe_approvals(last_seen="2025-01-01T00:00:00Z"):
192
+ if decision.approved:
193
+ print(f"Request {decision.request_id} was approved!")
194
+ elif decision.rejected:
195
+ print(f"Request {decision.request_id} was rejected: {decision.reason}")
196
+ """
197
+ url = f"{self.base_url}/api/sentinel/approvals/stream"
198
+ params = {"tenant_id": self.tenant_id}
199
+ if last_seen:
200
+ params["last_seen"] = last_seen
201
+
202
+ # Use a separate client for SSE with longer timeout
203
+ async with httpx.AsyncClient(
204
+ timeout=httpx.Timeout(None, connect=10.0), # No read timeout for SSE
205
+ headers={
206
+ "Accept": "text/event-stream",
207
+ "X-Tenant-Id": self.tenant_id,
208
+ "X-API-Key": self.api_key,
209
+ "X-Admin-Token": self.api_key, # Admin token for approval endpoints
210
+ },
211
+ ) as sse_client:
212
+ try:
213
+ async with sse_client.stream("GET", url, params=params) as response:
214
+ if response.status_code == 401:
215
+ raise JanusAuthError("Invalid API key")
216
+ if response.status_code >= 400:
217
+ raise JanusError(f"SSE connection failed: {response.status_code}")
218
+
219
+ async for line in response.aiter_lines():
220
+ if not line:
221
+ continue
222
+
223
+ # SSE format: "data: {...}" or ": heartbeat ..."
224
+ if line.startswith(":"):
225
+ # Heartbeat/comment, ignore
226
+ continue
227
+
228
+ if line.startswith("data: "):
229
+ try:
230
+ data = json.loads(line[6:]) # Skip "data: " prefix
231
+ except json.JSONDecodeError:
232
+ continue
233
+
234
+ event_type = data.get("type")
235
+
236
+ if event_type == "CONNECTED":
237
+ if on_connected:
238
+ on_connected()
239
+ continue
240
+
241
+ if event_type == "ERROR":
242
+ raise JanusError(f"SSE error: {data.get('message')}")
243
+
244
+ if event_type == "APPROVAL_DECISION":
245
+ yield ApprovalDecision(
246
+ request_id=data["request_id"],
247
+ status=ApprovalStatus(data["status"]),
248
+ approver=data.get("approver"),
249
+ reason=data.get("reason"),
250
+ agent_id=data.get("agent_id"),
251
+ action=data.get("action"),
252
+ timestamp=data.get("timestamp"),
253
+ is_catchup=data.get("catchup", False),
254
+ )
255
+
256
+ except httpx.RequestError as exc:
257
+ raise JanusConnectionError(f"SSE connection failed: {exc}")
258
+
259
+ async def wait_for_approval(
260
+ self,
261
+ approval_id: str,
262
+ timeout: float = 3600,
263
+ poll_interval: float = 5.0,
264
+ max_poll_interval: float = 30.0,
265
+ ) -> ApprovalDecision:
266
+ """
267
+ Wait for a specific approval request to be decided (async version).
268
+
269
+ Uses polling with exponential backoff. For long-running async services,
270
+ consider using subscribe_approvals() instead.
271
+
272
+ Args:
273
+ approval_id: The approval_id from CheckResult.approval_id
274
+ timeout: Maximum time to wait in seconds (default 1 hour)
275
+ poll_interval: Initial polling interval in seconds (default 5s)
276
+ max_poll_interval: Maximum polling interval after backoff (default 30s)
277
+
278
+ Returns:
279
+ ApprovalDecision when the request is decided
280
+
281
+ Raises:
282
+ JanusApprovalTimeoutError: If timeout is exceeded
283
+ JanusAuthError: If authentication fails
284
+ JanusError: For other API errors
285
+
286
+ Example:
287
+ result = await client.check("prune_logs", {"days": 30})
288
+ if result.requires_approval:
289
+ decision = await client.wait_for_approval(result.approval_id)
290
+ if decision.approved:
291
+ await prune_logs(days=30)
292
+ """
293
+ import asyncio
294
+ import time
295
+
296
+ start_time = time.time()
297
+ current_interval = poll_interval
298
+ backoff_factor = 1.5
299
+
300
+ while True:
301
+ elapsed = time.time() - start_time
302
+ if elapsed >= timeout:
303
+ raise JanusApprovalTimeoutError(
304
+ f"Approval {approval_id} not decided within {timeout}s timeout"
305
+ )
306
+
307
+ try:
308
+ response = await self._client.get(
309
+ f"{self.base_url}/api/sentinel/approval/{approval_id}",
310
+ )
311
+
312
+ if response.status_code == 401:
313
+ raise JanusAuthError("Invalid API key")
314
+ if response.status_code == 404:
315
+ raise JanusError(f"Approval {approval_id} not found")
316
+ if response.status_code >= 400:
317
+ raise JanusError(f"API error: {response.text}")
318
+
319
+ data = response.json()
320
+ status = data.get("status")
321
+
322
+ if status in ("approved", "rejected", "expired"):
323
+ return ApprovalDecision(
324
+ request_id=approval_id,
325
+ status=ApprovalStatus(status),
326
+ approver=data.get("approver"),
327
+ reason=data.get("reason"),
328
+ agent_id=data.get("agent_id"),
329
+ action=data.get("action"),
330
+ timestamp=data.get("decided_at"),
331
+ is_catchup=False,
332
+ )
333
+
334
+ # Still pending - wait and retry with backoff
335
+ await asyncio.sleep(current_interval)
336
+ current_interval = min(current_interval * backoff_factor, max_poll_interval)
337
+
338
+ except httpx.RequestError:
339
+ await asyncio.sleep(current_interval)
340
+ current_interval = min(current_interval * backoff_factor, max_poll_interval)