Transport adapters

Every backend implements the same interface: synchronous clients subclass ContreeSyncClient, asynchronous ones subclass ContreeAsyncClient. An adapter provides only the transport primitives — request, stream(spec, auto_decompress=True), open and close — the whole API surface lives in the base classes and is documented on the generated API page.

Synchronous adapters export ContreeClient, asynchronous ones export ContreeAsyncClient:

Backend

Extra

Import

http.client

— (stdlib)

from contree_client.http import ContreeClient

urllib3

contree-client[urllib3]

from contree_client.urllib3 import ContreeClient

requests

contree-client[requests]

from contree_client.requests import ContreeClient

httpx

contree-client[httpx]

from contree_client.httpx import ContreeClient / ContreeAsyncClient

aiohttp

contree-client[aiohttp]

from contree_client.aiohttp import ContreeAsyncClient

Thanks to the Liskov substitution principle any adapter of the matching flavour is interchangeable — annotate code against the base classes from contree_client.types and let the caller decide:

from contree_client.types import ContreeSyncClient


def biggest_image(client: ContreeSyncClient) -> str:
    images = client.list_images(tagged=True).images
    return max(images, key=lambda image: image.created_at or "").uuid


assert biggest_image(double) == IMAGE_UUID  # any backend, the test double too
from contree_client.types import ContreeAsyncClient


async def biggest_image(client: ContreeAsyncClient) -> str:
    images = (await client.list_images(tagged=True)).images
    return max(images, key=lambda image: image.created_at or "").uuid


assert await biggest_image(double) == IMAGE_UUID

Autodetect

When any installed backend will do, let the package pick one — the first importable backend wins, ordered by ecosystem popularity (sync: requests → urllib3 → httpx → stdlib http.client; async: aiohttp → httpx). Popularity is judged by all-time PyPI download totals from ClickPy (PyPI analytics powered by ClickHouse): requests ~34B, urllib3 ~39B (mostly transitive — it ships inside requests/botocore), aiohttp ~10B, httpx ~7.6B. The async variant raises an ImportError with an installation suggestion when neither aiohttp nor httpx is installed:

from contree_client.sync import ContreeClient
from contree_client.asyncio import ContreeAsyncClient

Creating a client

from contree_client.requests import ContreeClient

client = ContreeClient(
    "IAM_TOKEN",                    # Authorization: Bearer <token>
    project="my-project-id",        # Project header (IAM); omit for JWT
    # base_url defaults to the public endpoint from the spec;
    # override for self-hosted deployments:
    # base_url="https://contree.example.com",
    timeout=300.0,
)
from contree_client.httpx import ContreeAsyncClient

client = ContreeAsyncClient(
    "IAM_TOKEN",                    # Authorization: Bearer <token>
    project="my-project-id",        # Project header (IAM); omit for JWT
    # base_url defaults to the public endpoint from the spec;
    # override for self-hosted deployments:
    # base_url="https://contree.example.com",
    timeout=300.0,
)

All clients are context managers. Entering the context calls open() — asynchronous adapters use it to create loop-bound resources (the aiohttp.ClientSession) eagerly; close() releases the transport:

with ContreeClient("IAM_TOKEN", project="p") as client:
    print(client.whoami().permissions)
async with ContreeAsyncClient("IAM_TOKEN", project="p") as client:
    print((await client.whoami()).permissions)

Reuse a saved profile

With a Contree profile saved under $CONTREE_HOME (the configuration shared by all Contree tooling), every adapter can be built from the same profiles ($CONTREE_HOME/auth.ini):

client = ContreeClient.from_profile()           # the active profile
client = ContreeClient.from_profile("staging")  # a specific one
client = ContreeAsyncClient.from_profile()           # the active profile
client = ContreeAsyncClient.from_profile("staging")  # a specific one

Resolution order: explicit argument → CONTREE_PROFILE environment variable → the active profile from the config file.

Environments without config files (CI, containers) can describe a profile entirely through the standard Contree variables: contree_client.profiles.from_env() returns a Profile built from CONTREE_TOKEN (or NEBIUS_API_KEY), CONTREE_URL and optionally CONTREE_PROJECT (or NEBIUS_AI_PROJECT) — or None when they are not set, so a caller can fall through to from_profile().

Bring your own transport instance

Each adapter accepts a preconfigured transport object (proxies, TLS tweaks, connection pooling — anything the library supports):

from contree_client.urllib3 import ContreeClient as Urllib3Client
from contree_client.requests import ContreeClient as RequestsClient
from contree_client.httpx import ContreeAsyncClient as HttpxAsyncClient
from contree_client.aiohttp import ContreeAsyncClient as AiohttpClient

Urllib3Client("token", urllib3_pool_manager=urllib3.PoolManager(maxsize=50))
RequestsClient("token", requests_session=my_requests_session)
HttpxAsyncClient("token", httpx_client=httpx.AsyncClient(http2=True))
AiohttpClient("token", aiohttp_session=my_aiohttp_session)

Adapter-specific constructor arguments always carry the adapter name as a prefix (aiohttp_session, httpx_client, …) — everything unprefixed is part of the common interface and works identically on every backend.

A transport you pass in is not closed by client.close() — the client only closes what it created itself.

Custom TLS

Every adapter takes an optional ssl_context — a standard ssl.SSLContext handed to the transport untouched (private CAs, client certificates, pinned ciphers):

import ssl

context = ssl.create_default_context(cafile="internal-ca.pem")
client = ContreeClient("token", ssl_context=context)

ssl_context cannot be combined with a bring-your-own transport instance: the transport you built owns its TLS configuration, so passing both raises ValueError instead of silently ignoring one.

Connection reuse

Every adapter keeps pooled keepalive connections for the lifetime of the client: urllib3 (PoolManager), requests (Session), httpx (Client / AsyncClient), aiohttp (ClientSession), and the stdlib http.client adapter runs its own small LIFO pool (the http_max_connections constructor kwarg, 25 by default) — buffered requests borrow a warm connection instead of paying a TLS handshake per call, concurrent callers borrow distinct connections (the cap bounds the total; extra callers wait instead of stampeding the server). Before handing a pooled connection out the pool verifies it is still alive (an idle socket must be silent - EOF or unsolicited bytes mean the server dropped it), so an expired keepalive is replaced by a fresh dial without ever sending into a dead socket; a connection that dies in the race window between the check and the send is still covered by one transparent re-send. Streams always own a dedicated connection until EOF.

Compression

The server compresses every response (including streams) with gzip. Adapters decode it transparently, incrementally for streams (Z_SYNC_FLUSH-friendly), and every adapter advertises Accept-Encoding: gzip; passing auto_decompress=False to stream() yields the body exactly as served.

Retries

Retries are opt-in. A RetryPolicy retries APIConnectionError and 410/425/429/5xx responses. It honors Retry-After when the server sends one and uses a backoff ladder (0.1 → 5 s) otherwise. The budget is finite by default (10 attempts); unbounded retries are an explicit max_attempts=None. Non-idempotent requests (POST — spawn, import, upload) are never replayed unless you opt into the double-execution risk with retry_unsafe=True: a lost response may mean the server already executed the call. File-like request bodies are rewound to their initial offset before each attempt (non-seekable bodies fail fast). Buffered-request timeouts follow the same retry policy. The configured timeout applies to each attempt, so the complete call can take longer. An explicit wait_operation or follow_operation_events timeout covers event connections, status probes, reconnect delays, and the final status fetch. Sync buffered reads can report expiry after the response completes. This timeout is an absolute deadline. The client checks it whenever iteration resumes, but it does not interrupt caller code between yielded events. A synchronous native read started before expiry can delay TimeoutError until it returns. Status probes use one transport attempt because the event follower controls reconnection. Low-level streaming requests use the shared exception hierarchy and are not retried by call(). follow_operation_events handles network interruptions and reconnects with Last-Event-Id; a transport timeout only ends the follower when its absolute deadline has elapsed. Unexpected errors, including malformed event data and corrupt compressed bodies, propagate without retry.

After observing terminal status, the Python follower reads the retained log with follow=False, preserving the cursor, filters, and original deadline. Live and retained streams use the caller’s overall timeout. Both wait_operation and follow_operation_events accept idle_timeout, a float in seconds with a 15.0 default. Any incoming SSE frame, including ping/keepalive comments, renews this inactivity limit. Set it to 0 to disable the limit. When it expires, the client closes the stream before checking status and reconnecting. It never extends the overall timeout. An interrupted read resumes from the last received event id. These drain attempts use the configured RetryPolicy statuses, delays, and max_attempts, or three attempts with the default delays when no policy is configured. A clean EOF completes a filtered or explicitly resumed log even without a completion event. An unfiltered log must include completion; otherwise the follower raises APIConnectionError. A permanent HTTP failure or exhausted drain budget raises APIConnectionError with the original failure as its cause, rather than silently returning partial events.

wait_operation uses events for instances and polls image imports every 0.5 seconds when follow_events=None (the default). Set it to True or False to force events or polling. Both modes return failed and cancelled responses unchanged and share one deadline across requests, retries, and delays.

from contree_client import RetryPolicy

client = ContreeClient(
    "IAM_TOKEN",
    retry=RetryPolicy(),                     # finite budget: 10 attempts
    # retry=RetryPolicy(max_attempts=None),  # explicitly unbounded
    # retry=RetryPolicy(retry_unsafe=True),  # replay POSTs too (risky)
)
from contree_client import RetryPolicy

client = ContreeAsyncClient(
    "IAM_TOKEN",
    retry=RetryPolicy(),                     # finite budget: 10 attempts
    # retry=RetryPolicy(max_attempts=None),  # explicitly unbounded
    # retry=RetryPolicy(retry_unsafe=True),  # replay POSTs too (risky)
)

Request errors

All adapters use the shared exception hierarchy for both buffered request() and streaming stream(). HTTP statuses of 400 or greater become the matching APIStatusError, including the response error body and Retry-After when available. Connection failures and interrupted bodies become APIConnectionError, with the backend exception as __cause__. Its timed_out flag identifies a transport timeout; it does not mean the operation deadline has elapsed.

Streaming methods previously exposed native backend exceptions. Callers must now catch APIConnectionError or APIStatusError for transport failures. Unknown errors, malformed event data, and corrupt compressed bodies propagate unchanged in both request modes. Task cancellation also propagates unchanged.

Adding an adapter

Use one normalization boundary for request() and stream(). It must cover connection setup, body reads, and cleanup, including reads after yielded chunks. Convert only recognized network failures to APIConnectionError and preserve their cause and timeout flag. Use error_for_response() for HTTP errors. Keep parsing and programming errors visible.

Retry decisions belong to the shared client code. Adapters must not inspect RetryPolicy to classify errors or infer deadline expiry from a transport timeout. Add request/stream contract tests for native connect/read/reset/ truncated/status failures. Verify cursor resume, deadlines, cancellation, and stream closure with the shared lifecycle tests.

User-Agent

Every request carries contree-client/<version> <transport>/<version> Python/<version> <platform> unless the caller supplies its own User-Agent header. The tokens come from the UA_* class attributes of the base client; adapters override UA_TRANSPORT_LIBRARY (e.g. httpx/0.28.1, http.client for the stdlib backend).

An application announces itself with the identity constructor kwarg — its token leads and the library tokens stay intact:

client = ContreeClient("IAM_TOKEN", identity="my-app/1.2.3")
# User-Agent: my-app/1.2.3 contree-client/0.1.0 httpx/0.28.1 Python/...

assert client.user_agent().startswith("my-app/1.2.3 contree-client/")
client = ContreeAsyncClient("IAM_TOKEN", identity="my-app/1.2.3")
# User-Agent: my-app/1.2.3 contree-client/0.1.0 httpx/0.28.1 Python/...

assert client.user_agent().startswith("my-app/1.2.3 contree-client/")

Logging

The library logs under the contree_client logger with one child per adapter (contree_client.requests, contree_client.aiohttp, …). The base logger level is explicitly set to logging.ERROR, so even an application configured with root DEBUG sees nothing from the client unless it opts in:

import logging

from contree_client.types import set_log_level

set_log_level(logging.DEBUG)

At DEBUG the client logs the raw exchange:

  • outgoing requests — method, URL, headers and body (Authorization and other sensitive headers are redacted; JSON bodies are logged with the values of secret-suffixed keys structurally redacted, truncated at 4 KiB; binary bodies become a <binary NB> marker);

  • buffered responses — status, headers and body, same formatting;

  • streaming responses — the status line and per-chunk sizes;

  • every received SSE event (sse event: OperationEvent(...));

  • backend autodetection decisions.

Reference

contree_client.types

Typing-oriented re-exports of the client base classes and the package logging subsystem.

Annotate code against these interfaces instead of a concrete backend, so any transport can be substituted:

from contree_client.types import ContreeSyncClient


def biggest_image(client: ContreeSyncClient) -> str:
    ...

Every implementation logs into a child of logger. The base logger level is explicitly set to logging.ERROR, so the library stays silent unless the user opts in:

from contree_client.types import set_log_level

set_log_level(logging.DEBUG)
contree_client.types.set_log_level(level)[source]

Set the level of the package logger and all its children.

Parameters:

level (int | str)

Return type:

None

contree_client.sync

Autodetected synchronous client.

Tries the installed backends in priority order and exposes the first importable one as ContreeClient:

from contree_client.sync import ContreeClient

The stdlib http.client backend needs no third-party packages, so detection always succeeds; install contree-client[requests], [urllib3] or [httpx] to get a higher-priority backend.

contree_client.sync.detect_backend()[source]
Return type:

tuple[str, type[ContreeSyncClient]]

contree_client.asyncio

Autodetected asynchronous client.

Tries the installed backends in priority order and exposes the first importable one as ContreeAsyncClient:

from contree_client.asyncio import ContreeAsyncClient

Raises an ImportError with an installation suggestion when neither aiohttp nor httpx is available.

contree_client.asyncio.detect_backend()[source]
Return type:

tuple[str, type[ContreeAsyncClient]]

contree_client.http

Contree API client backed by the standard library http.client.

No third-party dependencies. The server compresses every response (including SSE streams) and http.client neither advertises nor decodes gzip, so both are handled here: buffered bodies are inflated in one go, streams are inflated incrementally (Z_SYNC_FLUSH-friendly), and reading uses read1() - a plain read(n) would block until n bytes arrive and stall SSE frames.

Buffered requests borrow keepalive connections from a small pool (saving a TLS handshake per call); each stream owns a dedicated connection until EOF.

contree_client.http.read_response(response)[source]

Read the whole body, inflating gzip when the server used it.

Content-Encoding/Content-Length are dropped after inflation so nobody downstream attempts a second decode against a stale length.

Parameters:

response (HTTPResponse)

Return type:

ResponseData

contree_client.http.connection_alive(connection)[source]

True when an idle keepalive connection is still usable.

An idle HTTP connection must be silent: a readable socket while no request is in flight means the server closed it (EOF/close_notify) or broke the protocol - either way it must not be handed out. The zero-timeout select works for TLS sockets too, where a MSG_PEEK recv would not.

Parameters:

connection (HTTPConnection)

Return type:

bool

contree_client.http.normalize_errors()[source]

Normalize transport failures for buffered and streaming requests.

Return type:

Iterator[None]

class contree_client.http.ConnectionPool(factory, maxsize=5)[source]

Bases: object

A bounded LIFO pool of keepalive http.client connections.

maxsize caps the TOTAL number of live connections, not just the idle ones: borrowing takes the most recently used idle connection (the warmest, least likely to have been closed by the server), dials a new one while under the cap, and otherwise blocks until a concurrent caller returns or discards one - concurrency cannot stampede the server with extra dials. A Condition rather than a Queue: discarding a broken connection frees a slot and must wake a blocked borrower, which a plain Queue.get() cannot express.

Parameters:
acquire(deadline=None)[source]

Borrow a connection before deadline.

True means the returned connection was reused and can be stale.

Parameters:

deadline (float | None)

Return type:

tuple[HTTPConnection, bool]

release(connection)[source]

Return a healthy connection for reuse.

Parameters:

connection (HTTPConnection)

Return type:

None

discard(connection)[source]

Close a broken connection and free its slot.

Parameters:

connection (HTTPConnection)

Return type:

None

close()[source]

Close every idle connection and free their slots.

Return type:

None

class contree_client.http.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, http_max_connections=25)[source]

Bases: ContreeSyncClient

Synchronous Contree API client on top of http.client.

Buffered requests share a keepalive ConnectionPool (default 25 connections) - a request re-sent once on a fresh connection when the borrowed one went stale server-side. Streams hold their socket until fully consumed, so each stream gets a dedicated connection closed at its end.

Parameters:
log: Logger = <Logger contree_client.http (ERROR)>
UA_TRANSPORT_LIBRARY = 'http.client'
request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

Iterator[bytes]

close()[source]

Close every idle pooled connection.

Return type:

None

contree_client.urllib3

Contree API client backed by urllib3.

contree_client.urllib3.normalize_errors()[source]

Normalize transport failures for buffered and streaming requests.

Return type:

Iterator[None]

class contree_client.urllib3.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, urllib3_pool_manager=None)[source]

Bases: ContreeSyncClient

Synchronous Contree API client on top of urllib3.PoolManager.

The server compresses every response (including streams); unlike requests/httpx/aiohttp, urllib3 does not advertise gzip support on its own, so the Accept-Encoding header is set explicitly and the responses are transparently decoded (decode_content=True).

Parameters:
log: Logger = <Logger contree_client.urllib3 (ERROR)>
UA_TRANSPORT_LIBRARY = 'urllib3/2.7.0'
request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

Iterator[bytes]

close()[source]

Release the underlying transport resources.

Return type:

None

contree_client.requests

Contree API client backed by requests.

contree_client.requests.normalize_errors()[source]

Normalize transport failures for buffered and streaming requests.

Return type:

Iterator[None]

class contree_client.requests.SSLContextAdapter(ssl_context, **kwargs)[source]

Bases: HTTPAdapter

An HTTPAdapter that hands a caller-supplied SSLContext down to the underlying urllib3 pool - requests has no direct kwarg for it.

Parameters:
init_poolmanager(*args, **kwargs)[source]

Initializes a urllib3 PoolManager.

This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • connections – The number of urllib3 connection pools to cache.

  • maxsize – The maximum number of connections to save in the pool.

  • block – Block when no free connections are available.

  • pool_kwargs – Extra keyword arguments used to initialize the Pool Manager.

  • args (Any)

  • kwargs (Any)

Return type:

None

class contree_client.requests.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, requests_session=None)[source]

Bases: ContreeSyncClient

Synchronous Contree API client on top of requests.Session.

Parameters:
log: Logger = <Logger contree_client.requests (ERROR)>
UA_TRANSPORT_LIBRARY = 'requests/2.34.2'
request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

Iterator[bytes]

close()[source]

Release the underlying transport resources.

Return type:

None

contree_client.httpx

Contree API clients backed by httpx (sync and async).

contree_client.httpx.normalize_errors()[source]

Normalize transport failures for sync/async requests and streams.

Return type:

Iterator[None]

class contree_client.httpx.ContreeClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, httpx_client=None)[source]

Bases: ContreeSyncClient

Synchronous Contree API client on top of httpx.Client.

Parameters:
log: Logger = <Logger contree_client.httpx (ERROR)>
UA_TRANSPORT_LIBRARY = 'httpx/0.28.1'
request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

Iterator[bytes]

close()[source]

Release the underlying transport resources.

Return type:

None

class contree_client.httpx.ContreeAsyncClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, httpx_client=None)[source]

Bases: ContreeAsyncClient

Asynchronous Contree API client on top of httpx.AsyncClient.

Parameters:
log: Logger = <Logger contree_client.httpx (ERROR)>
UA_TRANSPORT_LIBRARY = 'httpx/0.28.1'
async request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

async stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

AsyncGenerator[bytes, None]

async close()[source]

Release the underlying transport resources.

Return type:

None

contree_client.aiohttp

Contree API client backed by aiohttp.

contree_client.aiohttp.normalize_errors()[source]

Normalize transport failures for buffered and streaming requests.

Return type:

Iterator[None]

class contree_client.aiohttp.ContreeAsyncClient(token, *, base_url='https://api.tokenfactory.nebius.com/sandboxes', project=None, timeout=300.0, retry=None, identity=None, ssl_context=None, aiohttp_session=None)[source]

Bases: ContreeAsyncClient

Asynchronous Contree API client on top of aiohttp.ClientSession.

The owned session is created lazily inside a running event loop.

Parameters:
log: Logger = <Logger contree_client.aiohttp (ERROR)>
UA_TRANSPORT_LIBRARY = 'aiohttp/3.14.1'
async request(spec)[source]

Execute the request and return the buffered response.

Parameters:

spec (RequestSpec)

Return type:

ResponseData

async stream(spec, auto_decompress=True)[source]

Execute the request and yield response body chunks.

With auto_decompress=False the body is yielded exactly as served (e.g. the gzip the server always applies is kept).

Parameters:
Return type:

AsyncGenerator[bytes, None]

async close()[source]

Release the underlying transport resources.

Return type:

None

contree_client.profiles

Contree configuration profiles.

The INI files under $CONTREE_HOME: auth.ini (secrets) merged over $CONTREE_HOME/cli.ini (non-secret defaults), where CONTREE_HOME defaults to $XDG_CONFIG_HOME/contree and finally ~/.config/contree.

exception contree_client.profiles.ProfileError[source]

Bases: ValueError

The requested profile is missing or incomplete.

class contree_client.profiles.Profile(name, url, token, auth_type='jwt', project=None)[source]

Bases: object

One Contree authentication profile.

Frozen and comparable; the token never shows up in repr().

Parameters:
  • name (str)

  • url (str)

  • token (str | None)

  • auth_type (str)

  • project (str | None)

name: str
url: str
token: str | None
auth_type: str = 'jwt'
project: str | None = None
save(config)[source]
Parameters:

config (ConfigParser)

Return type:

None

contree_client.profiles.contree_home()[source]
Return type:

Path

contree_client.profiles.load_profiles(path=None)[source]

Read all profiles; return (profiles, active_profile_name).

cli.ini is read first, then auth.ini - values from auth.ini win on conflicts.

Parameters:

path (str | Path | None)

Return type:

tuple[dict[str, Profile], str]

contree_client.profiles.from_env()[source]

Build a profile from the environment, bypassing config files.

Reads the standard Contree variables: CONTREE_TOKEN (or NEBIUS_API_KEY), CONTREE_URL and optionally CONTREE_PROJECT (or NEBIUS_AI_PROJECT). Reports None unless both a token and a URL are present, so callers can fall through to resolve_profile().

Return type:

Profile | None

contree_client.profiles.resolve_profile(name=None, *, path=None)[source]

Resolve the active profile by name.

Priority: explicit name > CONTREE_PROFILE environment variable > the active profile recorded in the config file.

Parameters:
Return type:

Profile

contree_client.runtime

Transport-agnostic request/response plumbing and SSE parsing.

contree_client.runtime.closing_iterator(source)[source]

Release a closable iterator before the caller starts another request.

Parameters:

source (Iterator[IteratorItem])

Return type:

Iterator[Iterator[IteratorItem]]

contree_client.runtime.remaining_timeout(deadline, maximum)[source]

Return the smaller of the remaining deadline and maximum.

Raise TimeoutError when the absolute monotonic deadline has elapsed. This check cannot interrupt work already in progress.

Parameters:
Return type:

float | None

contree_client.runtime.redact_json(value)[source]

Recursively replace values of secret-suffixed keys.

Parameters:

value (Any)

Return type:

Any

class contree_client.runtime.HeaderFormatter(headers)[source]

Bases: object

Lazy %s argument for logging HTTP headers, redacts secrets.

Parameters:

headers (Iterable[tuple[str, str]])

class contree_client.runtime.BodyFormatter(body, content_type='', max_size=4096)[source]

Bases: object

Lazy %s argument for logging HTTP bodies.

JSON payloads are parsed and re-rendered with the values of secret-suffixed keys structurally redacted; other textual payloads are rendered as-is. Everything is truncated at max_size, binary payloads become a size marker and file-like bodies are never consumed.

Parameters:
truncated(text, total)[source]
Parameters:
Return type:

str

class contree_client.runtime.RequestSpec(method, path, query=<factory>, headers=<factory>, body=None, content_type=None, accept=None, idempotent=False, deadline=None, read_timeout=None)[source]

Bases: object

A backend-agnostic description of a single API request.

Parameters:
method: str
path: str
query: Mapping[str, str | Sequence[str]]
headers: dict[str, str]
body: bytes | IO[bytes] | None = None
content_type: str | None = None
accept: str | None = None
idempotent: bool = False
deadline: float | None = None
read_timeout: float | None = None
class contree_client.runtime.ResponseData(status, headers, body)[source]

Bases: object

A fully buffered response; header names are lower-cased.

Parameters:
status: int
headers: dict[str, str]
body: bytes
contree_client.runtime.distribution_version(name)[source]

The installed distribution version via package metadata.

Editable installs report "editable" (their recorded version is whatever was current at install time, i.e. a lie); missing metadata reports None.

Parameters:

name (str)

Return type:

str | None

contree_client.runtime.package_version()[source]
Return type:

str

contree_client.runtime.library_version(module)[source]

A name/version User-Agent token for a transport module.

Version resolution: package metadata (editable for editable installs), then the module’s __version__, then unknown - building the token must never fail the import.

Parameters:

module (Any)

Return type:

str

contree_client.runtime.is_uuid(ref)[source]

True if ref looks like an image/operation UUID.

Parameters:

ref (str)

Return type:

bool

contree_client.runtime.file_sha256(content)[source]

The sha256 hexdigest of an upload payload.

File-like payloads are hashed from their current position - the exact bytes a subsequent send would transmit - and the position is restored afterwards. A non-seekable stream cannot be re-read, so it reports None (the caller skips deduplication).

Parameters:

content (bytes | IO[bytes])

Return type:

str | None

contree_client.runtime.retry_generator(delays=(0.1, 0.2, 0.5, 1.0, 2.0, 5.0))[source]

An endless ladder of backoff delays.

Every next() returns a valid sleep time: the ladder is walked once and then the tail delay repeats forever, so callers never guard against StopIteration and never do index arithmetic. A finite retry budget is bounded externally (an attempt counter).

Parameters:

delays (tuple[float, ...])

Return type:

Iterator[float]

class contree_client.runtime.RetryPolicy(statuses=(410, 425, 429), server_errors=True, delays=(0.1, 0.2, 0.5, 1.0, 2.0, 5.0), max_attempts=10, retry_unsafe=False)[source]

Bases: object

Opt-in retries for buffered request failures.

Retries APIConnectionError and the configured HTTP statuses. server_errors extends this to every 5xx status. SSE consumers handle stream reconnection separately.

Parameters:
statuses: tuple[int, ...] = (410, 425, 429)
server_errors: bool = True
delays: tuple[float, ...] = (0.1, 0.2, 0.5, 1.0, 2.0, 5.0)
max_attempts: int | None = 10
retry_unsafe: bool = False
retryable_status(status)[source]
Parameters:

status (int)

Return type:

bool

contree_client.runtime.body_start(spec)[source]

The position a file-like body starts sending from.

Captured before the first attempt so a retry replays exactly the same bytes; None for absent/bytes/non-seekable bodies.

Parameters:

spec (RequestSpec)

Return type:

int | None

contree_client.runtime.rewind_body(spec, start)[source]

Rewind a file-like request body to start before a retry.

Parameters:
Return type:

None

contree_client.runtime.parse_retry_after(value)[source]

Parse a Retry-After header: delta-seconds or an HTTP-date.

Negative values clamp to 0.0; anything unparsable reports None.

Parameters:

value (str | None)

Return type:

float | None

contree_client.runtime.retry_after_delay(response)[source]

The Retry-After header as seconds, when present and valid.

Parameters:

response (ResponseData)

Return type:

float | None

contree_client.runtime.quote_path(value)[source]
Parameters:

value (str | int)

Return type:

str

contree_client.runtime.encode_query(query)[source]
Parameters:

query (Mapping[str, str | Sequence[str]])

Return type:

str

contree_client.runtime.format_time_param(value)[source]
Parameters:

value (str | int | float | datetime)

Return type:

str

contree_client.runtime.json_body(response)[source]
Parameters:

response (ResponseData)

Return type:

Any

contree_client.runtime.json_object(response)[source]
Parameters:

response (ResponseData)

Return type:

dict[str, Any]

contree_client.runtime.json_array(response)[source]
Parameters:

response (ResponseData)

Return type:

list[Any]

contree_client.runtime.error_for_response(status_code, headers, body)[source]

Build the exception matching an error response.

Parameters:
Return type:

APIStatusError

contree_client.runtime.preserve_response_status(status, headers)[source]

Keep a known HTTP failure when its error body is interrupted.

Parameters:
Return type:

Iterator[None]

class contree_client.runtime.GzipStreamDecoder[source]

Bases: object

Incremental gzip decoder for streamed response bodies.

Used by transports without built-in decompression (http.client); handles Z_SYNC_FLUSH-style streams, so decoded data comes out as soon as the server flushes it.

decompress(data)[source]
Parameters:

data (bytes)

Return type:

bytes

flush()[source]
Return type:

bytes

class contree_client.runtime.IdentityStreamDecoder[source]

Bases: object

No-op decoder for uncompressed response bodies.

decompress(data)[source]
Parameters:

data (bytes)

Return type:

bytes

flush()[source]
Return type:

bytes

contree_client.runtime.stream_decoder(content_encoding)[source]
Parameters:

content_encoding (str | None)

Return type:

GzipStreamDecoder | IdentityStreamDecoder

contree_client.runtime.request_content(body)[source]

Normalize a request body to something httpx accepts as content.

Parameters:

body (bytes | IO[bytes] | None)

Return type:

bytes | Iterator[bytes] | None

contree_client.runtime.async_request_content(body)[source]

Normalize a request body for an asynchronous transport.

A file-like body becomes an async iterator whose reads run in a worker thread, so blocking file I/O never stalls the event loop (and an async client never receives a sync iterator).

Parameters:

body (bytes | IO[bytes] | None)

Return type:

bytes | AsyncIterator[bytes] | None

class contree_client.runtime.SSEFrame(id=None, event=None, data='')[source]

Bases: object

One parsed Server-Sent Events frame.

Parameters:
  • id (int | None)

  • event (str | None)

  • data (str)

id: int | None = None
event: str | None = None
data: str = ''
class contree_client.runtime.SSEParser[source]

Bases: object

Incremental sans-io parser for text/event-stream bytes.

Feed raw chunks, get complete frames back. Comment lines (: keepalive) are discarded per the SSE specification.

MAX_BUFFER = 4194304
event: str | None
event_id: int | None
data_lines: list[str]
feed(chunk)[source]
Parameters:

chunk (bytes)

Return type:

list[SSEFrame]

flush()[source]

Return the pending frame, if any, and reset the state.

Return type:

SSEFrame | None

contree_client.runtime.decode_event_frame(frame, last_event_id=None)[source]

Decode an SSE frame into an OperationEvent.

Return None for frames that carry no event payload.

Parameters:
Return type:

OperationEvent | None