erghi-sdk 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.
erghi/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """Erghi Python SDK"""
2
+
3
+ from .client import ErghiClient
4
+ from .errors import (
5
+ ErghiError,
6
+ AuthenticationError,
7
+ ValidationError,
8
+ RateLimitError,
9
+ NetworkError,
10
+ NotFoundError,
11
+ HubException,
12
+ )
13
+ from .hmac import generate_identity_hash, verify_webhook_signature
14
+ from .types import (
15
+ User,
16
+ RegisterRequest,
17
+ LoginRequest,
18
+ AuthResponse,
19
+ Message,
20
+ Conversation,
21
+ Workspace,
22
+ )
23
+
24
+ __version__ = "1.0.0"
25
+ __all__ = [
26
+ "ErghiClient",
27
+ "ErghiError",
28
+ "AuthenticationError",
29
+ "ValidationError",
30
+ "RateLimitError",
31
+ "NetworkError",
32
+ "NotFoundError",
33
+ "HubException",
34
+ "User",
35
+ "RegisterRequest",
36
+ "LoginRequest",
37
+ "AuthResponse",
38
+ "Message",
39
+ "Conversation",
40
+ "Workspace",
41
+ "generate_identity_hash",
42
+ "verify_webhook_signature",
43
+ ]
erghi/client.py ADDED
@@ -0,0 +1,526 @@
1
+ """Erghi SDK Client"""
2
+
3
+ import asyncio
4
+ import json
5
+ import logging
6
+ import uuid
7
+ from typing import Any, Callable, Dict, Optional
8
+ from urllib.parse import urljoin
9
+
10
+ import httpx
11
+ import websockets
12
+ from websockets.asyncio.client import ClientConnection
13
+
14
+ from .errors import (
15
+ ErghiError,
16
+ AuthenticationError,
17
+ HubException,
18
+ NetworkError,
19
+ NotFoundError,
20
+ RateLimitError,
21
+ ValidationError,
22
+ )
23
+ from .resources.auth import AuthResource
24
+ from .resources.chat import ChatResource
25
+ from .resources.workspace import WorkspaceResource
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # ASP.NET Core SignalR's JSON Hub Protocol terminates every frame with this character.
30
+ _RECORD_SEPARATOR = "\x1e"
31
+
32
+ # Real hub broadcast names (Erghi.Conversation/Api/Hubs/ChatHub.cs /
33
+ # ConversationRealtimeNotifier.cs) mapped onto this SDK's documented dotted event names, so
34
+ # existing `client.on("message.received", ...)`-style consumer code keeps working unchanged.
35
+ _HUB_EVENT_MAP = {
36
+ "MessageReceived": "message.received",
37
+ "MessageRead": "message.read",
38
+ "UserTyping": "user.typing",
39
+ "ConversationClosed": "conversation.closed",
40
+ "ConversationAssigned": "conversation.assigned",
41
+ }
42
+
43
+
44
+ class ErghiClient:
45
+ """Main Erghi SDK Client"""
46
+
47
+ def __init__(
48
+ self,
49
+ api_url: str = "http://localhost:5000",
50
+ ws_url: str = "ws://localhost:5002",
51
+ api_key: Optional[str] = None,
52
+ access_token: Optional[str] = None,
53
+ client_id: Optional[str] = None,
54
+ client_secret: Optional[str] = None,
55
+ workspace_id: Optional[str] = None,
56
+ account_id: Optional[str] = None,
57
+ timeout: float = 30.0,
58
+ debug: bool = False,
59
+ ) -> None:
60
+ """
61
+ Initialize Erghi client
62
+
63
+ Args:
64
+ api_url: API base URL
65
+ ws_url: WebSocket URL
66
+ api_key: API key for authentication
67
+ access_token: Access token (JWT)
68
+ client_id: Client ID for M2M authentication
69
+ client_secret: Client Secret for M2M authentication
70
+ workspace_id: Workspace ID
71
+ account_id: Account ID
72
+ timeout: Request timeout in seconds
73
+ debug: Enable debug logging
74
+ """
75
+ self.api_url = api_url
76
+ self.ws_url = ws_url
77
+ self.api_key = api_key
78
+ self.access_token = access_token
79
+ self.client_id = client_id
80
+ self.client_secret = client_secret
81
+ self.workspace_id = workspace_id
82
+ self.account_id = account_id
83
+ self.visitor_id: Optional[str] = None
84
+ self.timeout = timeout
85
+ self.debug = debug
86
+
87
+ if debug:
88
+ logging.basicConfig(level=logging.DEBUG)
89
+
90
+ # Initialize HTTP client
91
+ self._http_client = httpx.AsyncClient(
92
+ base_url=api_url,
93
+ timeout=timeout,
94
+ headers={"Content-Type": "application/json"},
95
+ )
96
+
97
+ # Real-time hub connection (SignalR protocol over a raw websocket -- see connect())
98
+ self._ws: Optional[ClientConnection] = None
99
+ self._ws_task: Optional[asyncio.Task] = None
100
+ self._ping_task: Optional[asyncio.Task] = None
101
+ self._event_handlers: Dict[str, list[Callable]] = {}
102
+ self._reconnect_attempts = 0
103
+ self._max_reconnect_attempts = 5
104
+ self._pending_invocations: Dict[str, "asyncio.Future[Any]"] = {}
105
+
106
+ # Initialize resources
107
+ self.auth = AuthResource(self)
108
+ self.chat = ChatResource(self)
109
+ self.workspace = WorkspaceResource(self)
110
+
111
+ async def __aenter__(self) -> "ErghiClient":
112
+ """Async context manager entry"""
113
+ return self
114
+
115
+ async def __aexit__(self, *args: Any) -> None:
116
+ """Async context manager exit"""
117
+ await self.close()
118
+
119
+ async def close(self) -> None:
120
+ """Close client connections"""
121
+ await self.disconnect()
122
+ await self._http_client.aclose()
123
+
124
+ async def authenticate(self) -> str:
125
+ """Authenticate using Client Credentials to obtain a JWT token"""
126
+ if not self.client_id or not self.client_secret:
127
+ raise AuthenticationError("client_id and client_secret are required for token exchange")
128
+
129
+ try:
130
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
131
+ url = urljoin(self.api_url + "/", "api/v1/auth/token")
132
+ response = await client.post(
133
+ url,
134
+ json={
135
+ "grant_type": "client_credentials",
136
+ "client_id": self.client_id,
137
+ "client_secret": self.client_secret,
138
+ },
139
+ headers={"Content-Type": "application/json"},
140
+ )
141
+ response.raise_for_status()
142
+ data = response.json()
143
+ token = str(data["access_token"])
144
+ self.set_access_token(token)
145
+ return token
146
+ except httpx.HTTPStatusError as e:
147
+ try:
148
+ msg = e.response.json().get("message", str(e))
149
+ except Exception:
150
+ msg = str(e)
151
+ raise AuthenticationError(f"Failed to authenticate: {msg}")
152
+ except Exception as e:
153
+ raise AuthenticationError(f"Failed to authenticate: {str(e)}")
154
+
155
+ async def authenticate_visitor(self, widget_id: str, jwt_token: str) -> str:
156
+ """Authenticate a visitor using a signed JWT from the customer's backend."""
157
+ try:
158
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
159
+ url = urljoin(self.api_url + "/", "api/conversations/identity")
160
+ response = await client.post(
161
+ url,
162
+ json={
163
+ "widgetId": widget_id,
164
+ "jwtToken": jwt_token,
165
+ },
166
+ headers={"Content-Type": "application/json"},
167
+ )
168
+ response.raise_for_status()
169
+ data = response.json()
170
+ self.visitor_id = str(data.get("visitorId", data.get("VisitorId")))
171
+ return self.visitor_id
172
+ except httpx.HTTPStatusError as e:
173
+ try:
174
+ msg = e.response.json().get("error", str(e))
175
+ except Exception:
176
+ msg = str(e)
177
+ raise AuthenticationError(f"Failed to authenticate visitor: {msg}")
178
+ except Exception as e:
179
+ raise AuthenticationError(f"Failed to authenticate visitor: {str(e)}")
180
+
181
+ def _get_headers(self) -> Dict[str, str]:
182
+ """Get request headers"""
183
+ headers: Dict[str, str] = {}
184
+
185
+ if self.api_key:
186
+ headers["X-API-Key"] = self.api_key
187
+
188
+ if self.access_token:
189
+ headers["Authorization"] = f"Bearer {self.access_token}"
190
+
191
+ if self.workspace_id:
192
+ headers["X-Workspace-Id"] = self.workspace_id
193
+
194
+ if self.account_id:
195
+ headers["X-Account-Id"] = self.account_id
196
+
197
+ return headers
198
+
199
+ async def request(
200
+ self,
201
+ method: str,
202
+ path: str,
203
+ **kwargs: Any,
204
+ ) -> httpx.Response:
205
+ """Make HTTP request"""
206
+ if self.client_id and self.client_secret and not self.access_token:
207
+ try:
208
+ await self.authenticate()
209
+ except Exception as e:
210
+ logger.error(f"Auto-authentication failed: {e}")
211
+
212
+ try:
213
+ headers = self._get_headers()
214
+ headers.update(kwargs.pop("headers", {}))
215
+
216
+ response = await self._http_client.request(
217
+ method,
218
+ path,
219
+ headers=headers,
220
+ **kwargs,
221
+ )
222
+
223
+ response.raise_for_status()
224
+ return response
225
+
226
+ except httpx.HTTPStatusError as e:
227
+ raise self._handle_error(e)
228
+ except httpx.RequestError as e:
229
+ raise NetworkError(f"Network request failed: {str(e)}", details=str(e))
230
+
231
+ def _handle_error(self, error: httpx.HTTPStatusError) -> ErghiError:
232
+ """Handle HTTP errors"""
233
+ response = error.response
234
+
235
+ try:
236
+ data = response.json()
237
+ message = data.get("message", str(error))
238
+ details = data.get("errors")
239
+ except Exception:
240
+ message = str(error)
241
+ details = None
242
+
243
+ status_code = response.status_code
244
+
245
+ if status_code == 400:
246
+ return ValidationError(message, details)
247
+ elif status_code == 401:
248
+ return AuthenticationError(message)
249
+ elif status_code == 404:
250
+ return NotFoundError(message)
251
+ elif status_code == 429:
252
+ retry_after = int(response.headers.get("Retry-After", "60"))
253
+ return RateLimitError(message, retry_after)
254
+ else:
255
+ return ErghiError(message, "API_ERROR", status_code, details)
256
+
257
+ def set_access_token(self, token: str) -> None:
258
+ """Set access token"""
259
+ self.access_token = token
260
+
261
+ def set_workspace_id(self, workspace_id: str) -> None:
262
+ """Set workspace ID"""
263
+ self.workspace_id = workspace_id
264
+
265
+ async def connect(self) -> None:
266
+ """Connect to the real-time hub.
267
+
268
+ Was a bare `websockets.connect(...)` speaking a hand-rolled {type, data} envelope
269
+ directly at /hubs/chat -- that never completes the SignalR negotiate/handshake a real
270
+ ASP.NET Core SignalR hub requires (a POST to /negotiate for a connection token, then a
271
+ JSON handshake record before any invocation frames are accepted), so it could not
272
+ actually exchange messages with the real backend. This implements that protocol
273
+ directly on top of the same `websockets` library, since no official/maintained SignalR
274
+ client exists for Python.
275
+ """
276
+ if self._ws_is_open():
277
+ return
278
+
279
+ try:
280
+ connection_token = await self._negotiate()
281
+ ws_url = (
282
+ f"{self.ws_url}/hubs/chat?id={connection_token}"
283
+ f"&access_token={self.access_token or ''}"
284
+ )
285
+ self._ws = await websockets.connect(ws_url)
286
+ await self._handshake()
287
+
288
+ self._reconnect_attempts = 0
289
+ logger.debug("Hub connected")
290
+
291
+ self._ws_task = asyncio.create_task(self._listen())
292
+ self._ping_task = asyncio.create_task(self._keepalive())
293
+
294
+ await self._emit("connected", {})
295
+
296
+ except Exception as e:
297
+ logger.error(f"Hub connection failed: {e}")
298
+ await self._reconnect()
299
+
300
+ async def _negotiate(self) -> str:
301
+ """POST /hubs/chat/negotiate to obtain the connection token the WebSocket URL needs.
302
+ Requests negotiateVersion=1 explicitly and prefers connectionToken (that version's
303
+ field) over connectionId (the older/v0 field) if both are present."""
304
+ scheme = "https" if self.ws_url.startswith("wss://") else "http"
305
+ base = scheme + "://" + self.ws_url.split("://", 1)[-1]
306
+ url = urljoin(base + "/", "hubs/chat/negotiate")
307
+
308
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
309
+ response = await client.post(url, params={"negotiateVersion": 1}, headers=self._get_headers())
310
+ response.raise_for_status()
311
+ data = response.json()
312
+
313
+ if data.get("url"):
314
+ # Azure SignalR-style redirect to a different endpoint -- not used by this
315
+ # platform's self-hosted deployment, but fail clearly instead of silently
316
+ # connecting to the wrong place if it ever is.
317
+ raise ErghiError("Hub negotiate returned a redirect target; not supported", "WS_NEGOTIATE_REDIRECT")
318
+
319
+ token = data.get("connectionToken") or data.get("connectionId")
320
+ if not token:
321
+ raise ErghiError("Hub negotiate response had no connection token", "WS_NEGOTIATE_FAILED")
322
+ return str(token)
323
+
324
+ def _ws_is_open(self) -> bool:
325
+ """`websockets` 14+ replaced the connection object's `.closed` property with a
326
+ `.state` enum (`websockets.State.OPEN`/`CLOSED`/...) -- `.closed` no longer exists on
327
+ the connection object `websockets.connect()` returns."""
328
+ return self._ws is not None and self._ws.state is websockets.State.OPEN
329
+
330
+ async def _handshake(self) -> None:
331
+ """Send the SignalR handshake request record and wait for the response record --
332
+ required before the server will accept any invocation frames."""
333
+ assert self._ws is not None
334
+ await self._ws.send(json.dumps({"protocol": "json", "version": 1}) + _RECORD_SEPARATOR)
335
+
336
+ raw = await self._ws.recv()
337
+ text = raw.decode() if isinstance(raw, bytes) else raw
338
+ record, _, _rest = text.partition(_RECORD_SEPARATOR)
339
+ response = json.loads(record) if record else {}
340
+
341
+ if response.get("error"):
342
+ raise ErghiError(f"Hub handshake failed: {response['error']}", "WS_HANDSHAKE_FAILED")
343
+
344
+ async def disconnect(self) -> None:
345
+ """Disconnect from the hub."""
346
+ for task_attr in ("_ping_task", "_ws_task"):
347
+ task = getattr(self, task_attr)
348
+ if task:
349
+ task.cancel()
350
+ try:
351
+ await task
352
+ except asyncio.CancelledError:
353
+ pass
354
+ setattr(self, task_attr, None)
355
+
356
+ for future in self._pending_invocations.values():
357
+ if not future.done():
358
+ future.cancel()
359
+ self._pending_invocations.clear()
360
+
361
+ if self._ws:
362
+ await self._ws.close()
363
+ self._ws = None
364
+
365
+ async def invoke(self, method: str, *args: Any, wait_for_result: bool = True) -> Any:
366
+ """Invoke a real hub method (e.g. "SendTyping", "JoinConversation", "MarkAsRead").
367
+
368
+ By default waits for the server's Completion message and raises HubException if the
369
+ server rejected the call -- notably including ConversationOwnershipHubFilter denying
370
+ access to a conversation outside the caller's own workspace, which the previous
371
+ transport could never have surfaced since it never spoke to a real hub at all.
372
+ """
373
+ if not self._ws_is_open():
374
+ raise ErghiError("Hub is not connected", "WS_NOT_CONNECTED")
375
+
376
+ message: Dict[str, Any] = {"type": 1, "target": method, "arguments": list(args)}
377
+
378
+ future: Optional["asyncio.Future[Any]"] = None
379
+ invocation_id: Optional[str] = None
380
+ if wait_for_result:
381
+ invocation_id = str(uuid.uuid4())
382
+ message["invocationId"] = invocation_id
383
+ future = asyncio.get_event_loop().create_future()
384
+ self._pending_invocations[invocation_id] = future
385
+
386
+ assert self._ws is not None # guaranteed by the _ws_is_open() check above
387
+ await self._ws.send(json.dumps(message) + _RECORD_SEPARATOR)
388
+
389
+ if future is not None:
390
+ try:
391
+ return await asyncio.wait_for(future, timeout=self.timeout)
392
+ finally:
393
+ if invocation_id is not None:
394
+ self._pending_invocations.pop(invocation_id, None)
395
+ return None
396
+
397
+ async def send(self, event_type: str, data: Any) -> None:
398
+ """Preserved for API compatibility with the SDK's previous {type, data} envelope --
399
+ maps known event types onto real hub method invocations. Fire-and-forget, matching
400
+ this method's previous behavior (no waiting for a server response)."""
401
+ if event_type == "user.typing":
402
+ conversation_id = (data or {}).get("conversationId")
403
+ await self.invoke("SendTyping", conversation_id, wait_for_result=False)
404
+ else:
405
+ raise ErghiError(f"Unsupported real-time event type: {event_type}", "UNSUPPORTED_EVENT_TYPE")
406
+
407
+ async def join_conversation(self, conversation_id: str) -> None:
408
+ """Join a conversation's real-time group -- required before UserTyping/MessageRead
409
+ events for that conversation are delivered to this connection. Raises HubException if
410
+ the conversation isn't in the caller's own workspace."""
411
+ await self.invoke("JoinConversation", conversation_id)
412
+
413
+ async def leave_conversation(self, conversation_id: str) -> None:
414
+ await self.invoke("LeaveConversation", conversation_id, wait_for_result=False)
415
+
416
+ async def mark_as_read(self, conversation_id: str, message_id: str) -> None:
417
+ await self.invoke("MarkAsRead", conversation_id, message_id)
418
+
419
+ def on(self, event: str, handler: Callable) -> None:
420
+ """Register event handler"""
421
+ if event not in self._event_handlers:
422
+ self._event_handlers[event] = []
423
+ self._event_handlers[event].append(handler)
424
+
425
+ def off(self, event: str, handler: Optional[Callable] = None) -> None:
426
+ """Unregister event handler"""
427
+ if event not in self._event_handlers:
428
+ return
429
+
430
+ if handler is None:
431
+ del self._event_handlers[event]
432
+ else:
433
+ self._event_handlers[event].remove(handler)
434
+
435
+ async def _emit(self, event: str, data: Any) -> None:
436
+ """Emit event to handlers"""
437
+ if event in self._event_handlers:
438
+ for handler in self._event_handlers[event]:
439
+ try:
440
+ result = handler(data)
441
+ if asyncio.iscoroutine(result):
442
+ await result
443
+ except Exception as e:
444
+ logger.error(f"Error in event handler: {e}")
445
+
446
+ async def _keepalive(self) -> None:
447
+ """SignalR's JSON protocol expects periodic client activity, not just server pings --
448
+ matches the default @microsoft/signalr client's 15-second keep-alive interval."""
449
+ try:
450
+ while True:
451
+ await asyncio.sleep(15)
452
+ if self._ws_is_open():
453
+ assert self._ws is not None
454
+ await self._ws.send(json.dumps({"type": 6}) + _RECORD_SEPARATOR)
455
+ except asyncio.CancelledError:
456
+ pass
457
+
458
+ async def _listen(self) -> None:
459
+ """Listen for hub messages. A single WebSocket text frame can contain multiple
460
+ record-separator-terminated JSON records, so each frame is split before parsing."""
461
+ try:
462
+ async for raw in self._ws: # type: ignore
463
+ text = raw.decode() if isinstance(raw, bytes) else raw
464
+ for record in text.split(_RECORD_SEPARATOR):
465
+ if record:
466
+ await self._handle_record(record)
467
+
468
+ except websockets.exceptions.ConnectionClosed:
469
+ logger.debug("Hub connection closed")
470
+ await self._emit("disconnected", {})
471
+ await self._reconnect()
472
+
473
+ async def _handle_record(self, record: str) -> None:
474
+ try:
475
+ message = json.loads(record)
476
+ except json.JSONDecodeError:
477
+ logger.error(f"Failed to parse hub message: {record}")
478
+ return
479
+
480
+ msg_type = message.get("type")
481
+
482
+ if msg_type == 1:
483
+ # Invocation from the server -- a hub broadcast (MessageReceived, UserTyping, ...).
484
+ target = message.get("target")
485
+ arguments = message.get("arguments") or []
486
+ event_name = _HUB_EVENT_MAP.get(target, target)
487
+ logger.debug(f"Hub event: {target}")
488
+ await self._emit(event_name, arguments[0] if arguments else None)
489
+
490
+ elif msg_type == 3:
491
+ # Completion -- the response to one of our own invoke() calls.
492
+ invocation_id = message.get("invocationId")
493
+ future = self._pending_invocations.get(invocation_id) if invocation_id else None
494
+ if future and not future.done():
495
+ if message.get("error"):
496
+ future.set_exception(HubException(message["error"]))
497
+ else:
498
+ future.set_result(message.get("result"))
499
+
500
+ elif msg_type == 6:
501
+ # Server ping -- no application-level response required beyond our own keepalive.
502
+ pass
503
+
504
+ elif msg_type == 7:
505
+ # Server-initiated close.
506
+ logger.debug(f"Hub sent close: {message.get('error')}")
507
+ await self._emit("disconnected", {})
508
+ if message.get("allowReconnect"):
509
+ await self._reconnect()
510
+
511
+ # Types 2 (StreamItem), 4 (StreamInvocation), 5 (CancelInvocation) are not used by
512
+ # ChatHub/VisitorChatHub -- no client-to-server or server-to-client streaming today.
513
+
514
+ async def _reconnect(self) -> None:
515
+ """Reconnect to the hub."""
516
+ if self._reconnect_attempts >= self._max_reconnect_attempts:
517
+ logger.error("Max reconnect attempts reached")
518
+ return
519
+
520
+ self._reconnect_attempts += 1
521
+ delay = min(2**self._reconnect_attempts, 30)
522
+
523
+ logger.debug(f"Reconnecting in {delay}s (attempt {self._reconnect_attempts})")
524
+ await asyncio.sleep(delay)
525
+
526
+ await self.connect()
erghi/errors.py ADDED
@@ -0,0 +1,73 @@
1
+ """Custom exceptions for Erghi SDK"""
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+
6
+ class ErghiError(Exception):
7
+ """Base exception for Erghi SDK"""
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ code: str,
13
+ status_code: Optional[int] = None,
14
+ details: Optional[Any] = None,
15
+ ) -> None:
16
+ super().__init__(message)
17
+ self.message = message
18
+ self.code = code
19
+ self.status_code = status_code
20
+ self.details = details
21
+
22
+
23
+ class AuthenticationError(ErghiError):
24
+ """Authentication failed"""
25
+
26
+ def __init__(
27
+ self, message: str = "Authentication failed", details: Optional[Any] = None
28
+ ) -> None:
29
+ super().__init__(message, "AUTH_ERROR", 401, details)
30
+
31
+
32
+ class ValidationError(ErghiError):
33
+ """Validation failed"""
34
+
35
+ def __init__(
36
+ self,
37
+ message: str = "Validation failed",
38
+ details: Optional[Dict[str, Any]] = None,
39
+ ) -> None:
40
+ super().__init__(message, "VALIDATION_ERROR", 400, details)
41
+
42
+
43
+ class RateLimitError(ErghiError):
44
+ """Rate limit exceeded"""
45
+
46
+ def __init__(self, message: str = "Rate limit exceeded", retry_after: int = 60) -> None:
47
+ super().__init__(message, "RATE_LIMIT_ERROR", 429)
48
+ self.retry_after = retry_after
49
+
50
+
51
+ class NetworkError(ErghiError):
52
+ """Network request failed"""
53
+
54
+ def __init__(
55
+ self, message: str = "Network request failed", details: Optional[Any] = None
56
+ ) -> None:
57
+ super().__init__(message, "NETWORK_ERROR", None, details)
58
+
59
+
60
+ class NotFoundError(ErghiError):
61
+ """Resource not found"""
62
+
63
+ def __init__(self, message: str = "Resource not found") -> None:
64
+ super().__init__(message, "NOT_FOUND", 404)
65
+
66
+
67
+ class HubException(ErghiError):
68
+ """The real-time hub rejected an invocation (a SignalR Completion message with an
69
+ error) -- for example ConversationOwnershipHubFilter denying JoinConversation/
70
+ SendMessage/etc. for a conversation outside the caller's own workspace."""
71
+
72
+ def __init__(self, message: str) -> None:
73
+ super().__init__(message, "HUB_EXCEPTION")
erghi/hmac.py ADDED
@@ -0,0 +1,76 @@
1
+ """
2
+ Erghi Python SDK — HMAC utilities (server-side)
3
+
4
+ Stateless module-level helpers for generating visitor identity hashes and
5
+ verifying webhook signatures. They do not require an ``ErghiClient``
6
+ instance. Keep your widgetSecretKey / webhook secret on the server —
7
+ never expose it to clients.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import hmac as hmac_lib
14
+
15
+
16
+ def generate_identity_hash(visitor_id: str, secret_key: str) -> str:
17
+ """
18
+ Generate an HMAC-SHA256 hex digest for a visitor ID.
19
+
20
+ Call this server-side to securely link your logged-in user to the Erghi widget.
21
+
22
+ Args:
23
+ visitor_id: Your system's user/visitor identifier.
24
+ secret_key: The ``whsec_...`` secret from the Erghi Admin Portal.
25
+
26
+ Returns:
27
+ Lowercase hex-encoded HMAC-SHA256 digest (64 characters).
28
+
29
+ Raises:
30
+ ValueError: If ``visitor_id`` or ``secret_key`` is empty.
31
+
32
+ Example::
33
+
34
+ from erghi import generate_identity_hash
35
+
36
+ identity_hash = generate_identity_hash(
37
+ visitor_id=str(request.user.id),
38
+ secret_key=settings.ERGHI_WIDGET_SECRET,
39
+ )
40
+ """
41
+ if not visitor_id or not secret_key:
42
+ raise ValueError("visitor_id and secret_key are required")
43
+
44
+ digest = hmac_lib.new(
45
+ key=secret_key.encode("utf-8"),
46
+ msg=visitor_id.encode("utf-8"),
47
+ digestmod=hashlib.sha256,
48
+ ).hexdigest()
49
+ return digest
50
+
51
+
52
+ def verify_webhook_signature(payload: str, signature: str, secret: str) -> bool:
53
+ """
54
+ Verify an incoming Erghi webhook signature.
55
+
56
+ Erghi signs webhook payloads with ``HMAC-SHA256(raw_body, webhook_secret)``
57
+ and sends the result in the ``X-Erghi-Signature`` header. Always verify
58
+ this before processing webhook events.
59
+
60
+ Args:
61
+ payload: The raw request body string (do not parse JSON first).
62
+ signature: The value of the ``X-Erghi-Signature`` header.
63
+ secret: Your workspace webhook secret.
64
+
65
+ Returns:
66
+ ``True`` if the signature is valid, ``False`` otherwise.
67
+ """
68
+ if not payload or not signature or not secret:
69
+ return False
70
+
71
+ try:
72
+ expected = generate_identity_hash(payload, secret)
73
+ # Constant-time comparison to prevent timing attacks
74
+ return hmac_lib.compare_digest(expected.lower(), signature.lower())
75
+ except Exception:
76
+ return False
erghi/types.py ADDED
@@ -0,0 +1,140 @@
1
+ """Type definitions for Erghi SDK"""
2
+
3
+ from datetime import datetime
4
+ from typing import Any, Dict, List, Literal, Optional
5
+ from pydantic import BaseModel, EmailStr, Field
6
+
7
+
8
+ class User(BaseModel):
9
+ """User model"""
10
+
11
+ id: str
12
+ email: EmailStr
13
+ first_name: Optional[str] = Field(None, alias="firstName")
14
+ last_name: Optional[str] = Field(None, alias="lastName")
15
+ avatar: Optional[str] = None
16
+ role: str
17
+ email_verified: bool = Field(alias="emailVerified")
18
+ two_factor_enabled: bool = Field(alias="twoFactorEnabled")
19
+ created_at: datetime = Field(alias="createdAt")
20
+ last_login_at: Optional[datetime] = Field(None, alias="lastLoginAt")
21
+
22
+ class Config:
23
+ populate_by_name = True
24
+
25
+
26
+ class RegisterRequest(BaseModel):
27
+ """Register request"""
28
+
29
+ email: EmailStr
30
+ password: str
31
+ first_name: Optional[str] = Field(None, alias="firstName")
32
+ last_name: Optional[str] = Field(None, alias="lastName")
33
+
34
+
35
+ class LoginRequest(BaseModel):
36
+ """Login request"""
37
+
38
+ email: EmailStr
39
+ password: str
40
+ two_factor_code: Optional[str] = Field(None, alias="twoFactorCode")
41
+
42
+
43
+ class AuthResponse(BaseModel):
44
+ """Authentication response"""
45
+
46
+ access_token: str = Field(alias="accessToken")
47
+ refresh_token: str = Field(alias="refreshToken")
48
+ expires_in: int = Field(alias="expiresIn")
49
+ token_type: str = Field(alias="tokenType")
50
+ user: User
51
+
52
+ class Config:
53
+ populate_by_name = True
54
+
55
+
56
+ class Attachment(BaseModel):
57
+ """Message attachment"""
58
+
59
+ id: str
60
+ filename: str
61
+ content_type: str = Field(alias="contentType")
62
+ size: int
63
+ url: str
64
+
65
+ class Config:
66
+ populate_by_name = True
67
+
68
+
69
+ class Message(BaseModel):
70
+ """Chat message"""
71
+
72
+ id: str
73
+ conversation_id: str = Field(alias="conversationId")
74
+ sender: Literal["visitor", "agent", "system", "ai"]
75
+ sender_id: Optional[str] = Field(None, alias="senderId")
76
+ type: Literal["text", "image", "file", "system"]
77
+ content: str
78
+ attachments: Optional[List[Attachment]] = None
79
+ created_at: datetime = Field(alias="createdAt")
80
+ read_at: Optional[datetime] = Field(None, alias="readAt")
81
+ is_ai: bool = Field(alias="isAI")
82
+ ai_model: Optional[str] = Field(None, alias="aiModel")
83
+
84
+ class Config:
85
+ populate_by_name = True
86
+
87
+
88
+ class Conversation(BaseModel):
89
+ """Chat conversation"""
90
+
91
+ id: str
92
+ workspace_id: str = Field(alias="workspaceId")
93
+ widget_id: str = Field(alias="widgetId")
94
+ visitor_id: Optional[str] = Field(None, alias="visitorId")
95
+ assigned_agent_id: Optional[str] = Field(None, alias="assignedAgentId")
96
+ status: Literal["open", "assigned", "resolved", "closed"]
97
+ channel: Literal["web_widget", "email", "sms", "whatsapp"]
98
+ started_at: datetime = Field(alias="startedAt")
99
+ closed_at: Optional[datetime] = Field(None, alias="closedAt")
100
+ metadata: Optional[Dict[str, Any]] = None
101
+
102
+ class Config:
103
+ populate_by_name = True
104
+
105
+
106
+ class Workspace(BaseModel):
107
+ """Workspace model"""
108
+
109
+ id: str
110
+ name: str
111
+ slug: str
112
+ owner_id: str = Field(alias="ownerId")
113
+ plan: Literal["free", "starter", "growth", "enterprise"]
114
+ role: str
115
+ created_at: datetime = Field(alias="createdAt")
116
+
117
+ class Config:
118
+ populate_by_name = True
119
+
120
+
121
+ class PaginationParams(BaseModel):
122
+ """Pagination parameters"""
123
+
124
+ page: Optional[int] = 1
125
+ limit: Optional[int] = 50
126
+ sort: Optional[str] = None
127
+ order: Optional[Literal["asc", "desc"]] = "desc"
128
+
129
+
130
+ class PaginatedResponse(BaseModel):
131
+ """Paginated response"""
132
+
133
+ data: List[Any]
134
+ total: int
135
+ page: int
136
+ limit: int
137
+ total_pages: int = Field(alias="totalPages")
138
+
139
+ class Config:
140
+ populate_by_name = True
@@ -0,0 +1,421 @@
1
+ Metadata-Version: 2.4
2
+ Name: erghi-sdk
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for the Erghi customer-support platform
5
+ Author-email: Erghi Team <sdk@erghi.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://erghi.com
8
+ Project-URL: Documentation, https://erghi.com/docs/sdk/python
9
+ Project-URL: Repository, https://github.com/ErghiPlatform/erghi-sdks
10
+ Project-URL: Issues, https://github.com/ErghiPlatform/erghi-sdks/issues
11
+ Keywords: ai,chat,chatbot,sdk,websocket,real-time
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: httpx>=0.27.0
25
+ Requires-Dist: websockets>=12.0
26
+ Requires-Dist: pydantic>=2.10.0
27
+ Requires-Dist: python-dateutil>=2.9.0
28
+ Requires-Dist: email-validator>=2.0.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.3.0; extra == "dev"
31
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == "dev"
32
+ Requires-Dist: pytest-cov>=6.0.0; extra == "dev"
33
+ Requires-Dist: black>=24.10.0; extra == "dev"
34
+ Requires-Dist: ruff>=0.8.0; extra == "dev"
35
+ Requires-Dist: mypy>=1.13.0; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # Erghi Python SDK
39
+
40
+ Official Python SDK for the [Erghi Platform](https://erghi.ai).
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ pip install erghi-sdk
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ import asyncio
52
+ from erghi import ErghiClient, RegisterRequest, LoginRequest
53
+
54
+ async def main():
55
+ # Initialize the client
56
+ async with ErghiClient(
57
+ api_url="https://api.erghi.ai",
58
+ api_key="your-api-key",
59
+ workspace_id="your-workspace-id",
60
+ ) as client:
61
+ # Register a new user
62
+ auth_response = await client.auth.register(
63
+ RegisterRequest(
64
+ email="user@example.com",
65
+ password="SecurePassword123!",
66
+ first_name="John",
67
+ last_name="Doe",
68
+ )
69
+ )
70
+
71
+ # Login
72
+ login_response = await client.auth.login(
73
+ LoginRequest(
74
+ email="user@example.com",
75
+ password="SecurePassword123!",
76
+ )
77
+ )
78
+
79
+ # Get current user
80
+ user = await client.auth.me()
81
+ print(f"Current user: {user.email}")
82
+
83
+ # Create a conversation
84
+ conversation = await client.chat.create_conversation(
85
+ widget_id="widget-id",
86
+ metadata={"page": "https://example.com"},
87
+ )
88
+
89
+ # Send a message
90
+ message = await client.chat.send_message(
91
+ conversation_id=conversation.id,
92
+ content="Hello, I need help!",
93
+ )
94
+
95
+ # Connect to WebSocket for real-time updates
96
+ await client.connect()
97
+
98
+ # Register event handlers
99
+ client.on("message.received", lambda data: print(f"New message: {data}"))
100
+ client.on("user.typing", lambda data: print(f"User typing: {data}"))
101
+
102
+ # Keep connection alive
103
+ await asyncio.sleep(3600)
104
+
105
+ if __name__ == "__main__":
106
+ asyncio.run(main())
107
+ ```
108
+
109
+ ## Authentication
110
+
111
+ ### Register
112
+
113
+ ```python
114
+ from erghi import RegisterRequest
115
+
116
+ auth_response = await client.auth.register(
117
+ RegisterRequest(
118
+ email="user@example.com",
119
+ password="SecurePassword123!",
120
+ first_name="John",
121
+ last_name="Doe",
122
+ )
123
+ )
124
+ ```
125
+
126
+ ### Login
127
+
128
+ ```python
129
+ from erghi import LoginRequest
130
+
131
+ auth_response = await client.auth.login(
132
+ LoginRequest(
133
+ email="user@example.com",
134
+ password="SecurePassword123!",
135
+ )
136
+ )
137
+ ```
138
+
139
+ ### Refresh Token
140
+
141
+ ```python
142
+ auth_response = await client.auth.refresh("refresh-token")
143
+ ```
144
+
145
+ ### Logout
146
+
147
+ ```python
148
+ await client.auth.logout()
149
+ ```
150
+
151
+ ## Chat Operations
152
+
153
+ ### Create Conversation
154
+
155
+ ```python
156
+ conversation = await client.chat.create_conversation(
157
+ widget_id="widget-id",
158
+ metadata={"custom_data": "value"},
159
+ )
160
+ ```
161
+
162
+ ### Send Message
163
+
164
+ ```python
165
+ message = await client.chat.send_message(
166
+ conversation_id="conversation-id",
167
+ content="Hello!",
168
+ )
169
+ ```
170
+
171
+ ### Send Message with Attachments
172
+
173
+ ```python
174
+ with open("document.pdf", "rb") as f:
175
+ message = await client.chat.send_message(
176
+ conversation_id="conversation-id",
177
+ content="Here is the file",
178
+ attachments=[f],
179
+ )
180
+ ```
181
+
182
+ ### Get Messages
183
+
184
+ ```python
185
+ from erghi.types import PaginationParams
186
+
187
+ response = await client.chat.get_messages(
188
+ conversation_id="conversation-id",
189
+ params=PaginationParams(
190
+ page=1,
191
+ limit=50,
192
+ sort="createdAt",
193
+ order="desc",
194
+ ),
195
+ )
196
+
197
+ print(f"Total messages: {response.total}")
198
+ for message in response.data:
199
+ print(f"{message.sender}: {message.content}")
200
+ ```
201
+
202
+ ## WebSocket Real-time Events
203
+
204
+ ```python
205
+ # Connect to WebSocket
206
+ await client.connect()
207
+
208
+ # Listen for new messages
209
+ def on_message(message):
210
+ print(f"New message: {message}")
211
+
212
+ client.on("message.received", on_message)
213
+
214
+ # Listen for typing indicators
215
+ client.on("user.typing", lambda data: print(f"User typing: {data}"))
216
+
217
+ # Listen for conversation assignment
218
+ client.on("conversation.assigned", lambda data: print(f"Assigned: {data}"))
219
+
220
+ # Send typing indicator
221
+ await client.chat.send_typing("conversation-id")
222
+
223
+ # Disconnect
224
+ await client.disconnect()
225
+ ```
226
+
227
+ ## Workspace Management
228
+
229
+ ```python
230
+ # List workspaces
231
+ workspaces = await client.workspace.list()
232
+
233
+ # Create workspace
234
+ workspace = await client.workspace.create(
235
+ name="My Company",
236
+ slug="my-company",
237
+ )
238
+
239
+ # Switch workspace
240
+ client.workspace.switch_workspace("workspace-id")
241
+ ```
242
+
243
+ ## Identity Verification & Webhooks (Server-Side)
244
+
245
+ `generate_identity_hash` and `verify_webhook_signature` are stateless module-level functions —
246
+ they don't need an `ErghiClient` instance. Only call them from your backend; never ship your
247
+ widget secret key or webhook secret to the browser.
248
+
249
+ ```python
250
+ from erghi import generate_identity_hash, verify_webhook_signature
251
+
252
+ # On your server, after the user logs in:
253
+ identity_hash = generate_identity_hash(
254
+ visitor_id=str(current_user.id),
255
+ secret_key=settings.ERGHI_WIDGET_SECRET,
256
+ )
257
+ # Send `identity_hash` and `current_user.id` to your frontend for use with the widget.
258
+
259
+ # In your webhook handler (use the raw body, not the parsed JSON):
260
+ def handle_webhook(request):
261
+ signature = request.headers.get("X-Erghi-Signature", "")
262
+ if not verify_webhook_signature(request.body.decode("utf-8"), signature, settings.ERGHI_WEBHOOK_SECRET):
263
+ return HttpResponseUnauthorized("Invalid signature")
264
+
265
+ event = json.loads(request.body)
266
+ # ... handle event
267
+ ```
268
+
269
+ ## Error Handling
270
+
271
+ ```python
272
+ from erghi import (
273
+ AuthenticationError,
274
+ ValidationError,
275
+ RateLimitError,
276
+ NetworkError,
277
+ NotFoundError,
278
+ )
279
+
280
+ try:
281
+ await client.auth.login(
282
+ LoginRequest(email="invalid", password="wrong")
283
+ )
284
+ except AuthenticationError as e:
285
+ print(f"Login failed: {e.message}")
286
+ except ValidationError as e:
287
+ print(f"Validation errors: {e.details}")
288
+ except RateLimitError as e:
289
+ print(f"Rate limited. Retry after {e.retry_after}s")
290
+ except NetworkError as e:
291
+ print(f"Network error: {e.message}")
292
+ except NotFoundError:
293
+ print("Resource not found")
294
+ ```
295
+
296
+ ## Type Safety
297
+
298
+ The SDK is fully typed with Pydantic models:
299
+
300
+ ```python
301
+ from erghi.types import User, Message, Conversation, AuthResponse
302
+
303
+ user: User = await client.auth.me()
304
+ messages: PaginatedResponse = await client.chat.get_messages("conv-id")
305
+
306
+ # Type checking with mypy
307
+ reveal_type(user) # Revealed type is "User"
308
+ ```
309
+
310
+ ## Configuration
311
+
312
+ ```python
313
+ client = ErghiClient(
314
+ # API base URL (default: http://localhost:5000)
315
+ api_url="https://api.erghi.ai",
316
+
317
+ # WebSocket URL (default: ws://localhost:5002)
318
+ ws_url="wss://ws.erghi.ai",
319
+
320
+ # API Key for authentication
321
+ api_key="your-api-key",
322
+
323
+ # Access token (JWT)
324
+ access_token="your-access-token",
325
+
326
+ # Workspace ID
327
+ workspace_id="your-workspace-id",
328
+
329
+ # Request timeout in seconds (default: 30.0)
330
+ timeout=30.0,
331
+
332
+ # Enable debug logging (default: False)
333
+ debug=True,
334
+ )
335
+ ```
336
+
337
+ ## Context Manager
338
+
339
+ Use the client as an async context manager for automatic cleanup:
340
+
341
+ ```python
342
+ async with ErghiClient(api_url="https://api.erghi.ai") as client:
343
+ user = await client.auth.me()
344
+ # Connections automatically closed on exit
345
+ ```
346
+
347
+ ## Advanced Usage
348
+
349
+ ### Custom Event Handlers
350
+
351
+ ```python
352
+ class MyEventHandler:
353
+ async def handle_message(self, data):
354
+ print(f"Message: {data}")
355
+ # Process message asynchronously
356
+ await self.process_message(data)
357
+
358
+ async def process_message(self, data):
359
+ # Custom processing logic
360
+ pass
361
+
362
+ handler = MyEventHandler()
363
+ client.on("message.received", handler.handle_message)
364
+ ```
365
+
366
+ ### Concurrent Operations
367
+
368
+ ```python
369
+ import asyncio
370
+
371
+ # Run multiple operations concurrently
372
+ results = await asyncio.gather(
373
+ client.chat.get_conversation("conv-1"),
374
+ client.chat.get_conversation("conv-2"),
375
+ client.chat.get_messages("conv-1"),
376
+ )
377
+
378
+ conversation1, conversation2, messages = results
379
+ ```
380
+
381
+ ## Development
382
+
383
+ ### Install development dependencies
384
+
385
+ ```bash
386
+ pip install -e ".[dev]"
387
+ ```
388
+
389
+ ### Run tests
390
+
391
+ ```bash
392
+ pytest
393
+ ```
394
+
395
+ ### Run tests with coverage
396
+
397
+ ```bash
398
+ pytest --cov=erghi --cov-report=html
399
+ ```
400
+
401
+ ### Format code
402
+
403
+ ```bash
404
+ black erghi tests
405
+ ```
406
+
407
+ ### Lint code
408
+
409
+ ```bash
410
+ ruff check erghi tests
411
+ ```
412
+
413
+ ### Type checking
414
+
415
+ ```bash
416
+ mypy erghi
417
+ ```
418
+
419
+ ## License
420
+
421
+ MIT
@@ -0,0 +1,10 @@
1
+ erghi/__init__.py,sha256=IAIDYuyF3KiKXxETMFZlsmJSoa4g6iu03zO4zCKsf2A,816
2
+ erghi/client.py,sha256=422d7xvQHnBl-EBBcFw3-pqPKjJ5FQNefp-CZ6hBpyI,20904
3
+ erghi/errors.py,sha256=QVKT8_qTuEvm1c87sfjzoahsDNpiuoXV27Vrv_3m6og,2083
4
+ erghi/hmac.py,sha256=mrK2Uc4nya-7G3B2IB-2eYDbTRI8DB0BXCJTcGhJJRc,2360
5
+ erghi/types.py,sha256=R5cvjUiBgJyMJgXNg6E8WgmYw9czpkLiXRcQNXTl8OI,3693
6
+ erghi_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=W6DB6hMPWK33COC5QmO2nhoqvgoIa9YeTN2RUeSn08M,1071
7
+ erghi_sdk-1.0.0.dist-info/METADATA,sha256=fxr52GaTE4s1EKLN9SJgthNED-JDjhUI-w56hPGG1Mw,9687
8
+ erghi_sdk-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ erghi_sdk-1.0.0.dist-info/top_level.txt,sha256=-N-onoUo8LXwCWl6nQs3u2jjv_wSfLkDwUFyTAuvWmI,6
10
+ erghi_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erghi Platform
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 @@
1
+ erghi