agentic-platform-sdk 0.1.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.
Files changed (41) hide show
  1. agentic_platform_sdk/__init__.py +9 -0
  2. agentic_platform_sdk/_a2a.py +133 -0
  3. agentic_platform_sdk/_client.py +152 -0
  4. agentic_platform_sdk/_contract.py +72 -0
  5. agentic_platform_sdk/_generated/__init__.py +0 -0
  6. agentic_platform_sdk/_generated/_base.py +20 -0
  7. agentic_platform_sdk/_generated/models.py +698 -0
  8. agentic_platform_sdk/_paging.py +117 -0
  9. agentic_platform_sdk/_spec/call_areas.json +13 -0
  10. agentic_platform_sdk/_spec/chat-events.schema.json +371 -0
  11. agentic_platform_sdk/_spec/errors.json +2365 -0
  12. agentic_platform_sdk/_spec/operations.json +230 -0
  13. agentic_platform_sdk/_transport.py +630 -0
  14. agentic_platform_sdk/_util.py +133 -0
  15. agentic_platform_sdk/agents.py +793 -0
  16. agentic_platform_sdk/approvals.py +66 -0
  17. agentic_platform_sdk/auth.py +336 -0
  18. agentic_platform_sdk/chat.py +599 -0
  19. agentic_platform_sdk/datasets.py +69 -0
  20. agentic_platform_sdk/errors.py +204 -0
  21. agentic_platform_sdk/kb.py +288 -0
  22. agentic_platform_sdk/llm.py +40 -0
  23. agentic_platform_sdk/me.py +28 -0
  24. agentic_platform_sdk/models.py +91 -0
  25. agentic_platform_sdk/ontology.py +209 -0
  26. agentic_platform_sdk/py.typed +0 -0
  27. agentic_platform_sdk/testing/__init__.py +19 -0
  28. agentic_platform_sdk/testing/conformance.py +803 -0
  29. agentic_platform_sdk/testing/fake.py +902 -0
  30. agentic_platform_sdk/testing/standin.py +165 -0
  31. agentic_platform_sdk/toolchains.py +137 -0
  32. agentic_platform_sdk/tools/__init__.py +70 -0
  33. agentic_platform_sdk/tools/_jcs.py +218 -0
  34. agentic_platform_sdk/tools/asgi.py +228 -0
  35. agentic_platform_sdk/tools/mcp.py +751 -0
  36. agentic_platform_sdk/tools/verify.py +379 -0
  37. agentic_platform_sdk/vision.py +300 -0
  38. agentic_platform_sdk-0.1.0.dist-info/METADATA +226 -0
  39. agentic_platform_sdk-0.1.0.dist-info/RECORD +41 -0
  40. agentic_platform_sdk-0.1.0.dist-info/WHEEL +4 -0
  41. agentic_platform_sdk-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,66 @@
1
+ """The ``approvals`` area: decide the approval a composer run is waiting on
2
+ (``POST /approvals/{id}/decision``).
3
+
4
+ The ``request_id`` is the one an ``Approval`` chat event carries (``chat.Approval.request_id``);
5
+ show the buttons only when ``decidable_by_caller`` is true. Only the platform's approvers may
6
+ decide: the requester (unless the template allows self-approval), a non-approver and a superuser
7
+ all get the same ``NotFound`` (``approval.not_found``) as an unknown id.
8
+
9
+ Codes of a decision that does not go through (``error.code``):
10
+
11
+ * ``Conflict`` ``approval.already_decided``: this approver already decided it.
12
+ * ``Conflict`` ``approval.request_not_pending``: it is decided, cancelled or expired. A task has
13
+ a wall cap of 210 s that includes an approval wait: a decision that comes after it is this
14
+ 409, and the task ended ``FAILED`` with ``a2a.task_timeout`` (``chat.Done.code``).
15
+ * ``Conflict`` ``approval.step_not_open``: the approval's stage moved on meanwhile.
16
+
17
+ A decision is never repeated by the SDK after a 5xx: a second one would be a second decision.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Literal
23
+
24
+ from ._generated import models as gen
25
+ from ._transport import AsyncTransport, Call, SyncTransport
26
+ from ._util import parse
27
+
28
+ ApprovalDecisionResult = gen.OpenApprovalDecisionResult
29
+ Verdict = Literal["approve", "reject"]
30
+
31
+
32
+ def _call(request_id: str, decision: Verdict, comment: str | None) -> Call:
33
+ body: dict[str, str] = {"decision": decision}
34
+ if comment is not None:
35
+ body["comment"] = comment
36
+ return Call(
37
+ operation="decideApproval",
38
+ area="approvals",
39
+ path_params={"request_id": request_id},
40
+ json=body,
41
+ )
42
+
43
+
44
+ class ApprovalsArea:
45
+ def __init__(self, transport: SyncTransport) -> None:
46
+ self._t = transport
47
+
48
+ def decide(
49
+ self, request_id: str, decision: Verdict, comment: str | None = None
50
+ ) -> ApprovalDecisionResult:
51
+ return parse(ApprovalDecisionResult, self._t.request(_call(request_id, decision, comment)))
52
+
53
+
54
+ class AsyncApprovalsArea:
55
+ def __init__(self, transport: AsyncTransport) -> None:
56
+ self._t = transport
57
+
58
+ async def decide(
59
+ self, request_id: str, decision: Verdict, comment: str | None = None
60
+ ) -> ApprovalDecisionResult:
61
+ return parse(
62
+ ApprovalDecisionResult, await self._t.request(_call(request_id, decision, comment))
63
+ )
64
+
65
+
66
+ __all__ = ["ApprovalDecisionResult", "ApprovalsArea", "AsyncApprovalsArea", "Verdict"]
@@ -0,0 +1,336 @@
1
+ """Credentials for the platform: API keys, token callables, Keycloak token exchange, DPoP.
2
+
3
+ A ``TokenProvider`` hands the transport a bearer token on every attempt, so a provider that caches
4
+ (``KeycloakTokenExchange``) refreshes on its own and the transport never holds a token past its
5
+ life. Nothing here puts a secret in a ``repr`` or an error message.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import base64
12
+ import copy
13
+ import hashlib
14
+ import json
15
+ import re
16
+ import threading
17
+ import time
18
+ import uuid
19
+ from collections.abc import Awaitable, Callable
20
+ from typing import Any, Protocol, runtime_checkable
21
+ from urllib.parse import urlsplit
22
+
23
+ import httpx
24
+ import jwt
25
+ from cryptography.hazmat.primitives import serialization
26
+ from cryptography.hazmat.primitives.asymmetric import ec
27
+
28
+ from .errors import Unavailable
29
+
30
+ _IDP_UNAVAILABLE = "auth.idp_unavailable"
31
+ _TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange"
32
+ _ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"
33
+ _OAUTH_ERROR = re.compile(r"[A-Za-z0-9_.:-]{1,64}") # RFC 6749 error codes, e.g. invalid_grant
34
+
35
+
36
+ def _refusal_data(response: httpx.Response) -> dict[str, Any]:
37
+ """The status and, if it is a short OAuth error code, the body's ``error``; nothing else."""
38
+ data: dict[str, Any] = {"status": response.status_code}
39
+ try:
40
+ error = response.json()["error"]
41
+ except (ValueError, KeyError, TypeError):
42
+ return data
43
+ if isinstance(error, str) and _OAUTH_ERROR.fullmatch(error):
44
+ data["error"] = error
45
+ return data
46
+
47
+
48
+ def _now() -> float:
49
+ """Monotonic seconds for cache expiry (replaced in tests)."""
50
+ return time.monotonic()
51
+
52
+
53
+ @runtime_checkable
54
+ class TokenProvider(Protocol):
55
+ """Yields the bearer token for the next request. ``token`` may block; ``atoken`` must not."""
56
+
57
+ def token(self) -> str: ...
58
+
59
+ async def atoken(self) -> str: ...
60
+
61
+
62
+ class BaseTokenProvider:
63
+ """Implements ``atoken`` by running ``token`` in a worker thread."""
64
+
65
+ def token(self) -> str:
66
+ raise NotImplementedError
67
+
68
+ async def atoken(self) -> str:
69
+ return await asyncio.to_thread(self.token)
70
+
71
+
72
+ class ApiKey(BaseTokenProvider):
73
+ """A platform API key (``agk_...``), sent as the bearer token."""
74
+
75
+ __slots__ = ("_key",)
76
+
77
+ def __init__(self, key: str) -> None:
78
+ if not isinstance(key, str) or not key.startswith("agk_"):
79
+ raise ValueError("an API key starts with 'agk_'")
80
+ self._key = key
81
+
82
+ def token(self) -> str:
83
+ return self._key
84
+
85
+ def __repr__(self) -> str:
86
+ return "ApiKey(agk_…)"
87
+
88
+ __str__ = __repr__
89
+
90
+
91
+ class TokenCallable(BaseTokenProvider):
92
+ """Wraps a function returning the current token (an app's own session or refresh logic)."""
93
+
94
+ def __init__(self, fn: Callable[[], str]) -> None:
95
+ self._fn = fn
96
+
97
+ def token(self) -> str:
98
+ return self._fn()
99
+
100
+ def __repr__(self) -> str:
101
+ return "TokenCallable(...)"
102
+
103
+
104
+ class AsyncTokenCallable:
105
+ """Wraps an async function returning the current token. Async clients only."""
106
+
107
+ def __init__(self, fn: Callable[[], Awaitable[str]]) -> None:
108
+ self._fn = fn
109
+
110
+ def token(self) -> str:
111
+ raise TypeError("AsyncTokenCallable needs an async client: call atoken()")
112
+
113
+ async def atoken(self) -> str:
114
+ return await self._fn()
115
+
116
+ def __repr__(self) -> str:
117
+ return "AsyncTokenCallable(...)"
118
+
119
+
120
+ class _Flight:
121
+ """One exchange in progress for a subject token, which its other callers wait on."""
122
+
123
+ def __init__(self) -> None:
124
+ self.done = threading.Event()
125
+ self.token: str | None = None
126
+ self.error: BaseException | None = None
127
+
128
+ def wait(self) -> str:
129
+ self.done.wait()
130
+ if self.error is not None:
131
+ # A copy for each waiter: one exception object raised in several threads at once
132
+ # would have its traceback rewritten under the others.
133
+ raise copy.copy(self.error) from None
134
+ assert self.token is not None
135
+ return self.token
136
+
137
+
138
+ class KeycloakTokenExchange(BaseTokenProvider):
139
+ """Exchanges the user's login token for a platform access token (RFC 8693, Keycloak).
140
+
141
+ ``subject_token`` is called on every ``token()`` and returns the user's current login token.
142
+ The platform token is cached per subject token until ``expires_in - margin_s``, so one
143
+ session makes one exchange per platform-token lifetime. The exchange is single-flight per
144
+ subject token: concurrent callers with the same one wait for one IdP call (and share its
145
+ token or its failure), while callers with other subject tokens go ahead in parallel, so one
146
+ slow IdP answer does not hold up every user of a shared instance. ``atoken`` runs ``token``
147
+ in a worker thread, so async callers get the same.
148
+
149
+ ``scope`` and ``requested_token_type`` are sent only when set. A failure raises
150
+ ``Unavailable("auth.idp_unavailable")``; for an HTTP failure its ``data`` is ``{"status": n}``
151
+ plus ``"error"`` (the OAuth error code, e.g. ``invalid_grant``) when the body has one, so a
152
+ caller can tell a refused subject token from an IdP that is down. ``data`` is ``{}`` when
153
+ there was no response. The response body is never kept.
154
+ """
155
+
156
+ def __init__(
157
+ self,
158
+ token_url: str,
159
+ client_id: str,
160
+ client_secret: str,
161
+ audience: str,
162
+ subject_token: Callable[[], str],
163
+ margin_s: int = 30,
164
+ http: Callable[[], httpx.Client] | None = None,
165
+ *,
166
+ scope: str | None = None,
167
+ requested_token_type: str | None = None,
168
+ ) -> None:
169
+ self._scope = scope
170
+ self._requested_token_type = requested_token_type
171
+ self._token_url = token_url
172
+ self._client_id = client_id
173
+ self._client_secret = client_secret
174
+ self._audience = audience
175
+ self._subject_token = subject_token
176
+ self._margin_s = margin_s
177
+ self._http = http or (lambda: httpx.Client(timeout=10.0))
178
+ # Guards `_cache` and `_inflight` only; it is never held across a call to the IdP.
179
+ self._lock = threading.Lock()
180
+ self._cache: dict[str, tuple[str, float]] = {}
181
+ self._inflight: dict[str, _Flight] = {}
182
+
183
+ def token(self) -> str:
184
+ subject = self._subject_token()
185
+ with self._lock:
186
+ now = _now()
187
+ self._cache = {k: v for k, v in self._cache.items() if v[1] > now}
188
+ hit = self._cache.get(subject)
189
+ if hit is not None:
190
+ return hit[0]
191
+ flight = self._inflight.get(subject)
192
+ leading = flight is None
193
+ if flight is None:
194
+ flight = self._inflight[subject] = _Flight()
195
+ if not leading:
196
+ return flight.wait()
197
+ try:
198
+ access_token, expires_in = self._exchange(subject)
199
+ except BaseException as exc:
200
+ flight.error = exc
201
+ raise
202
+ else:
203
+ flight.token = access_token
204
+ with self._lock:
205
+ self._cache[subject] = (access_token, now + expires_in - self._margin_s)
206
+ return access_token
207
+ finally:
208
+ with self._lock:
209
+ del self._inflight[subject]
210
+ flight.done.set()
211
+
212
+ def _exchange(self, subject: str) -> tuple[str, float]:
213
+ form: dict[str, str] = {
214
+ "grant_type": _TOKEN_EXCHANGE_GRANT,
215
+ "subject_token": subject,
216
+ "subject_token_type": _ACCESS_TOKEN_TYPE,
217
+ "audience": self._audience,
218
+ "client_id": self._client_id,
219
+ "client_secret": self._client_secret,
220
+ }
221
+ if self._requested_token_type is not None:
222
+ form["requested_token_type"] = self._requested_token_type
223
+ if self._scope is not None:
224
+ form["scope"] = self._scope
225
+ try:
226
+ with self._http() as client:
227
+ response = client.post(self._token_url, data=form)
228
+ except httpx.HTTPError as exc:
229
+ raise Unavailable(_IDP_UNAVAILABLE, detail=type(exc).__name__) from None
230
+ if response.status_code != 200:
231
+ raise Unavailable(
232
+ _IDP_UNAVAILABLE,
233
+ detail=f"token endpoint answered {response.status_code}",
234
+ data=_refusal_data(response),
235
+ )
236
+ try:
237
+ body = response.json()
238
+ access_token = body["access_token"]
239
+ expires_in = body["expires_in"]
240
+ except (ValueError, KeyError, TypeError):
241
+ raise Unavailable(_IDP_UNAVAILABLE, detail="unreadable token response") from None
242
+ if (
243
+ not isinstance(access_token, str)
244
+ or not access_token
245
+ or isinstance(expires_in, bool)
246
+ or not isinstance(expires_in, int | float)
247
+ ):
248
+ raise Unavailable(_IDP_UNAVAILABLE, detail="unreadable token response")
249
+ return access_token, float(expires_in)
250
+
251
+ def __repr__(self) -> str:
252
+ return (
253
+ f"KeycloakTokenExchange(token_url={self._token_url!r}, client_id={self._client_id!r})"
254
+ )
255
+
256
+
257
+ # --- DPoP (RFC 9449) -------------------------------------------------------------------------
258
+
259
+ _THUMBPRINT_MEMBERS = {
260
+ "EC": ("crv", "kty", "x", "y"),
261
+ "RSA": ("e", "kty", "n"),
262
+ "OKP": ("crv", "kty", "x"),
263
+ }
264
+
265
+
266
+ def _b64url(data: bytes) -> str:
267
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
268
+
269
+
270
+ def _jwk_thumbprint(jwk: dict[str, Any]) -> str:
271
+ """RFC 7638: SHA-256 over the required members, in lexicographic order, no whitespace."""
272
+ members = _THUMBPRINT_MEMBERS.get(jwk.get("kty")) # type: ignore[arg-type]
273
+ if members is None or any(m not in jwk for m in members):
274
+ raise ValueError("unsupported or incomplete JWK")
275
+ canonical = json.dumps({m: jwk[m] for m in members}, separators=(",", ":"))
276
+ return _b64url(hashlib.sha256(canonical.encode()).digest())
277
+
278
+
279
+ def _htu(url: str) -> str:
280
+ """The request URL without userinfo, query or fragment (RFC 9449 section 4.2)."""
281
+ parts = urlsplit(url)
282
+ netloc = parts.netloc.rpartition("@")[2].lower()
283
+ return f"{parts.scheme.lower()}://{netloc}{parts.path}"
284
+
285
+
286
+ class DPoPKey:
287
+ """A P-256 key that signs DPoP proofs binding a token to this client."""
288
+
289
+ def __init__(self, key: ec.EllipticCurvePrivateKey) -> None:
290
+ if not isinstance(key, ec.EllipticCurvePrivateKey) or not isinstance(
291
+ key.curve, ec.SECP256R1
292
+ ):
293
+ raise ValueError("a DPoP key is an EC P-256 private key")
294
+ self._key = key
295
+ self._jwk: dict[str, Any] = jwt.algorithms.ECAlgorithm.to_jwk(
296
+ key.public_key(), as_dict=True
297
+ )
298
+ self._thumbprint = _jwk_thumbprint(self._jwk)
299
+
300
+ @classmethod
301
+ def generate(cls) -> DPoPKey:
302
+ return cls(ec.generate_private_key(ec.SECP256R1()))
303
+
304
+ @classmethod
305
+ def from_pem(cls, pem: bytes) -> DPoPKey:
306
+ try:
307
+ key = serialization.load_pem_private_key(pem, password=None)
308
+ except (ValueError, TypeError):
309
+ raise ValueError("not an unencrypted PEM private key") from None
310
+ if not isinstance(key, ec.EllipticCurvePrivateKey):
311
+ raise ValueError("a DPoP key is an EC P-256 private key")
312
+ return cls(key)
313
+
314
+ @property
315
+ def public_jwk(self) -> dict[str, Any]:
316
+ return dict(self._jwk)
317
+
318
+ @property
319
+ def thumbprint(self) -> str:
320
+ return self._thumbprint
321
+
322
+ def proof(self, method: str, url: str, access_token: str, nonce: str | None = None) -> str:
323
+ claims: dict[str, Any] = {
324
+ "htm": method.upper(),
325
+ "htu": _htu(url),
326
+ "iat": int(time.time()),
327
+ "jti": str(uuid.uuid4()),
328
+ "ath": _b64url(hashlib.sha256(access_token.encode()).digest()),
329
+ }
330
+ if nonce is not None:
331
+ claims["nonce"] = nonce
332
+ headers = {"typ": "dpop+jwt", "jwk": self.public_jwk}
333
+ return jwt.encode(claims, self._key, algorithm="ES256", headers=headers)
334
+
335
+ def __repr__(self) -> str:
336
+ return f"DPoPKey(thumbprint={self._thumbprint})"