chat-client-sdk 0.1.1__py3-none-win_amd64.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.
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: chat-client-sdk
3
+ Version: 0.1.1
4
+ Summary: Python wrapper for the Rust chat client C ABI
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+
9
+ # Python Chat SDK
10
+
11
+ This package wraps the Rust `chat-client-sdk` C ABI using only the Python standard library. It supports Windows, Linux, and macOS on x86-64 and ARM64. Starting with package version 0.1.1, PyPI releases include the native library automatically for Windows x86-64 and Linux x86-64 (glibc 2.39 or newer). Other OS/architecture combinations still need the matching native library in a `builds/` folder.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ python -m pip install .
17
+ ```
18
+
19
+ Install the SDK from PyPI with `python -m pip install chat-client-sdk`. On Windows x86-64 and Linux x86-64 with glibc 2.39 or newer, pip selects a wheel that contains the matching native library. On macOS, ARM64, and older Linux distributions, follow the native-library placement steps below.
20
+
21
+ ### Publishing releases from GitLab
22
+
23
+ The repository's `.gitlab-ci.yml` builds and checks a source distribution, a pure Python fallback wheel, and bundled Windows x86-64 and Linux x86-64 wheels for merge requests and the default branch. It uploads them to PyPI only for a version tag such as `v0.1.1`, and rejects a tag that does not match `project.version` in this directory's `pyproject.toml`.
24
+
25
+ Set up PyPI Trusted Publishing once for the PyPI project (no long-lived PyPI token is needed):
26
+
27
+ 1. On PyPI, add a Trusted Publisher for GitLab.com. If the package does not exist yet, create a pending publisher under your PyPI account's publishing settings.
28
+ 2. Set the GitLab namespace to `soberonlineemail-group`, repository to `chat-subsystem`, workflow filename to `.gitlab-ci.yml`, and environment to `pypi`.
29
+ 3. Set the package version in `pyproject.toml`, commit the change, then push a matching tag. For example, after setting the version to `0.1.2`:
30
+
31
+ ```sh
32
+ git tag v0.1.2
33
+ git push origin v0.1.2
34
+ ```
35
+
36
+ GitLab runs the packaging job first, then uses its OIDC identity to upload the artifacts. Protect release tags in GitLab so only maintainers can trigger a publish. Each version can be uploaded to PyPI only once.
37
+
38
+ The x86-64 Windows and Linux wheels bundle their native library. The pure wheel remains available as a fallback for macOS and ARM64; those platforms still use separately distributed Rust `.dll`, `.so`, or `.dylib` builds.
39
+
40
+ Place the native library for each platform you distribute in an OS/architecture subfolder beneath the application's `builds/` directory:
41
+
42
+ ```text
43
+ your-project/
44
+ builds/
45
+ windows-x86_64/chat_client_sdk.dll
46
+ windows-aarch64/chat_client_sdk.dll
47
+ linux-x86_64/libchat_client_sdk.so
48
+ linux-aarch64/libchat_client_sdk.so
49
+ darwin-x86_64/libchat_client_sdk.dylib
50
+ darwin-aarch64/libchat_client_sdk.dylib
51
+ app.py
52
+ ```
53
+
54
+ The SDK chooses the matching subfolder automatically. A library placed directly in `builds/` is also accepted. When using this source checkout, `python-sdk/builds/` is checked too. If no local library is found, initialization downloads the version-matched Windows x86-64 or Linux x86-64 wheel from PyPI, verifies the wheel and library SHA-256 hashes, and places the library in `./builds/<os>-<arch>/`. If that directory is not writable, it uses the user's cache directory. Automatic downloads for macOS and ARM64 will be enabled when matching release binaries are available.
55
+
56
+ Set `auto_download=False` on `ChatClient` or `CHAT_SDK_AUTO_DOWNLOAD=0` to disable downloads, for example in offline environments. Set `CHAT_SDK_NATIVE_DIR` to choose a writable builds directory. Advanced users can override library discovery with `CHAT_SDK_LIBRARY` or `library_path`:
57
+
58
+ ```powershell
59
+ $env:CHAT_SDK_LIBRARY = "C:\path\to\chat_client_sdk.dll"
60
+ ```
61
+
62
+ ```sh
63
+ export CHAT_SDK_LIBRARY=/path/to/libchat_client_sdk.so
64
+ ```
65
+
66
+ ## Use
67
+
68
+ ```python
69
+ from chat_sdk import ChatClient
70
+
71
+ with ChatClient(url="ws://127.0.0.1:8080/ws", bearer_token="alice-token") as chat:
72
+ request, accepted = chat.send_message_and_wait(
73
+ "<conversation-uuid>",
74
+ "Hello from Python",
75
+ )
76
+ print("persisted as:", accepted["data"]["message_id"])
77
+ print("correlation key:", request.idempotency_key)
78
+ ```
79
+
80
+ Passing `url` and `bearer_token` connects immediately and starts the event pump for you. `send_message_and_wait()` returns after persistence is acknowledged. `send_event(event_type, data)` sends any version 1 event from the protocol. `receive()` returns a decoded server event dictionary or `None` when no event arrives before its timeout. The background pump is the only native socket reader; concurrent `receive()` and `wait_for_ack()` calls are routed safely. Concurrent sends are serialized through a bounded queue. If the event queue fills, the pump applies backpressure instead of dropping events. `receive()` calls distribute events between concurrent consumers. Retrying a message after a timeout must reuse its `idempotency_key`; duplicate live message events are deduplicated by conversation sequence within a bounded cache of the most recent 8,192 messages per client instance. WSS connections use the Rust SDK's bundled WebPKI root certificates.
81
+
82
+ Create a conversation with `create_conversation(user_ids)` after connecting as one of its participants. It returns the server-generated `conversation_id`; save that ID in your application's database and reuse it when reopening the chat. An async version, `create_conversation_async(user_ids)`, is also available. In production, your backend should call this endpoint after it has decided that the participants are allowed to chat.
83
+
84
+ The synchronous API can also be used from asyncio without blocking the event loop:
85
+
86
+ ```python
87
+ import asyncio
88
+ from chat_sdk import ChatClient
89
+
90
+ async def main():
91
+ async with ChatClient() as chat:
92
+ await chat.aconnect("wss://chat.example.com/ws", "alice-token")
93
+ sent, accepted = await chat.send_message_and_wait_async(
94
+ "<conversation-uuid>", "Hello from asyncio"
95
+ )
96
+ print(sent.idempotency_key, accepted["data"]["sequence"])
97
+ event = await chat.receive_async(timeout_ms=1000)
98
+
99
+ asyncio.run(main())
100
+ ```
101
+
102
+ These async methods run the blocking C ABI and HTTP calls in worker threads; they keep the asyncio loop responsive but do not turn the native C ABI into a nonblocking socket API. Network errors and server slow-consumer disconnects are reported to the caller. Reconnect explicitly with `await chat.aconnect(...)`, then request missed conversation history using the protocol's `history` event and your last confirmed sequence.
103
+
104
+ For a short-lived token refresh, ask your backend for a new token after a connection error, then call `chat.reconnect(url, new_token, {conversation_id: last_saved_sequence})`. The helper reconnects and sends one history request per conversation. Use `await chat.areconnect(...)` from asyncio. Save your sequence only after your app has handled the corresponding message.
105
+
106
+ Conversation setup is repeat-safe with `ensure_conversation(external_key, user_ids)`. Choose a stable key from your app record, such as `tenant-12:support-ticket:4812`, and save the returned ID. Calling it again with the same participants returns the same conversation. Using that key with different participants returns a conflict.
107
+
108
+ ## Attachments
109
+
110
+ The native library handles WebSocket traffic. Attachment bytes use the server's HTTP endpoints and are handled by Python's standard library:
111
+
112
+ ```python
113
+ with ChatClient(url="wss://chat.example.com/ws", bearer_token="alice-token") as chat:
114
+ attachment = chat.upload_attachment(
115
+ "<conversation-uuid>", "photo.jpg", content_type="image/jpeg"
116
+ )
117
+ send, _accepted = chat.send_message_and_wait(
118
+ "<conversation-uuid>",
119
+ "Photo",
120
+ attachments=[attachment["attachment_id"]],
121
+ )
122
+ # For a received message, use its attachment reference's `download` path:
123
+ # chat.download_attachment(reference["download"], "downloads/photo.jpg")
124
+ ```
125
+
126
+ Uploads and downloads follow the server's 10 MiB limit and membership checks. Upload MIME type is inferred from the filename unless supplied explicitly.
127
+
128
+ ## Native runtime requirements
129
+
130
+ - Linux `.so`: GitHub Actions builds target glibc 2.35 on x86-64 and ARM64. The checked-in x86-64 library in this workspace was built on glibc 2.39 and requires glibc 2.39 or newer; use the CI artifact for older distributions.
131
+ - Windows `.dll`: x64 or ARM64 Windows and the matching Microsoft Visual C++ runtime.
132
+ - macOS `.dylib`: x86-64 or ARM64 macOS.
133
+
134
+ See `../crates/client-sdk/include/chat_sdk.h` for the underlying C ABI.
@@ -0,0 +1,6 @@
1
+ chat_sdk/__init__.py,sha256=RpyW8_hNYBlHhMNvoSfMeszpW1okbV2yHCuW_l-W6ik,44094
2
+ chat_sdk/builds/windows-x86_64/chat_client_sdk.dll,sha256=Q7-qHhuC8ErMBDSV8bocNmWgw8vgKoKRUOW5bWD8Buo,1763840
3
+ chat_client_sdk-0.1.1.dist-info/METADATA,sha256=sxW0GhU2HyiaRMpDbonIeiv8Wyshrqglqe1ziEuVcBI,8714
4
+ chat_client_sdk-0.1.1.dist-info/WHEEL,sha256=QR8DNjG6Lr6bNErJWJgF4dP2dJ2N7NpY-BWly1OvcTM,97
5
+ chat_client_sdk-0.1.1.dist-info/top_level.txt,sha256=MR6HAUyRz5eYDeH1flvaCdr-6Y2PZUuX6mTHPOP22WQ,9
6
+ chat_client_sdk-0.1.1.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-win_amd64
5
+
@@ -0,0 +1 @@
1
+ chat_sdk
chat_sdk/__init__.py ADDED
@@ -0,0 +1,1070 @@
1
+ """Python wrapper for the Rust chat client's version 1 C ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import ctypes
7
+ import hashlib
8
+ import io
9
+ import json
10
+ import mimetypes
11
+ import os
12
+ import platform
13
+ import queue
14
+ import tempfile
15
+ import threading
16
+ import time
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+ import uuid
21
+ import zipfile
22
+ from collections import OrderedDict, deque
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Deque, Mapping, Optional, Union
26
+
27
+ __all__ = ["ChatClient", "ChatSDKError", "MessageSend"]
28
+
29
+ _ABI_VERSION = 1
30
+ _SDK_VERSION = "0.1.1"
31
+ _PYPI_JSON_URL = "https://pypi.org/pypi/chat-client-sdk/{}/json".format(_SDK_VERSION)
32
+ _MAX_NATIVE_LIBRARY_BYTES = 128 * 1024 * 1024
33
+ _MAX_EVENT_BYTES = 16 * 1024
34
+ _DEFAULT_RECEIVE_BUFFER = 1024 * 1024
35
+ _MAX_RECEIVE_BUFFER = 16 * 1024 * 1024
36
+ _MAX_UPLOAD_BYTES = 10 * 1024 * 1024
37
+ _MAX_QUEUED_COMMANDS = 256
38
+ _MAX_QUEUED_EVENTS = 4096
39
+ _MAX_CACHED_ACKS = 2048
40
+ _MAX_SEEN_MESSAGES = 8192
41
+ _COMMAND_ENQUEUE_TIMEOUT = 5.0
42
+ _COMMAND_SEND_TIMEOUT = 15.0
43
+
44
+ _NATIVE_ARTIFACTS = {
45
+ ("Windows", "x86_64"): (
46
+ "win_amd64",
47
+ "windows-x86_64/chat_client_sdk.dll",
48
+ "chat_sdk/builds/windows-x86_64/chat_client_sdk.dll",
49
+ "43bfaa1e1b82f04acc043495f1ba1c3665a0c3cbe02a829150e5b96d60fc06ea",
50
+ ),
51
+ ("Linux", "x86_64"): (
52
+ "manylinux_2_39_x86_64",
53
+ "linux-x86_64/libchat_client_sdk.so",
54
+ "chat_sdk/builds/linux-x86_64/libchat_client_sdk.so",
55
+ "3f16fc03a88d2378d99a1af3ababb35c75cf69467428111101c05d57adc44208",
56
+ ),
57
+ }
58
+
59
+
60
+ class ChatSDKError(RuntimeError):
61
+ """An error returned by the native client or attachment HTTP API."""
62
+
63
+ def __init__(self, message: str, code: Optional[int] = None) -> None:
64
+ super().__init__(message)
65
+ self.code = code
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class MessageSend:
70
+ """Identifiers for a sent message request and its idempotency key."""
71
+
72
+ request_id: str
73
+ idempotency_key: str
74
+
75
+
76
+ @dataclass
77
+ class _PendingWaiter:
78
+ predicate: Any
79
+ ready: threading.Event
80
+ result: Optional[dict[str, Any]] = None
81
+ error: Optional[BaseException] = None
82
+
83
+
84
+ def _native_architecture() -> str:
85
+ machine = platform.machine().lower()
86
+ architectures = {
87
+ "amd64": "x86_64",
88
+ "x86_64": "x86_64",
89
+ "arm64": "aarch64",
90
+ "aarch64": "aarch64",
91
+ }
92
+ architecture = architectures.get(machine)
93
+ if architecture is None:
94
+ raise ChatSDKError("native SDK builds are currently available for x86_64 and ARM64")
95
+ return architecture
96
+
97
+
98
+ def _native_filename() -> str:
99
+ system = platform.system()
100
+ architecture = _native_architecture()
101
+ if system == "Windows":
102
+ return "chat_client_sdk.dll"
103
+ if system == "Linux":
104
+ return "libchat_client_sdk.so"
105
+ if system == "Darwin":
106
+ return "libchat_client_sdk.dylib"
107
+ raise ChatSDKError("the native SDK currently supports Windows, Linux, and macOS")
108
+
109
+
110
+ def _library_candidates() -> list[Path]:
111
+ filename = _native_filename()
112
+ package_dir = Path(__file__).resolve().parent
113
+ sdk_dir = Path(__file__).resolve().parents[2]
114
+ system_dir = "{}-{}".format(platform.system().lower(), _native_architecture())
115
+ filename = _native_filename()
116
+ candidates = [
117
+ Path.cwd() / "builds" / system_dir / filename,
118
+ Path.cwd() / "builds" / filename,
119
+ package_dir / "builds" / system_dir / filename,
120
+ package_dir / "builds" / filename,
121
+ sdk_dir / "builds" / system_dir / filename,
122
+ sdk_dir / "builds" / filename,
123
+ ]
124
+ configured_builds_dir = os.environ.get("CHAT_SDK_NATIVE_DIR")
125
+ if configured_builds_dir:
126
+ candidates.insert(
127
+ 0, Path(configured_builds_dir).expanduser() / system_dir / filename
128
+ )
129
+ return candidates
130
+
131
+
132
+ def _native_cache_path() -> Path:
133
+ if os.name == "nt":
134
+ cache_root = Path(
135
+ os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData" / "Local"))
136
+ ) / "chat-client-sdk" / _SDK_VERSION
137
+ elif platform.system() == "Darwin":
138
+ cache_root = Path.home() / "Library" / "Caches" / "chat-client-sdk" / _SDK_VERSION
139
+ else:
140
+ cache_root = Path(
141
+ os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
142
+ ) / "chat-client-sdk" / _SDK_VERSION
143
+ return cache_root / "{}-{}".format(
144
+ platform.system().lower(), _native_architecture()
145
+ ) / _native_filename()
146
+
147
+
148
+ def _writable_native_path(preferred_path: Path) -> Path:
149
+ for destination in (preferred_path, _native_cache_path()):
150
+ try:
151
+ destination.parent.mkdir(parents=True, exist_ok=True)
152
+ with tempfile.NamedTemporaryFile(
153
+ prefix=".chat-sdk-write-check-", dir=str(destination.parent)
154
+ ):
155
+ pass
156
+ return destination
157
+ except OSError:
158
+ continue
159
+ raise ChatSDKError(
160
+ "cannot write the native library to ./builds/ or the user cache; "
161
+ "set CHAT_SDK_NATIVE_DIR to a writable directory or pass library_path"
162
+ )
163
+
164
+
165
+ def _native_artifact() -> Optional[tuple[str, str, str, str]]:
166
+ return _NATIVE_ARTIFACTS.get((platform.system(), _native_architecture()))
167
+
168
+
169
+ def _wheel_supports_platform(filename: str, platform_tag: str) -> bool:
170
+ if not filename.endswith(".whl"):
171
+ return False
172
+ wheel_platforms = filename[:-4].rsplit("-", 1)[-1].split(".")
173
+ return platform_tag in wheel_platforms
174
+
175
+
176
+ def _download_native_library(destination: Path) -> Path:
177
+ artifact = _native_artifact()
178
+ if artifact is None:
179
+ system_dir = "{}-{}".format(
180
+ platform.system().lower(), _native_architecture()
181
+ )
182
+ raise ChatSDKError(
183
+ "automatic native-library download is not available for {} yet; "
184
+ "place {} in ./builds/{}/ or set CHAT_SDK_LIBRARY".format(
185
+ system_dir, _native_filename(), system_dir
186
+ )
187
+ )
188
+
189
+ platform_tag, _relative_path, wheel_member, expected_library_sha256 = artifact
190
+ destination.parent.mkdir(parents=True, exist_ok=True)
191
+ headers = {"User-Agent": "chat-client-sdk/{}".format(_SDK_VERSION)}
192
+ archive_path: Optional[str] = None
193
+ library_path: Optional[str] = None
194
+ try:
195
+ metadata_request = urllib.request.Request(_PYPI_JSON_URL, headers=headers)
196
+ with urllib.request.urlopen(metadata_request, timeout=30) as response:
197
+ metadata_bytes = response.read(4 * 1024 * 1024 + 1)
198
+ if len(metadata_bytes) > 4 * 1024 * 1024:
199
+ raise ChatSDKError("PyPI returned oversized release metadata")
200
+ release = json.loads(metadata_bytes.decode("utf-8"))
201
+ wheel_info = next(
202
+ (
203
+ item
204
+ for item in release.get("urls", [])
205
+ if _wheel_supports_platform(item.get("filename", ""), platform_tag)
206
+ ),
207
+ None,
208
+ )
209
+ if wheel_info is None:
210
+ raise ChatSDKError(
211
+ "PyPI release {} has no native wheel for {}".format(
212
+ _SDK_VERSION, platform_tag
213
+ )
214
+ )
215
+ wheel_url = wheel_info.get("url", "")
216
+ parsed_wheel_url = urllib.parse.urlparse(wheel_url)
217
+ if parsed_wheel_url.scheme != "https" or parsed_wheel_url.hostname != "files.pythonhosted.org":
218
+ raise ChatSDKError("PyPI returned an unexpected native-wheel download URL")
219
+ expected_wheel_sha256 = wheel_info.get("digests", {}).get("sha256", "")
220
+ if len(expected_wheel_sha256) != 64:
221
+ raise ChatSDKError("PyPI release metadata has no valid wheel SHA-256 digest")
222
+
223
+ archive_digest = hashlib.sha256()
224
+ archive_size = 0
225
+ archive_request = urllib.request.Request(wheel_url, headers=headers)
226
+ with urllib.request.urlopen(archive_request, timeout=30) as response:
227
+ with tempfile.NamedTemporaryFile(
228
+ mode="wb", prefix=".chat-sdk-wheel-", dir=str(destination.parent), delete=False
229
+ ) as archive_file:
230
+ archive_path = archive_file.name
231
+ while True:
232
+ chunk = response.read(1024 * 1024)
233
+ if not chunk:
234
+ break
235
+ archive_size += len(chunk)
236
+ if archive_size > _MAX_NATIVE_LIBRARY_BYTES:
237
+ raise ChatSDKError("downloaded native wheel exceeds the size limit")
238
+ archive_digest.update(chunk)
239
+ archive_file.write(chunk)
240
+ archive_file.flush()
241
+ os.fsync(archive_file.fileno())
242
+
243
+ if archive_digest.hexdigest() != expected_wheel_sha256:
244
+ raise ChatSDKError("downloaded native wheel failed SHA-256 verification")
245
+
246
+ library_digest = hashlib.sha256()
247
+ library_size = 0
248
+ with zipfile.ZipFile(archive_path) as archive:
249
+ try:
250
+ member_info = archive.getinfo(wheel_member)
251
+ except KeyError as exc:
252
+ raise ChatSDKError(
253
+ "published native wheel is missing its expected library"
254
+ ) from exc
255
+ if member_info.file_size > _MAX_NATIVE_LIBRARY_BYTES:
256
+ raise ChatSDKError("native library in wheel exceeds the size limit")
257
+ with archive.open(member_info) as member, tempfile.NamedTemporaryFile(
258
+ mode="wb", prefix=".chat-sdk-library-", dir=str(destination.parent), delete=False
259
+ ) as library_file:
260
+ library_path = library_file.name
261
+ while True:
262
+ chunk = member.read(1024 * 1024)
263
+ if not chunk:
264
+ break
265
+ library_size += len(chunk)
266
+ library_digest.update(chunk)
267
+ library_file.write(chunk)
268
+ library_file.flush()
269
+ os.fsync(library_file.fileno())
270
+
271
+ if library_digest.hexdigest() != expected_library_sha256:
272
+ raise ChatSDKError("native library extracted from the wheel failed SHA-256 verification")
273
+ os.replace(library_path, destination)
274
+ library_path = None
275
+ return destination
276
+ except ChatSDKError:
277
+ raise
278
+ except (OSError, urllib.error.URLError, TimeoutError, UnicodeDecodeError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
279
+ raise ChatSDKError(
280
+ "could not download the native SDK library from PyPI: {}".format(exc)
281
+ ) from exc
282
+ finally:
283
+ for temporary_path in (archive_path, library_path):
284
+ if temporary_path is not None:
285
+ try:
286
+ os.unlink(temporary_path)
287
+ except OSError:
288
+ pass
289
+
290
+
291
+ def _load_library(
292
+ library_path: Optional[Union[str, os.PathLike[str]]], auto_download: bool
293
+ ) -> ctypes.CDLL:
294
+ configured_path = library_path or os.environ.get("CHAT_SDK_LIBRARY")
295
+ if configured_path:
296
+ path = Path(configured_path).expanduser()
297
+ if not path.is_file():
298
+ raise ChatSDKError("native library does not exist: {}".format(path))
299
+ try:
300
+ return ctypes.CDLL(str(path.resolve()))
301
+ except OSError as exc:
302
+ raise ChatSDKError("could not load native library {}: {}".format(path, exc)) from exc
303
+
304
+ candidates = _library_candidates()
305
+ for path in candidates:
306
+ if path.is_file():
307
+ try:
308
+ return ctypes.CDLL(str(path))
309
+ except OSError as exc:
310
+ raise ChatSDKError("could not load native library {}: {}".format(path, exc)) from exc
311
+
312
+ download_setting = os.environ.get("CHAT_SDK_AUTO_DOWNLOAD", "1").strip().lower()
313
+ if auto_download and download_setting not in {"0", "false", "no", "off"}:
314
+ artifact = _native_artifact()
315
+ if artifact is not None:
316
+ _platform_tag, relative_path, _wheel_member, expected_sha256 = artifact
317
+ cache_path = _native_cache_path()
318
+ if cache_path.is_file():
319
+ actual_sha256 = hashlib.sha256(cache_path.read_bytes()).hexdigest()
320
+ if actual_sha256 == expected_sha256:
321
+ try:
322
+ return ctypes.CDLL(str(cache_path))
323
+ except OSError as exc:
324
+ raise ChatSDKError(
325
+ "could not load cached native library {}: {}".format(
326
+ cache_path, exc
327
+ )
328
+ ) from exc
329
+ try:
330
+ cache_path.unlink()
331
+ except OSError:
332
+ pass
333
+
334
+ configured_builds_dir = os.environ.get("CHAT_SDK_NATIVE_DIR")
335
+ if configured_builds_dir:
336
+ preferred_path = Path(configured_builds_dir).expanduser() / relative_path
337
+ else:
338
+ preferred_path = Path.cwd() / "builds" / relative_path
339
+ destination = _writable_native_path(preferred_path)
340
+ downloaded_path = _download_native_library(destination)
341
+ try:
342
+ return ctypes.CDLL(str(downloaded_path))
343
+ except OSError as exc:
344
+ raise ChatSDKError(
345
+ "downloaded native library {} could not be loaded: {}".format(
346
+ downloaded_path, exc
347
+ )
348
+ ) from exc
349
+
350
+ checked = "\n".join(" - {}".format(path) for path in candidates)
351
+ raise ChatSDKError(
352
+ "native chat SDK library not found. Download the matching platform build "
353
+ "and place it in ./builds/ ({}). You can also set CHAT_SDK_LIBRARY or "
354
+ "pass library_path. Checked:\n{}".format(_native_filename(), checked)
355
+ )
356
+
357
+
358
+ class ChatClient:
359
+ """WebSocket client backed by ``chat-client-sdk`` with a background event pump.
360
+
361
+ The SDK automatically selects the native library for the current operating
362
+ system and architecture from ``./builds/``. When no local copy is found,
363
+ supported builds are downloaded and SHA-256 verified on first use. Set
364
+ ``auto_download=False`` or ``CHAT_SDK_AUTO_DOWNLOAD=0`` to disable this.
365
+ ``library_path`` and ``CHAT_SDK_LIBRARY`` can override discovery. ``url``
366
+ and ``bearer_token`` can be provided to connect immediately; native
367
+ operations are serialized by the event pump.
368
+ """
369
+
370
+ def __init__(
371
+ self,
372
+ library_path: Optional[Union[str, os.PathLike[str]]] = None,
373
+ *,
374
+ url: Optional[str] = None,
375
+ bearer_token: Optional[str] = None,
376
+ receive_buffer_size: int = _DEFAULT_RECEIVE_BUFFER,
377
+ auto_download: bool = True,
378
+ ) -> None:
379
+ if not 2 <= receive_buffer_size <= _MAX_RECEIVE_BUFFER:
380
+ raise ValueError(
381
+ "receive_buffer_size must be between 2 and {} bytes".format(
382
+ _MAX_RECEIVE_BUFFER
383
+ )
384
+ )
385
+ self._receive_buffer_size = receive_buffer_size
386
+ self._library = _load_library(library_path, auto_download)
387
+ self._bind_functions()
388
+ abi = self._library.chat_sdk_abi_version()
389
+ if abi != _ABI_VERSION:
390
+ raise ChatSDKError(
391
+ "native ABI version {} is incompatible with Python SDK ABI {}".format(
392
+ abi, _ABI_VERSION
393
+ )
394
+ )
395
+ self._handle = self._library.chat_client_create()
396
+ if not self._handle:
397
+ raise ChatSDKError("native SDK could not create a client handle")
398
+ self._token: Optional[str] = None
399
+ self._http_base: Optional[str] = None
400
+ self._commands: Optional[queue.Queue[dict[str, Any]]] = None
401
+ self._event_condition = threading.Condition()
402
+ self._incoming: Deque[dict[str, Any]] = deque()
403
+ self._ack_events: OrderedDict[str, dict[str, Any]] = OrderedDict()
404
+ self._seen_messages: OrderedDict[tuple[str, int], None] = OrderedDict()
405
+ self._waiters: list[_PendingWaiter] = []
406
+ self._worker: Optional[threading.Thread] = None
407
+ self._ready: Optional[threading.Event] = None
408
+ self._worker_error: Optional[BaseException] = None
409
+ self._stop = threading.Event()
410
+ if (url is None) != (bearer_token is None):
411
+ self.close()
412
+ raise ValueError("provide both url and bearer_token, or neither")
413
+ if url is not None and bearer_token is not None:
414
+ self._start_background(url, bearer_token)
415
+
416
+ def _bind_functions(self) -> None:
417
+ lib = self._library
418
+ lib.chat_sdk_abi_version.argtypes = []
419
+ lib.chat_sdk_abi_version.restype = ctypes.c_uint32
420
+ lib.chat_client_create.argtypes = []
421
+ lib.chat_client_create.restype = ctypes.c_void_p
422
+ lib.chat_client_connect.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p]
423
+ lib.chat_client_connect.restype = ctypes.c_int32
424
+ lib.chat_client_send.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
425
+ lib.chat_client_send.restype = ctypes.c_int32
426
+ lib.chat_client_receive.argtypes = [
427
+ ctypes.c_void_p,
428
+ ctypes.POINTER(ctypes.c_char),
429
+ ctypes.c_size_t,
430
+ ctypes.c_uint32,
431
+ ]
432
+ lib.chat_client_receive.restype = ctypes.c_int32
433
+ lib.chat_client_destroy.argtypes = [ctypes.c_void_p]
434
+ lib.chat_client_destroy.restype = None
435
+ lib.chat_sdk_error_string.argtypes = [
436
+ ctypes.c_int32,
437
+ ctypes.POINTER(ctypes.c_char),
438
+ ctypes.c_size_t,
439
+ ]
440
+ lib.chat_sdk_error_string.restype = ctypes.c_int32
441
+
442
+ def _ensure_open(self) -> None:
443
+ if not self._handle:
444
+ raise ChatSDKError("client is closed")
445
+
446
+ def _error(self, code: int) -> ChatSDKError:
447
+ buffer = ctypes.create_string_buffer(256)
448
+ self._library.chat_sdk_error_string(code, buffer, len(buffer))
449
+ message = buffer.value.decode("utf-8", errors="replace") or "native SDK error"
450
+ return ChatSDKError(message, code)
451
+
452
+ @staticmethod
453
+ def _cstring(value: str, label: str) -> bytes:
454
+ if not isinstance(value, str):
455
+ raise TypeError("{} must be str".format(label))
456
+ if "\x00" in value:
457
+ raise ValueError("{} must not contain a NUL character".format(label))
458
+ return value.encode("utf-8")
459
+
460
+ def connect(self, url: str, bearer_token: str) -> "ChatClient":
461
+ """Connect to a ``ws://`` or ``wss://`` endpoint."""
462
+ if self._worker is not None and self._worker.is_alive():
463
+ raise ChatSDKError("client is already connected")
464
+ if self._worker is not None:
465
+ self._worker.join()
466
+ self._worker = None
467
+ self._worker_error = None
468
+ if not self._handle:
469
+ self._handle = self._library.chat_client_create()
470
+ if not self._handle:
471
+ raise ChatSDKError("native SDK could not create a client handle")
472
+ self._start_background(url, bearer_token)
473
+ return self
474
+
475
+ async def aconnect(self, url: str, bearer_token: str) -> "ChatClient":
476
+ """Connect without blocking an asyncio event loop."""
477
+ return await asyncio.to_thread(self.connect, url, bearer_token)
478
+
479
+ def reconnect(
480
+ self,
481
+ url: str,
482
+ bearer_token: str,
483
+ last_sequences: Optional[Mapping[str, int]] = None,
484
+ ) -> list[str]:
485
+ """Reconnect with a fresh token and request missed history for known chats.
486
+
487
+ The mapping contains conversation IDs and the last sequence your app has
488
+ safely saved for each conversation. Call this after a connection error.
489
+ """
490
+ self.close()
491
+ self.connect(url, bearer_token)
492
+ requests = []
493
+ for conversation_id, sequence in (last_sequences or {}).items():
494
+ requests.append(
495
+ self.send_event(
496
+ "history",
497
+ {
498
+ "conversation_id": str(uuid.UUID(conversation_id)),
499
+ "after_sequence": int(sequence),
500
+ "limit": 200,
501
+ },
502
+ )
503
+ )
504
+ return requests
505
+
506
+ async def areconnect(
507
+ self,
508
+ url: str,
509
+ bearer_token: str,
510
+ last_sequences: Optional[Mapping[str, int]] = None,
511
+ ) -> list[str]:
512
+ """Asyncio-friendly reconnect and history recovery helper."""
513
+ return await asyncio.to_thread(
514
+ self.reconnect, url, bearer_token, last_sequences
515
+ )
516
+
517
+ def _connect_native(self, url: str, bearer_token: str) -> "ChatClient":
518
+ self._ensure_open()
519
+ url_bytes = self._cstring(url, "url")
520
+ token_bytes = self._cstring(bearer_token, "bearer_token")
521
+ parsed = urllib.parse.urlsplit(url)
522
+ if parsed.scheme not in ("ws", "wss") or not parsed.netloc:
523
+ raise ValueError("url must be an absolute ws:// or wss:// URL")
524
+ code = self._library.chat_client_connect(self._handle, url_bytes, token_bytes)
525
+ if code != 0:
526
+ raise self._error(code)
527
+ http_scheme = "https" if parsed.scheme == "wss" else "http"
528
+ self._http_base = "{}://{}".format(http_scheme, parsed.netloc)
529
+ self._token = bearer_token
530
+ return self
531
+
532
+ def _start_background(self, url: str, bearer_token: str) -> None:
533
+ self._commands = queue.Queue(maxsize=_MAX_QUEUED_COMMANDS)
534
+ self._ready = threading.Event()
535
+ self._worker_error = None
536
+ self._stop = threading.Event()
537
+ self._worker = threading.Thread(
538
+ target=self._background_main,
539
+ args=(url, bearer_token),
540
+ name="chat-sdk-events",
541
+ daemon=True,
542
+ )
543
+ self._worker.start()
544
+ self._ready.wait()
545
+ if self._worker_error is not None:
546
+ error = self._worker_error
547
+ self.close()
548
+ if isinstance(error, Exception):
549
+ raise error
550
+ raise ChatSDKError("native connection failed")
551
+
552
+ def _background_main(self, url: str, bearer_token: str) -> None:
553
+ assert self._ready is not None
554
+ assert self._commands is not None
555
+ try:
556
+ self._connect_native(url, bearer_token)
557
+ self._ready.set()
558
+ while not self._stop.is_set():
559
+ try:
560
+ command = self._commands.get(timeout=0.01)
561
+ except queue.Empty:
562
+ command = None
563
+ if command is not None:
564
+ try:
565
+ code = self._library.chat_client_send(self._handle, command["raw"])
566
+ if code != 0:
567
+ command["error"] = self._error(code)
568
+ except BaseException as exc:
569
+ command["error"] = exc
570
+ finally:
571
+ command["done"].set()
572
+ event = self._receive_raw(10)
573
+ if event is not None:
574
+ self._route_event(event)
575
+ except BaseException as exc:
576
+ self._worker_error = exc
577
+ self._ready.set()
578
+ finally:
579
+ while True:
580
+ try:
581
+ command = self._commands.get_nowait()
582
+ except queue.Empty:
583
+ break
584
+ command["error"] = ChatSDKError("client event worker has stopped")
585
+ command["done"].set()
586
+ if self._handle:
587
+ self._library.chat_client_destroy(self._handle)
588
+ self._handle = None
589
+ stopped = ChatSDKError("background client has stopped")
590
+ with self._event_condition:
591
+ for waiter in self._waiters:
592
+ waiter.error = self._worker_error or stopped
593
+ waiter.ready.set()
594
+ self._waiters.clear()
595
+ self._event_condition.notify_all()
596
+
597
+ def _route_event(self, event: dict[str, Any]) -> None:
598
+ with self._event_condition:
599
+ event_type = event.get("type")
600
+ data = event.get("data") or {}
601
+ if event_type == "message":
602
+ message = data.get("message") or {}
603
+ conversation = message.get("conversation_id")
604
+ sequence = message.get("sequence")
605
+ if conversation is not None and isinstance(sequence, int):
606
+ key = (conversation, sequence)
607
+ if key in self._seen_messages:
608
+ return
609
+ self._seen_messages[key] = None
610
+ while len(self._seen_messages) > _MAX_SEEN_MESSAGES:
611
+ self._seen_messages.popitem(last=False)
612
+ request_id = data.get("request_id")
613
+ if event_type in ("accepted", "error") and request_id:
614
+ self._ack_events[request_id] = event
615
+ self._ack_events.move_to_end(request_id)
616
+ while len(self._ack_events) > _MAX_CACHED_ACKS:
617
+ self._ack_events.popitem(last=False)
618
+ for waiter in tuple(self._waiters):
619
+ try:
620
+ matches = waiter.predicate(event)
621
+ except BaseException as exc:
622
+ self._waiters.remove(waiter)
623
+ waiter.error = exc
624
+ waiter.ready.set()
625
+ continue
626
+ if matches:
627
+ self._waiters.remove(waiter)
628
+ waiter.result = event
629
+ waiter.ready.set()
630
+ self._event_condition.notify_all()
631
+ return
632
+ while len(self._incoming) >= _MAX_QUEUED_EVENTS and not self._stop.is_set():
633
+ # Backpressure the socket reader instead of dropping events or growing
634
+ # memory without a bound. Receiving an event wakes this producer.
635
+ self._event_condition.wait(timeout=0.1)
636
+ if not self._stop.is_set():
637
+ self._incoming.append(event)
638
+ self._event_condition.notify_all()
639
+
640
+ def send_event(
641
+ self,
642
+ event_type: str,
643
+ data: Mapping[str, Any],
644
+ *,
645
+ request_id: Optional[str] = None,
646
+ ) -> str:
647
+ """Send one version 1 protocol event and return its request ID."""
648
+ self._ensure_open()
649
+ if not isinstance(data, Mapping):
650
+ raise TypeError("data must be a mapping")
651
+ rid = str(uuid.UUID(request_id)) if request_id is not None else str(uuid.uuid4())
652
+ envelope = {
653
+ "version": _ABI_VERSION,
654
+ "request_id": rid,
655
+ "event": {"type": event_type, "data": dict(data)},
656
+ }
657
+ encoded = json.dumps(envelope, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
658
+ raw = encoded.encode("utf-8")
659
+ if len(raw) > _MAX_EVENT_BYTES:
660
+ raise ValueError("encoded event exceeds the 16 KiB protocol limit")
661
+ if b"\x00" in raw:
662
+ raise ValueError("encoded event must not contain a NUL byte")
663
+ worker = self._worker
664
+ commands = self._commands
665
+ if worker is None or not worker.is_alive() or commands is None:
666
+ detail = ": {}".format(self._worker_error) if self._worker_error else ""
667
+ raise ChatSDKError("client is not connected{}".format(detail))
668
+ done = threading.Event()
669
+ command: dict[str, Any] = {"raw": raw, "done": done}
670
+ try:
671
+ commands.put(command, timeout=_COMMAND_ENQUEUE_TIMEOUT)
672
+ except queue.Full as exc:
673
+ raise TimeoutError("client send queue remained full") from exc
674
+ if not done.wait(_COMMAND_SEND_TIMEOUT):
675
+ raise TimeoutError(
676
+ "timed out waiting for the native client send; retry with the same idempotency key"
677
+ )
678
+ if "error" in command:
679
+ raise command["error"]
680
+ return rid
681
+
682
+ def send_message(
683
+ self,
684
+ conversation_id: str,
685
+ body: str,
686
+ *,
687
+ idempotency_key: Optional[str] = None,
688
+ reply_to: Optional[str] = None,
689
+ attachments: Optional[list[str]] = None,
690
+ ) -> MessageSend:
691
+ """Send a chat message; attachment IDs come from ``upload_attachment``."""
692
+ key = str(uuid.UUID(idempotency_key)) if idempotency_key else str(uuid.uuid4())
693
+ data: dict[str, Any] = {
694
+ "conversation_id": str(uuid.UUID(conversation_id)),
695
+ "idempotency_key": key,
696
+ "body": body,
697
+ "reply_to": str(uuid.UUID(reply_to)) if reply_to else None,
698
+ "attachments": [str(uuid.UUID(item)) for item in (attachments or [])],
699
+ }
700
+ request_id = self.send_event("send_message", data)
701
+ return MessageSend(request_id=request_id, idempotency_key=key)
702
+
703
+ def send_message_and_wait(
704
+ self,
705
+ conversation_id: str,
706
+ body: str,
707
+ *,
708
+ timeout: float = 10.0,
709
+ idempotency_key: Optional[str] = None,
710
+ reply_to: Optional[str] = None,
711
+ attachments: Optional[list[str]] = None,
712
+ ) -> tuple[MessageSend, dict[str, Any]]:
713
+ """Send a message and wait until the server confirms it was persisted."""
714
+ sent = self.send_message(
715
+ conversation_id,
716
+ body,
717
+ idempotency_key=idempotency_key,
718
+ reply_to=reply_to,
719
+ attachments=attachments,
720
+ )
721
+ return sent, self.wait_for_ack(sent.request_id, timeout=timeout)
722
+
723
+ def receive(self, timeout_ms: int = 1000) -> Optional[dict[str, Any]]:
724
+ """Receive one event, or return ``None`` on timeout.
725
+
726
+ Concurrent calls are safe: each queued event is delivered to one reader.
727
+ """
728
+ if not isinstance(timeout_ms, int) or not 0 <= timeout_ms <= 0xFFFFFFFF:
729
+ raise ValueError("timeout_ms must be an integer from 0 to 2^32-1")
730
+ deadline = time.monotonic() + timeout_ms / 1000.0
731
+ with self._event_condition:
732
+ while not self._incoming:
733
+ if self._worker_error is not None:
734
+ raise ChatSDKError("background client failed: {}".format(self._worker_error))
735
+ worker = self._worker
736
+ if worker is None or not worker.is_alive():
737
+ raise ChatSDKError("client is not connected")
738
+ remaining = deadline - time.monotonic()
739
+ if remaining <= 0:
740
+ return None
741
+ self._event_condition.wait(remaining)
742
+ event = self._incoming.popleft()
743
+ self._event_condition.notify_all()
744
+ return event
745
+
746
+ def _receive_raw(self, timeout_ms: int) -> Optional[dict[str, Any]]:
747
+ self._ensure_open()
748
+ buffer = ctypes.create_string_buffer(self._receive_buffer_size)
749
+ result = self._library.chat_client_receive(
750
+ self._handle, buffer, self._receive_buffer_size, timeout_ms
751
+ )
752
+ if result < 0:
753
+ raise self._error(result)
754
+ if result == 0:
755
+ return None
756
+ if result >= self._receive_buffer_size - 1:
757
+ raise ChatSDKError(
758
+ "received event may exceed the configured buffer; increase receive_buffer_size"
759
+ )
760
+ try:
761
+ return json.loads(buffer.raw[:result].decode("utf-8"))
762
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
763
+ raise ChatSDKError("native SDK returned an invalid or truncated JSON event") from exc
764
+
765
+ def wait_for(self, predicate: Any, *, timeout: float = 10.0) -> dict[str, Any]:
766
+ """Wait for a matching event without competing with other event readers."""
767
+ if timeout < 0:
768
+ raise ValueError("timeout must be non-negative")
769
+ deadline = time.monotonic() + timeout
770
+ with self._event_condition:
771
+ for request_id, event in tuple(self._ack_events.items()):
772
+ if predicate(event):
773
+ self._ack_events.pop(request_id, None)
774
+ try:
775
+ self._incoming.remove(event)
776
+ except ValueError:
777
+ pass
778
+ return event
779
+ for index, event in enumerate(self._incoming):
780
+ if predicate(event):
781
+ del self._incoming[index]
782
+ self._event_condition.notify_all()
783
+ return event
784
+ worker = self._worker
785
+ if worker is None or not worker.is_alive():
786
+ if self._worker_error is not None:
787
+ raise ChatSDKError("background client failed: {}".format(self._worker_error))
788
+ raise ChatSDKError("client is not connected")
789
+ waiter = _PendingWaiter(predicate=predicate, ready=threading.Event())
790
+ self._waiters.append(waiter)
791
+ while not waiter.ready.is_set():
792
+ remaining = deadline - time.monotonic()
793
+ if remaining <= 0:
794
+ if waiter in self._waiters:
795
+ self._waiters.remove(waiter)
796
+ raise TimeoutError("timed out waiting for a chat event")
797
+ self._event_condition.wait(remaining)
798
+ if waiter.error is not None:
799
+ raise waiter.error
800
+ assert waiter.result is not None
801
+ event = waiter.result
802
+ data = event.get("data") or {}
803
+ request_id = data.get("request_id")
804
+ if request_id:
805
+ self._ack_events.pop(request_id, None)
806
+ return event
807
+
808
+ def wait_for_ack(self, request_id: str, *, timeout: float = 10.0) -> dict[str, Any]:
809
+ """Wait for the persisted-message acknowledgement or raise on server error."""
810
+ rid = str(uuid.UUID(request_id))
811
+
812
+ def matches(event: dict[str, Any]) -> bool:
813
+ data = event.get("data") or {}
814
+ return (
815
+ event.get("type") == "accepted" and data.get("request_id") == rid
816
+ ) or (event.get("type") == "error" and data.get("request_id") == rid)
817
+
818
+ event = self.wait_for(matches, timeout=timeout)
819
+ if event.get("type") == "error":
820
+ data = event.get("data") or {}
821
+ raise ChatSDKError(data.get("message", data.get("code", "request failed")))
822
+ return event
823
+
824
+ def upload_attachment(
825
+ self,
826
+ conversation_id: str,
827
+ file_path: Union[str, os.PathLike[str]],
828
+ *,
829
+ content_type: Optional[str] = None,
830
+ ) -> dict[str, Any]:
831
+ """Upload a file using the server HTTP API and return its attachment metadata."""
832
+ self._require_http_auth()
833
+ path = Path(file_path)
834
+ payload = path.read_bytes()
835
+ if len(payload) > _MAX_UPLOAD_BYTES:
836
+ raise ValueError("attachment exceeds the server's 10 MiB upload limit")
837
+ media_type = content_type or mimetypes.guess_type(path.name)[0] or "application/octet-stream"
838
+ query = urllib.parse.urlencode({"name": path.name, "content_type": media_type})
839
+ conv = str(uuid.UUID(conversation_id))
840
+ url = "{}/conversations/{}/upload?{}".format(self._http_base, conv, query)
841
+ request = urllib.request.Request(
842
+ url,
843
+ data=payload,
844
+ method="POST",
845
+ headers={
846
+ "Authorization": "Bearer {}".format(self._token),
847
+ "Content-Type": media_type,
848
+ },
849
+ )
850
+ try:
851
+ with urllib.request.urlopen(request, timeout=30) as response:
852
+ return json.loads(response.read().decode("utf-8"))
853
+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:
854
+ raise ChatSDKError("attachment upload failed: {}".format(exc)) from exc
855
+
856
+ def download_attachment(self, download_url: str, destination: Union[str, os.PathLike[str]]) -> Path:
857
+ """Download an attachment reference from a server message to ``destination``."""
858
+ self._require_http_auth()
859
+ target = urllib.parse.urljoin(self._http_base + "/", download_url)
860
+ base_parts = urllib.parse.urlsplit(self._http_base)
861
+ target_parts = urllib.parse.urlsplit(target)
862
+ if (target_parts.scheme, target_parts.netloc) != (base_parts.scheme, base_parts.netloc):
863
+ raise ValueError("attachment URL must belong to the connected chat server")
864
+ request = urllib.request.Request(
865
+ target, headers={"Authorization": "Bearer {}".format(self._token)}
866
+ )
867
+ try:
868
+ with urllib.request.urlopen(request, timeout=30) as response:
869
+ payload = response.read(_MAX_UPLOAD_BYTES + 1)
870
+ if len(payload) > _MAX_UPLOAD_BYTES:
871
+ raise ChatSDKError("downloaded attachment exceeds the 10 MiB server limit")
872
+ path = Path(destination)
873
+ path.parent.mkdir(parents=True, exist_ok=True)
874
+ path.write_bytes(payload)
875
+ return path
876
+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:
877
+ raise ChatSDKError("attachment download failed: {}".format(exc)) from exc
878
+
879
+ async def send_event_async(
880
+ self,
881
+ event_type: str,
882
+ data: Mapping[str, Any],
883
+ *,
884
+ request_id: Optional[str] = None,
885
+ ) -> str:
886
+ """Asyncio-friendly form of ``send_event``."""
887
+ return await asyncio.to_thread(
888
+ self.send_event, event_type, data, request_id=request_id
889
+ )
890
+
891
+ async def send_message_async(
892
+ self,
893
+ conversation_id: str,
894
+ body: str,
895
+ *,
896
+ idempotency_key: Optional[str] = None,
897
+ reply_to: Optional[str] = None,
898
+ attachments: Optional[list[str]] = None,
899
+ ) -> MessageSend:
900
+ """Asyncio-friendly form of ``send_message``."""
901
+ return await asyncio.to_thread(
902
+ self.send_message,
903
+ conversation_id,
904
+ body,
905
+ idempotency_key=idempotency_key,
906
+ reply_to=reply_to,
907
+ attachments=attachments,
908
+ )
909
+
910
+ async def send_message_and_wait_async(
911
+ self,
912
+ conversation_id: str,
913
+ body: str,
914
+ *,
915
+ timeout: float = 10.0,
916
+ idempotency_key: Optional[str] = None,
917
+ reply_to: Optional[str] = None,
918
+ attachments: Optional[list[str]] = None,
919
+ ) -> tuple[MessageSend, dict[str, Any]]:
920
+ """Asyncio-friendly form that waits for the durable server acknowledgement."""
921
+ return await asyncio.to_thread(
922
+ self.send_message_and_wait,
923
+ conversation_id,
924
+ body,
925
+ timeout=timeout,
926
+ idempotency_key=idempotency_key,
927
+ reply_to=reply_to,
928
+ attachments=attachments,
929
+ )
930
+
931
+ async def receive_async(self, timeout_ms: int = 1000) -> Optional[dict[str, Any]]:
932
+ """Asyncio-friendly form of ``receive``."""
933
+ return await asyncio.to_thread(self.receive, timeout_ms)
934
+
935
+ async def upload_attachment_async(
936
+ self,
937
+ conversation_id: str,
938
+ file_path: Union[str, os.PathLike[str]],
939
+ *,
940
+ content_type: Optional[str] = None,
941
+ ) -> dict[str, Any]:
942
+ """Asyncio-friendly form of ``upload_attachment``."""
943
+ return await asyncio.to_thread(
944
+ self.upload_attachment,
945
+ conversation_id,
946
+ file_path,
947
+ content_type=content_type,
948
+ )
949
+
950
+ async def download_attachment_async(
951
+ self,
952
+ download_url: str,
953
+ destination: Union[str, os.PathLike[str]],
954
+ ) -> Path:
955
+ """Asyncio-friendly form of ``download_attachment``."""
956
+ return await asyncio.to_thread(
957
+ self.download_attachment, download_url, destination
958
+ )
959
+
960
+ async def create_conversation_async(self, user_ids: list[str]) -> dict[str, Any]:
961
+ """Create a conversation through the server's authenticated HTTP API."""
962
+ return await asyncio.to_thread(self.create_conversation, user_ids)
963
+
964
+ async def ensure_conversation_async(
965
+ self, external_key: str, user_ids: list[str]
966
+ ) -> dict[str, Any]:
967
+ """Reuse a conversation for a stable application key, or create it."""
968
+ return await asyncio.to_thread(
969
+ self.ensure_conversation, external_key, user_ids
970
+ )
971
+
972
+ async def aclose(self) -> None:
973
+ """Close the client without blocking the current asyncio event loop."""
974
+ await asyncio.to_thread(self.close)
975
+
976
+ def _require_http_auth(self) -> None:
977
+ self._ensure_open()
978
+ if not self._http_base or not self._token:
979
+ raise ChatSDKError("connect the client before using authenticated HTTP methods")
980
+
981
+ def create_conversation(self, user_ids: list[str]) -> dict[str, Any]:
982
+ """Create a conversation and return its server-generated conversation ID."""
983
+ self._require_http_auth()
984
+ if not isinstance(user_ids, list) or any(
985
+ not isinstance(user_id, str) or not user_id.strip() for user_id in user_ids
986
+ ):
987
+ raise ValueError("user_ids must be a list of non-empty strings")
988
+ payload = json.dumps(user_ids, separators=(",", ":")).encode("utf-8")
989
+ request = urllib.request.Request(
990
+ "{}/conversations".format(self._http_base),
991
+ data=payload,
992
+ method="POST",
993
+ headers={
994
+ "Authorization": "Bearer {}".format(self._token),
995
+ "Content-Type": "application/json",
996
+ },
997
+ )
998
+ try:
999
+ with urllib.request.urlopen(request, timeout=30) as response:
1000
+ return json.loads(response.read().decode("utf-8"))
1001
+ except (urllib.error.URLError, urllib.error.HTTPError) as exc:
1002
+ raise ChatSDKError("conversation creation failed: {}".format(exc)) from exc
1003
+
1004
+ def ensure_conversation(
1005
+ self, external_key: str, user_ids: list[str]
1006
+ ) -> dict[str, Any]:
1007
+ """Return the same conversation for this user's stable application key."""
1008
+ self._require_http_auth()
1009
+ if not isinstance(external_key, str) or not external_key.strip():
1010
+ raise ValueError("external_key must be a non-empty string")
1011
+ if not isinstance(user_ids, list) or any(
1012
+ not isinstance(user_id, str) or not user_id.strip() for user_id in user_ids
1013
+ ):
1014
+ raise ValueError("user_ids must be a list of non-empty strings")
1015
+ payload = json.dumps(
1016
+ {"external_key": external_key, "user_ids": user_ids},
1017
+ separators=(",", ":"),
1018
+ ).encode("utf-8")
1019
+ request = urllib.request.Request(
1020
+ "{}/conversations/ensure".format(self._http_base),
1021
+ data=payload,
1022
+ method="POST",
1023
+ headers={
1024
+ "Authorization": "Bearer {}".format(self._token),
1025
+ "Content-Type": "application/json",
1026
+ },
1027
+ )
1028
+ try:
1029
+ with urllib.request.urlopen(request, timeout=30) as response:
1030
+ return json.loads(response.read().decode("utf-8"))
1031
+ except urllib.error.HTTPError as exc:
1032
+ if exc.code == 409:
1033
+ raise ChatSDKError(
1034
+ "conversation key is already linked to different participants",
1035
+ exc.code,
1036
+ ) from exc
1037
+ raise ChatSDKError("conversation setup failed: {}".format(exc)) from exc
1038
+ except urllib.error.URLError as exc:
1039
+ raise ChatSDKError("conversation setup failed: {}".format(exc)) from exc
1040
+
1041
+ def close(self) -> None:
1042
+ """Close the native handle. Safe to call more than once."""
1043
+ if self._worker is not None:
1044
+ self._stop.set()
1045
+ if threading.current_thread() is not self._worker:
1046
+ self._worker.join()
1047
+ self._worker = None
1048
+ elif self._handle:
1049
+ self._library.chat_client_destroy(self._handle)
1050
+ self._handle = None
1051
+
1052
+ def __enter__(self) -> "ChatClient":
1053
+ self._ensure_open()
1054
+ return self
1055
+
1056
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
1057
+ self.close()
1058
+
1059
+ async def __aenter__(self) -> "ChatClient":
1060
+ self._ensure_open()
1061
+ return self
1062
+
1063
+ async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
1064
+ await self.aclose()
1065
+
1066
+ def __del__(self) -> None:
1067
+ try:
1068
+ self.close()
1069
+ except Exception:
1070
+ pass