learning-sdk 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ """Python entry point for CopilotKit Learning."""
2
+
3
+ from ._event import TrajectoryEvent, parse_trajectory_event
4
+ from ._grant import (
5
+ Realtime,
6
+ TrajectoryGrant,
7
+ TrajectoryGrantError,
8
+ TrajectoryGrantIssuer,
9
+ )
10
+
11
+ __all__ = [
12
+ "Realtime",
13
+ "TrajectoryEvent",
14
+ "TrajectoryGrant",
15
+ "TrajectoryGrantError",
16
+ "TrajectoryGrantIssuer",
17
+ "parse_trajectory_event",
18
+ ]
learning_sdk/_event.py ADDED
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ from collections.abc import Mapping
6
+ from typing import Any, Literal, TypedDict
7
+
8
+ # Matches packages/learning-sdk/src/capture/event.ts. JavaScript limits count UTF-16 code units.
9
+ _MAX_NAME_UNITS = 400
10
+ _MAX_NAME_CHARACTERS = 200
11
+ _TIMESTAMP_LIMIT = 253_402_300_800_000 # 10000-01-01T00:00:00Z in Unix milliseconds
12
+
13
+
14
+ class TrajectoryEvent(TypedDict):
15
+ type: Literal["CUSTOM"]
16
+ name: str
17
+ timestamp: int | float
18
+ value: Any
19
+
20
+
21
+ def utf16_length(text: str) -> int:
22
+ return len(text.encode("utf-16-le", "surrogatepass")) // 2
23
+
24
+
25
+ def _reject_constant(name: str) -> Any:
26
+ raise ValueError(name)
27
+
28
+
29
+ def parse_trajectory_event(input: object) -> TrajectoryEvent:
30
+ """Validate a collector event and take a JSON snapshot of its payload.
31
+
32
+ Raises TypeError for an event that the Learning capture queue would refuse.
33
+ """
34
+ if not isinstance(input, Mapping):
35
+ raise TypeError("Expected a trajectory event object.")
36
+
37
+ kind = input.get("type")
38
+ name = input.get("name")
39
+ timestamp = input.get("timestamp")
40
+ if (
41
+ kind != "CUSTOM"
42
+ or not isinstance(name, str)
43
+ or len(name) == 0
44
+ or utf16_length(name) > _MAX_NAME_UNITS
45
+ or len(name) > _MAX_NAME_CHARACTERS
46
+ or isinstance(timestamp, bool)
47
+ or not isinstance(timestamp, (int, float))
48
+ or not math.isfinite(timestamp)
49
+ or timestamp <= 0
50
+ or timestamp >= _TIMESTAMP_LIMIT
51
+ ):
52
+ raise TypeError("Expected a CUSTOM event with a valid name and timestamp.")
53
+
54
+ if "value" not in input:
55
+ raise TypeError("The trajectory event value must be JSON-serializable.")
56
+ try:
57
+ text = json.dumps(input["value"], allow_nan=False)
58
+ except (TypeError, ValueError, RecursionError):
59
+ raise TypeError(
60
+ "The trajectory event value must be JSON-serializable."
61
+ ) from None
62
+
63
+ return {
64
+ "type": "CUSTOM",
65
+ "name": name,
66
+ "timestamp": timestamp,
67
+ "value": json.loads(text, parse_constant=_reject_constant),
68
+ }
learning_sdk/_grant.py ADDED
@@ -0,0 +1,256 @@
1
+ from __future__ import annotations
2
+
3
+ import http.client
4
+ import json
5
+ import re
6
+ import urllib.error
7
+ import urllib.request
8
+ from collections.abc import Callable, Sequence
9
+ from typing import Any, Protocol, TypedDict
10
+ from urllib.parse import urlsplit
11
+
12
+ from ._event import utf16_length
13
+
14
+ # Matches packages/learning-sdk/src/capture/server.ts.
15
+ _RESPONSE_LIMIT = 8192
16
+ _DEFAULT_TIMEOUT = 15.0
17
+ _LOOPBACK = {"127.0.0.1", "::1", "localhost"}
18
+ # The UUID pattern of zod 4's z.uuid(): RFC 9562 versions 1 to 8, plus the nil and max UUIDs.
19
+ _UUID = re.compile(
20
+ r"^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}"
21
+ r"|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
22
+ )
23
+ _CONTAINER_ID = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
24
+ # The characters that JavaScript's String.prototype.trim removes.
25
+ _JS_SPACE = "\t\n\v\f\r              

   "
26
+
27
+
28
+ class TrajectoryGrantError(Exception):
29
+ """A grant failure. Its status and code are safe to return from the host's grant route."""
30
+
31
+ def __init__(self, status: int, code: str) -> None:
32
+ super().__init__(code)
33
+ self.status = status
34
+ self.code = code
35
+
36
+
37
+ class Realtime(TypedDict):
38
+ clientUrl: str
39
+ topic: str
40
+
41
+
42
+ class TrajectoryGrant(TypedDict):
43
+ joinToken: str
44
+ realtime: Realtime
45
+
46
+
47
+ class HttpResponse(Protocol):
48
+ @property
49
+ def status(self) -> int | None: ...
50
+
51
+ def read(self, size: int = ..., /) -> bytes: ...
52
+
53
+
54
+ Transport = Callable[[urllib.request.Request, float], HttpResponse]
55
+
56
+
57
+ class _RefuseRedirects(urllib.request.HTTPRedirectHandler):
58
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
59
+ raise TrajectoryGrantError(503, "CONNECTION_FAILED")
60
+
61
+
62
+ _opener = urllib.request.build_opener(_RefuseRedirects)
63
+
64
+
65
+ def _default_transport(request: urllib.request.Request, timeout: float) -> HttpResponse:
66
+ try:
67
+ response: HttpResponse = _opener.open(request, timeout=timeout)
68
+ return response
69
+ except urllib.error.HTTPError as error:
70
+ return error # An HTTP error response still carries the problem body.
71
+
72
+
73
+ def _endpoint(value: str, websocket: bool) -> str:
74
+ try:
75
+ url = urlsplit(value)
76
+ host = url.hostname
77
+ url.port # Raises ValueError for an invalid port.
78
+ except (ValueError, TypeError):
79
+ raise TrajectoryGrantError(500, "INVALID_CAPTURE_CONFIG") from None
80
+ secure, local = ("wss", "ws") if websocket else ("https", "http")
81
+ loopback = host in _LOOPBACK
82
+ if (
83
+ not host
84
+ or not (url.scheme == secure or (loopback and url.scheme == local))
85
+ or url.username is not None
86
+ or url.password is not None
87
+ or url.query
88
+ or url.fragment
89
+ or "?" in value
90
+ or "#" in value
91
+ ):
92
+ raise TrajectoryGrantError(500, "INVALID_CAPTURE_CONFIG")
93
+ return f"{url.scheme}://{url.netloc.lower()}{url.path}".rstrip("/")
94
+
95
+
96
+ def _bounded_text(value: Any, maximum: int) -> str | None:
97
+ if not isinstance(value, str):
98
+ return None
99
+ text = value.strip(_JS_SPACE)
100
+ return text if 1 <= utf16_length(text) <= maximum else None
101
+
102
+
103
+ def _read_json(response: HttpResponse) -> Any:
104
+ try:
105
+ body = response.read(_RESPONSE_LIMIT + 1)
106
+ if not body or len(body) > _RESPONSE_LIMIT:
107
+ return None
108
+ return json.loads(body.decode("utf-8"), parse_constant=_refuse_constant)
109
+ except (OSError, http.client.HTTPException, ValueError, RecursionError):
110
+ return None
111
+
112
+
113
+ def _refuse_constant(name: str) -> Any:
114
+ raise ValueError(name)
115
+
116
+
117
+ def _upstream_error(status: int, body: Any) -> TrajectoryGrantError:
118
+ error = body.get("error") if isinstance(body, dict) else None
119
+ code = error.get("code") if isinstance(error, dict) else None
120
+ if not isinstance(code, str):
121
+ code = None
122
+ if status == 409 and code in ("TRAJECTORY_CLOSED", "TRAJECTORY_APP_USER_CONFLICT"):
123
+ return TrajectoryGrantError(status, code)
124
+ if status == 503 and code == "TRAJECTORIES_ENTITLEMENT_UNAVAILABLE":
125
+ return TrajectoryGrantError(status, "ENTITLEMENT_UNAVAILABLE")
126
+ if status == 403 and code in (
127
+ "TRAJECTORIES_NOT_ENABLED",
128
+ "MARKETPLACE_LICENSE_REQUIRED",
129
+ ):
130
+ return TrajectoryGrantError(status, code)
131
+ if status == 429:
132
+ return TrajectoryGrantError(status, "RATE_LIMIT_EXCEEDED")
133
+ return TrajectoryGrantError(status, "CONNECTION_FAILED")
134
+
135
+
136
+ class TrajectoryGrantIssuer:
137
+ """Mint one-use capture grants for users that the host server has verified.
138
+
139
+ The host supplies the user and any container assignment from its authenticated session,
140
+ and reads only the trajectory ID from the browser. ``app_api_url`` is the Intelligence base
141
+ URL. ``gateway_url`` is the public realtime socket endpoint, including its ``/client`` path.
142
+ Keep ``api_key`` in the server process.
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ *,
148
+ app_api_url: str,
149
+ gateway_url: str,
150
+ api_key: str,
151
+ timeout: float = _DEFAULT_TIMEOUT,
152
+ transport: Transport | None = None,
153
+ ) -> None:
154
+ self._url = f"{_endpoint(app_api_url, False)}/api/trajectories/join"
155
+ self._client_url = _endpoint(gateway_url, True)
156
+ if not isinstance(api_key, str) or not api_key.strip(_JS_SPACE):
157
+ raise TrajectoryGrantError(500, "INVALID_CAPTURE_CONFIG")
158
+ self._api_key = api_key
159
+ self._timeout = timeout
160
+ self._transport = transport or _default_transport
161
+
162
+ def issue(
163
+ self,
164
+ *,
165
+ trajectory_id: str,
166
+ app_user_id: str,
167
+ app_user_name: str | None = None,
168
+ learning_container_ids: Sequence[str] | None = None,
169
+ ) -> TrajectoryGrant:
170
+ """Return the grant JSON for the browser capture, or raise TrajectoryGrantError."""
171
+ payload = self._payload(
172
+ trajectory_id, app_user_id, app_user_name, learning_container_ids
173
+ )
174
+ request = urllib.request.Request(
175
+ self._url,
176
+ data=json.dumps(payload).encode("utf-8"),
177
+ method="POST",
178
+ headers={
179
+ "Authorization": f"Bearer {self._api_key}",
180
+ "Content-Type": "application/json",
181
+ "Accept": "application/json",
182
+ },
183
+ )
184
+ try:
185
+ response = self._transport(request, self._timeout)
186
+ try:
187
+ status = response.status
188
+ body = _read_json(response)
189
+ finally:
190
+ close = getattr(response, "close", None)
191
+ if callable(close):
192
+ close()
193
+ except TrajectoryGrantError:
194
+ raise
195
+ except (OSError, http.client.HTTPException, ValueError):
196
+ raise TrajectoryGrantError(503, "CONNECTION_FAILED") from None
197
+
198
+ if status is None:
199
+ raise TrajectoryGrantError(503, "CONNECTION_FAILED")
200
+ if not 200 <= status < 300:
201
+ raise _upstream_error(status, body)
202
+ grant_id = body.get("trajectoryId") if isinstance(body, dict) else None
203
+ token = (
204
+ _bounded_text(body.get("joinToken"), 4096)
205
+ if isinstance(body, dict)
206
+ else None
207
+ )
208
+ if (
209
+ token is None
210
+ or not isinstance(grant_id, str)
211
+ or not _UUID.fullmatch(grant_id)
212
+ or grant_id != payload["trajectoryId"]
213
+ ):
214
+ raise TrajectoryGrantError(502, "INVALID_GRANT")
215
+ return {
216
+ "joinToken": token,
217
+ "realtime": {
218
+ "clientUrl": self._client_url,
219
+ "topic": f"trajectory:{grant_id}",
220
+ },
221
+ }
222
+
223
+ @staticmethod
224
+ def _payload(
225
+ trajectory_id: object,
226
+ app_user_id: object,
227
+ app_user_name: object,
228
+ learning_container_ids: object,
229
+ ) -> dict[str, Any]:
230
+ invalid = TrajectoryGrantError(400, "VALIDATION_ERROR")
231
+ if not isinstance(trajectory_id, str) or not _UUID.fullmatch(trajectory_id):
232
+ raise invalid
233
+ user_id = _bounded_text(app_user_id, 255)
234
+ if user_id is None:
235
+ raise invalid
236
+ payload: dict[str, Any] = {"trajectoryId": trajectory_id, "appUserId": user_id}
237
+ if app_user_name is not None:
238
+ user_name = _bounded_text(app_user_name, 255)
239
+ if user_name is None:
240
+ raise invalid
241
+ payload["appUserName"] = user_name
242
+ if learning_container_ids is not None:
243
+ if isinstance(learning_container_ids, (str, bytes)) or not isinstance(
244
+ learning_container_ids, Sequence
245
+ ):
246
+ raise invalid
247
+ if len(learning_container_ids) > 100:
248
+ raise invalid
249
+ ids = []
250
+ for value in learning_container_ids:
251
+ item = _bounded_text(value, 64)
252
+ if item is None or not _CONTAINER_ID.fullmatch(item):
253
+ raise invalid
254
+ ids.append(item)
255
+ payload["learningContainerIds"] = ids
256
+ return payload
learning_sdk/py.typed ADDED
File without changes
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: learning-sdk
3
+ Version: 0.0.1
4
+ Summary: Validate Learning collector events and issue trajectory capture grants from a Python server.
5
+ Author: CopilotKit
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 2 - Pre-Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.10
13
+ Project-URL: Homepage, https://www.copilotkit.ai
14
+ Description-Content-Type: text/markdown
15
+
16
+ # learning-sdk
17
+
18
+ The Python entry point for CopilotKit Learning. Use it in a Python web server to connect your product to a self-hosted or managed Learning deployment.
19
+
20
+ The package has no dependencies. It needs Python 3.10 or later.
21
+
22
+ ```sh
23
+ pip install learning-sdk
24
+ ```
25
+
26
+ ## Issue a capture grant
27
+
28
+ The browser capture asks your server for a grant before it records a trajectory. Mount an authenticated `POST /api/learning/trajectory/{trajectory_id}/connect` route. Resolve the user from your own session. Keep the Project API key in the server process.
29
+
30
+ ```python
31
+ from learning_sdk import TrajectoryGrantError, TrajectoryGrantIssuer
32
+
33
+ issuer = TrajectoryGrantIssuer(
34
+ app_api_url=settings.intelligence_url,
35
+ gateway_url=settings.realtime_socket_url, # for example wss://gateway.example/client
36
+ api_key=settings.project_api_key,
37
+ )
38
+
39
+ def connect(trajectory_id: str, user_id: str | None):
40
+ if user_id is None:
41
+ return {"code": "IDENTITY_REQUIRED"}, 401
42
+ try:
43
+ return issuer.issue(trajectory_id=trajectory_id, app_user_id=user_id), 200
44
+ except TrajectoryGrantError as error:
45
+ return {"code": error.code}, error.status
46
+ ```
47
+
48
+ Send the grant with `Cache-Control: no-store`. Return the error status and code without change, so that the browser can tell a closed trajectory from an ownership conflict.
49
+
50
+ `issue` blocks for up to 15 seconds. In an async framework, call it with `asyncio.to_thread`.
51
+
52
+ ## Validate a collector event
53
+
54
+ ```python
55
+ from learning_sdk import parse_trajectory_event
56
+
57
+ event = parse_trajectory_event(
58
+ {"type": "CUSTOM", "name": "reservation.changed", "timestamp": 1_700_000_000_000, "value": {"change": "seat"}}
59
+ )
60
+ ```
61
+
62
+ The function returns a JSON copy of the event. It raises `TypeError` for an event that Learning refuses. A value with `NaN` or infinity is refused.
@@ -0,0 +1,8 @@
1
+ learning_sdk/__init__.py,sha256=i3s8WywpTeGKpZ9qvGrc9YIhHmAWvh6rDPqTK916z3w,387
2
+ learning_sdk/_event.py,sha256=-AVFdmKBBYzsFRbt5PoaA6fvdDMSCdqmAZpC8Nh2V8E,2078
3
+ learning_sdk/_grant.py,sha256=vxH-_HSu7Lumx8BiraOi86k1jd15Fu6BoakCsZzHEnI,9056
4
+ learning_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ learning_sdk-0.0.1.dist-info/licenses/LICENSE,sha256=bTWmuxB65QjaNGNjh_YgjnWmk455e8DVv6lInSypW60,1067
6
+ learning_sdk-0.0.1.dist-info/WHEEL,sha256=WvwXFgRajeoYkfRVmDhkP4Qlqo31Mk687zIO2QQoFmw,80
7
+ learning_sdk-0.0.1.dist-info/METADATA,sha256=4VCV1XAFWnqjIN6VSAcEq93xi7ncIDxm2GzzRgruuoU,2320
8
+ learning_sdk-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CopilotKit
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.