caitlyn-core 0.8.1__tar.gz

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,30 @@
1
+ # Build output: the prepared model, generator builds, conformance reports, bundles.
2
+ /build/
3
+ /codegen/build/
4
+ /codegen/*/build/
5
+ /codegen/.gradle/
6
+ node_modules/
7
+ /typescript/dist/
8
+ /python/.venv/
9
+ /rust/target/
10
+ /conformance/rust/target/
11
+ __pycache__/
12
+ *.pyc
13
+ .DS_Store
14
+ /codegen/smithy-build.local.json
15
+ /typescript/packages/*/dist-*/
16
+ /typescript/packages/*/README.md
17
+ /typescript/packages/*/*.tgz
18
+ /typescript/packages/*/LICENSE
19
+ /typescript/packages/*/NOTICE
20
+ # The API reference's programs, written from the model's @examples by scripts/docs-snippets.mjs for the
21
+ # language jobs to compile; the developer site and its build output.
22
+ /examples/typescript/reference/
23
+ /examples/python/reference/
24
+ /examples/go/reference/
25
+ /examples/rust/examples/
26
+ /examples/rust/target/
27
+ /docs/site/src/content/docs/
28
+ /docs/site/src/generated/
29
+ /docs/site/.astro/
30
+ /docs/site/public/api/
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.5
2
+ Name: caitlyn-core
3
+ Version: 0.8.1
4
+ Summary: Runtime core for Caitlyn's generated Python SDKs: transport, retries, errors, SSE, telemetry.
5
+ Project-URL: Homepage, https://build.caitlyn.ai/
6
+ Project-URL: Documentation, https://build.caitlyn.ai/
7
+ Project-URL: Repository, https://github.com/caitlyn-ai/sdk
8
+ Author: Custom D Ltd
9
+ License-Expression: Apache-2.0
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: httpx<0.29,>=0.28
12
+ Requires-Dist: opentelemetry-api<2,>=1.38
13
+ Requires-Dist: pydantic<3,>=2.11
14
+ Description-Content-Type: text/markdown
15
+
16
+ # caitlyn-core
17
+
18
+ The runtime behind [`caitlyn`](https://pypi.org/project/caitlyn/), the Python SDK for the Caitlyn API: sign-in,
19
+ retries, errors, streamed answers, pagination, uploads and OpenTelemetry tracing.
20
+
21
+ Install `caitlyn`, not this package: `pip install caitlyn` brings the matching version of `caitlyn-core` with it.
22
+
23
+ The documentation is at https://build.caitlyn.ai/. The source is at https://github.com/caitlyn-ai/sdk. Apache-2.0.
@@ -0,0 +1,8 @@
1
+ # caitlyn-core
2
+
3
+ The runtime behind [`caitlyn`](https://pypi.org/project/caitlyn/), the Python SDK for the Caitlyn API: sign-in,
4
+ retries, errors, streamed answers, pagination, uploads and OpenTelemetry tracing.
5
+
6
+ Install `caitlyn`, not this package: `pip install caitlyn` brings the matching version of `caitlyn-core` with it.
7
+
8
+ The documentation is at https://build.caitlyn.ai/. The source is at https://github.com/caitlyn-ai/sdk. Apache-2.0.
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "caitlyn-core"
3
+ version = "0.8.1"
4
+ description = "Runtime core for Caitlyn's generated Python SDKs: transport, retries, errors, SSE, telemetry."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ authors = [{ name = "Custom D Ltd" }]
8
+ requires-python = ">=3.12"
9
+ dependencies = [
10
+ "httpx>=0.28,<0.29",
11
+ "pydantic>=2.11,<3",
12
+ "opentelemetry-api>=1.38,<2",
13
+ ]
14
+
15
+ [project.urls]
16
+ Homepage = "https://build.caitlyn.ai/"
17
+ Documentation = "https://build.caitlyn.ai/"
18
+ Repository = "https://github.com/caitlyn-ai/sdk"
19
+
20
+ [build-system]
21
+ requires = ["hatchling"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build]
25
+ # Build from the files on disk, whatever an enclosing repository ignores.
26
+ ignore-vcs = true
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/caitlyn_core"]
@@ -0,0 +1,63 @@
1
+ """caitlyn-core: the hand-written runtime under Caitlyn's generated Python SDK.
2
+
3
+ Generated packages import from here; applications normally import from ``caitlyn`` instead."""
4
+
5
+ from ._client import (
6
+ workspace_endpoint,
7
+ AsyncClientCore,
8
+ AsyncEventStream,
9
+ ClientConfig,
10
+ EventDecoder,
11
+ EventStream,
12
+ Resume,
13
+ SyncClientCore,
14
+ )
15
+ from ._errors import CaitlynConnectionError, CaitlynError, NotSupportedByServer, StreamLostError
16
+ from ._hooks import CallContext, Interceptor
17
+ from .auth import AsyncAuthSession, Auth, CaitlynAuthError, SyncAuthSession
18
+ from ._models import CaitlynEvent, CaitlynModel, CaitlynResult, FieldError, OpenEnum, ResponseMetadata
19
+ from ._pagination import AsyncPaginator, Paginator
20
+ from ._retry import RetryPolicy
21
+ from ._spec import Member, OperationSpec
22
+ from ._waiter import WaiterError, WaitState, wait_async, wait_sync
23
+ from ._uploads import UploadFile, read_upload
24
+
25
+ __version__ = "0.8.1"
26
+
27
+ __all__ = [
28
+ "AsyncAuthSession",
29
+ "AsyncClientCore",
30
+ "AsyncEventStream",
31
+ "AsyncPaginator",
32
+ "Auth",
33
+ "CaitlynAuthError",
34
+ "CaitlynConnectionError",
35
+ "CaitlynError",
36
+ "CaitlynEvent",
37
+ "CaitlynModel",
38
+ "CaitlynResult",
39
+ "CallContext",
40
+ "ClientConfig",
41
+ "EventDecoder",
42
+ "EventStream",
43
+ "FieldError",
44
+ "Interceptor",
45
+ "Member",
46
+ "NotSupportedByServer",
47
+ "OpenEnum",
48
+ "OperationSpec",
49
+ "Paginator",
50
+ "ResponseMetadata",
51
+ "Resume",
52
+ "RetryPolicy",
53
+ "StreamLostError",
54
+ "SyncAuthSession",
55
+ "SyncClientCore",
56
+ "UploadFile",
57
+ "WaitState",
58
+ "WaiterError",
59
+ "read_upload",
60
+ "wait_async",
61
+ "wait_sync",
62
+ "workspace_endpoint",
63
+ ]
@@ -0,0 +1,140 @@
1
+ """The AWS half of the ``AwsIam`` sign-in mode, with no AWS SDK: a minimal Signature Version 4 signer, the two
2
+ credential sources AWS workloads actually use (environment variables, and the container credentials endpoint
3
+ that ECS, Fargate and AgentCore runtimes set), and one call, STS ``GetWebIdentityToken``. Anything else
4
+ (profiles, single sign-on, instance metadata) is reached by passing ``credentials``, for example a function
5
+ that returns boto3's ``Session().get_credentials().get_frozen_credentials()`` as ``AwsCredentials``."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import hmac
11
+ import os
12
+ import re
13
+ from dataclasses import dataclass, field
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Any
17
+ from urllib.parse import quote, urlencode
18
+
19
+ import httpx
20
+
21
+ from ._steps import Steps, send
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class AwsCredentials:
26
+ access_key_id: str
27
+ secret_access_key: str = field(repr=False)
28
+ session_token: str | None = field(default=None, repr=False)
29
+ expiration: datetime | None = None
30
+ """When the credentials stop working, when known."""
31
+
32
+
33
+ class AwsStsError(Exception):
34
+ """STS refused the call: ``code`` is the STS error code (``SignatureDoesNotMatch``…)."""
35
+
36
+ def __init__(self, message: str, code: str, status: int) -> None:
37
+ super().__init__(message)
38
+ self.code = code
39
+ self.status = status
40
+
41
+
42
+ def _sha256(data: bytes) -> str:
43
+ return hashlib.sha256(data).hexdigest()
44
+
45
+
46
+ def _hmac(key: bytes, data: str) -> bytes:
47
+ return hmac.new(key, data.encode(), hashlib.sha256).digest()
48
+
49
+
50
+ def _encode(s: str) -> str:
51
+ """RFC 3986 encoding, as Signature Version 4 requires."""
52
+ return quote(s, safe="-_.~")
53
+
54
+
55
+ def sign_v4(
56
+ method: str, url: httpx.URL, headers: dict[str, str], body: bytes, credentials: AwsCredentials, region: str, service: str, now: datetime | None = None
57
+ ) -> dict[str, str]:
58
+ """Signs a request with Signature Version 4 (header form) and returns the headers to send, including
59
+ ``authorization``, ``x-amz-date``, ``x-amz-content-sha256`` and, for temporary credentials,
60
+ ``x-amz-security-token``. ``host`` is signed but not returned: the HTTP client sets it."""
61
+ amz_date = (now or datetime.now(UTC)).strftime("%Y%m%dT%H%M%SZ")
62
+ day = amz_date[:8]
63
+ payload_hash = _sha256(body)
64
+ signed: dict[str, str] = {k.lower(): " ".join(v.split()) for k, v in headers.items()}
65
+ signed["host"] = url.netloc.decode()
66
+ signed["x-amz-date"] = amz_date
67
+ signed["x-amz-content-sha256"] = payload_hash
68
+ if credentials.session_token:
69
+ signed["x-amz-security-token"] = credentials.session_token
70
+ names = sorted(signed)
71
+ query = "&".join(f"{k}={v}" for k, v in sorted((_encode(k), _encode(v)) for k, v in url.params.multi_items()))
72
+ path = "/".join(_encode(p) for p in url.path.split("/")) or "/"
73
+ canonical = "\n".join([method, path, query, "".join(f"{n}:{signed[n]}\n" for n in names), ";".join(names), payload_hash])
74
+ scope = f"{day}/{region}/{service}/aws4_request"
75
+ to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, _sha256(canonical.encode())])
76
+ key = _hmac(f"AWS4{credentials.secret_access_key}".encode(), day)
77
+ for part in (region, service, "aws4_request"):
78
+ key = _hmac(key, part)
79
+ signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
80
+ signed["authorization"] = f"AWS4-HMAC-SHA256 Credential={credentials.access_key_id}/{scope}, SignedHeaders={';'.join(names)}, Signature={signature}"
81
+ del signed["host"]
82
+ return signed
83
+
84
+
85
+ def default_credentials() -> Steps[AwsCredentials]:
86
+ """``AWS_ACCESS_KEY_ID`` and ``AWS_SECRET_ACCESS_KEY`` (with ``AWS_SESSION_TOKEN``), as Lambda and CI runners
87
+ set them; otherwise the container credentials endpoint (``AWS_CONTAINER_CREDENTIALS_FULL_URI`` or
88
+ ``_RELATIVE_URI``), as ECS, Fargate and AgentCore runtimes set it."""
89
+ env = os.environ
90
+ key_id, secret = env.get("AWS_ACCESS_KEY_ID"), env.get("AWS_SECRET_ACCESS_KEY")
91
+ if key_id and secret:
92
+ return AwsCredentials(key_id, secret, env.get("AWS_SESSION_TOKEN") or None)
93
+ url = env.get("AWS_CONTAINER_CREDENTIALS_FULL_URI")
94
+ if not url and (relative := env.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")):
95
+ url = f"http://169.254.170.2{relative}"
96
+ if url:
97
+ token = env.get("AWS_CONTAINER_AUTHORIZATION_TOKEN")
98
+ if not token and (token_file := env.get("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE")):
99
+ token = Path(token_file).read_text().strip()
100
+ response = yield from send(httpx.Request("GET", url, headers={"Authorization": token} if token else {}))
101
+ if not response.is_success:
102
+ raise RuntimeError(f"awsIam: the container credentials endpoint answered {response.status_code}")
103
+ c: dict[str, Any] = response.json()
104
+ expiration = datetime.fromisoformat(c["Expiration"].replace("Z", "+00:00")) if c.get("Expiration") else None
105
+ return AwsCredentials(c["AccessKeyId"], c["SecretAccessKey"], c.get("Token"), expiration)
106
+ raise RuntimeError(
107
+ "awsIam: no AWS credentials found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, run where the container "
108
+ "credentials endpoint is set, or pass credentials= (an AwsCredentials, or a function that returns one)."
109
+ )
110
+
111
+
112
+ def _xml_text(xml: str, tag: str) -> str | None:
113
+ m = re.search(rf"<{tag}>([^<]*)</{tag}>", xml)
114
+ return m.group(1) if m else None
115
+
116
+
117
+ def get_web_identity_token(
118
+ *, region: str, audience: str, credentials: AwsCredentials, signing_algorithm: str, duration_seconds: int, sts_endpoint: str | None
119
+ ) -> Steps[str]:
120
+ """Calls STS ``GetWebIdentityToken`` (outbound identity federation) on a regional endpoint; returns the JWT."""
121
+ url = httpx.URL(sts_endpoint or f"https://sts.{region}.amazonaws.com/")
122
+ body = urlencode(
123
+ {
124
+ "Action": "GetWebIdentityToken",
125
+ "Version": "2011-06-15",
126
+ "Audience.member.1": audience,
127
+ "DurationSeconds": str(duration_seconds),
128
+ "SigningAlgorithm": signing_algorithm,
129
+ }
130
+ ).encode()
131
+ headers = sign_v4("POST", url, {"content-type": "application/x-www-form-urlencoded; charset=utf-8"}, body, credentials, region, "sts")
132
+ response = yield from send(httpx.Request("POST", url, headers=headers, content=body))
133
+ text = response.text
134
+ if not response.is_success:
135
+ code = _xml_text(text, "Code") or f"HTTP {response.status_code}"
136
+ raise AwsStsError(f"awsIam: STS GetWebIdentityToken failed: {code}: {_xml_text(text, 'Message') or ''}".strip(), code, response.status_code)
137
+ token = _xml_text(text, "WebIdentityToken")
138
+ if not token:
139
+ raise RuntimeError("awsIam: STS answered without a WebIdentityToken")
140
+ return token