Skip to content

anyenv

Class info

Re-exported classes

Class Module Description
HttpError anyenv.download.exceptions Base class for HTTP errors.
HttpResponse anyenv.download.base An HTTP response with its body already read.
HttpSession anyenv.download.session One httpx client for many requests (connection reuse); see http_session.
JsonDumpError anyenv.json_tools.base Unified exception for all JSON serialization errors.
JsonLoadError anyenv.json_tools.base Unified exception for all JSON parsing errors.
MultiEventHandler anyenv.calling.multieventhandler Manages multiple callbacks/event handlers with various execution modes.
ProcessManager anyenv.process_manager.process_manager Manages background processes for an agent pool.
ProcessOutput anyenv.process_manager.models Output from a running process.
RequestError anyenv.download.exceptions Exception raised when a request fails due to network or connection issues.
ResponseError anyenv.download.exceptions Exception raised when a response contains an error status code.
RunningProcess anyenv.process_manager.process Represents a running background process.
ThreadGroup anyenv.calling.threadgroup Class that executes functions in parallel, with TaskGroup-like API.
TomlDumpError anyenv.toml_tools.base Unified exception for all TOML serialization errors.
TomlLoadError anyenv.toml_tools.base Unified exception for all TOML parsing errors.

🛈 DocStrings

AnyEnv: main package.

Compatibility layer for some basic operations to allow painless operation in PyOdide and Python pre-releases.

DEFAULT_TIMEOUT module-attribute

DEFAULT_TIMEOUT: float = 30.0

Default per-operation HTTP timeout in seconds (connect is capped at 10 s).

HttpError

Bases: Exception

Base class for HTTP errors.

Source code in src/anyenv/download/exceptions.py
class HttpError(Exception):
    """Base class for HTTP errors."""

    def __init__(self, message: str, response: HttpResponse | None = None) -> None:
        super().__init__(message)
        self.response = response

HttpResponse

An HTTP response with its body already read.

A thin wrapper over the response of whichever httpx flavour is installed (httpx2 or httpx), so callers don't depend on the flavour.

Source code in src/anyenv/download/base.py
class HttpResponse:
    """An HTTP response with its body already read.

    A thin wrapper over the response of whichever httpx flavour is installed
    (httpx2 or httpx), so callers don't depend on the flavour.
    """

    __slots__ = ("_response",)

    def __init__(self, response: httpx.Response) -> None:
        self._response = response

    def __repr__(self) -> str:
        return f"<HttpResponse [{self.status_code} {self.reason}] {self.url}>"

    @property
    def status_code(self) -> int:
        """HTTP status code."""
        return self._response.status_code

    @property
    def reason(self) -> str:
        """Reason phrase of the status (e.g. "Not Found")."""
        return self._response.reason_phrase

    @property
    def url(self) -> str:
        """Final URL of the response (after redirects)."""
        return str(self._response.url)

    @property
    def headers(self) -> Mapping[str, str]:
        """Response headers (case-insensitive, read-only; repeated headers joined by commas)."""
        return ResponseHeaders(self._response.headers)

    @property
    def content(self) -> bytes:
        """Response body as bytes."""
        return self._response.content

    @property
    def text(self) -> str:
        """Response body decoded as text (charset from the headers, else guessed)."""
        return self._response.text

    def json(self) -> Any:
        """Response body parsed as JSON."""
        from anyenv import load_json

        return load_json(self._response.content)

    def validated_json[T](self, return_type: type[T]) -> T:
        """Response body parsed as JSON and validated against a type.

        Args:
            return_type: The type to validate the response against

        Raises:
            TypeError: If validation fails
        """
        from anyenv.validate import validate_json_data

        return validate_json_data(self.json(), return_type)

content property

content: bytes

Response body as bytes.

headers property

headers: Mapping[str, str]

Response headers (case-insensitive, read-only; repeated headers joined by commas).

reason property

reason: str

Reason phrase of the status (e.g. "Not Found").

status_code property

status_code: int

HTTP status code.

text property

text: str

Response body decoded as text (charset from the headers, else guessed).

url property

url: str

Final URL of the response (after redirects).

json

json() -> Any

Response body parsed as JSON.

Source code in src/anyenv/download/base.py
def json(self) -> Any:
    """Response body parsed as JSON."""
    from anyenv import load_json

    return load_json(self._response.content)

validated_json

validated_json(return_type: type[T]) -> T

Response body parsed as JSON and validated against a type.

Parameters:

Name Type Description Default
return_type type[T]

The type to validate the response against

required

Raises:

Type Description
TypeError

If validation fails

Source code in src/anyenv/download/base.py
def validated_json[T](self, return_type: type[T]) -> T:
    """Response body parsed as JSON and validated against a type.

    Args:
        return_type: The type to validate the response against

    Raises:
        TypeError: If validation fails
    """
    from anyenv.validate import validate_json_data

    return validate_json_data(self.json(), return_type)

HttpSession

One httpx client for many requests (connection reuse); see http_session.

base_url resolves relative URLs. The session's headers go with requests to base_url (relative URLs and absolute ones under it); without a base_url, with every request through the session, including those of libraries that use anyenv's helpers inside the async with block.

Source code in src/anyenv/download/session.py
class HttpSession:
    """One httpx client for many requests (connection reuse); see `http_session`.

    ``base_url`` resolves relative URLs. The session's ``headers`` go with requests
    to ``base_url`` (relative URLs and absolute ones under it); without a
    ``base_url``, with every request through the session, including those of
    libraries that use anyenv's helpers inside the ``async with`` block.
    """

    def __init__(
        self,
        *,
        base_url: str | None = None,
        headers: HeaderType | None = None,
        cache: CacheSettings | None = None,
        timeout: float | None = _UNSET,
    ) -> None:
        self.base_url = base_url
        self.headers: HeaderType = dict(headers or {})
        self.cache = cache or CacheSettings.create(False)
        self.timeout: float | None = DEFAULT_TIMEOUT if timeout is _UNSET else timeout
        self._timeout_arg: float | None = timeout
        self._client, self._httpx = create_client(self.cache, timeout)
        self._closed = False
        self._loop: asyncio.AbstractEventLoop | None = None

    @property
    def closed(self) -> bool:
        """Whether the session's client was closed."""
        return self._closed

    async def aclose(self) -> None:
        """Close the client (and its connections)."""
        self._closed = True
        self._loop = None  # no reference that keeps a finished loop alive
        await self._client.aclose()

    async def __aenter__(self) -> Self:
        self._loop = asyncio.get_running_loop()
        return self

    async def __aexit__(self, *exc_info: object) -> None:
        await self.aclose()

    def usable_here(self) -> bool:
        """Whether this context can use the client: it's open and on its event loop.

        (Another loop may see the session through a copied context, e.g. in
        ``run_sync``; a client can't be shared between loops.)
        """
        if self._closed:
            return False
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:
            return False
        return self._loop is None or self._loop is loop

    def accepts(
        self,
        cache: bool | None,
        cache_dir: StrPath | None,
        cache_ttl: int | str | None,
    ) -> bool:
        """Whether a helper call with these cache options can go through this session."""
        if self._closed:
            return False
        if cache is not None and cache != self.cache.enabled:
            return False
        if cache_dir is not None and pathlib.Path(cache_dir) != self.cache.directory:
            return False
        return cache_ttl is None or parse_ttl(cache_ttl) == self.cache.ttl

    def resolve(self, url: str) -> str:
        """The absolute URL of a request (relative URLs are appended to ``base_url``)."""
        if self.base_url is None or _is_absolute(url):
            return url
        return f"{self.base_url.rstrip('/')}/{url.lstrip('/')}"

    def _under_base_url(self, url: str) -> bool:
        if self.base_url is None:
            return True
        base = self.base_url.rstrip("/")
        return url == base or url.startswith((f"{base}/", f"{base}?"))

    def _headers_for(self, url: str, headers: HeaderType | None) -> HeaderType:
        own = self.headers if self._under_base_url(url) else {}
        return header_middlewares.apply(url, {**own, **(headers or {})})

    async def request(
        self,
        method: Method,
        url: str,
        *,
        json: Any = None,
        data: Any = None,
        files: FilesType | None = None,
        **options: Unpack[RequestOptions],
    ) -> HttpResponse:
        """Send a request; returns the response once its body is read.

        Raises:
            RequestError: The request failed (connection, timeout)
            ResponseError: The response has a 4xx / 5xx status
        """
        url = self.resolve(url)
        headers, params = apply_auth(
            self._headers_for(url, options.get("headers")),
            options.get("params"),
            api_key=options.get("api_key"),
            auth_type=options.get("auth_type", "bearer"),
            auth_username=options.get("auth_username"),
            auth_header_name=options.get("auth_header_name"),
        )
        extra: dict[str, Any] = {}
        if "timeout" in options and options["timeout"] is not _UNSET:
            extra["timeout"] = options["timeout"]
        try:
            response = await self._client.request(
                method,
                url,
                params=params,
                headers=headers,
                json=json,
                data=data,
                files=files,
                **extra,
            )
        except self._httpx.RequestError as exc:
            msg = f"Request failed: {exc!s}"
            raise RequestError(msg) from exc
        return check_response(HttpResponse(response))

    async def get(self, url: str, **options: Unpack[RequestOptions]) -> HttpResponse:
        """Send a GET request."""
        return await self.request("GET", url, **options)

    async def post(
        self,
        url: str,
        *,
        json: Any = None,
        data: Any = None,
        files: FilesType | None = None,
        **options: Unpack[RequestOptions],
    ) -> HttpResponse:
        """Send a POST request."""
        return await self.request("POST", url, json=json, data=data, files=files, **options)

    async def get_text(self, url: str, **options: Unpack[RequestOptions]) -> str:
        """GET a URL and return the body as text."""
        return (await self.get(url, **options)).text

    async def get_bytes(self, url: str, **options: Unpack[RequestOptions]) -> bytes:
        """GET a URL and return the body as bytes."""
        return (await self.get(url, **options)).content

    async def get_json[T](
        self, url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
    ) -> T:
        """GET a URL and return the body parsed as JSON (validated if `return_type`)."""
        from anyenv.validate import validate_json_data

        return validate_json_data((await self.get(url, **options)).json(), return_type)

    async def post_json[T](
        self,
        url: str,
        json_data: Any,
        *,
        files: FilesType | None = None,
        return_type: type[T] | None = None,
        **options: Unpack[RequestOptions],
    ) -> T:
        """POST JSON (form data with `files`) and return the response parsed as JSON."""
        from anyenv.validate import validate_json_data

        if files:
            response = await self.post(url, data=json_data, files=files, **options)
        else:
            response = await self.post(url, json=json_data, **options)
        return validate_json_data(response.json(), return_type)

    async def download(
        self,
        url: str,
        path: StrPath,
        *,
        headers: HeaderType | None = None,
        progress_callback: ProgressCallback | None = None,
        timeout: float | None = _UNSET,
    ) -> None:
        """Stream a URL into a file (``<path>.part`` until complete).

        The read timeout applies per read (not to the whole download), so large
        downloads keep working as long as data keeps arriving; pass
        ``timeout=None`` to disable timeouts altogether.
        """
        url = self.resolve(url)
        extra: dict[str, Any] = {} if timeout is _UNSET else {"timeout": timeout}
        try:
            async with self._client.stream(
                "GET", url, headers=self._headers_for(url, headers), **extra
            ) as response:
                if 400 <= response.status_code < 600:  # noqa: PLR2004
                    await response.aread()
                    message = f"HTTP Error {response.status_code}"
                    raise ResponseError(message, HttpResponse(response))
                total = int(response.headers.get("content-length", "0"))
                current = 0
                with open_download_target(path) as f:
                    async for chunk in response.aiter_bytes():
                        f.write(chunk)
                        current += len(chunk)
                        if progress_callback:
                            result = progress_callback(current, total)
                            if inspect.isawaitable(result):
                                await result
        except self._httpx.RequestError as exc:
            msg = f"Download failed: {exc!s}"
            raise RequestError(msg) from exc

closed property

closed: bool

Whether the session's client was closed.

accepts

accepts(cache: bool | None, cache_dir: StrPath | None, cache_ttl: int | str | None) -> bool

Whether a helper call with these cache options can go through this session.

Source code in src/anyenv/download/session.py
def accepts(
    self,
    cache: bool | None,
    cache_dir: StrPath | None,
    cache_ttl: int | str | None,
) -> bool:
    """Whether a helper call with these cache options can go through this session."""
    if self._closed:
        return False
    if cache is not None and cache != self.cache.enabled:
        return False
    if cache_dir is not None and pathlib.Path(cache_dir) != self.cache.directory:
        return False
    return cache_ttl is None or parse_ttl(cache_ttl) == self.cache.ttl

aclose async

aclose() -> None

Close the client (and its connections).

Source code in src/anyenv/download/session.py
async def aclose(self) -> None:
    """Close the client (and its connections)."""
    self._closed = True
    self._loop = None  # no reference that keeps a finished loop alive
    await self._client.aclose()

download async

download(
    url: str,
    path: StrPath,
    *,
    headers: HeaderType | None = None,
    progress_callback: ProgressCallback | None = None,
    timeout: float | None = _UNSET,
) -> None

Stream a URL into a file (<path>.part until complete).

The read timeout applies per read (not to the whole download), so large downloads keep working as long as data keeps arriving; pass timeout=None to disable timeouts altogether.

Source code in src/anyenv/download/session.py
async def download(
    self,
    url: str,
    path: StrPath,
    *,
    headers: HeaderType | None = None,
    progress_callback: ProgressCallback | None = None,
    timeout: float | None = _UNSET,
) -> None:
    """Stream a URL into a file (``<path>.part`` until complete).

    The read timeout applies per read (not to the whole download), so large
    downloads keep working as long as data keeps arriving; pass
    ``timeout=None`` to disable timeouts altogether.
    """
    url = self.resolve(url)
    extra: dict[str, Any] = {} if timeout is _UNSET else {"timeout": timeout}
    try:
        async with self._client.stream(
            "GET", url, headers=self._headers_for(url, headers), **extra
        ) as response:
            if 400 <= response.status_code < 600:  # noqa: PLR2004
                await response.aread()
                message = f"HTTP Error {response.status_code}"
                raise ResponseError(message, HttpResponse(response))
            total = int(response.headers.get("content-length", "0"))
            current = 0
            with open_download_target(path) as f:
                async for chunk in response.aiter_bytes():
                    f.write(chunk)
                    current += len(chunk)
                    if progress_callback:
                        result = progress_callback(current, total)
                        if inspect.isawaitable(result):
                            await result
    except self._httpx.RequestError as exc:
        msg = f"Download failed: {exc!s}"
        raise RequestError(msg) from exc

get async

get(url: str, **options: Unpack[RequestOptions]) -> HttpResponse

Send a GET request.

Source code in src/anyenv/download/session.py
async def get(self, url: str, **options: Unpack[RequestOptions]) -> HttpResponse:
    """Send a GET request."""
    return await self.request("GET", url, **options)

get_bytes async

get_bytes(url: str, **options: Unpack[RequestOptions]) -> bytes

GET a URL and return the body as bytes.

Source code in src/anyenv/download/session.py
async def get_bytes(self, url: str, **options: Unpack[RequestOptions]) -> bytes:
    """GET a URL and return the body as bytes."""
    return (await self.get(url, **options)).content

get_json async

get_json(
    url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
) -> T

GET a URL and return the body parsed as JSON (validated if return_type).

Source code in src/anyenv/download/session.py
async def get_json[T](
    self, url: str, *, return_type: type[T] | None = None, **options: Unpack[RequestOptions]
) -> T:
    """GET a URL and return the body parsed as JSON (validated if `return_type`)."""
    from anyenv.validate import validate_json_data

    return validate_json_data((await self.get(url, **options)).json(), return_type)

get_text async

get_text(url: str, **options: Unpack[RequestOptions]) -> str

GET a URL and return the body as text.

Source code in src/anyenv/download/session.py
async def get_text(self, url: str, **options: Unpack[RequestOptions]) -> str:
    """GET a URL and return the body as text."""
    return (await self.get(url, **options)).text

post async

post(
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse

Send a POST request.

Source code in src/anyenv/download/session.py
async def post(
    self,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse:
    """Send a POST request."""
    return await self.request("POST", url, json=json, data=data, files=files, **options)

post_json async

post_json(
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **options: Unpack[RequestOptions],
) -> T

POST JSON (form data with files) and return the response parsed as JSON.

Source code in src/anyenv/download/session.py
async def post_json[T](
    self,
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **options: Unpack[RequestOptions],
) -> T:
    """POST JSON (form data with `files`) and return the response parsed as JSON."""
    from anyenv.validate import validate_json_data

    if files:
        response = await self.post(url, data=json_data, files=files, **options)
    else:
        response = await self.post(url, json=json_data, **options)
    return validate_json_data(response.json(), return_type)

request async

request(
    method: Method,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse

Send a request; returns the response once its body is read.

Raises:

Type Description
RequestError

The request failed (connection, timeout)

ResponseError

The response has a 4xx / 5xx status

Source code in src/anyenv/download/session.py
async def request(
    self,
    method: Method,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **options: Unpack[RequestOptions],
) -> HttpResponse:
    """Send a request; returns the response once its body is read.

    Raises:
        RequestError: The request failed (connection, timeout)
        ResponseError: The response has a 4xx / 5xx status
    """
    url = self.resolve(url)
    headers, params = apply_auth(
        self._headers_for(url, options.get("headers")),
        options.get("params"),
        api_key=options.get("api_key"),
        auth_type=options.get("auth_type", "bearer"),
        auth_username=options.get("auth_username"),
        auth_header_name=options.get("auth_header_name"),
    )
    extra: dict[str, Any] = {}
    if "timeout" in options and options["timeout"] is not _UNSET:
        extra["timeout"] = options["timeout"]
    try:
        response = await self._client.request(
            method,
            url,
            params=params,
            headers=headers,
            json=json,
            data=data,
            files=files,
            **extra,
        )
    except self._httpx.RequestError as exc:
        msg = f"Request failed: {exc!s}"
        raise RequestError(msg) from exc
    return check_response(HttpResponse(response))

resolve

resolve(url: str) -> str

The absolute URL of a request (relative URLs are appended to base_url).

Source code in src/anyenv/download/session.py
def resolve(self, url: str) -> str:
    """The absolute URL of a request (relative URLs are appended to ``base_url``)."""
    if self.base_url is None or _is_absolute(url):
        return url
    return f"{self.base_url.rstrip('/')}/{url.lstrip('/')}"

usable_here

usable_here() -> bool

Whether this context can use the client: it's open and on its event loop.

(Another loop may see the session through a copied context, e.g. in run_sync; a client can't be shared between loops.)

Source code in src/anyenv/download/session.py
def usable_here(self) -> bool:
    """Whether this context can use the client: it's open and on its event loop.

    (Another loop may see the session through a copied context, e.g. in
    ``run_sync``; a client can't be shared between loops.)
    """
    if self._closed:
        return False
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        return False
    return self._loop is None or self._loop is loop

JsonDumpError

Bases: Exception

Unified exception for all JSON serialization errors.

Source code in src/anyenv/json_tools/base.py
class JsonDumpError(Exception):
    """Unified exception for all JSON serialization errors."""

JsonLoadError

Bases: Exception

Unified exception for all JSON parsing errors.

Source code in src/anyenv/json_tools/base.py
class JsonLoadError(Exception):
    """Unified exception for all JSON parsing errors."""

    def __init__(
        self,
        message: str,
        *,
        line: int | None = None,
        column: int | None = None,
        source_path: str | Path | None = None,
        source_content: str | None = None,
    ) -> None:
        super().__init__(message)
        self.info = ParseErrorInfo(
            message=message,
            format_name="JSON Parse",
            line=line,
            column=column,
            source_path=source_path,
            source_content=source_content,
        )

    @property
    def line(self) -> int | None:
        """Line number where the error occurred."""
        return self.info.line

    @property
    def column(self) -> int | None:
        """Column number where the error occurred."""
        return self.info.column

    @property
    def source_path(self) -> str | Path | None:
        """Path to the source file that caused the error."""
        return self.info.source_path

    @property
    def source_content(self) -> str | None:
        """Source content that caused the error."""
        return self.info.source_content

    def format(self, context_lines: int = 2, use_color: bool = True) -> str:
        """Format error with source context for display.

        Args:
            context_lines: Number of lines to show before/after the error line.
            use_color: Whether to include ANSI color codes.
        """
        return self.info.format(context_lines=context_lines, use_color=use_color)

column property

column: int | None

Column number where the error occurred.

line property

line: int | None

Line number where the error occurred.

source_content property

source_content: str | None

Source content that caused the error.

source_path property

source_path: str | Path | None

Path to the source file that caused the error.

format

format(context_lines: int = 2, use_color: bool = True) -> str

Format error with source context for display.

Parameters:

Name Type Description Default
context_lines int

Number of lines to show before/after the error line.

2
use_color bool

Whether to include ANSI color codes.

True
Source code in src/anyenv/json_tools/base.py
def format(self, context_lines: int = 2, use_color: bool = True) -> str:
    """Format error with source context for display.

    Args:
        context_lines: Number of lines to show before/after the error line.
        use_color: Whether to include ANSI color codes.
    """
    return self.info.format(context_lines=context_lines, use_color=use_color)

MultiEventHandler

Manages multiple callbacks/event handlers with various execution modes.

Provides a unified interface for executing multiple callbacks either sequentially, in parallel, or as background tasks, with support for dynamic handler management and optional debouncing. Sync functions are automatically wrapped to work with the async interface.

The generic parameters HandlerT and Mode provide type safety: - HandlerT: callable type (function signature) - Mode: execution mode literal for return type inference

Parameters:

Name Type Description Default
handlers Sequence[HandlerT] | HandlerT | None

Initial list of async or sync callable event handlers, or single handler

None
mode Mode

Execution mode - "sequential", "parallel", or "task"

'parallel'
debounce_delay float | None

Optional delay in seconds for debouncing rapid calls

None
Example
from collections.abc import Awaitable
from typing import Callable, Literal

async def async_handler(x: int, y: str) -> str:
    return f"Async Handler: {x}, {y}"

def sync_handler(x: int, y: str) -> str:
    return f"Sync Handler: {x}, {y}"

# Type-safe handler with task mode
Handler = Callable[[int, str], str | Awaitable[str]]
manager = MultiEventHandler[Handler, Literal["task"]](
    [async_handler, sync_handler],
    "task",
    debounce_delay=0.1
)
tasks: list[asyncio.Task[Any]] = await manager(42, "test")
Source code in src/anyenv/calling/multieventhandler.py
class MultiEventHandler[HandlerT: Callable[..., Any], Mode: ExecutionMode = DefaultMode]:
    """Manages multiple callbacks/event handlers with various execution modes.

    Provides a unified interface for executing multiple callbacks either sequentially,
    in parallel, or as background tasks, with support for dynamic handler management
    and optional debouncing. Sync functions are automatically wrapped to work with
    the async interface.

    The generic parameters HandlerT and Mode provide type safety:
    - HandlerT: callable type (function signature)
    - Mode: execution mode literal for return type inference

    Args:
        handlers: Initial list of async or sync callable event handlers, or single handler
        mode: Execution mode - "sequential", "parallel", or "task"
        debounce_delay: Optional delay in seconds for debouncing rapid calls

    Example:
        ```python
        from collections.abc import Awaitable
        from typing import Callable, Literal

        async def async_handler(x: int, y: str) -> str:
            return f"Async Handler: {x}, {y}"

        def sync_handler(x: int, y: str) -> str:
            return f"Sync Handler: {x}, {y}"

        # Type-safe handler with task mode
        Handler = Callable[[int, str], str | Awaitable[str]]
        manager = MultiEventHandler[Handler, Literal["task"]](
            [async_handler, sync_handler],
            "task",
            debounce_delay=0.1
        )
        tasks: list[asyncio.Task[Any]] = await manager(42, "test")
        ```
    """

    def __init__(
        self,
        handlers: Sequence[HandlerT] | HandlerT | None = None,
        # Only valid while Mode is the default; type checkers cannot express that.
        mode: Mode = "parallel",  # ty: ignore[invalid-parameter-default]
        debounce_delay: float | None = None,
    ) -> None:
        self._handlers: list[HandlerT] = []
        self._wrapped_handlers: list[Callable[..., Awaitable[Any]]] = []
        self._handler_mapping: dict[HandlerT, Callable[..., Awaitable[Any]]] = {}
        self._mode: Mode = mode
        self._debounce_delay = debounce_delay
        # The round still in its delay (a new call replaces it), the callers waiting
        # for that round, and every round task (asyncio keeps only weak references).
        self._debounce_task: asyncio.Task[Any] | None = None
        self._debounce_waiters: list[asyncio.Future[Any]] = []
        self._debounce_rounds: set[asyncio.Task[Any]] = set()

        if handlers is not None:
            match handlers:
                case Sequence():
                    for handler in handlers:
                        self.add_handler(handler)
                case _:
                    # Single handler
                    self.add_handler(handlers)

    async def __call__(self, *args: Any, **kwargs: Any) -> Any:
        """Execute all handlers with the configured mode and debouncing.

        Returns:
            - For "sequential"/"parallel": list[Any] (handler results)
            - For "task": list[asyncio.Task[Any]] (task objects)
        """
        if self._debounce_delay is not None:
            return await self._execute_debounced(self._mode, *args, **kwargs)
        return await self._execute_handlers(self._mode, *args, **kwargs)

    @overload
    async def call_handlers(
        self, mode: Literal["task"], *args: Any, **kwargs: Any
    ) -> list[asyncio.Task[Any]]: ...

    @overload
    async def call_handlers(
        self, mode: Literal["sequential", "parallel"], *args: Any, **kwargs: Any
    ) -> list[Any]: ...

    async def call_handlers(
        self, mode: ExecutionMode, *args: Any, **kwargs: Any
    ) -> list[Any] | list[asyncio.Task[Any]]:
        """Execute handlers with explicit mode, bypassing configured mode and debouncing.

        Args:
            mode: Execution mode to use for this call
            *args: Arguments to pass to handlers
            **kwargs: Keyword arguments to pass to handlers

        Returns:
            - For "sequential"/"parallel": list[Any] (handler results)
            - For "task": list[asyncio.Task[Any]] (task objects)
        """
        return await self._execute_handlers(mode, *args, **kwargs)

    async def _execute_debounced(
        self, mode: ExecutionMode, *args: Any, **kwargs: Any
    ) -> list[Any] | list[asyncio.Task[Any]]:
        """Execute handlers with debouncing.

        A call within the delay replaces the pending one. Callers of replaced
        calls get the result of the call that runs (they are not cancelled).
        """
        if self._debounce_task is not None and not self._debounce_task.done():
            self._debounce_task.cancel()
        waiter: asyncio.Future[Any] = asyncio.get_running_loop().create_future()
        self._debounce_waiters.append(waiter)
        task = asyncio.create_task(self._debounce_round(mode, args, kwargs))
        self._debounce_task = task
        self._debounce_rounds.add(task)
        task.add_done_callback(self._debounce_rounds.discard)
        return await waiter  # type: ignore[no-any-return]

    async def _debounce_round(
        self, mode: ExecutionMode, args: tuple[Any, ...], kwargs: dict[str, Any]
    ) -> None:
        if self._debounce_delay is not None:
            await anyio.sleep(self._debounce_delay)
        # Past the delay: this round runs for the callers so far; later calls start
        # a new round instead of cancelling this one.
        waiters, self._debounce_waiters = self._debounce_waiters, []
        if self._debounce_task is asyncio.current_task():
            self._debounce_task = None
        try:
            result = await self._execute_handlers(mode, *args, **kwargs)
        except BaseException as exc:
            for waiter in waiters:
                if waiter.done():
                    continue
                if isinstance(exc, asyncio.CancelledError):
                    waiter.cancel()
                else:
                    waiter.set_exception(exc)
            if not isinstance(exc, Exception):
                raise
            return  # delivered to the callers; the round task itself ends cleanly
        for waiter in waiters:
            if not waiter.done():
                waiter.set_result(result)

    async def _execute_handlers(
        self, mode: ExecutionMode, *args: Any, **kwargs: Any
    ) -> list[Any] | list[asyncio.Task[Any]]:
        """Execute handlers with specified mode."""
        if not self._wrapped_handlers:
            return []

        match mode:
            case "sequential":
                return await self._execute_sequential(*args, **kwargs)
            case "parallel":
                return await self._execute_parallel(*args, **kwargs)
            case "task":
                return self._execute_as_tasks(*args, **kwargs)

    async def _execute_sequential(self, *args: Any, **kwargs: Any) -> list[Any]:
        """Execute handlers sequentially."""
        return [await handler(*args, **kwargs) for handler in self._wrapped_handlers]

    async def _execute_parallel(self, *args: Any, **kwargs: Any) -> list[Any]:
        """Execute handlers in parallel using asyncio.gather."""
        tasks = [handler(*args, **kwargs) for handler in self._wrapped_handlers]
        return await asyncio.gather(*tasks)

    def _execute_as_tasks(self, *args: Any, **kwargs: Any) -> list[asyncio.Task[Any]]:
        """Execute handlers as background tasks (non-blocking)."""
        tasks: list[asyncio.Task[Any]] = []
        for handler in self._wrapped_handlers:
            result = handler(*args, **kwargs)
            # Ensure we have a coroutine for asyncio.create_task
            if inspect.iscoroutine(result):
                task = asyncio.create_task(result)
            else:
                # If it's not a coroutine, wrap it in one
                async def wrapper(captured_result: Any = result) -> Any:
                    return captured_result

                task = asyncio.create_task(wrapper())
            tasks.append(task)
        return tasks

    def add_handler(self, handler: HandlerT) -> None:
        """Add a new handler to the manager.

        Both sync and async handlers are supported.
        """
        if handler in self._handlers:
            return

        # Check if handler is already async (function or callable class)
        if inspect.iscoroutinefunction(handler):
            wrapped_handler = handler
        elif callable(handler) and inspect.iscoroutinefunction(handler.__call__):
            wrapped_handler = handler.__call__
        else:
            # Wrap sync handler
            wrapped_handler = self._wrap_sync_handler(handler)  # type: ignore[assignment]

        self._handlers.append(handler)
        self._wrapped_handlers.append(wrapped_handler)
        self._handler_mapping[handler] = wrapped_handler

    def remove_handler(self, handler: HandlerT) -> None:
        """Remove a handler from the manager.

        Note: For sync handlers, you must pass the original sync function,
        not the wrapped async version.
        """
        if handler not in self._handlers:
            return

        with contextlib.suppress(ValueError):
            # Remove from all tracking structures
            wrapped_handler = self._handler_mapping[handler]
            self._handlers.remove(handler)
            self._wrapped_handlers.remove(wrapped_handler)
            del self._handler_mapping[handler]

    def _wrap_sync_handler(self, handler: HandlerT) -> Callable[..., Awaitable[Any]]:
        """Wrap a synchronous handler to work with async interface."""

        async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
            return handler(*args, **kwargs)

        return async_wrapper

    def clear(self) -> None:
        """Remove all handlers."""
        self._handlers.clear()
        self._wrapped_handlers.clear()
        self._handler_mapping.clear()

    @property
    def mode(self) -> Mode:
        """Current execution mode."""
        return self._mode

    @property
    def debounce_delay(self) -> float | None:
        """Current debounce delay in seconds."""
        return self._debounce_delay

    @debounce_delay.setter
    def debounce_delay(self, value: float | None) -> None:
        """Set debounce delay in seconds."""
        self._debounce_delay = value

    def __len__(self) -> int:
        """Return number of handlers."""
        return len(self._handlers)

    def __bool__(self) -> bool:
        """Return True if there are handlers registered."""
        return bool(self._handlers)

    def __repr__(self) -> str:
        """Return string representation showing handlers, mode, and debounce."""
        handler_names = [
            h.__qualname__ if hasattr(h, "__qualname__") else repr(h) for h in self._handlers
        ]
        debounce_info = f", debounce={self._debounce_delay}s" if self._debounce_delay else ""
        return f"MultiEventHandler(handlers={handler_names}, mode={self._mode!r}{debounce_info})"

debounce_delay property writable

debounce_delay: float | None

Current debounce delay in seconds.

mode property

mode: Mode

Current execution mode.

__bool__

__bool__() -> bool

Return True if there are handlers registered.

Source code in src/anyenv/calling/multieventhandler.py
def __bool__(self) -> bool:
    """Return True if there are handlers registered."""
    return bool(self._handlers)

__call__ async

__call__(*args: Any, **kwargs: Any) -> Any

Execute all handlers with the configured mode and debouncing.

Returns:

Type Description
Any
  • For "sequential"/"parallel": list[Any] (handler results)
Any
  • For "task": list[asyncio.Task[Any]] (task objects)
Source code in src/anyenv/calling/multieventhandler.py
async def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Execute all handlers with the configured mode and debouncing.

    Returns:
        - For "sequential"/"parallel": list[Any] (handler results)
        - For "task": list[asyncio.Task[Any]] (task objects)
    """
    if self._debounce_delay is not None:
        return await self._execute_debounced(self._mode, *args, **kwargs)
    return await self._execute_handlers(self._mode, *args, **kwargs)

__len__

__len__() -> int

Return number of handlers.

Source code in src/anyenv/calling/multieventhandler.py
def __len__(self) -> int:
    """Return number of handlers."""
    return len(self._handlers)

__repr__

__repr__() -> str

Return string representation showing handlers, mode, and debounce.

Source code in src/anyenv/calling/multieventhandler.py
def __repr__(self) -> str:
    """Return string representation showing handlers, mode, and debounce."""
    handler_names = [
        h.__qualname__ if hasattr(h, "__qualname__") else repr(h) for h in self._handlers
    ]
    debounce_info = f", debounce={self._debounce_delay}s" if self._debounce_delay else ""
    return f"MultiEventHandler(handlers={handler_names}, mode={self._mode!r}{debounce_info})"

add_handler

add_handler(handler: HandlerT) -> None

Add a new handler to the manager.

Both sync and async handlers are supported.

Source code in src/anyenv/calling/multieventhandler.py
def add_handler(self, handler: HandlerT) -> None:
    """Add a new handler to the manager.

    Both sync and async handlers are supported.
    """
    if handler in self._handlers:
        return

    # Check if handler is already async (function or callable class)
    if inspect.iscoroutinefunction(handler):
        wrapped_handler = handler
    elif callable(handler) and inspect.iscoroutinefunction(handler.__call__):
        wrapped_handler = handler.__call__
    else:
        # Wrap sync handler
        wrapped_handler = self._wrap_sync_handler(handler)  # type: ignore[assignment]

    self._handlers.append(handler)
    self._wrapped_handlers.append(wrapped_handler)
    self._handler_mapping[handler] = wrapped_handler

call_handlers async

call_handlers(mode: Literal['task'], *args: Any, **kwargs: Any) -> list[Task[Any]]
call_handlers(mode: Literal['sequential', 'parallel'], *args: Any, **kwargs: Any) -> list[Any]
call_handlers(mode: ExecutionMode, *args: Any, **kwargs: Any) -> list[Any] | list[Task[Any]]

Execute handlers with explicit mode, bypassing configured mode and debouncing.

Parameters:

Name Type Description Default
mode ExecutionMode

Execution mode to use for this call

required
*args Any

Arguments to pass to handlers

()
**kwargs Any

Keyword arguments to pass to handlers

{}

Returns:

Type Description
list[Any] | list[Task[Any]]
  • For "sequential"/"parallel": list[Any] (handler results)
list[Any] | list[Task[Any]]
  • For "task": list[asyncio.Task[Any]] (task objects)
Source code in src/anyenv/calling/multieventhandler.py
async def call_handlers(
    self, mode: ExecutionMode, *args: Any, **kwargs: Any
) -> list[Any] | list[asyncio.Task[Any]]:
    """Execute handlers with explicit mode, bypassing configured mode and debouncing.

    Args:
        mode: Execution mode to use for this call
        *args: Arguments to pass to handlers
        **kwargs: Keyword arguments to pass to handlers

    Returns:
        - For "sequential"/"parallel": list[Any] (handler results)
        - For "task": list[asyncio.Task[Any]] (task objects)
    """
    return await self._execute_handlers(mode, *args, **kwargs)

clear

clear() -> None

Remove all handlers.

Source code in src/anyenv/calling/multieventhandler.py
def clear(self) -> None:
    """Remove all handlers."""
    self._handlers.clear()
    self._wrapped_handlers.clear()
    self._handler_mapping.clear()

remove_handler

remove_handler(handler: HandlerT) -> None

Remove a handler from the manager.

Note: For sync handlers, you must pass the original sync function, not the wrapped async version.

Source code in src/anyenv/calling/multieventhandler.py
def remove_handler(self, handler: HandlerT) -> None:
    """Remove a handler from the manager.

    Note: For sync handlers, you must pass the original sync function,
    not the wrapped async version.
    """
    if handler not in self._handlers:
        return

    with contextlib.suppress(ValueError):
        # Remove from all tracking structures
        wrapped_handler = self._handler_mapping[handler]
        self._handlers.remove(handler)
        self._wrapped_handlers.remove(wrapped_handler)
        del self._handler_mapping[handler]

ProcessManager

Bases: ProcessManagerProtocol

Manages background processes for an agent pool.

Source code in src/anyenv/process_manager/process_manager.py
class ProcessManager(ProcessManagerProtocol):
    """Manages background processes for an agent pool."""

    def __init__(self) -> None:
        """Initialize process manager."""
        self._processes: dict[str, RunningProcess] = {}
        self._output_tasks: dict[str, asyncio.Task[None]] = {}

    @property
    def processes(self) -> dict[str, RunningProcess]:
        """Get the running processes."""
        return self._processes

    @property
    def output_tasks(self) -> dict[str, asyncio.Task[None]]:
        """Get the output tasks."""
        return self._output_tasks

    async def start_process(
        self,
        command: str,
        args: list[str] | None = None,
        cwd: str | Path | None = None,
        env: dict[str, str] | None = None,
        output_limit: int | None = None,
    ) -> str:
        """Start a background process.

        Args:
            command: Command to execute. When args is None/empty, this is
                interpreted as a shell command string (supporting pipes,
                redirects, etc.). When args is provided, command is the
                program name executed directly.
            args: Command arguments. If provided, command is executed directly
                with these arguments. If None/empty, command is run through
                the shell.
            cwd: Working directory
            env: Environment variables (added to current env)
            output_limit: Maximum bytes of output to retain

        Returns:
            Process ID for tracking

        Raises:
            OSError: If process creation fails
        """
        process_id = f"proc_{uuid.uuid4().hex[:8]}"
        proc_env = dict(os.environ)
        if env:
            proc_env.update(env)
        work_dir = Path(cwd) if cwd else None
        try:
            if args:
                # Direct execution with explicit args
                process = await create_process(
                    command,
                    *args,
                    cwd=work_dir,
                    env=proc_env,
                    stdout="pipe",
                    stderr="pipe",
                    # Own process group: kill() reaches the children of a shell too.
                    start_new_session=True,
                )
            else:
                # Shell execution for command strings (supports pipes, redirects, etc.)
                process = await create_shell_process(
                    command,
                    cwd=work_dir,
                    env=proc_env,
                    stdout="pipe",
                    stderr="pipe",
                    # Own process group: kill() reaches the children of a shell too.
                    start_new_session=True,
                )
            args = args or []

            # Create tracking object
            running_proc = RunningProcess(
                process_id=process_id,
                command=command,
                args=args,
                cwd=work_dir,
                env=env or {},
                process=process,
                output_limit=output_limit,
            )
            self._processes[process_id] = running_proc
            # Start output collection task
            self._output_tasks[process_id] = asyncio.create_task(self._collect_output(running_proc))
            logger.info("Started process %s: %s %s", process_id, command, " ".join(args))
        except Exception as e:
            msg = f"Failed to start process: {command} {' '.join(args or [])}"
            logger.exception(msg, exc_info=e)
            raise OSError(msg) from e
        else:
            return process_id

    async def _collect_output(self, proc: RunningProcess) -> None:
        """Collect output from process in background."""

        async def pump(stream: asyncio.StreamReader | None, name: str) -> None:
            if stream is None:
                return
            # Incremental: a character split across two reads decodes intact.
            decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
            while data := await stream.read(8192):
                if text := decoder.decode(data):
                    proc.add_output(**{name: text})
            if text := decoder.decode(b"", final=True):
                proc.add_output(**{name: text})

        try:
            await asyncio.gather(
                pump(proc.process.stdout, "stdout"), pump(proc.process.stderr, "stderr")
            )
        except Exception:
            logger.exception("Error collecting output for %s", proc.process_id)

    async def get_output(self, process_id: str) -> ProcessOutput:
        """Get current output from a process.

        Args:
            process_id: Process identifier

        Returns:
            Current process output

        Raises:
            ValueError: If process not found
        """
        if process_id not in self._processes:
            msg = f"Process {process_id} not found"
            raise ValueError(msg)

        proc = self._processes[process_id]
        return proc.get_output()

    async def wait_for_exit(self, process_id: str) -> int:
        """Wait for process to complete.

        Args:
            process_id: Process identifier

        Returns:
            Exit code

        Raises:
            ValueError: If process not found
        """
        if process_id not in self._processes:
            msg = f"Process {process_id} not found"
            raise ValueError(msg)

        proc = self._processes[process_id]
        exit_code = await proc.wait_for_exit()
        if process_id in self._output_tasks:
            await self._output_tasks[process_id]

        return exit_code

    async def kill_process(self, process_id: str) -> None:
        """Kill a running process.

        Args:
            process_id: Process identifier

        Raises:
            ValueError: If process not found
        """
        if process_id not in self._processes:
            msg = f"Process {process_id} not found"
            raise ValueError(msg)

        proc = self._processes[process_id]
        await proc.kill()
        if process_id in self._output_tasks:
            self._output_tasks[process_id].cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await self._output_tasks[process_id]

        logger.info("Killed process %s", process_id)

    async def release_process(self, process_id: str) -> None:
        """Release resources for a process.

        Args:
            process_id: Process identifier

        Raises:
            ValueError: If process not found
        """
        if process_id not in self._processes:
            msg = f"Process {process_id} not found"
            raise ValueError(msg)
        proc = self._processes[process_id]
        if await proc.is_running():
            await proc.kill()
        if process_id in self._output_tasks:
            self._output_tasks[process_id].cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await self._output_tasks[process_id]
            del self._output_tasks[process_id]

        del self._processes[process_id]
        logger.info("Released process %s", process_id)

    async def list_processes(self) -> list[str]:
        """List all tracked process IDs."""
        return list(self._processes.keys())

    async def get_process_info(self, process_id: str) -> dict[str, Any]:
        """Get information about a process.

        Args:
            process_id: Process identifier

        Returns:
            Process information dict

        Raises:
            ValueError: If process not found
        """
        if process_id not in self._processes:
            msg = f"Process {process_id} not found"
            raise ValueError(msg)

        proc = self._processes[process_id]
        return {
            "process_id": process_id,
            "command": proc.command,
            "args": proc.args,
            "cwd": str(proc.cwd) if proc.cwd else None,
            "created_at": proc.created_at.isoformat(),
            "is_running": await proc.is_running(),
            "exit_code": proc.process.returncode,
            "output_limit": proc.output_limit,
        }

    async def cleanup(self) -> None:
        """Clean up all processes."""
        logger.info("Cleaning up %s processes", len(self._processes))
        # Concurrently: each gets SIGTERM, then SIGKILL after the grace period.
        await asyncio.gather(
            *(proc.kill() for proc in self._processes.values()), return_exceptions=True
        )

        if self._output_tasks:
            for task in self._output_tasks.values():
                task.cancel()
            await asyncio.gather(*self._output_tasks.values(), return_exceptions=True)

        # Clear all tracking
        self._processes.clear()
        self._output_tasks.clear()
        logger.info("Process cleanup completed")

output_tasks property

output_tasks: dict[str, Task[None]]

Get the output tasks.

processes property

processes: dict[str, RunningProcess]

Get the running processes.

__init__

__init__() -> None

Initialize process manager.

Source code in src/anyenv/process_manager/process_manager.py
def __init__(self) -> None:
    """Initialize process manager."""
    self._processes: dict[str, RunningProcess] = {}
    self._output_tasks: dict[str, asyncio.Task[None]] = {}

cleanup async

cleanup() -> None

Clean up all processes.

Source code in src/anyenv/process_manager/process_manager.py
async def cleanup(self) -> None:
    """Clean up all processes."""
    logger.info("Cleaning up %s processes", len(self._processes))
    # Concurrently: each gets SIGTERM, then SIGKILL after the grace period.
    await asyncio.gather(
        *(proc.kill() for proc in self._processes.values()), return_exceptions=True
    )

    if self._output_tasks:
        for task in self._output_tasks.values():
            task.cancel()
        await asyncio.gather(*self._output_tasks.values(), return_exceptions=True)

    # Clear all tracking
    self._processes.clear()
    self._output_tasks.clear()
    logger.info("Process cleanup completed")

get_output async

get_output(process_id: str) -> ProcessOutput

Get current output from a process.

Parameters:

Name Type Description Default
process_id str

Process identifier

required

Returns:

Type Description
ProcessOutput

Current process output

Raises:

Type Description
ValueError

If process not found

Source code in src/anyenv/process_manager/process_manager.py
async def get_output(self, process_id: str) -> ProcessOutput:
    """Get current output from a process.

    Args:
        process_id: Process identifier

    Returns:
        Current process output

    Raises:
        ValueError: If process not found
    """
    if process_id not in self._processes:
        msg = f"Process {process_id} not found"
        raise ValueError(msg)

    proc = self._processes[process_id]
    return proc.get_output()

get_process_info async

get_process_info(process_id: str) -> dict[str, Any]

Get information about a process.

Parameters:

Name Type Description Default
process_id str

Process identifier

required

Returns:

Type Description
dict[str, Any]

Process information dict

Raises:

Type Description
ValueError

If process not found

Source code in src/anyenv/process_manager/process_manager.py
async def get_process_info(self, process_id: str) -> dict[str, Any]:
    """Get information about a process.

    Args:
        process_id: Process identifier

    Returns:
        Process information dict

    Raises:
        ValueError: If process not found
    """
    if process_id not in self._processes:
        msg = f"Process {process_id} not found"
        raise ValueError(msg)

    proc = self._processes[process_id]
    return {
        "process_id": process_id,
        "command": proc.command,
        "args": proc.args,
        "cwd": str(proc.cwd) if proc.cwd else None,
        "created_at": proc.created_at.isoformat(),
        "is_running": await proc.is_running(),
        "exit_code": proc.process.returncode,
        "output_limit": proc.output_limit,
    }

kill_process async

kill_process(process_id: str) -> None

Kill a running process.

Parameters:

Name Type Description Default
process_id str

Process identifier

required

Raises:

Type Description
ValueError

If process not found

Source code in src/anyenv/process_manager/process_manager.py
async def kill_process(self, process_id: str) -> None:
    """Kill a running process.

    Args:
        process_id: Process identifier

    Raises:
        ValueError: If process not found
    """
    if process_id not in self._processes:
        msg = f"Process {process_id} not found"
        raise ValueError(msg)

    proc = self._processes[process_id]
    await proc.kill()
    if process_id in self._output_tasks:
        self._output_tasks[process_id].cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self._output_tasks[process_id]

    logger.info("Killed process %s", process_id)

list_processes async

list_processes() -> list[str]

List all tracked process IDs.

Source code in src/anyenv/process_manager/process_manager.py
async def list_processes(self) -> list[str]:
    """List all tracked process IDs."""
    return list(self._processes.keys())

release_process async

release_process(process_id: str) -> None

Release resources for a process.

Parameters:

Name Type Description Default
process_id str

Process identifier

required

Raises:

Type Description
ValueError

If process not found

Source code in src/anyenv/process_manager/process_manager.py
async def release_process(self, process_id: str) -> None:
    """Release resources for a process.

    Args:
        process_id: Process identifier

    Raises:
        ValueError: If process not found
    """
    if process_id not in self._processes:
        msg = f"Process {process_id} not found"
        raise ValueError(msg)
    proc = self._processes[process_id]
    if await proc.is_running():
        await proc.kill()
    if process_id in self._output_tasks:
        self._output_tasks[process_id].cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await self._output_tasks[process_id]
        del self._output_tasks[process_id]

    del self._processes[process_id]
    logger.info("Released process %s", process_id)

start_process async

start_process(
    command: str,
    args: list[str] | None = None,
    cwd: str | Path | None = None,
    env: dict[str, str] | None = None,
    output_limit: int | None = None,
) -> str

Start a background process.

Parameters:

Name Type Description Default
command str

Command to execute. When args is None/empty, this is interpreted as a shell command string (supporting pipes, redirects, etc.). When args is provided, command is the program name executed directly.

required
args list[str] | None

Command arguments. If provided, command is executed directly with these arguments. If None/empty, command is run through the shell.

None
cwd str | Path | None

Working directory

None
env dict[str, str] | None

Environment variables (added to current env)

None
output_limit int | None

Maximum bytes of output to retain

None

Returns:

Type Description
str

Process ID for tracking

Raises:

Type Description
OSError

If process creation fails

Source code in src/anyenv/process_manager/process_manager.py
async def start_process(
    self,
    command: str,
    args: list[str] | None = None,
    cwd: str | Path | None = None,
    env: dict[str, str] | None = None,
    output_limit: int | None = None,
) -> str:
    """Start a background process.

    Args:
        command: Command to execute. When args is None/empty, this is
            interpreted as a shell command string (supporting pipes,
            redirects, etc.). When args is provided, command is the
            program name executed directly.
        args: Command arguments. If provided, command is executed directly
            with these arguments. If None/empty, command is run through
            the shell.
        cwd: Working directory
        env: Environment variables (added to current env)
        output_limit: Maximum bytes of output to retain

    Returns:
        Process ID for tracking

    Raises:
        OSError: If process creation fails
    """
    process_id = f"proc_{uuid.uuid4().hex[:8]}"
    proc_env = dict(os.environ)
    if env:
        proc_env.update(env)
    work_dir = Path(cwd) if cwd else None
    try:
        if args:
            # Direct execution with explicit args
            process = await create_process(
                command,
                *args,
                cwd=work_dir,
                env=proc_env,
                stdout="pipe",
                stderr="pipe",
                # Own process group: kill() reaches the children of a shell too.
                start_new_session=True,
            )
        else:
            # Shell execution for command strings (supports pipes, redirects, etc.)
            process = await create_shell_process(
                command,
                cwd=work_dir,
                env=proc_env,
                stdout="pipe",
                stderr="pipe",
                # Own process group: kill() reaches the children of a shell too.
                start_new_session=True,
            )
        args = args or []

        # Create tracking object
        running_proc = RunningProcess(
            process_id=process_id,
            command=command,
            args=args,
            cwd=work_dir,
            env=env or {},
            process=process,
            output_limit=output_limit,
        )
        self._processes[process_id] = running_proc
        # Start output collection task
        self._output_tasks[process_id] = asyncio.create_task(self._collect_output(running_proc))
        logger.info("Started process %s: %s %s", process_id, command, " ".join(args))
    except Exception as e:
        msg = f"Failed to start process: {command} {' '.join(args or [])}"
        logger.exception(msg, exc_info=e)
        raise OSError(msg) from e
    else:
        return process_id

wait_for_exit async

wait_for_exit(process_id: str) -> int

Wait for process to complete.

Parameters:

Name Type Description Default
process_id str

Process identifier

required

Returns:

Type Description
int

Exit code

Raises:

Type Description
ValueError

If process not found

Source code in src/anyenv/process_manager/process_manager.py
async def wait_for_exit(self, process_id: str) -> int:
    """Wait for process to complete.

    Args:
        process_id: Process identifier

    Returns:
        Exit code

    Raises:
        ValueError: If process not found
    """
    if process_id not in self._processes:
        msg = f"Process {process_id} not found"
        raise ValueError(msg)

    proc = self._processes[process_id]
    exit_code = await proc.wait_for_exit()
    if process_id in self._output_tasks:
        await self._output_tasks[process_id]

    return exit_code

ProcessOutput dataclass

Output from a running process.

Source code in src/anyenv/process_manager/models.py
@dataclass
class ProcessOutput:
    """Output from a running process."""

    stdout: str
    stderr: str
    combined: str
    truncated: bool = False
    exit_code: int | None = None
    signal: str | None = None

RequestError

Bases: HttpError

Exception raised when a request fails due to network or connection issues.

Source code in src/anyenv/download/exceptions.py
class RequestError(HttpError):
    """Exception raised when a request fails due to network or connection issues."""

    def __init__(self, message: str, original_error: Exception | None = None) -> None:
        super().__init__(message)
        self.__cause__ = original_error

ResponseError

Bases: HttpError

Exception raised when a response contains an error status code.

Source code in src/anyenv/download/exceptions.py
class ResponseError(HttpError):
    """Exception raised when a response contains an error status code."""

    def __init__(self, message: str, response: HttpResponse) -> None:
        super().__init__(message, response)
        self.status_code = response.status_code

RunningProcess dataclass

Represents a running background process.

Source code in src/anyenv/process_manager/process.py
@dataclass
class RunningProcess:
    """Represents a running background process."""

    process_id: str
    command: str
    args: list[str]
    process: asyncio.subprocess.Process
    cwd: Path | None = None
    env: dict[str, str] = field(default_factory=dict)
    created_at: datetime = field(default_factory=datetime.now)
    output_limit: int | None = None
    _stdout_buffer: list[str] = field(default_factory=list)
    _stderr_buffer: list[str] = field(default_factory=list)
    _output_size: int = 0
    _truncated: bool = False

    def add_output(self, stdout: str = "", stderr: str = "") -> None:
        """Add output to buffers, applying size limits."""
        if stdout:
            self._stdout_buffer.append(stdout)
            self._output_size += len(stdout.encode())
        if stderr:
            self._stderr_buffer.append(stderr)
            self._output_size += len(stderr.encode())

        # Apply truncation if limit exceeded
        if self.output_limit and self._output_size > self.output_limit:
            self._truncate_output()
            self._truncated = True

    def _truncate_output(self) -> None:
        """Drop output from the beginning, keeping the combined tail within the limit.

        The budget (90% of the limit, in bytes) is shared: a stream that needs less
        than half keeps all of it, the other gets the rest.
        """
        if not self.output_limit:
            return

        all_stdout = "".join(self._stdout_buffer).encode()
        all_stderr = "".join(self._stderr_buffer).encode()
        budget = int(self.output_limit * 0.9)  # Keep 90% of limit
        stderr_budget = min(len(all_stderr), max(budget // 2, budget - len(all_stdout)))
        stdout_budget = budget - stderr_budget
        stdout = _tail(all_stdout, stdout_budget)
        stderr = _tail(all_stderr, stderr_budget)
        self._stdout_buffer = [stdout] if stdout else []
        self._stderr_buffer = [stderr] if stderr else []
        self._output_size = len(stdout.encode()) + len(stderr.encode())

    def get_output(self) -> ProcessOutput:
        """Get current process output."""
        stdout = "".join(self._stdout_buffer)
        stderr = "".join(self._stderr_buffer)
        combined = stdout + stderr
        return ProcessOutput(
            stdout=stdout,
            stderr=stderr,
            combined=combined,
            truncated=self._truncated,
            exit_code=self.process.returncode,
            signal=None,  # TODO: Extract signal info if available,
        )

    async def is_running(self) -> bool:
        """Check if process is still running."""
        return self.process.returncode is None

    async def wait_for_exit(self) -> int:
        """Wait for process to complete and return exit code."""
        return await self.process.wait()

    async def kill(self) -> None:
        """Terminate the process and its children (SIGTERM, then SIGKILL)."""
        if await self.is_running():
            await hard_kill(self.process)

add_output

add_output(stdout: str = '', stderr: str = '') -> None

Add output to buffers, applying size limits.

Source code in src/anyenv/process_manager/process.py
def add_output(self, stdout: str = "", stderr: str = "") -> None:
    """Add output to buffers, applying size limits."""
    if stdout:
        self._stdout_buffer.append(stdout)
        self._output_size += len(stdout.encode())
    if stderr:
        self._stderr_buffer.append(stderr)
        self._output_size += len(stderr.encode())

    # Apply truncation if limit exceeded
    if self.output_limit and self._output_size > self.output_limit:
        self._truncate_output()
        self._truncated = True

get_output

get_output() -> ProcessOutput

Get current process output.

Source code in src/anyenv/process_manager/process.py
def get_output(self) -> ProcessOutput:
    """Get current process output."""
    stdout = "".join(self._stdout_buffer)
    stderr = "".join(self._stderr_buffer)
    combined = stdout + stderr
    return ProcessOutput(
        stdout=stdout,
        stderr=stderr,
        combined=combined,
        truncated=self._truncated,
        exit_code=self.process.returncode,
        signal=None,  # TODO: Extract signal info if available,
    )

is_running async

is_running() -> bool

Check if process is still running.

Source code in src/anyenv/process_manager/process.py
async def is_running(self) -> bool:
    """Check if process is still running."""
    return self.process.returncode is None

kill async

kill() -> None

Terminate the process and its children (SIGTERM, then SIGKILL).

Source code in src/anyenv/process_manager/process.py
async def kill(self) -> None:
    """Terminate the process and its children (SIGTERM, then SIGKILL)."""
    if await self.is_running():
        await hard_kill(self.process)

wait_for_exit async

wait_for_exit() -> int

Wait for process to complete and return exit code.

Source code in src/anyenv/process_manager/process.py
async def wait_for_exit(self) -> int:
    """Wait for process to complete and return exit code."""
    return await self.process.wait()

ThreadGroup

Class that executes functions in parallel, with TaskGroup-like API.

Source code in src/anyenv/calling/threadgroup.py
class ThreadGroup[R = Any]:
    """Class that executes functions in parallel, with TaskGroup-like API."""

    def __init__(
        self,
        max_workers: int | None = None,
        raise_exceptions: bool = True,
        preserve_context: bool = False,
    ) -> None:
        """Thread task group that executes functions in parallel.

        Supports both sync and async context managers.

        Args:
            max_workers: Maximum number of worker threads
            raise_exceptions: If True, raises exceptions from tasks
            preserve_context: If True, preserves context variables across threads
        """
        self.max_workers = max_workers
        self.raise_exceptions = raise_exceptions
        self.preserve_context = preserve_context

        if preserve_context:
            self.executor: ThreadPoolExecutor = ContextExecutor(max_workers=self.max_workers)
        else:
            self.executor = ThreadPoolExecutor(max_workers=self.max_workers)

        self.futures: list[concurrent.futures.Future[R]] = []
        self._results: list[R] = []
        self._exceptions: list[Exception] = []
        self._logger = logging.getLogger(self.__class__.__name__)

    def spawn(
        self, func: Callable[..., R], *args: Any, **kwargs: Any
    ) -> concurrent.futures.Future[R]:
        """Submit a task immediately to the executor.

        Args:
            func: The function to execute
            *args: Positional arguments to pass to the function
            **kwargs: Keyword arguments to pass to the function

        Returns:
            Future object representing the execution of the function
        """
        future = self.executor.submit(func, *args, **kwargs)
        self.futures.append(future)
        return future

    def __enter__(self) -> ThreadGroup[R]:
        """Enter the context manager."""
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the context manager: wait for all tasks and shut the executor down.

        Results are collected in spawn order. On the first failure (with
        ``raise_exceptions``) tasks that haven't started are cancelled, the running
        ones are waited for, then the first failure in spawn order is raised.
        """
        futures, self.futures = self.futures, []
        try:
            done, _ = concurrent.futures.wait(
                futures, return_when=concurrent.futures.FIRST_EXCEPTION
            )
            if self.raise_exceptions and any(
                not f.cancelled() and f.exception() is not None for f in done
            ):
                for future in futures:
                    future.cancel()
            concurrent.futures.wait(futures)
        finally:
            self.executor.shutdown(wait=True)

        first_error: Exception | None = None
        for future in futures:
            if future.cancelled():
                continue
            try:
                self._results.append(future.result())
            except Exception as e:
                self._exceptions.append(e)
                self._logger.exception("Task error")
                first_error = first_error or e
        if first_error is not None and self.raise_exceptions:
            raise first_error

    async def __aenter__(self) -> ThreadGroup[R]:
        """Enter the async context manager."""
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit the async context manager, waiting without blocking the event loop."""
        await asyncio.to_thread(self.__exit__, exc_type, exc_val, exc_tb)

    def shutdown(self) -> None:
        """Shutdown the executor when done with the ThreadGroup."""
        self.executor.shutdown()

    @property
    def results(self) -> list[R]:
        """List of results from completed tasks."""
        return self._results

    @property
    def exceptions(self) -> list[Exception]:
        """List of exceptions raised by tasks."""
        return self._exceptions

exceptions property

exceptions: list[Exception]

List of exceptions raised by tasks.

results property

results: list[R]

List of results from completed tasks.

__aenter__ async

__aenter__() -> ThreadGroup[R]

Enter the async context manager.

Source code in src/anyenv/calling/threadgroup.py
async def __aenter__(self) -> ThreadGroup[R]:
    """Enter the async context manager."""
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit the async context manager, waiting without blocking the event loop.

Source code in src/anyenv/calling/threadgroup.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the async context manager, waiting without blocking the event loop."""
    await asyncio.to_thread(self.__exit__, exc_type, exc_val, exc_tb)

__enter__

__enter__() -> ThreadGroup[R]

Enter the context manager.

Source code in src/anyenv/calling/threadgroup.py
def __enter__(self) -> ThreadGroup[R]:
    """Enter the context manager."""
    return self

__exit__

__exit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Exit the context manager: wait for all tasks and shut the executor down.

Results are collected in spawn order. On the first failure (with raise_exceptions) tasks that haven't started are cancelled, the running ones are waited for, then the first failure in spawn order is raised.

Source code in src/anyenv/calling/threadgroup.py
def __exit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Exit the context manager: wait for all tasks and shut the executor down.

    Results are collected in spawn order. On the first failure (with
    ``raise_exceptions``) tasks that haven't started are cancelled, the running
    ones are waited for, then the first failure in spawn order is raised.
    """
    futures, self.futures = self.futures, []
    try:
        done, _ = concurrent.futures.wait(
            futures, return_when=concurrent.futures.FIRST_EXCEPTION
        )
        if self.raise_exceptions and any(
            not f.cancelled() and f.exception() is not None for f in done
        ):
            for future in futures:
                future.cancel()
        concurrent.futures.wait(futures)
    finally:
        self.executor.shutdown(wait=True)

    first_error: Exception | None = None
    for future in futures:
        if future.cancelled():
            continue
        try:
            self._results.append(future.result())
        except Exception as e:
            self._exceptions.append(e)
            self._logger.exception("Task error")
            first_error = first_error or e
    if first_error is not None and self.raise_exceptions:
        raise first_error

__init__

__init__(
    max_workers: int | None = None, raise_exceptions: bool = True, preserve_context: bool = False
) -> None

Thread task group that executes functions in parallel.

Supports both sync and async context managers.

Parameters:

Name Type Description Default
max_workers int | None

Maximum number of worker threads

None
raise_exceptions bool

If True, raises exceptions from tasks

True
preserve_context bool

If True, preserves context variables across threads

False
Source code in src/anyenv/calling/threadgroup.py
def __init__(
    self,
    max_workers: int | None = None,
    raise_exceptions: bool = True,
    preserve_context: bool = False,
) -> None:
    """Thread task group that executes functions in parallel.

    Supports both sync and async context managers.

    Args:
        max_workers: Maximum number of worker threads
        raise_exceptions: If True, raises exceptions from tasks
        preserve_context: If True, preserves context variables across threads
    """
    self.max_workers = max_workers
    self.raise_exceptions = raise_exceptions
    self.preserve_context = preserve_context

    if preserve_context:
        self.executor: ThreadPoolExecutor = ContextExecutor(max_workers=self.max_workers)
    else:
        self.executor = ThreadPoolExecutor(max_workers=self.max_workers)

    self.futures: list[concurrent.futures.Future[R]] = []
    self._results: list[R] = []
    self._exceptions: list[Exception] = []
    self._logger = logging.getLogger(self.__class__.__name__)

shutdown

shutdown() -> None

Shutdown the executor when done with the ThreadGroup.

Source code in src/anyenv/calling/threadgroup.py
def shutdown(self) -> None:
    """Shutdown the executor when done with the ThreadGroup."""
    self.executor.shutdown()

spawn

spawn(func: Callable[..., R], *args: Any, **kwargs: Any) -> Future[R]

Submit a task immediately to the executor.

Parameters:

Name Type Description Default
func Callable[..., R]

The function to execute

required
*args Any

Positional arguments to pass to the function

()
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
Future[R]

Future object representing the execution of the function

Source code in src/anyenv/calling/threadgroup.py
def spawn(
    self, func: Callable[..., R], *args: Any, **kwargs: Any
) -> concurrent.futures.Future[R]:
    """Submit a task immediately to the executor.

    Args:
        func: The function to execute
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        Future object representing the execution of the function
    """
    future = self.executor.submit(func, *args, **kwargs)
    self.futures.append(future)
    return future

TomlDumpError

Bases: Exception

Unified exception for all TOML serialization errors.

Source code in src/anyenv/toml_tools/base.py
class TomlDumpError(Exception):
    """Unified exception for all TOML serialization errors."""

TomlLoadError

Bases: Exception

Unified exception for all TOML parsing errors.

Source code in src/anyenv/toml_tools/base.py
class TomlLoadError(Exception):
    """Unified exception for all TOML parsing errors."""

    def __init__(
        self,
        message: str,
        *,
        line: int | None = None,
        column: int | None = None,
        source_path: str | Path | None = None,
        source_content: str | None = None,
    ) -> None:
        super().__init__(message)
        self.info = ParseErrorInfo(
            message=message,
            format_name="TOML Parse",
            line=line,
            column=column,
            source_path=source_path,
            source_content=source_content,
        )

    @property
    def line(self) -> int | None:
        """Line number where the error occurred."""
        return self.info.line

    @property
    def column(self) -> int | None:
        """Column number where the error occurred."""
        return self.info.column

    @property
    def source_path(self) -> str | Path | None:
        """Path to the source file that caused the error."""
        return self.info.source_path

    @property
    def source_content(self) -> str | None:
        """Source content that caused the error."""
        return self.info.source_content

    def format(self, context_lines: int = 2, use_color: bool = True) -> str:
        """Format error with source context for display.

        Args:
            context_lines: Number of lines to show before/after the error line.
            use_color: Whether to include ANSI color codes.
        """
        return self.info.format(context_lines=context_lines, use_color=use_color)

column property

column: int | None

Column number where the error occurred.

line property

line: int | None

Line number where the error occurred.

source_content property

source_content: str | None

Source content that caused the error.

source_path property

source_path: str | Path | None

Path to the source file that caused the error.

format

format(context_lines: int = 2, use_color: bool = True) -> str

Format error with source context for display.

Parameters:

Name Type Description Default
context_lines int

Number of lines to show before/after the error line.

2
use_color bool

Whether to include ANSI color codes.

True
Source code in src/anyenv/toml_tools/base.py
def format(self, context_lines: int = 2, use_color: bool = True) -> str:
    """Format error with source context for display.

    Args:
        context_lines: Number of lines to show before/after the error line.
        use_color: Whether to include ANSI color codes.
    """
    return self.info.format(context_lines=context_lines, use_color=use_color)

call_and_gather async

call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]],
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None,
    return_exceptions: Literal[True],
    limit: int | None = None,
) -> Sequence[T | BaseException]
call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    *,
    return_exceptions: Literal[True],
    limit: int | None = None,
) -> Sequence[T | BaseException]
call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    return_exceptions: Literal[False] = False,
    limit: int | None = None,
) -> Sequence[T]
call_and_gather(
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    return_exceptions: bool = False,
    limit: int | None = None,
) -> Sequence[T | BaseException]

Call multiple callables and gather their results concurrently.

This is a helper for the common pattern of calling multiple handlers/functions and gathering their results concurrently. Supports two modes:

  1. Broadcast mode: Same args/kwargs for all callables
  2. Per-callable mode: Different args/kwargs for each callable

Uses aioitertools.asyncio.gather if available for limit support, falls back to the local gather implementation otherwise.

Parameters:

Name Type Description Default
callables Sequence[Callable[..., Awaitable[T]]]

Sequence of callable objects that return awaitables

required
args tuple[Any, ...] | Sequence[tuple[Any, ...]]

Single tuple (broadcast) or sequence of tuples (per-callable)

()
kwargs dict[str, Any] | Sequence[dict[str, Any]] | None

Single dict (broadcast) or sequence of dicts (per-callable)

None
return_exceptions bool

If True, exceptions are returned instead of raised

False
limit int | None

Maximum concurrent tasks (None for unlimited, only with aioitertools)

None

Returns:

Type Description
Sequence[T | BaseException]

A sequence of results in the same order as the input callables

Source code in src/anyenv/async_run.py
async def call_and_gather[T](
    callables: Sequence[Callable[..., Awaitable[T]]],
    args: tuple[Any, ...] | Sequence[tuple[Any, ...]] = (),
    kwargs: dict[str, Any] | Sequence[dict[str, Any]] | None = None,
    return_exceptions: bool = False,
    limit: int | None = None,
) -> Sequence[T | BaseException]:
    """Call multiple callables and gather their results concurrently.

    This is a helper for the common pattern of calling multiple handlers/functions
    and gathering their results concurrently. Supports two modes:

    1. Broadcast mode: Same args/kwargs for all callables
    2. Per-callable mode: Different args/kwargs for each callable

    Uses aioitertools.asyncio.gather if available for limit support,
    falls back to the local gather implementation otherwise.

    Args:
        callables: Sequence of callable objects that return awaitables
        args: Single tuple (broadcast) or sequence of tuples (per-callable)
        kwargs: Single dict (broadcast) or sequence of dicts (per-callable)
        return_exceptions: If True, exceptions are returned instead of raised
        limit: Maximum concurrent tasks (None for unlimited, only with aioitertools)

    Returns:
        A sequence of results in the same order as the input callables
    """
    from aioitertools.asyncio import gather as aioitertools_gather

    if kwargs is None:
        kwargs = {}

    # Detect mode based on types
    args_is_broadcast = isinstance(args, tuple)
    kwargs_is_broadcast = isinstance(kwargs, dict)

    # Validate consistent mode
    if args_is_broadcast and not kwargs_is_broadcast:
        msg = "Mixed modes: args is broadcast (tuple) but kwargs is per-callable (sequence)"
        raise ValueError(msg)
    if not args_is_broadcast and kwargs_is_broadcast:
        msg = "Mixed modes: args is per-callable (sequence) but kwargs is broadcast (dict)"
        raise ValueError(msg)

    if args_is_broadcast and kwargs_is_broadcast:
        # Broadcast mode: same args/kwargs for all

        args_tuple = cast(tuple[Any, ...], args)
        kwargs_dict = cast(dict[str, Any], kwargs)
        coros = [callable_obj(*args_tuple, **kwargs_dict) for callable_obj in callables]
    else:
        # Per-callable mode: different args/kwargs for each

        args_seq = cast(Sequence[tuple[Any, ...]], args)
        kwargs_seq = cast(Sequence[dict[str, Any]], kwargs)

        if not (len(args_seq) == len(kwargs_seq) == len(callables)):
            msg = (
                f"Length mismatch: callables({len(callables)}), "
                f"args({len(args_seq)}), kwargs({len(kwargs_seq)}) must all be equal"
            )
            raise ValueError(msg)

        coros = [
            callable_obj(*call_args, **call_kwargs)
            for callable_obj, call_args, call_kwargs in zip(
                callables,
                args_seq,
                kwargs_seq,
                strict=True,
            )
        ]

    if limit is not None:
        # Use aioitertools.asyncio.gather with limit support
        return await aioitertools_gather(*coros, return_exceptions=return_exceptions, limit=limit)
    # Fall back to our local gather implementation
    if return_exceptions:
        return await gather(*coros, return_exceptions=True)
    return await gather(*coros, return_exceptions=False)

create_process async

create_process(
    command: str | PathLike[str],
    *args: str | PathLike[str],
    stdin: Mode | None = None,
    stdout: Mode | None = None,
    stderr: Mode | None = None,
    limit: int = 10 * 1024 * 1024,
    env: dict[str, str] | None = None,
    cwd: str | PathLike[str] | None = None,
    start_new_session: bool = False,
) -> Process

Small create_subprocess_exec wrapper.

Source code in src/anyenv/processes.py
async def create_process(
    command: str | os.PathLike[str],
    *args: str | os.PathLike[str],
    stdin: Mode | None = None,
    stdout: Mode | None = None,
    stderr: Mode | None = None,
    limit: int = 10 * 1024 * 1024,
    env: dict[str, str] | None = None,
    cwd: str | os.PathLike[str] | None = None,
    start_new_session: bool = False,
) -> Process:
    """Small create_subprocess_exec wrapper."""
    return await asyncio.create_subprocess_exec(
        command,
        *args,
        stdin=MAP[stdin] if stdin else None,
        stdout=MAP[stdout] if stdout else None,
        stderr=MAP[stderr] if stderr else None,
        limit=limit,
        cwd=cwd,
        env=env,
        start_new_session=start_new_session,
    )

create_shell_process async

create_shell_process(
    command: str,
    stdin: Mode | None = None,
    stdout: Mode | None = None,
    stderr: Mode | None = None,
    limit: int = 10 * 1024 * 1024,
    cwd: str | PathLike[str] | None = None,
    env: dict[str, str] | None = None,
    start_new_session: bool = False,
) -> Process

Small create_subprocess_shell wrapper.

Source code in src/anyenv/processes.py
async def create_shell_process(
    command: str,
    stdin: Mode | None = None,
    stdout: Mode | None = None,
    stderr: Mode | None = None,
    limit: int = 10 * 1024 * 1024,
    cwd: str | os.PathLike[str] | None = None,
    env: dict[str, str] | None = None,
    start_new_session: bool = False,
) -> Process:
    """Small create_subprocess_shell wrapper."""
    return await asyncio.create_subprocess_shell(
        command,
        stdin=MAP[stdin] if stdin else None,
        stdout=MAP[stdout] if stdout else None,
        stderr=MAP[stderr] if stderr else None,
        limit=limit,
        cwd=cwd,
        env=env,
        start_new_session=start_new_session,
    )

download_sync

download_sync(
    url: str,
    path: StrPath,
    *,
    headers: HeaderType | None = None,
    progress_callback: ProgressCallback | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
) -> None

Synchronous version of download.

Source code in src/anyenv/download/functional.py
def download_sync(
    url: str,
    path: StrPath,
    *,
    headers: HeaderType | None = None,
    progress_callback: ProgressCallback | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
) -> None:
    """Synchronous version of `download`."""
    from anyenv.async_run import run_sync

    coro = download(
        url,
        path,
        headers=headers,
        progress_callback=progress_callback,
        timeout=timeout,
        cache=cache,
        cache_dir=cache_dir,
        cache_ttl=cache_ttl,
    )
    run_sync(without_session(coro))

dump_json

dump_json(
    data: Any,
    indent: bool = False,
    naive_utc: bool = False,
    serialize_numpy: bool = False,
    sort_keys: bool = False,
    backend: BackendType = "auto",
) -> str

Serialize data to a JSON string.

Parameters:

Name Type Description Default
data Any

The data to serialize

required
indent bool

Whether to format the output with indentation

False
naive_utc bool

Whether to interpret naive datetime objects as UTC

False
serialize_numpy bool

Whether to serialize numpy arrays

False
sort_keys bool

Sort dictionary keys

False
backend BackendType

JSON backend to use for serialization

'auto'

Returns:

Type Description
str

The serialized JSON string

Raises:

Type Description
JsonDumpError

If serialization fails

Source code in src/anyenv/json_tools/__init__.py
def dump_json(
    data: Any,
    indent: bool = False,
    naive_utc: bool = False,
    serialize_numpy: bool = False,
    sort_keys: bool = False,
    backend: BackendType = "auto",
) -> str:
    """Serialize data to a JSON string.

    Args:
        data: The data to serialize
        indent: Whether to format the output with indentation
        naive_utc: Whether to interpret naive datetime objects as UTC
        serialize_numpy: Whether to serialize numpy arrays
        sort_keys: Sort dictionary keys
        backend: JSON backend to use for serialization

    Returns:
        The serialized JSON string

    Raises:
        JsonDumpError: If serialization fails
    """
    provider = get_json_provider(backend)
    return provider.dump_json(
        data,
        indent=indent,
        naive_utc=naive_utc,
        serialize_numpy=serialize_numpy,
        sort_keys=sort_keys,
    )

dump_toml

dump_toml(data: Any, *, pretty: bool = False, backend: BackendType = 'auto') -> str

Serialize data to a TOML string.

Parameters:

Name Type Description Default
data Any

The data to serialize

required
pretty bool

Whether to format the output with pretty formatting

False
backend BackendType

TOML backend to use for serialization

'auto'

Returns:

Type Description
str

The serialized TOML string

Raises:

Type Description
TomlDumpError

If serialization fails

Source code in src/anyenv/toml_tools/__init__.py
def dump_toml(data: Any, *, pretty: bool = False, backend: BackendType = "auto") -> str:
    """Serialize data to a TOML string.

    Args:
        data: The data to serialize
        pretty: Whether to format the output with pretty formatting
        backend: TOML backend to use for serialization

    Returns:
        The serialized TOML string

    Raises:
        TomlDumpError: If serialization fails
    """
    provider = get_toml_provider(backend)
    return provider.dump_toml(data, pretty=pretty)

function_spawner

function_spawner(func: Callable[P, Awaitable[T]]) -> AsyncExecutor[P, T]
function_spawner(func: Callable[P, AsyncIterator[T]]) -> AsyncIteratorExecutor[P, T]
function_spawner(
    func: Callable[P, Awaitable[T] | AsyncIterator[T]],
) -> AsyncExecutor[P, T] | AsyncIteratorExecutor[P, T]

Decorator for standalone async functions and async generators.

Usage

@function_spawner async def my_func(x: int) -> str: return str(x)

@function_spawner async def my_generator(x: int): for i in range(x): yield i

Usage:

result = my_func.sync(42) # Sync for item in my_generator.sync(3): # iteration print(item)

Source code in src/anyenv/calling/async_executor.py
def function_spawner[**P, T](
    func: Callable[P, Awaitable[T] | AsyncIterator[T]],
) -> AsyncExecutor[P, T] | AsyncIteratorExecutor[P, T]:
    """Decorator for standalone async functions and async generators.

    Usage:
        @function_spawner
        async def my_func(x: int) -> str:
            return str(x)

        @function_spawner
        async def my_generator(x: int):
            for i in range(x):
                yield i

        # Usage:
        result = my_func.sync(42)            # Sync
        for item in my_generator.sync(3):   # iteration
            print(item)
    """
    if inspect.iscoroutinefunction(func):
        return AsyncExecutor(func, is_bound=False)
    if inspect.isasyncgenfunction(func):
        return AsyncIteratorExecutor(func, is_bound=False)
    msg = f"@function_spawner can only be applied to async fns / generators, got {func}"
    raise TypeError(msg)

gather async

gather(
    *coros_or_futures: Awaitable[T], return_exceptions: Literal[True]
) -> Sequence[T | Exception]
gather(
    *coros_or_futures: Awaitable[T], return_exceptions: Literal[False] = False
) -> Sequence[T]
gather(
    *coros_or_futures: Awaitable[T], return_exceptions: bool = False
) -> Sequence[T | Exception]

Run awaitables concurrently using anyio's task groups.

Like asyncio.gather, a failure raises the failing awaitable's own exception (the first one, if several fail), not an ExceptionGroup; the others are cancelled. Cancellation is never returned as a result.

Parameters:

Name Type Description Default
*coros_or_futures Awaitable[T]

Awaitables (coroutines or futures) to run concurrently

()
return_exceptions bool

If True, exceptions are returned instead of raised

False

Returns:

Type Description
Sequence[T | Exception]

A list of results in the same order as the input awaitables

Source code in src/anyenv/async_run.py
async def gather[T](
    *coros_or_futures: Awaitable[T],
    return_exceptions: bool = False,
) -> Sequence[T | Exception]:
    """Run awaitables concurrently using anyio's task groups.

    Like `asyncio.gather`, a failure raises the failing awaitable's own exception
    (the first one, if several fail), not an ExceptionGroup; the others are
    cancelled. Cancellation is never returned as a result.

    Args:
        *coros_or_futures: Awaitables (coroutines or futures) to run concurrently
        return_exceptions: If True, exceptions are returned instead of raised

    Returns:
        A list of results in the same order as the input awaitables
    """
    results: list[Any] = [None] * len(coros_or_futures)
    error: BaseException | None = None

    try:
        async with anyio.create_task_group() as tg:
            for i, coro in enumerate(coros_or_futures):

                async def run_and_store(idx: int = i, awaitable: Awaitable[T] = coro) -> None:
                    try:
                        results[idx] = await awaitable
                    except Exception as exc:
                        if return_exceptions:
                            results[idx] = exc
                        else:
                            raise

                tg.start_soon(run_and_store)
    except BaseExceptionGroup as group:
        # The task group's own wrapper: its members are the children's exceptions.
        error = group.exceptions[0]
    if error is not None:
        # Raised outside the except block, so its __context__ stays its own.
        raise error
    return results

get async

get(
    url: str,
    *,
    params: ParamsType | None = None,
    headers: HeaderType | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    api_key: str | SecretStr | None = None,
    auth_type: AuthType = "bearer",
    auth_username: str | None = None,
    auth_header_name: str | None = None,
) -> HttpResponse

Make a GET request (options as for request).

Source code in src/anyenv/download/functional.py
async def get(
    url: str,
    *,
    params: ParamsType | None = None,
    headers: HeaderType | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    api_key: str | SecretStr | None = None,
    auth_type: AuthType = "bearer",
    auth_username: str | None = None,
    auth_header_name: str | None = None,
) -> HttpResponse:
    """Make a GET request (options as for `request`)."""
    return await request(
        "GET",
        url,
        params=params,
        headers=headers,
        timeout=timeout,
        cache=cache,
        cache_dir=cache_dir,
        cache_ttl=cache_ttl,
        api_key=api_key,
        auth_type=auth_type,
        auth_username=auth_username,
        auth_header_name=auth_header_name,
    )

get_bytes async

get_bytes(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> bytes

GET a URL and return the body as bytes (options as for request).

Source code in src/anyenv/download/functional.py
async def get_bytes(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> bytes:
    """GET a URL and return the body as bytes (options as for `request`)."""
    return (await get(url, **kwargs)).content

get_bytes_sync

get_bytes_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> bytes

Synchronous version of get_bytes.

Source code in src/anyenv/download/functional.py
def get_bytes_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> bytes:
    """Synchronous version of `get_bytes`."""
    from anyenv.async_run import run_sync

    return run_sync(without_session(get_bytes(url, **kwargs)))

get_json async

get_json(
    url: str, *, return_type: type[T] | None = None, **kwargs: Unpack[DataRetrievalOptions]
) -> T

GET a URL and return the body parsed as JSON (options as for request).

Parameters:

Name Type Description Default
url str

URL to request

required
return_type type[T] | None

Type to validate the data against (pydantic models, dataclasses, TypedDicts, ...); without it the data is returned as parsed

None
kwargs Unpack[DataRetrievalOptions]

Options as for request

{}
Source code in src/anyenv/download/functional.py
async def get_json[T](
    url: str,
    *,
    return_type: type[T] | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> T:
    """GET a URL and return the body parsed as JSON (options as for `request`).

    Args:
        url: URL to request
        return_type: Type to validate the data against (pydantic models, dataclasses,
            TypedDicts, ...); without it the data is returned as parsed
        kwargs: Options as for `request`
    """
    from anyenv.validate import validate_json_data

    return validate_json_data((await get(url, **kwargs)).json(), return_type)

get_json_sync

get_json_sync(
    url: str, *, return_type: type[T] | None = None, **kwargs: Unpack[DataRetrievalOptions]
) -> T

Synchronous version of get_json.

Source code in src/anyenv/download/functional.py
def get_json_sync[T](
    url: str,
    *,
    return_type: type[T] | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> T:
    """Synchronous version of `get_json`."""
    from anyenv.async_run import run_sync

    return run_sync(without_session(get_json(url, return_type=return_type, **kwargs)))

get_os_command_provider

get_os_command_provider(
    system: Literal["Windows", "Darwin", "Linux"] | None = None,
) -> OSCommandProvider

Auto-detect OS and return appropriate command provider.

Parameters:

Name Type Description Default
system Literal['Windows', 'Darwin', 'Linux'] | None

The system to use. If None, the current system is used.

None

Returns:

Type Description
OSCommandProvider

OS-specific command provider based on current platform

Source code in src/anyenv/os_commands/providers.py
def get_os_command_provider(
    system: Literal["Windows", "Darwin", "Linux"] | None = None,
) -> OSCommandProvider:
    """Auto-detect OS and return appropriate command provider.

    Args:
        system: The system to use. If None, the current system is used.

    Returns:
        OS-specific command provider based on current platform
    """
    system_ = system or platform.system()

    if system_ == "Windows":
        return WindowsCommandProvider()
    if system_ == "Darwin":  # macOS
        return MacOSCommandProvider()
    # Linux and other Unix-like systems
    return UnixCommandProvider()

get_sync

get_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> HttpResponse

Synchronous version of get.

Source code in src/anyenv/download/functional.py
def get_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> HttpResponse:
    """Synchronous version of `get`."""
    return request_sync("GET", url, **kwargs)

get_text async

get_text(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> str

GET a URL and return the body as text (options as for request).

Source code in src/anyenv/download/functional.py
async def get_text(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> str:
    """GET a URL and return the body as text (options as for `request`)."""
    return (await get(url, **kwargs)).text

get_text_sync

get_text_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> str

Synchronous version of get_text.

Source code in src/anyenv/download/functional.py
def get_text_sync(url: str, **kwargs: Unpack[DataRetrievalOptions]) -> str:
    """Synchronous version of `get_text`."""
    from anyenv.async_run import run_sync

    return run_sync(without_session(get_text(url, **kwargs)))

http_session async

http_session(
    *,
    base_url: str | None = None,
    headers: HeaderType | None = None,
    cache: bool = False,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    cache_backend: CacheType = "file",
    timeout: float | None = _UNSET,
) -> AsyncGenerator[HttpSession]

Open one HTTP client for many requests.

While the block runs, the module-level helpers (anyenv.get_json(...) etc.) in this context use the session too; leaving it restores the outer session (if any). Helper calls asking for other cache settings get a client of their own.

Parameters:

Name Type Description Default
base_url str | None

Prefix for relative URLs; the session's headers only go to it

None
headers HeaderType | None

Headers for every request (see HttpSession)

None
cache bool

Cache responses (hishel; keyed by URL and credentials)

False
cache_dir StrPath | None

Directory of the cache database (default: the user cache dir)

None
cache_ttl int | str | None

How long cached responses are used: seconds or e.g. "1h", "2d"

None
cache_backend CacheType

"file" (an SQLite file in cache_dir, also "sqlite") or "memory"

'file'
timeout float | None

Default timeout per request in seconds (default: DEFAULT_TIMEOUT, 30 s per operation with a 10 s connect limit; pass None to disable)

_UNSET
Example
async with anyenv.http_session(base_url="https://api.github.com") as s:
    repo = await s.get_json("/repos/phil65/anyenv")
    user = await anyenv.get_json("https://api.github.com/users/phil65")
Source code in src/anyenv/download/session.py
@contextlib.asynccontextmanager
async def http_session(
    *,
    base_url: str | None = None,
    headers: HeaderType | None = None,
    cache: bool = False,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    cache_backend: CacheType = "file",
    timeout: float | None = _UNSET,
) -> AsyncGenerator[HttpSession]:
    """Open one HTTP client for many requests.

    While the block runs, the module-level helpers (``anyenv.get_json(...)`` etc.)
    in this context use the session too; leaving it restores the outer session (if
    any). Helper calls asking for other cache settings get a client of their own.

    Args:
        base_url: Prefix for relative URLs; the session's headers only go to it
        headers: Headers for every request (see `HttpSession`)
        cache: Cache responses (hishel; keyed by URL and credentials)
        cache_dir: Directory of the cache database (default: the user cache dir)
        cache_ttl: How long cached responses are used: seconds or e.g. "1h", "2d"
        cache_backend: "file" (an SQLite file in `cache_dir`, also "sqlite") or "memory"
        timeout: Default timeout per request in seconds (default: `DEFAULT_TIMEOUT`,
            30 s per operation with a 10 s connect limit; pass `None` to disable)

    Example:
        ```python
        async with anyenv.http_session(base_url="https://api.github.com") as s:
            repo = await s.get_json("/repos/phil65/anyenv")
            user = await anyenv.get_json("https://api.github.com/users/phil65")
        ```
    """
    settings = CacheSettings.create(cache, cache_dir, cache_ttl, cache_backend)
    session = HttpSession(base_url=base_url, headers=headers, cache=settings, timeout=timeout)
    token = _current_session.set(session)
    try:
        async with session:
            yield session
    finally:
        _current_session.reset(token)

install async

install(package_name: str, version: str | None = None, upgrade: bool = False) -> None

Install a package using the appropriate installer for the current environment.

Parameters:

Name Type Description Default
package_name str

Name of the package to install.

required
version str | None

Optional version specifier.

None
upgrade bool

Whether to upgrade an existing package.

False

Raises:

Type Description
ImportError

If no suitable installer is available.

Source code in src/anyenv/package_install/functional.py
async def install(
    package_name: str,
    version: str | None = None,
    upgrade: bool = False,
) -> None:
    """Install a package using the appropriate installer for the current environment.

    Args:
        package_name: Name of the package to install.
        version: Optional version specifier.
        upgrade: Whether to upgrade an existing package.

    Raises:
        ImportError: If no suitable installer is available.
    """
    # Format version string if needed
    if version and version[0] not in ("=", "<", ">", "!"):
        version = "==" + version

    # Choose installer based on environment
    if _is_pyodide() and importlib.util.find_spec("micropip"):
        from anyenv.package_install.micropip_install import MicropipInstaller

        installer: PackageInstaller = MicropipInstaller()
        await installer.install(package_name, version, upgrade)
        return

    # Default to pip if available
    if importlib.util.find_spec("pip"):
        from anyenv.package_install.pip_install import PipInstaller

        installer = PipInstaller()
        await installer.install(package_name, version, upgrade)
        return

    msg = (
        "No suitable package installer found. "
        "Please install either pip or run in a Pyodide environment."
    )
    raise ImportError(msg)

install_sync

install_sync(package_name: str, version: str | None = None, upgrade: bool = False) -> None

Synchronous version of install.

Source code in src/anyenv/package_install/functional.py
def install_sync(
    package_name: str,
    version: str | None = None,
    upgrade: bool = False,
) -> None:
    """Synchronous version of install."""
    from anyenv.async_run import run_sync

    return run_sync(install(package_name=package_name, version=version, upgrade=upgrade))

load_json

load_json(
    data: str | bytes | TextIOWrapper, return_type: type[T], backend: BackendType = "auto"
) -> T
load_json(
    data: str | bytes | TextIOWrapper, return_type: UnionType, backend: BackendType = "auto"
) -> Any
load_json(
    data: str | bytes | TextIOWrapper, return_type: None = None, backend: BackendType = "auto"
) -> Any
load_json(
    data: str | bytes | TextIOWrapper,
    return_type: type[Any] | UnionType | None = None,
    backend: BackendType = "auto",
) -> Any

Load JSON data with optional type validation.

Parameters:

Name Type Description Default
data str | bytes | TextIOWrapper

The JSON data to parse (string, bytes, or file-like object)

required
return_type type[Any] | UnionType | None

Optional type to validate the data against

None
backend BackendType

JSON backend to use for parsing

'auto'

Returns:

Type Description
Any

The parsed and validated data

Raises:

Type Description
JsonLoadError

If parsing fails

TypeError

If validation against return_type fails

Source code in src/anyenv/json_tools/__init__.py
def load_json(
    data: str | bytes | TextIOWrapper,
    return_type: type[Any] | types.UnionType | None = None,
    backend: BackendType = "auto",
) -> Any:
    """Load JSON data with optional type validation.

    Args:
        data: The JSON data to parse (string, bytes, or file-like object)
        return_type: Optional type to validate the data against
        backend: JSON backend to use for parsing

    Returns:
        The parsed and validated data

    Raises:
        JsonLoadError: If parsing fails
        TypeError: If validation against return_type fails
    """
    provider = get_json_provider(backend)
    parsed_data = provider.load_json(data)

    if return_type is not None:
        from anyenv.validate import validate_json_data

        return validate_json_data(parsed_data, return_type)
    return parsed_data

load_toml

load_toml(
    data: str | bytes | TextIOWrapper | Path,
    return_type: type[T] | None = None,
    backend: BackendType = "auto",
) -> T

Load TOML data with optional type validation.

Parameters:

Name Type Description Default
data str | bytes | TextIOWrapper | Path

The TOML data to parse (string, bytes, file-like object, or Path)

required
return_type type[T] | None

Optional type to validate the data against

None
backend BackendType

TOML backend to use for parsing

'auto'

Returns:

Type Description
T

The parsed and validated data

Raises:

Type Description
TomlLoadError

If parsing fails

TypeError

If validation against return_type fails

Source code in src/anyenv/toml_tools/__init__.py
def load_toml[T = dict[str, Any]](
    data: str | bytes | TextIOWrapper | Path,
    return_type: type[T] | None = None,
    backend: BackendType = "auto",
) -> T:
    """Load TOML data with optional type validation.

    Args:
        data: The TOML data to parse (string, bytes, file-like object, or Path)
        return_type: Optional type to validate the data against
        backend: TOML backend to use for parsing

    Returns:
        The parsed and validated data

    Raises:
        TomlLoadError: If parsing fails
        TypeError: If validation against return_type fails
    """
    provider = get_toml_provider(backend)
    parsed_data = provider.load_toml(data)

    if return_type is not None:
        from anyenv.validate import validate_json_data

        return validate_json_data(parsed_data, return_type)
    return parsed_data  # type: ignore[no-any-return]

method_spawner

method_spawner(func: Callable[Concatenate[Any, P], Awaitable[T]]) -> AsyncExecutor[P, T]
method_spawner(
    func: Callable[Concatenate[Any, P], AsyncIterator[T]],
) -> AsyncIteratorExecutor[P, T]
method_spawner(
    func: Callable[Concatenate[Any, P], Awaitable[T] | AsyncIterator[T]],
) -> AsyncExecutor[P, T] | AsyncIteratorExecutor[P, T]

Decorator for async methods and async generator methods.

Usage

class MyClass: @method_spawner async def my_method(self, x: int) -> str: return str(x)

@method_spawner
async def my_generator(self, x: int):
    for i in range(x):
        yield i

Usage:

obj = MyClass() result = obj.my_method.sync(42) # Sync for item in obj.my_generator.sync(3): # iteration print(item)

Source code in src/anyenv/calling/async_executor.py
def method_spawner[**P, T](
    func: Callable[Concatenate[Any, P], Awaitable[T] | AsyncIterator[T]],
) -> AsyncExecutor[P, T] | AsyncIteratorExecutor[P, T]:
    """Decorator for async methods and async generator methods.

    Usage:
        class MyClass:
            @method_spawner
            async def my_method(self, x: int) -> str:
                return str(x)

            @method_spawner
            async def my_generator(self, x: int):
                for i in range(x):
                    yield i

        # Usage:
        obj = MyClass()
        result = obj.my_method.sync(42)            # Sync
        for item in obj.my_generator.sync(3):     #  iteration
            print(item)
    """
    if inspect.iscoroutinefunction(func):
        return AsyncExecutor(func, is_bound=True)
    if inspect.isasyncgenfunction(func):
        return AsyncIteratorExecutor(func, is_bound=True)
    msg = f"@method_spawner must applied to async methods or async generators, got {func}"
    raise TypeError(msg)

open_in_playground

open_in_playground(
    file: ModuleType | str | PathLike[str],
    title: str = "Open in Pydantic Playground",
    dependencies: list[str] | None = None,
    open_browser: bool = True,
) -> str

Create a link to Pydantic playground with a pre-populated file.

Parameters:

Name Type Description Default
file ModuleType | str | PathLike[str]

The file to include in the playground. Can be: - A module - A file path

required
title str

The title of the link (not used in URL generation)

'Open in Pydantic Playground'
dependencies list[str] | None

List of package dependencies to include as PEP 723 header

None
open_browser bool

Whether to automatically open the link in a browser

True

Returns:

Type Description
str

A URL string pointing to the Pydantic playground

Source code in src/anyenv/testing.py
def open_in_playground(
    file: types.ModuleType | str | os.PathLike[str],
    title: str = "Open in Pydantic Playground",
    dependencies: list[str] | None = None,
    open_browser: bool = True,
) -> str:
    """Create a link to Pydantic playground with a pre-populated file.

    Args:
        file: The file to include in the playground. Can be:
               - A module
               - A file path
        title: The title of the link (not used in URL generation)
        dependencies: List of package dependencies to include as PEP 723 header
        open_browser: Whether to automatically open the link in a browser

    Returns:
        A URL string pointing to the Pydantic playground
    """
    import inspect
    import json
    from urllib.parse import quote
    import webbrowser

    # Create file data based on the type of input
    match file:
        case types.ModuleType():
            content = inspect.getsource(file)
            filename = f"{file.__name__}.py"
        case str() | os.PathLike():
            file_path = AnyPath(file)
            content = file_path.read_text("utf-8")
            filename = file_path.name
        case _:
            msg = f"Unsupported file type: {type(file)}"
            raise TypeError(msg)

    # Add PEP 723 header for dependencies if specified
    if dependencies:
        deps_str = ", ".join(f'"{dep}"' for dep in dependencies)
        pep723_header = f"# /// script\n# dependencies = [{deps_str}]\n# ///\n\n"
        content = pep723_header + content

    file_data = [{"name": filename, "content": content, "activeIndex": 1}]
    json_str = json.dumps(file_data)
    encoded = quote(json_str)
    url = f"https://pydantic.run/new?files={encoded}"
    if open_browser:
        webbrowser.open(url)
    return url

post async

post(
    url: str,
    *,
    params: ParamsType | None = None,
    headers: HeaderType | None = None,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    api_key: str | SecretStr | None = None,
    auth_type: AuthType = "bearer",
    auth_username: str | None = None,
    auth_header_name: str | None = None,
) -> HttpResponse

Make a POST request (options as for request).

Source code in src/anyenv/download/functional.py
async def post(
    url: str,
    *,
    params: ParamsType | None = None,
    headers: HeaderType | None = None,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    api_key: str | SecretStr | None = None,
    auth_type: AuthType = "bearer",
    auth_username: str | None = None,
    auth_header_name: str | None = None,
) -> HttpResponse:
    """Make a POST request (options as for `request`)."""
    return await request(
        "POST",
        url,
        params=params,
        headers=headers,
        json=json,
        data=data,
        files=files,
        timeout=timeout,
        cache=cache,
        cache_dir=cache_dir,
        cache_ttl=cache_ttl,
        api_key=api_key,
        auth_type=auth_type,
        auth_username=auth_username,
        auth_header_name=auth_header_name,
    )

post_json async

post_json(
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> T

POST JSON and return the response parsed as JSON (options as for request).

Parameters:

Name Type Description Default
url str

URL to request

required
json_data Any

Data sent as JSON body (as form fields when files are given)

required
files FilesType | None

Files to upload (multipart)

None
return_type type[T] | None

Type to validate the response against

None
kwargs Unpack[DataRetrievalOptions]

Options as for request

{}
Source code in src/anyenv/download/functional.py
async def post_json[T](
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> T:
    """POST JSON and return the response parsed as JSON (options as for `request`).

    Args:
        url: URL to request
        json_data: Data sent as JSON body (as form fields when `files` are given)
        files: Files to upload (multipart)
        return_type: Type to validate the response against
        kwargs: Options as for `request`
    """
    from anyenv.validate import validate_json_data

    if files:
        response = await post(url, data=json_data, files=files, **kwargs)
    else:
        response = await post(url, json=json_data, **kwargs)
    return validate_json_data(response.json(), return_type)

post_json_sync

post_json_sync(
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> T

Synchronous version of post_json.

Source code in src/anyenv/download/functional.py
def post_json_sync[T](
    url: str,
    json_data: Any,
    *,
    files: FilesType | None = None,
    return_type: type[T] | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> T:
    """Synchronous version of `post_json`."""
    from anyenv.async_run import run_sync

    coro = post_json(url, json_data, files=files, return_type=return_type, **kwargs)
    return run_sync(without_session(coro))

post_sync

post_sync(
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> HttpResponse

Synchronous version of post.

Source code in src/anyenv/download/functional.py
def post_sync(
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> HttpResponse:
    """Synchronous version of `post`."""
    return request_sync("POST", url, json=json, data=data, files=files, **kwargs)

request async

request(
    method: Method,
    url: str,
    *,
    params: ParamsType | None = None,
    headers: HeaderType | None = None,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    api_key: str | SecretStr | None = None,
    auth_type: AuthType = "bearer",
    auth_username: str | None = None,
    auth_header_name: str | None = None,
) -> HttpResponse

Make an HTTP request; the response's body is read already.

Parameters:

Name Type Description Default
method Method

HTTP method to use

required
url str

URL to request (relative URLs resolve against the session's base_url)

required
params ParamsType | None

Query parameters

None
headers HeaderType | None

Request headers

None
json Any

JSON body

None
data Any

Form data or raw body

None
files FilesType | None

Files to upload (multipart)

None
timeout float | None

Timeout in seconds. When omitted, uses the open session's timeout, or DEFAULT_TIMEOUT (30 s per operation, 10 s connect) outside a session. Pass None to disable timeouts.

_UNSET
cache bool | None

Cache responses (default: as the open session does, else no)

None
cache_dir StrPath | None

Directory of the cache database

None
cache_ttl int | str | None

How long cached responses are used: seconds or e.g. "1h", "2d"

None
api_key str | SecretStr | None

API key or token for authentication

None
auth_type AuthType

How the api_key is sent ("bearer", "basic", "header", "query")

'bearer'
auth_username str | None

Username for basic authentication

None
auth_header_name str | None

Header name for auth_type="header" (default: X-API-Key)

None

Raises:

Type Description
RequestError

The request failed (connection, timeout)

ResponseError

The response has a 4xx / 5xx status

Source code in src/anyenv/download/functional.py
async def request(
    method: Method,
    url: str,
    *,
    params: ParamsType | None = None,
    headers: HeaderType | None = None,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    timeout: float | None = _UNSET,
    cache: bool | None = None,
    cache_dir: StrPath | None = None,
    cache_ttl: int | str | None = None,
    api_key: str | SecretStr | None = None,
    auth_type: AuthType = "bearer",
    auth_username: str | None = None,
    auth_header_name: str | None = None,
) -> HttpResponse:
    """Make an HTTP request; the response's body is read already.

    Args:
        method: HTTP method to use
        url: URL to request (relative URLs resolve against the session's base_url)
        params: Query parameters
        headers: Request headers
        json: JSON body
        data: Form data or raw body
        files: Files to upload (multipart)
        timeout: Timeout in seconds. When omitted, uses the open session's timeout,
            or `DEFAULT_TIMEOUT` (30 s per operation, 10 s connect) outside a
            session. Pass `None` to disable timeouts.
        cache: Cache responses (default: as the open session does, else no)
        cache_dir: Directory of the cache database
        cache_ttl: How long cached responses are used: seconds or e.g. "1h", "2d"
        api_key: API key or token for authentication
        auth_type: How the api_key is sent ("bearer", "basic", "header", "query")
        auth_username: Username for basic authentication
        auth_header_name: Header name for auth_type="header" (default: X-API-Key)

    Raises:
        RequestError: The request failed (connection, timeout)
        ResponseError: The response has a 4xx / 5xx status
    """
    async with session_for(cache, cache_dir, cache_ttl, timeout) as session:
        extra: dict[str, Any] = {} if timeout is _UNSET else {"timeout": timeout}
        return await session.request(
            method,
            url,
            params=params,
            headers=headers,
            json=json,
            data=data,
            files=files,
            api_key=api_key,
            auth_type=auth_type,
            auth_username=auth_username,
            auth_header_name=auth_header_name,
            **extra,
        )

request_sync

request_sync(
    method: Method,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> HttpResponse

Synchronous version of request.

Source code in src/anyenv/download/functional.py
def request_sync(
    method: Method,
    url: str,
    *,
    json: Any = None,
    data: Any = None,
    files: FilesType | None = None,
    **kwargs: Unpack[DataRetrievalOptions],
) -> HttpResponse:
    """Synchronous version of `request`."""
    from anyenv.async_run import run_sync

    return run_sync(
        without_session(request(method, url, json=json, data=data, files=files, **kwargs))
    )

run_in_thread async

run_in_thread(
    func: Callable[[*PosArgsT], T_Retval],
    *args: *PosArgsT,
    abandon_on_cancel: bool = False,
    cancellable: bool | None = None,
    limiter: Any = None,
    **kwargs: Any,
) -> T_Retval

Run a function in a separate thread using anyio.

Parameters:

Name Type Description Default
func Callable[[*PosArgsT], T_Retval]

The function to run in a thread

required
*args *PosArgsT

Positional arguments to pass to the function

()
abandon_on_cancel bool

Whether to abandon execution on cancellation

False
cancellable bool | None

Whether the operation can be cancelled

None
limiter Any

Optional capacity limiter for limiting concurrent threads

None
**kwargs Any

Keyword arguments to pass to the function

{}

Returns:

Type Description
T_Retval

The return value of the function

Source code in src/anyenv/async_run.py
async def run_in_thread[T_Retval, *PosArgsT](
    func: Callable[[*PosArgsT], T_Retval],
    *args: *PosArgsT,
    abandon_on_cancel: bool = False,
    cancellable: bool | None = None,
    limiter: Any = None,
    **kwargs: Any,
) -> T_Retval:
    """Run a function in a separate thread using anyio.

    Args:
        func: The function to run in a thread
        *args: Positional arguments to pass to the function
        abandon_on_cancel: Whether to abandon execution on cancellation
        cancellable: Whether the operation can be cancelled
        limiter: Optional capacity limiter for limiting concurrent threads
        **kwargs: Keyword arguments to pass to the function

    Returns:
        The return value of the function
    """
    fn: Callable[[*PosArgsT], T_Retval] = partial(func, **kwargs) if kwargs else func
    return await to_thread.run_sync(
        fn,
        *args,
        abandon_on_cancel=abandon_on_cancel,
        cancellable=cancellable,
        limiter=limiter,
    )

run_sync

run_sync(coro: Coroutine[Any, Any, T]) -> T

Run a coroutine synchronously.

This function uses anyio to run a coroutine in a synchronous context: outside an event loop with anyio's run function directly; inside one (an async frame calling sync code) in a new thread. The latter blocks the calling loop until the coroutine is done.

Context variables are properly propagated between threads in all cases.

Example:

async def f(x: int) -> int:
    return x + 1

result = run_sync(f(1))

Parameters:

Name Type Description Default
coro Coroutine[Any, Any, T]

The coroutine to run synchronously

required

Returns:

Type Description
T

The result of the coroutine

Source code in src/anyenv/async_run.py
def run_sync[T](coro: Coroutine[Any, Any, T]) -> T:
    """Run a coroutine synchronously.

    This function uses anyio to run a coroutine in a synchronous context:
    outside an event loop with anyio's run function directly; inside one (an
    async frame calling sync code) in a new thread. The latter blocks the calling
    loop until the coroutine is done.

    Context variables are properly propagated between threads in all cases.

    Example:
    ```python
    async def f(x: int) -> int:
        return x + 1

    result = run_sync(f(1))
    ```

    Args:
        coro: The coroutine to run synchronously

    Returns:
        The result of the coroutine
    """
    ctx = contextvars.copy_context()

    async def wrapper() -> T:
        return await coro

    # Decided upfront: retrying after a failure could re-run a coroutine that
    # already ran, and would misread the coroutine's own errors.
    if _in_event_loop():
        return run_sync_in_thread(coro)
    return ctx.run(anyio.run, wrapper)

run_sync_in_thread

run_sync_in_thread(coro: Coroutine[Any, Any, T]) -> T

Run a coroutine synchronously in a new thread.

This function creates a new thread to run the coroutine with anyio. Context variables are properly propagated between threads. This is useful when you need to run async code in a context where you can't use the current event loop (e.g., inside an async frame).

Example:

async def f(x: int) -> int:
    return x + 1

result = run_sync_in_thread(f(1))

Parameters:

Name Type Description Default
coro Coroutine[Any, Any, T]

The coroutine to run synchronously

required

Returns:

Type Description
T

The result of the coroutine

Source code in src/anyenv/async_run.py
def run_sync_in_thread[T](coro: Coroutine[Any, Any, T]) -> T:
    """Run a coroutine synchronously in a new thread.

    This function creates a new thread to run the coroutine with anyio.
    Context variables are properly propagated between threads.
    This is useful when you need to run async code in a context where you can't use
    the current event loop (e.g., inside an async frame).

    Example:
    ```python
    async def f(x: int) -> int:
        return x + 1

    result = run_sync_in_thread(f(1))
    ```

    Args:
        coro: The coroutine to run synchronously

    Returns:
        The result of the coroutine
    """
    result: T | None = None
    error: BaseException | None = None
    done = threading.Event()
    ctx = contextvars.copy_context()

    def thread_target() -> None:
        nonlocal result, error
        try:
            result = ctx.run(anyio.run, lambda: coro)
        except BaseException as e:  # noqa: BLE001
            error = e
        finally:
            done.set()

    thread = threading.Thread(target=thread_target)
    thread.start()
    done.wait()
    if error is not None:
        raise error
    return result  # type: ignore