centcom 1.0.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.
centcom/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .client import CentcomClient
2
+ from .webhook import verify_webhook
3
+
4
+ __all__ = ["CentcomClient", "verify_webhook"]
5
+ __version__ = "1.0.0"
centcom/client.py ADDED
@@ -0,0 +1,171 @@
1
+ """CENTCOM Python SDK - CentcomClient for creating and managing HITL requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Optional
7
+
8
+ import httpx
9
+
10
+ DEFAULT_BASE_URL = "https://contro1.com/api/centcom/v1"
11
+ DEFAULT_TIMEOUT = 30.0
12
+
13
+ # States that indicate the request lifecycle is complete or has a response
14
+ TERMINAL_STATES = {
15
+ "answered", "callback_pending", "callback_delivered",
16
+ "callback_failed", "closed", "expired", "cancelled",
17
+ }
18
+
19
+
20
+ class CentcomError(Exception):
21
+ """Raised when the CENTCOM API returns an error."""
22
+
23
+ def __init__(self, message: str, status_code: int = 0, response: dict | None = None):
24
+ super().__init__(message)
25
+ self.status_code = status_code
26
+ self.response = response or {}
27
+
28
+
29
+ class CentcomClient:
30
+ """
31
+ Synchronous client for the CENTCOM Human Approval API.
32
+
33
+ Usage:
34
+ client = CentcomClient(api_key="cc_test_xxxx")
35
+ req = client.create_request(
36
+ type="yes_no",
37
+ context="Order #12345 from VIP customer",
38
+ question="Approve this $2,500 order?",
39
+ callback_url="https://my-agent.example.com/webhook",
40
+ )
41
+ print(req["id"], req["state"])
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ api_key: str,
47
+ base_url: str = DEFAULT_BASE_URL,
48
+ timeout: float = DEFAULT_TIMEOUT,
49
+ ):
50
+ if not api_key:
51
+ raise ValueError("api_key is required")
52
+ self.api_key = api_key
53
+ self.base_url = base_url.rstrip("/")
54
+ self._http = httpx.Client(
55
+ base_url=self.base_url,
56
+ headers={
57
+ "Authorization": f"Bearer {api_key}",
58
+ "Content-Type": "application/json",
59
+ },
60
+ timeout=timeout,
61
+ )
62
+
63
+ def _request(self, method: str, path: str, **kwargs: Any) -> dict:
64
+ res = self._http.request(method, path, **kwargs)
65
+ data = res.json()
66
+ if res.status_code >= 400:
67
+ raise CentcomError(
68
+ message=data.get("message", f"HTTP {res.status_code}"),
69
+ status_code=res.status_code,
70
+ response=data,
71
+ )
72
+ return data
73
+
74
+ def create_request(
75
+ self,
76
+ type: str,
77
+ context: str,
78
+ question: str,
79
+ callback_url: str,
80
+ priority: str = "normal",
81
+ required_role: Optional[str] = None,
82
+ response_schema: Optional[dict] = None,
83
+ metadata: Optional[dict] = None,
84
+ sla_minutes: Optional[int] = None,
85
+ idempotency_key: Optional[str] = None,
86
+ ) -> dict:
87
+ """
88
+ Create a new human-in-the-loop request.
89
+
90
+ Args:
91
+ type: Interaction type - "yes_no", "free_text", or "approval"
92
+ context: Background info displayed to the operator
93
+ question: The question for the human operator
94
+ callback_url: Webhook URL for HMAC-signed response delivery
95
+ priority: "normal" (10 min SLA) or "urgent" (3 min SLA)
96
+ required_role: Role tag required to answer (e.g. "manager")
97
+ response_schema: Expected response structure for validation
98
+ metadata: Arbitrary data returned in the callback
99
+ sla_minutes: Override SLA timeout
100
+ idempotency_key: Unique key to prevent duplicate requests
101
+
102
+ Returns:
103
+ dict with the created request data including 'id' and 'state'
104
+ """
105
+ body: dict[str, Any] = {
106
+ "type": type,
107
+ "context": context,
108
+ "question": question,
109
+ "callback_url": callback_url,
110
+ "priority": priority,
111
+ }
112
+ if required_role:
113
+ body["required_role"] = required_role
114
+ if response_schema:
115
+ body["response_schema"] = response_schema
116
+ if metadata:
117
+ body["metadata"] = metadata
118
+ if sla_minutes is not None:
119
+ body["sla_minutes"] = sla_minutes
120
+
121
+ headers = {}
122
+ if idempotency_key:
123
+ headers["Idempotency-Key"] = idempotency_key
124
+
125
+ return self._request("POST", "/requests", json=body, headers=headers)
126
+
127
+ def get_request(self, request_id: str) -> dict:
128
+ """Get the current state of a request."""
129
+ return self._request("GET", f"/requests/{request_id}")
130
+
131
+ def cancel_request(self, request_id: str) -> dict:
132
+ """Cancel a pending request (must not yet be answered)."""
133
+ return self._request("DELETE", f"/requests/{request_id}")
134
+
135
+ def wait_for_response(
136
+ self,
137
+ request_id: str,
138
+ interval: float = 3.0,
139
+ timeout: float = 600.0,
140
+ ) -> dict:
141
+ """
142
+ Poll until the request reaches a terminal state.
143
+
144
+ Args:
145
+ request_id: The request to poll
146
+ interval: Seconds between polls (default: 3)
147
+ timeout: Total timeout in seconds (default: 600)
148
+
149
+ Returns:
150
+ The request dict once it has a response or is terminal
151
+
152
+ Raises:
153
+ TimeoutError: If timeout expires before a response
154
+ """
155
+ deadline = time.time() + timeout
156
+ while time.time() < deadline:
157
+ req = self.get_request(request_id)
158
+ if req.get("state") in TERMINAL_STATES:
159
+ return req
160
+ time.sleep(interval)
161
+ raise TimeoutError(f"Timeout waiting for response on request {request_id}")
162
+
163
+ def close(self) -> None:
164
+ """Close the underlying HTTP client."""
165
+ self._http.close()
166
+
167
+ def __enter__(self) -> "CentcomClient":
168
+ return self
169
+
170
+ def __exit__(self, *args: Any) -> None:
171
+ self.close()
centcom/webhook.py ADDED
@@ -0,0 +1,53 @@
1
+ """CENTCOM webhook signature verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import time
8
+
9
+
10
+ MAX_TIMESTAMP_AGE_SECONDS = 300 # 5 minutes
11
+
12
+
13
+ def verify_webhook(
14
+ raw_body: str | bytes,
15
+ signature: str,
16
+ timestamp: str,
17
+ secret: str,
18
+ ) -> bool:
19
+ """
20
+ Verify an incoming CENTCOM webhook signature.
21
+
22
+ Args:
23
+ raw_body: The raw HTTP request body (string or bytes)
24
+ signature: The X-CentCom-Signature header value (hex string)
25
+ timestamp: The X-CentCom-Timestamp header value (unix seconds)
26
+ secret: Your organization's webhook signing secret (whsec_xxx)
27
+
28
+ Returns:
29
+ True if the signature is valid and the timestamp is fresh
30
+ """
31
+ # Validate timestamp
32
+ try:
33
+ ts = int(timestamp)
34
+ except (ValueError, TypeError):
35
+ return False
36
+
37
+ age = abs(int(time.time()) - ts)
38
+ if age > MAX_TIMESTAMP_AGE_SECONDS:
39
+ return False
40
+
41
+ # Compute expected signature
42
+ if isinstance(raw_body, bytes):
43
+ raw_body = raw_body.decode("utf-8")
44
+
45
+ payload = f"{timestamp}.{raw_body}"
46
+ expected = hmac.new(
47
+ secret.encode("utf-8"),
48
+ payload.encode("utf-8"),
49
+ hashlib.sha256,
50
+ ).hexdigest()
51
+
52
+ # Constant-time comparison
53
+ return hmac.compare_digest(signature, expected)
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.3
2
+ Name: centcom
3
+ Version: 1.0.0
4
+ Summary: Official CENTCOM Python SDK for requests and webhook verification
5
+ Project-URL: Homepage, https://contro1.com
6
+ Project-URL: Documentation, https://contro1.com/docs
7
+ Project-URL: Repository, https://github.com/contro1-hq/centcom-langgraph
8
+ Author-email: Contro1 <dev@contro1.com>
9
+ License: MIT
10
+ Keywords: approval,centcom,hitl,human-in-the-loop,webhook
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Internet :: WWW/HTTP
15
+ Requires-Python: >=3.9
16
+ Requires-Dist: httpx>=0.27.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # centcom
20
+
21
+ Official CENTCOM Python SDK for human-in-the-loop approval requests and webhook verification.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install centcom
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ```python
32
+ from centcom import CentcomClient, verify_webhook
33
+
34
+ client = CentcomClient(api_key="cc_live_xxx")
35
+ req = client.create_request(
36
+ type="approval",
37
+ context="Order #123 refund request",
38
+ question="Approve refund?",
39
+ callback_url="https://your-app.com/centcom-webhook",
40
+ )
41
+ print(req["id"])
42
+ ```
@@ -0,0 +1,7 @@
1
+ centcom/__init__.py,sha256=xzmVc8EvGZn38wyT6ziMnXyj2uhOXnWEhc5iGUBV1PQ,144
2
+ centcom/client.py,sha256=RyYoD6Lk_1sjDgMo5-ze2M16uEehegj6N9IZ6k36Zu0,5755
3
+ centcom/webhook.py,sha256=6TDXeBRT_94Ey0WG5t7DMFQUzIKmElHdi07v1QWe1Eg,1358
4
+ centcom-1.0.0.dist-info/METADATA,sha256=Lh_UKRkQhCEo1YLIhmjKK0VzcpYUX9AOyeVS3Jta1Z8,1153
5
+ centcom-1.0.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
6
+ centcom-1.0.0.dist-info/licenses/LICENSE,sha256=E2NpDGLMsWJ8edDJJN9GHGqyUMfhzE0t6dO7--q6v70,1085
7
+ centcom-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.26.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Contro1
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.