opal-agent-sdk 0.1.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,72 @@
1
+ """Opal Agent SDK — async Python client for invoking Opal agents.
2
+
3
+ Public symbols:
4
+ - ``OpalClient`` — the async client
5
+ - ``PATAuth`` — Personal Access Token auth strategy
6
+ - ``OpalEvent`` — discriminated-union event for streams
7
+ - ``OpalError`` (+ typed subclasses) — exception hierarchy
8
+ - ``run`` / ``stream`` — module-level convenience helpers (Phase 6)
9
+
10
+ See ``docs/tech-spec/agent-framework/agent-sdk/python-sdk.md`` in the opal-app repo.
11
+ """
12
+
13
+ from opal_agent_sdk._auth import OpalAuth, PATAuth
14
+ from opal_agent_sdk._config import OpalConfig
15
+ from opal_agent_sdk._convenience import aclose, run, stream
16
+ from opal_agent_sdk._version import __version__
17
+ from opal_agent_sdk.client import OpalClient
18
+ from opal_agent_sdk.errors import (
19
+ OpalAuthError,
20
+ OpalConcurrencyError,
21
+ OpalConnectionError,
22
+ OpalError,
23
+ OpalNotFoundError,
24
+ OpalRateLimitError,
25
+ OpalReplayMissedError,
26
+ OpalServerError,
27
+ OpalUnsupportedError,
28
+ )
29
+ from opal_agent_sdk.types import (
30
+ PAT,
31
+ Artifact,
32
+ CommitInfo,
33
+ FileAttachment,
34
+ OpalChatTurn,
35
+ OpalEvent,
36
+ OpalRunResult,
37
+ OpalSpace,
38
+ OpalStepExecution,
39
+ OpalWorkflowExecution,
40
+ TokenUsage,
41
+ )
42
+
43
+ __all__ = [
44
+ "PAT",
45
+ "Artifact",
46
+ "CommitInfo",
47
+ "FileAttachment",
48
+ "OpalAuth",
49
+ "OpalAuthError",
50
+ "OpalChatTurn",
51
+ "OpalClient",
52
+ "OpalConcurrencyError",
53
+ "OpalConfig",
54
+ "OpalConnectionError",
55
+ "OpalError",
56
+ "OpalEvent",
57
+ "OpalNotFoundError",
58
+ "OpalRateLimitError",
59
+ "OpalReplayMissedError",
60
+ "OpalRunResult",
61
+ "OpalServerError",
62
+ "OpalSpace",
63
+ "OpalStepExecution",
64
+ "OpalUnsupportedError",
65
+ "OpalWorkflowExecution",
66
+ "PATAuth",
67
+ "TokenUsage",
68
+ "__version__",
69
+ "aclose",
70
+ "run",
71
+ "stream",
72
+ ]
@@ -0,0 +1,53 @@
1
+ """Authentication strategies.
2
+
3
+ v1 ships `PATAuth` only. `ClientCredentialsAuth` and `AuthorizationCodeAuth`
4
+ follow in v1.1 with the same `auth=` constructor slot on `OpalClient`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import MutableMapping
10
+ from typing import Protocol, runtime_checkable
11
+
12
+
13
+ @runtime_checkable
14
+ class OpalAuth(Protocol):
15
+ """Protocol every auth strategy implements.
16
+
17
+ `apply()` mutates the headers mapping to add whatever the wire needs
18
+ (today: an `Authorization: Bearer <token>` header). `bearer_token`
19
+ exposes the raw token for socket.io handshakes that need it in the
20
+ `auth` payload rather than a header.
21
+ """
22
+
23
+ @property
24
+ def bearer_token(self) -> str: ...
25
+
26
+ def apply(self, headers: MutableMapping[str, str]) -> None: ...
27
+
28
+
29
+ class PATAuth:
30
+ """Personal Access Token auth — the v1 default.
31
+
32
+ The token is opaque to the SDK; identity is resolved per-request by the
33
+ API Gateway via authz-server introspect. No caching, no refresh — when
34
+ the PAT is revoked, the next call raises ``OpalAuthError``.
35
+ """
36
+
37
+ __slots__ = ("_token",)
38
+
39
+ def __init__(self, token: str) -> None:
40
+ if not token or not isinstance(token, str):
41
+ raise ValueError("PATAuth requires a non-empty string token")
42
+ self._token = token
43
+
44
+ @property
45
+ def bearer_token(self) -> str:
46
+ return self._token
47
+
48
+ def apply(self, headers: MutableMapping[str, str]) -> None:
49
+ headers["Authorization"] = f"Bearer {self._token}"
50
+
51
+ def __repr__(self) -> str:
52
+ # Never log the token, even via repr().
53
+ return "PATAuth(token=<redacted>)"
@@ -0,0 +1,64 @@
1
+ """Client configuration — endpoints, timeouts, retry policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from urllib.parse import urlparse, urlunparse
8
+
9
+ _DEFAULT_BASE_URL = "https://api.opal.optimizely.com"
10
+
11
+
12
+ def _derive_ws_url(base_url: str) -> str:
13
+ """Default WS URL: same host as base_url, http(s) → ws(s)."""
14
+ parsed = urlparse(base_url)
15
+ scheme = "wss" if parsed.scheme == "https" else "ws"
16
+ return urlunparse((scheme, parsed.netloc, "", "", "", ""))
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class OpalConfig:
21
+ """Endpoint + timeout + retry configuration for an `OpalClient`.
22
+
23
+ `instance_id` is part of the URL path on hypatia endpoints
24
+ (``/api/v1/{instance_id}/agents/...``). The gateway routes ``/hypatia/api``
25
+ → ``hypatia:/api`` without rewriting the path, so the SDK is responsible
26
+ for filling in instance_id. A future improvement (not in v1) is for the
27
+ SDK to extract it lazily from the PAT JWT's ``instance_id`` claim.
28
+ """
29
+
30
+ base_url: str = _DEFAULT_BASE_URL
31
+ ws_url: str | None = None
32
+ instance_id: str | None = None
33
+ timeout_s: float = 30.0
34
+ retry_max_attempts: int = 3
35
+ verify_ssl: bool = True # Localdev only — do not disable in production
36
+
37
+ @property
38
+ def effective_ws_url(self) -> str:
39
+ """Resolved WS URL — explicit `ws_url`, else derived from `base_url`."""
40
+ return self.ws_url if self.ws_url else _derive_ws_url(self.base_url)
41
+
42
+ def require_instance_id(self) -> str:
43
+ """Return ``instance_id`` or raise a clear error if it wasn't supplied."""
44
+ if not self.instance_id:
45
+ raise ValueError(
46
+ "instance_id is required for this call. Either pass "
47
+ "OpalConfig(instance_id=...) or set the OPAL_INSTANCE_ID "
48
+ "environment variable."
49
+ )
50
+ return self.instance_id
51
+
52
+ @classmethod
53
+ def from_env(cls) -> OpalConfig:
54
+ """Build a config from `OPAL_BASE_URL` / `OPAL_WS_URL` / `OPAL_INSTANCE_ID` env vars.
55
+
56
+ Endpoint vars have defaults; instance_id does not — it stays None and
57
+ ``require_instance_id()`` raises at call time if the caller never
58
+ supplied one.
59
+ """
60
+ return cls(
61
+ base_url=os.environ.get("OPAL_BASE_URL", _DEFAULT_BASE_URL),
62
+ ws_url=os.environ.get("OPAL_WS_URL") or None,
63
+ instance_id=os.environ.get("OPAL_INSTANCE_ID") or None,
64
+ )
@@ -0,0 +1,118 @@
1
+ """Module-level convenience: ``from opal_agent_sdk import run, stream``.
2
+
3
+ Wraps a process-global default :class:`OpalClient` built from environment
4
+ variables on first call. The client is closed at interpreter exit via
5
+ ``atexit``. Anthropic-style convenience surface — fine for scripts, not
6
+ recommended for long-lived services (use an explicit client there).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import atexit
13
+ import logging
14
+ import threading
15
+ from collections.abc import AsyncIterator, Mapping
16
+ from typing import Any
17
+
18
+ from opal_agent_sdk._auth import PATAuth
19
+ from opal_agent_sdk._config import OpalConfig
20
+ from opal_agent_sdk.client import OpalClient
21
+ from opal_agent_sdk.types import OpalEvent, OpalRunResult
22
+
23
+ logger = logging.getLogger("opal_agent_sdk.convenience")
24
+
25
+ _default_client: OpalClient | None = None
26
+ _default_client_lock = threading.Lock()
27
+ _atexit_registered = False
28
+
29
+
30
+ def _build_default_client() -> OpalClient:
31
+ """Construct the singleton client from env vars.
32
+
33
+ Requires ``OPAL_PAT``; raises ``RuntimeError`` if missing so callers
34
+ aren't surprised by a delayed auth error on the first request.
35
+ """
36
+ import os
37
+
38
+ pat = os.environ.get("OPAL_PAT")
39
+ if not pat:
40
+ raise RuntimeError(
41
+ "OPAL_PAT environment variable is not set. The top-level run()/stream() "
42
+ "helpers require it. For explicit control, construct an OpalClient yourself."
43
+ )
44
+ return OpalClient(auth=PATAuth(pat), config=OpalConfig.from_env())
45
+
46
+
47
+ def _get_default_client() -> OpalClient:
48
+ """Thread-safely fetch (or create) the process-global default client."""
49
+ global _default_client, _atexit_registered
50
+ with _default_client_lock:
51
+ if _default_client is None:
52
+ _default_client = _build_default_client()
53
+ if not _atexit_registered:
54
+ atexit.register(_close_default_client_at_exit)
55
+ _atexit_registered = True
56
+ return _default_client
57
+
58
+
59
+ def _close_default_client_at_exit() -> None:
60
+ """Best-effort cleanup at interpreter shutdown.
61
+
62
+ If the user has their own event loop running (e.g. asyncio.run already
63
+ returned and the loop is gone, but they didn't aclose() us), call
64
+ ``asyncio.run(client.aclose())``. If that fails because a loop is still
65
+ running on this thread, log and bail — the OS will reclaim the
66
+ connection. Best-effort hygiene, not correctness.
67
+ """
68
+ global _default_client
69
+ client = _default_client
70
+ if client is None:
71
+ return
72
+ try:
73
+ asyncio.run(client.aclose())
74
+ except RuntimeError as exc:
75
+ logger.debug("default client atexit cleanup skipped: %s", exc)
76
+ _default_client = None
77
+
78
+
79
+ async def aclose() -> None:
80
+ """Explicitly close the process-global default client.
81
+
82
+ Long-lived services that built one via ``run()``/``stream()`` should
83
+ call this at shutdown so resources are released deterministically.
84
+ """
85
+ global _default_client
86
+ with _default_client_lock:
87
+ client = _default_client
88
+ _default_client = None
89
+ if client is not None:
90
+ await client.aclose()
91
+
92
+
93
+ async def run(
94
+ agent_id: str,
95
+ *,
96
+ parameters: Mapping[str, Any] | None = None,
97
+ ) -> OpalRunResult:
98
+ """Top-level convenience: run a specialized agent once using a default client.
99
+
100
+ Equivalent to::
101
+
102
+ async with OpalClient.from_env() as client:
103
+ return await client.agents.specialized.run(agent_id=..., parameters=...)
104
+
105
+ but the client is reused across calls within the process.
106
+ """
107
+ client = _get_default_client()
108
+ return await client.agents.specialized.run(agent_id, parameters=parameters)
109
+
110
+
111
+ def stream(
112
+ agent_id: str,
113
+ *,
114
+ parameters: Mapping[str, Any] | None = None,
115
+ ) -> AsyncIterator[OpalEvent]:
116
+ """Top-level convenience: stream events from a specialized agent execution."""
117
+ client = _get_default_client()
118
+ return client.agents.specialized.stream(agent_id, parameters=parameters)
@@ -0,0 +1,320 @@
1
+ """Internal async HTTP client wrapping httpx.AsyncClient.
2
+
3
+ Handles auth header injection, X-Request-Id generation, error mapping, and
4
+ retry-on-5xx for idempotent verbs. Not part of the public surface — callers
5
+ use the namespaced APIs on `OpalClient` instead.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import uuid
13
+ from collections.abc import AsyncIterator, Mapping
14
+ from contextlib import asynccontextmanager
15
+ from types import TracebackType
16
+ from typing import Any
17
+
18
+ import httpx
19
+
20
+ from opal_agent_sdk._auth import OpalAuth
21
+ from opal_agent_sdk._config import OpalConfig
22
+ from opal_agent_sdk.errors import (
23
+ OpalConnectionError,
24
+ OpalError,
25
+ OpalRateLimitError,
26
+ OpalServerError,
27
+ _http_status_to_error,
28
+ )
29
+
30
+ logger = logging.getLogger("opal_agent_sdk")
31
+
32
+ # Methods that are safe to auto-retry on 5xx. POSTs that create resources
33
+ # stay un-retried until server-side request-id dedup ships (see spec §15.6).
34
+ _IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "DELETE"})
35
+
36
+
37
+ def _read_request_id(response: httpx.Response) -> str | None:
38
+ """Pull the gateway's request id back out of the response for support correlation."""
39
+ value = response.headers.get("x-request-id") or response.headers.get("X-Request-Id")
40
+ return str(value) if value else None
41
+
42
+
43
+ def _retry_after_seconds(response: httpx.Response) -> float | None:
44
+ """Parse a Retry-After header. Accepts seconds-as-int (RFC 7231 §7.1.3)."""
45
+ value = response.headers.get("retry-after") or response.headers.get("Retry-After")
46
+ if not value:
47
+ return None
48
+ try:
49
+ return float(value)
50
+ except (TypeError, ValueError):
51
+ return None
52
+
53
+
54
+ def _raise_for_status(response: httpx.Response, *, body_preview: str | None = None) -> None:
55
+ """Map a non-2xx response to the right OpalError subclass and raise.
56
+
57
+ Body is best-effort decoded for the error message; if the body's already
58
+ been consumed by a streaming call, callers pass `body_preview` explicitly.
59
+ """
60
+ if response.is_success:
61
+ return
62
+
63
+ if body_preview is None:
64
+ try:
65
+ body_preview = response.text
66
+ except Exception:
67
+ body_preview = "<unreadable response body>"
68
+
69
+ cls = _http_status_to_error(response.status_code)
70
+ request_id = _read_request_id(response)
71
+ message = f"HTTP {response.status_code} from {response.request.url}: {body_preview[:500]}"
72
+
73
+ if cls is OpalRateLimitError:
74
+ raise OpalRateLimitError(
75
+ message,
76
+ status=response.status_code,
77
+ request_id=request_id,
78
+ retry_after_seconds=_retry_after_seconds(response),
79
+ )
80
+ raise cls(message, status=response.status_code, request_id=request_id)
81
+
82
+
83
+ class _HttpClient:
84
+ """Thin wrapper around httpx.AsyncClient with auth + error mapping + retries.
85
+
86
+ Lifecycle: async context manager OR explicit `aclose()`. The client is
87
+ created lazily on first use so import-time cost stays zero.
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ auth: OpalAuth,
93
+ config: OpalConfig,
94
+ *,
95
+ client: httpx.AsyncClient | None = None,
96
+ ) -> None:
97
+ self._auth = auth
98
+ self._config = config
99
+ self._client: httpx.AsyncClient | None = client
100
+ self._owns_client = client is None
101
+ if not config.verify_ssl:
102
+ logger.warning(
103
+ "SSL verification is disabled (verify_ssl=False). "
104
+ "This is intended for local development only — do not use in production."
105
+ )
106
+
107
+ async def __aenter__(self) -> _HttpClient:
108
+ self._ensure_client()
109
+ return self
110
+
111
+ async def __aexit__(
112
+ self,
113
+ exc_type: type[BaseException] | None,
114
+ exc: BaseException | None,
115
+ tb: TracebackType | None,
116
+ ) -> None:
117
+ await self.aclose()
118
+
119
+ async def aclose(self) -> None:
120
+ if self._client is not None and self._owns_client:
121
+ await self._client.aclose()
122
+ self._client = None
123
+
124
+ def _ensure_client(self) -> httpx.AsyncClient:
125
+ if self._client is None:
126
+ self._client = httpx.AsyncClient(
127
+ base_url=self._config.base_url,
128
+ timeout=self._config.timeout_s,
129
+ verify=self._config.verify_ssl,
130
+ )
131
+ return self._client
132
+
133
+ def _build_headers(self, extra: Mapping[str, str] | None = None) -> dict[str, str]:
134
+ headers: dict[str, str] = {"X-Request-Id": str(uuid.uuid4())}
135
+ if self._config.instance_id:
136
+ headers["X-Instance-Id"] = self._config.instance_id
137
+ self._auth.apply(headers)
138
+ if extra:
139
+ headers.update(extra)
140
+ return headers
141
+
142
+ async def request_json(
143
+ self,
144
+ method: str,
145
+ path: str,
146
+ *,
147
+ params: Mapping[str, Any] | None = None,
148
+ json: Any | None = None,
149
+ content: bytes | str | None = None,
150
+ headers: Mapping[str, str] | None = None,
151
+ ) -> Any:
152
+ """Perform a non-streaming request; return parsed JSON.
153
+
154
+ Retries idempotent verbs up to `retry_max_attempts` on `OpalServerError`
155
+ with exponential backoff (1s, 2s, 4s).
156
+ """
157
+ return await self._with_retry(
158
+ method,
159
+ self._do_request_json,
160
+ method=method,
161
+ path=path,
162
+ params=params,
163
+ json=json,
164
+ content=content,
165
+ headers=headers,
166
+ )
167
+
168
+ async def _do_request_json(
169
+ self,
170
+ *,
171
+ method: str,
172
+ path: str,
173
+ params: Mapping[str, Any] | None,
174
+ json: Any | None,
175
+ content: bytes | str | None,
176
+ headers: Mapping[str, str] | None,
177
+ ) -> Any:
178
+ client = self._ensure_client()
179
+ try:
180
+ response = await client.request(
181
+ method,
182
+ path,
183
+ params=params,
184
+ json=json,
185
+ content=content,
186
+ headers=self._build_headers(headers),
187
+ )
188
+ except httpx.ConnectError as exc:
189
+ raise OpalConnectionError(f"connection error: {exc}") from exc
190
+ except httpx.TimeoutException as exc:
191
+ raise OpalConnectionError(f"timeout: {exc}") from exc
192
+ except httpx.RequestError as exc:
193
+ raise OpalConnectionError(f"request error: {exc}") from exc
194
+
195
+ _raise_for_status(response)
196
+ if response.status_code == 204 or not response.content:
197
+ return None
198
+ return response.json()
199
+
200
+ async def request_bytes(
201
+ self,
202
+ method: str,
203
+ path: str,
204
+ *,
205
+ params: Mapping[str, Any] | None = None,
206
+ headers: Mapping[str, str] | None = None,
207
+ ) -> bytes:
208
+ """Perform a request and return raw bytes (e.g. canvas content fetches)."""
209
+ result = await self._with_retry(
210
+ method,
211
+ self._do_request_bytes,
212
+ method=method,
213
+ path=path,
214
+ params=params,
215
+ headers=headers,
216
+ )
217
+ assert isinstance(result, bytes)
218
+ return result
219
+
220
+ async def _do_request_bytes(
221
+ self,
222
+ *,
223
+ method: str,
224
+ path: str,
225
+ params: Mapping[str, Any] | None,
226
+ headers: Mapping[str, str] | None,
227
+ ) -> bytes:
228
+ client = self._ensure_client()
229
+ try:
230
+ response = await client.request(
231
+ method,
232
+ path,
233
+ params=params,
234
+ headers=self._build_headers(headers),
235
+ )
236
+ except httpx.ConnectError as exc:
237
+ raise OpalConnectionError(f"connection error: {exc}") from exc
238
+ except httpx.TimeoutException as exc:
239
+ raise OpalConnectionError(f"timeout: {exc}") from exc
240
+ except httpx.RequestError as exc:
241
+ raise OpalConnectionError(f"request error: {exc}") from exc
242
+
243
+ _raise_for_status(response)
244
+ return response.content
245
+
246
+ @asynccontextmanager
247
+ async def stream(
248
+ self,
249
+ method: str,
250
+ path: str,
251
+ *,
252
+ params: Mapping[str, Any] | None = None,
253
+ json: Any | None = None,
254
+ content: bytes | str | None = None,
255
+ headers: Mapping[str, str] | None = None,
256
+ ) -> AsyncIterator[httpx.Response]:
257
+ """Open a streaming response (used for SSE).
258
+
259
+ Streaming responses are not auto-retried — the caller may have already
260
+ consumed bytes by the time a downstream error fires.
261
+ """
262
+ client = self._ensure_client()
263
+ try:
264
+ async with client.stream(
265
+ method,
266
+ path,
267
+ params=params,
268
+ json=json,
269
+ content=content,
270
+ headers=self._build_headers(headers),
271
+ ) as response:
272
+ if not response.is_success:
273
+ # Body's not consumed yet; eagerly read for the error message.
274
+ body = await response.aread()
275
+ _raise_for_status(response, body_preview=body.decode(errors="replace"))
276
+ yield response
277
+ except httpx.ConnectError as exc:
278
+ raise OpalConnectionError(f"connection error: {exc}") from exc
279
+ except httpx.TimeoutException as exc:
280
+ raise OpalConnectionError(f"timeout: {exc}") from exc
281
+ except httpx.RequestError as exc:
282
+ raise OpalConnectionError(f"request error: {exc}") from exc
283
+
284
+ async def _with_retry(
285
+ self,
286
+ http_method: str,
287
+ fn: Any,
288
+ **kwargs: Any,
289
+ ) -> Any:
290
+ """Retry-on-5xx for idempotent verbs. Otherwise call once.
291
+
292
+ `http_method` is the HTTP verb (passed positionally to disambiguate it
293
+ from the `method=` kwarg already in `kwargs`, which is the same string
294
+ but flowing to the inner `fn`).
295
+ """
296
+ if http_method.upper() not in _IDEMPOTENT_METHODS:
297
+ return await fn(**kwargs)
298
+
299
+ delay = 1.0
300
+ last_exc: OpalError | None = None
301
+ for attempt in range(1, self._config.retry_max_attempts + 1):
302
+ try:
303
+ return await fn(**kwargs)
304
+ except OpalServerError as exc:
305
+ last_exc = exc
306
+ if attempt == self._config.retry_max_attempts:
307
+ raise
308
+ logger.warning(
309
+ "Retrying %s %s after 5xx (attempt %d/%d): %s",
310
+ http_method,
311
+ kwargs.get("path"),
312
+ attempt,
313
+ self._config.retry_max_attempts,
314
+ exc,
315
+ )
316
+ await asyncio.sleep(delay)
317
+ delay *= 2
318
+ # Unreachable — loop either returns or raises.
319
+ assert last_exc is not None
320
+ raise last_exc