Skip to content

clabe.ui

How clabe talks to the user: requests that describe and validate themselves, a session API to ask them (ui.ask, ui.confirm, ui.group, ...), and clients (console, TUI) that render and collect answers.

Client

Bases: Protocol

A user interface that renders messages and collects raw answers (it never validates).

ask

ask(request: Request) -> Any

Shows request and blocks until the user answers; returns the raw answer.

Raises:

Type Description
PromptCancelledError

cancel was called while the prompt was shown.

Source code in src/clabe/ui/_client.py
def ask(self, request: Request) -> Any:
    """Shows ``request`` and blocks until the user answers; returns the raw answer.

    Raises:
        PromptCancelledError: `cancel` was called while the prompt was shown.
    """
    ...

cancel

cancel() -> None

Cancels the prompt being shown, if any. Thread-safe.

Source code in src/clabe/ui/_client.py
def cancel(self) -> None:
    """Cancels the prompt being shown, if any. Thread-safe."""
    ...

notify

notify(message: str, level: MessageLevel = INFO) -> None

Shows the user a message, without expecting an answer.

Source code in src/clabe/ui/_client.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Shows the user a message, without expecting an answer."""
    ...

header

header(text: str) -> None

Shows the user a prominent header.

Source code in src/clabe/ui/_client.py
def header(self, text: str) -> None:
    """Shows the user a prominent header."""
    ...

close

close() -> None

Releases the interface (e.g. tears down a TUI).

Source code in src/clabe/ui/_client.py
def close(self) -> None:
    """Releases the interface (e.g. tears down a TUI)."""
    ...

ClientSession

ClientSession(client: Client)

Uses a Client as the Session outside a run.

Resolves FieldRequest s, validates answers with the request's own rules and asks again (showing the reason) until an answer is accepted, as a run does.

Parameters:

Name Type Description Default
client Client

The client that asks and renders.

required
Source code in src/clabe/ui/_client.py
def __init__(self, client: Client) -> None:
    self._client = client

client property writable

client: Client

The client this session asks through.

ask

ask(request: Request) -> Any

Asks request until it gets a valid answer and returns that answer, validated and coerced.

Raises:

Type Description
PromptCancelledError

The client's prompt was cancelled.

Source code in src/clabe/ui/_client.py
def ask(self, request: Request) -> Any:
    """Asks ``request`` until it gets a valid answer and returns that answer, validated and coerced.

    Raises:
        PromptCancelledError: The client's prompt was cancelled.
    """
    convert = None
    if isinstance(request, FieldRequest):
        request, convert = request.resolve()
    from ._session import NavigationRequested

    while True:
        try:
            raw = self._client.ask(request)
        except NavigationRequested:
            self._client.notify("Going back or forward is only possible during a run.", MessageLevel.WARNING)
            continue
        try:
            value = request.validate_answer(raw)
        except AnswerRejected as exc:
            self._client.notify(str(exc), MessageLevel.ERROR)
            continue
        return convert(value) if convert is not None else value

notify

notify(message: str, level: MessageLevel = INFO) -> None

Shows message on the client (and records it in the log file, at debug level).

Source code in src/clabe/ui/_client.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Shows ``message`` on the client (and records it in the log file, at debug level)."""
    logger.debug("UI» %s", message)
    self._client.notify(message, level)

header

header(text: str) -> None

Shows a header on the client.

Source code in src/clabe/ui/_client.py
def header(self, text: str) -> None:
    """Shows a header on the client."""
    self._client.header(text)

HeadlessClient

HeadlessClient()

A client with no screen: prompts wait until answered elsewhere (e.g. the web UI), messages go to the log.

For runs started without a terminal (by the daemon, a scheduler or a service) and served over HTTP.

Source code in src/clabe/ui/_client.py
def __init__(self) -> None:
    import threading

    self._cancelled = threading.Event()

ask

ask(request: Request) -> Any

Waits until the prompt is answered by another client (which cancels this one).

Source code in src/clabe/ui/_client.py
def ask(self, request: Request) -> Any:
    """Waits until the prompt is answered by another client (which cancels this one)."""
    from ._session import PromptCancelledError

    self._cancelled.wait()
    self._cancelled.clear()
    raise PromptCancelledError()

cancel

cancel() -> None

Releases the waiting prompt.

Source code in src/clabe/ui/_client.py
def cancel(self) -> None:
    """Releases the waiting prompt."""
    self._cancelled.set()

notify

notify(message: str, level: MessageLevel = INFO) -> None

Logs the message.

Source code in src/clabe/ui/_client.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Logs the message."""
    logger.log(MessageLevel(level).logging_level, "%s", message)

header

header(text: str) -> None

Logs the header.

Source code in src/clabe/ui/_client.py
def header(self, text: str) -> None:
    """Logs the header."""
    logger.info("%s", text)

close

close() -> None

Nothing to tear down.

Source code in src/clabe/ui/_client.py
def close(self) -> None:
    """Nothing to tear down."""

ConsoleClient

ConsoleClient(console: Console | None = None)

A Client using rich for styled, line-based prompts.

Renders messages and prompts with colour and structure on an interactive terminal while degrading gracefully: rich strips styling automatically and falls back to plain input when output is not a terminal (e.g. piped to a file or running in CI), so this also serves as the non-interactive fallback.

Like every client it never validates: ask returns the raw answer and whoever drives the client (a run, or a ClientSession) validates it and asks again if needed.

On an interactive terminal every prompt reads the keyboard key by key, so cancel can abort it from another thread. When stdin or stdout is not a terminal, prompts fall back to input() and cannot be cancelled.

Parameters:

Name Type Description Default
console Console | None

The rich console to render on. Defaults to the shared clabe console so output coordinates with the logging handler.

None
Source code in src/clabe/ui/_console.py
def __init__(self, console: Console | None = None) -> None:
    if console is None:
        from ..logging import clabe_console

        console = clabe_console
    self._console = console
    # The last path submitted, by request: a rejected path is asked again starting from what was typed.
    self._last_path: tuple[int, str] | None = None
    self._cancel = threading.Event()

ask

ask(request: Request) -> Any

Shows request and returns the raw answer.

Raises:

Type Description
PromptCancelledError

cancel was called while the prompt was shown.

ValueError

request is not a primitive prompt (e.g. an unresolved field request).

Source code in src/clabe/ui/_console.py
def ask(self, request: Request) -> Any:
    """Shows ``request`` and returns the raw answer.

    Raises:
        PromptCancelledError: `cancel` was called while the prompt was shown.
        ValueError: ``request`` is not a primitive prompt (e.g. an unresolved field request).
    """
    handler = self._HANDLERS.get(request.prompt_kind)
    if handler is None:
        raise ValueError(f"Clients cannot ask {request.prompt_kind!r} prompts; resolve the request first.")
    return getattr(self, handler)(request)

cancel

cancel() -> None

Aborts the waiting prompt; it raises PromptCancelledError.

Source code in src/clabe/ui/_console.py
def cancel(self) -> None:
    """Aborts the waiting prompt; it raises `PromptCancelledError`."""
    self._cancel.set()

notify

notify(message: str, level: MessageLevel = INFO) -> None

Prints a message with level-appropriate styling.

Source code in src/clabe/ui/_console.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Prints a message with level-appropriate styling."""
    self._console.print(Text(f"{_LEVEL_PREFIXES[level]}{message}", style=_LEVEL_STYLES[level]))

header

header(text: str) -> None

Prints a prominent header as a horizontal rule.

Source code in src/clabe/ui/_console.py
def header(self, text: str) -> None:
    """Prints a prominent header as a horizontal rule."""
    self._console.rule(Text(text, style="bold"))

close

close() -> None

Nothing to release for a console.

Source code in src/clabe/ui/_console.py
def close(self) -> None:
    """Nothing to release for a console."""

MessageLevel

Bases: Enum

Severity/intent of a message surfaced to the user by a frontend.

This is intentionally separate from logging levels: it describes how a message should be presented to the user, not how it should be recorded. The frontend maps each level to an appropriate logging level when writing the message to the persistent transcript.

logging_level property

logging_level: int

The standard logging level used when recording this message.

AcknowledgeRequest dataclass

AcknowledgeRequest(
    message: str,
    title: str = "Notice",
    button_label: str = "OK",
    field: str | None = None,
)

Bases: Request

A declarative acknowledgement gate.

Displays a message (optionally with a title) in a modal overlay and blocks until the user dismisses it. No answer is collected — the sole purpose is to ensure the user has read the message before execution continues.

Attributes:

Name Type Description
message str

The body text the user must read before continuing.

title str

Optional bold heading shown above the message.

button_label str

Label on the dismiss button. Defaults to "OK".

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

Returns the JSON Schema a valid answer must satisfy (no answer, by default).

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """Returns the JSON Schema a valid answer must satisfy (no answer, by default)."""
    return {"type": "null"}

validate_answer

validate_answer(value: Any) -> None

Accepts anything: dismissing the message is the answer (None).

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> None:
    """Accepts anything: dismissing the message is the answer (``None``)."""

AnswerRejected

Bases: ValueError

An answer does not satisfy its request; the message is shown to whoever answered.

AutoCompleteRequest dataclass

AutoCompleteRequest(
    label: str,
    options: Sequence[str] | OptionsFunction,
    default: str | None = None,
    strict: bool = False,
    validators: list[Validator] = list(),
    field: str | None = None,
    help: str | None = None,
)

Bases: Request

A declarative request for text with autocompletion against a list.

As the user types, frontends narrow the offered options; the user may keep typing a free-form value to the end, or pick a suggestion with the arrow keys. Unlike PickRequest, the answer is not constrained to the provided options unless strict is set.

options may be a function of the text typed so far returning the options (e.g. a database search): clients call it as the user types (the run server through GET /api/prompts/{id}/options?q=) and its spec says dynamic_options: true, with options holding its result for "".

Attributes:

Name Type Description
label str

The prompt shown to the user.

options Sequence[str] | OptionsFunction

The suggestions to complete against, or a function (typed) -> options.

default str | None

Value returned when the user submits an empty answer.

strict bool

When set, only a value present in options is accepted (for a function: a value it returns when called with that value).

validators list[Validator]

Validators applied to the answer; the frontend re-prompts and surfaces the returned error until they all pass.

field str | None

Logical field name used in the persisted transcript.

help str | None

Optional supplementary help text.

dynamic property

dynamic: bool

Whether the options come from a function of the typed text.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

suggestions

suggestions(typed: str = '') -> list[str]

The options as strings: a function's result for typed; a list as it is (clients filter it).

Raises:

Type Description
Exception

Whatever the options function raised.

Source code in src/clabe/ui/_requests.py
def suggestions(self, typed: str = "") -> list[str]:
    """The options as strings: a function's result for ``typed``; a list as it is (clients filter it).

    Raises:
        Exception: Whatever the options function raised.
    """
    options = self.options(typed) if callable(self.options) else self.options
    return [str(option) for option in options]

answer_schema

answer_schema() -> dict[str, Any]

A string; one of the suggestions when the request is strict (and its options are a list).

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """A string; one of the suggestions when the request is strict (and its options are a list)."""
    return (
        {"type": "string", "enum": self.suggestions()} if self.strict and not self.dynamic else {"type": "string"}
    )

accepts

accepts(value: str) -> bool

Whether value is one of the options (for a function: one it returns for value).

Source code in src/clabe/ui/_requests.py
def accepts(self, value: str) -> bool:
    """Whether ``value`` is one of the options (for a function: one it returns for ``value``)."""
    try:
        return value in self.suggestions(value)
    except Exception as exc:  # noqa: BLE001 -- an options function that fails accepts nothing
        logger.warning("The options of %r could not be listed: %s", self.label, exc)
        return False

validate_answer

validate_answer(value: Any) -> str

Like a text answer, but a strict request only accepts one of its suggestions (checked first).

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> str:
    """Like a text answer, but a strict request only accepts one of its suggestions (checked first)."""
    if not isinstance(value, str):
        raise AnswerRejected("Expected text.")
    if value == "" and self.default is not None:
        value = self.default
    if self.strict and not self.accepts(value):
        raise AnswerRejected("Please choose one of the offered options.")
    return _text(self, value)

Choice dataclass

Choice(value: str, label: str | None = None)

A single selectable option in a PickRequest.

Attributes:

Name Type Description
value str

The value returned when this option is chosen.

label str | None

Optional human-readable label. Defaults to value.

display property

display: str

The text shown to the user for this choice.

ConfirmRequest dataclass

ConfirmRequest(
    label: str,
    default: bool = False,
    field: str | None = None,
)

Bases: Request

A declarative yes/no question.

Attributes:

Name Type Description
label str

The question shown to the user.

default bool

The value used when the user accepts the default.

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

A boolean.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """A boolean."""
    return {"type": "boolean"}

validate_answer

validate_answer(value: Any) -> bool

Accepts a strict boolean.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> bool:
    """Accepts a strict boolean."""
    return _boolean(value)

FieldRequest dataclass

FieldRequest(
    model: type,
    field_name: str,
    initial: object | None = None,
)

Bases: Request

A declarative request to enter a single field from a Pydantic model.

The asker resolves it (resolve) into the most appropriate primitive request from the field's type annotation: strict autocomplete for Literal / Enum fields, yes/no for bool, a path for Path and a validated text prompt for everything else. Clients never see it.

Attributes:

Name Type Description
model type

The Pydantic model class that owns the field.

field_name str

The name of the field to prompt for.

initial object | None

Optional value to use as the pre-filled default (overrides the field's declared default).

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

The field's JSON Schema; {} (anything) when pydantic cannot describe it.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """The field's JSON Schema; ``{}`` (anything) when pydantic cannot describe it."""
    try:
        return self._adapter().json_schema()
    except (PydanticInvalidForJsonSchema, PydanticSchemaGenerationError) as exc:
        logger.debug("No answer schema for field prompt on %s: %s", self.model.__name__, exc)
        return {}

validate_answer

validate_answer(value: Any) -> Any

Validates a field value answered directly (as answer_schema describes it).

An empty answer falls back to the default, else None if the field is optional. Askers do not open field prompts: they ask the request resolve returns, whose answers are validated by that request.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> Any:
    """Validates a field value answered directly (as `answer_schema` describes it).

    An empty answer falls back to the default, else ``None`` if the field is optional. Askers do not open field
    prompts: they ask the request `resolve` returns, whose answers are validated by that request.
    """
    if value == "":
        info = self.model.model_fields[self.field_name]
        default = resolve_field_default(info, self.initial)
        if default is not None:
            value = default
        elif resolve_field_type(info.annotation)[1]:
            value = None
    try:
        return self._adapter().validate_python(value)
    except ValidationError as exc:
        raise AnswerRejected(_message(exc)) from None

resolve

resolve() -> tuple[Request, Callable[[Any], Any]]

Returns the primitive request to ask for this field, and how to turn its answer into the field value.

Routing rules:

  • bool → yes/no confirm.
  • Literal[...] → strict autocomplete on the literal values (as text); converts back to the literal.
  • Enum → strict autocomplete on the member names; converts to the member.
  • Path → any path, which need not exist (a plain Path field does not imply it does).
  • Anything else → text validated by the field's type and constraints; converts to the typed value. An empty answer (or the default's text) gives the default value itself, else None for an optional field.

Returns:

Type Description
tuple[Request, Callable[[Any], Any]]

The primitive request, and a function mapping its validated answer to the typed field value.

Source code in src/clabe/ui/_requests.py
def resolve(self) -> tuple[Request, Callable[[Any], Any]]:
    """Returns the primitive request to ask for this field, and how to turn its answer into the field value.

    Routing rules:

    * ``bool`` → yes/no confirm.
    * ``Literal[...]`` → strict autocomplete on the literal values (as text); converts back to the literal.
    * ``Enum`` → strict autocomplete on the member names; converts to the member.
    * ``Path`` → any path, which need not exist (a plain ``Path`` field does not imply it does).
    * Anything else → text validated by the field's type and constraints; converts to the typed value. An
      empty answer (or the default's text) gives the default value itself, else ``None`` for an optional field.

    Returns:
        The primitive request, and a function mapping its validated answer to the typed field value.
    """
    info = self.model.model_fields[self.field_name]
    inner, is_optional = resolve_field_type(info.annotation)
    label = getattr(info, "title", None) or _humanize_field(self.field_name)
    default = resolve_field_default(info, self.initial)
    default_str = str(default) if default is not None else None
    field = self.field_name

    if inner is bool:
        confirm = ConfirmRequest(label=label, default=bool(default) if default is not None else False, field=field)
        return confirm, _identity

    if get_origin(inner) is Literal:
        values = get_args(inner)

        def to_literal(answer: Any) -> Any:
            return next((v for v in values if str(v) == answer), answer)

        options = [str(v) for v in values]
        return AutoCompleteRequest(
            label=label, options=options, default=default_str, strict=True, field=field
        ), to_literal

    if isinstance(inner, type) and issubclass(inner, Enum):
        enum_type = inner
        if isinstance(default, Enum):
            default_str = default.name
        options = [m.name for m in enum_type]
        return AutoCompleteRequest(
            label=label, options=options, default=default_str, strict=True, field=field
        ), lambda a: enum_type[a]

    if isinstance(inner, type) and issubclass(inner, Path):
        path = PathRequest(
            label=label, start=default_str, default=default_str, must_exist=False, kind="any", field=field
        )
        return path, _identity

    adapter = self._adapter()

    def typed(raw: str) -> Any:
        # An empty answer becomes ``default_str`` (the text request's default): give back the real default, not
        # its text round-tripped (``str([1, 2])`` is not a list; ``str(SecretStr(...))`` is its mask).
        if default is not None and raw in ("", default_str):
            return default
        return adapter.validate_python(None if (is_optional and raw == "") else raw)

    def check(raw: str) -> str | None:
        try:
            typed(raw)
            return None
        except ValidationError as exc:
            errors = exc.errors()
            return errors[0]["msg"] if errors else "Invalid value."
        except Exception as exc:  # noqa: BLE001 -- any validator failure must surface as a re-promptable message
            return str(exc)

    return TextRequest(label=label, default=default_str, validators=[check], field=field), typed

FormRequest dataclass

FormRequest(
    model: type,
    title: str | None = None,
    initial: object | None = None,
    field: str | None = None,
)

Bases: Request

A declarative request to fill in a Pydantic model as a form.

Attributes:

Name Type Description
model type

The Pydantic model class to render.

title str | None

Optional title override. Defaults to the humanized class name.

initial object | None

Optional pre-populated model instance to seed field defaults.

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

The model's JSON Schema, or null (cancelled); {} (anything) when pydantic cannot describe it.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """The model's JSON Schema, or ``null`` (cancelled); ``{}`` (anything) when pydantic cannot describe it."""
    try:
        return {"anyOf": [self.model.model_json_schema(), {"type": "null"}]}
    except (PydanticInvalidForJsonSchema, PydanticSchemaGenerationError) as exc:
        logger.debug("No answer schema for form prompt on %s: %s", self.model.__name__, exc)
        return {}

validate_answer

validate_answer(value: Any) -> Any

Accepts None (cancelled), a model instance, or data that validates as the model.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> Any:
    """Accepts ``None`` (cancelled), a model instance, or data that validates as the model."""
    if value is None or isinstance(value, self.model):
        return value
    try:
        return self.model.model_validate(value)
    except ValidationError as exc:
        raise AnswerRejected(_message(exc)) from None

GroupRequest dataclass

GroupRequest(
    items: Mapping[str, Request],
    title: str | None = None,
    field: str | None = None,
)

Bases: Request

Several prompts asked together as one: e.g. a text input and a slider shown side by side.

The run opens a single prompt; the answer maps each item name to its validated value. Items may be text, number, confirm, pick, autocomplete, path and field requests (not groups, forms, tables or acknowledgements).

Example
from clabe import ui

answer = ui.group(
    "Session",
    notes=ui.TextRequest(label="Notes"),
    gain=ui.NumberRequest(label="Gain", minimum=0, maximum=1, step=0.05, widget="slider"),
)
answer["gain"]  # a float in [0, 1]

Attributes:

Name Type Description
items Mapping[str, Request]

The prompts, by name (each name must be a Python identifier).

title str | None

Optional title shown above the group.

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

model

model() -> type[BaseModel]

The pydantic model the group compiles to (one field per item); clients render it as a form.

Source code in src/clabe/ui/_requests.py
def model(self) -> type[BaseModel]:
    """The pydantic model the group compiles to (one field per item); clients render it as a form."""
    if self._model is None:
        fields = {name: _group_field(item) for name, item in self.items.items()}
        self._model = create_model("Group", **fields)
    return self._model

answer_schema

answer_schema() -> dict[str, Any]

The compiled model's JSON Schema; {} (anything) when pydantic cannot describe it.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """The compiled model's JSON Schema; ``{}`` (anything) when pydantic cannot describe it."""
    try:
        return self.model().model_json_schema()
    except (PydanticInvalidForJsonSchema, PydanticSchemaGenerationError) as exc:
        logger.debug("No answer schema for group prompt: %s", exc)
        return {}

validate_answer

validate_answer(value: Any) -> dict[str, Any]

Accepts a mapping (or an instance of the compiled model) and returns each item's typed value.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> dict[str, Any]:
    """Accepts a mapping (or an instance of the compiled model) and returns each item's typed value."""
    model = self.model()
    if isinstance(value, BaseModel):
        value = {name: getattr(value, name) for name in self.items if hasattr(value, name)}
    try:
        validated = model.model_validate(value)
    except ValidationError as exc:
        raise AnswerRejected(_message(exc)) from None
    return {name: getattr(validated, name) for name in self.items}

MarkdownRequest dataclass

MarkdownRequest(
    markdown: str,
    title: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
)

Bases: Request

Shows a Markdown document and blocks until the user continues (no answer is collected).

The web UI and the TUI render the Markdown; the console prints it with Rich. Raw HTML in the document is not rendered (use MediaRequest with media="html" for HTML).

Attributes:

Name Type Description
markdown str

The document (CommonMark, plus tables and strikethrough).

title str | None

Optional heading shown above it.

button_label str

Label of the button that continues.

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

Returns the JSON Schema a valid answer must satisfy (no answer, by default).

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """Returns the JSON Schema a valid answer must satisfy (no answer, by default)."""
    return {"type": "null"}

validate_answer

validate_answer(value: Any) -> None

Accepts anything: continuing is the answer (None).

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> None:
    """Accepts anything: continuing is the answer (``None``)."""

MediaRequest dataclass

MediaRequest(
    source: str | Path,
    media: MediaKind = "image",
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
)

Bases: Request

Shows an image, an HTML page or a web page, and blocks until the user continues (no answer is collected).

The web UI shows all three: local files are served by the run server (only the file of this prompt), URLs are loaded by the browser and inline HTML is shown in a sandboxed frame. Clients that cannot show the media (the console, the TUI) log a warning naming the file or URL instead, and still wait for the user to continue.

Attributes:

Name Type Description
source str | Path

A local file (image or HTML page), an http(s) URL, or — for media="html" — the HTML itself.

media MediaKind

"image", "html" (a page or a fragment) or "url" (a web page, shown in a frame when the site allows it).

title str | None

Optional heading shown above it.

caption str | None

Optional text shown below it.

button_label str

Label of the button that continues.

field str | None

Logical field name used in the persisted transcript.

location property

location: Literal['url', 'file', 'inline']

Where the media is: a URL, a local file, or (HTML only) the source itself.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

Returns the JSON Schema a valid answer must satisfy (no answer, by default).

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """Returns the JSON Schema a valid answer must satisfy (no answer, by default)."""
    return {"type": "null"}

local_file

local_file() -> Path | None

The local file to show, when the media is one and it exists.

Source code in src/clabe/ui/_requests.py
def local_file(self) -> Path | None:
    """The local file to show, when the media is one and it exists."""
    if self.location != "file":
        return None
    path = Path(self.source).expanduser().resolve()
    return path if path.is_file() else None

describe

describe() -> str

A one-line description for clients that cannot show the media.

Source code in src/clabe/ui/_requests.py
def describe(self) -> str:
    """A one-line description for clients that cannot show the media."""
    where = "inline HTML" if self.location == "inline" else str(self.source)
    return f"{self.media} {where}"

validate_answer

validate_answer(value: Any) -> None

Accepts anything: continuing is the answer (None).

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> None:
    """Accepts anything: continuing is the answer (``None``)."""

NumberRequest dataclass

NumberRequest(
    label: str,
    default: float | None = None,
    field: str | None = None,
    minimum: float | None = None,
    maximum: float | None = None,
    step: float | None = None,
    widget: Literal["input", "slider"] = "input",
)

Bases: Request

A declarative request for a floating-point number, optionally bounded.

Attributes:

Name Type Description
label str

The prompt shown to the user.

default float | None

Value returned when the user submits an empty answer.

field str | None

Logical field name used in the persisted transcript.

minimum float | None

Smallest accepted value (inclusive), if any.

maximum float | None

Largest accepted value (inclusive), if any.

step float | None

The value must be a multiple of step, if set.

widget Literal['input', 'slider']

Rendering hint: "input" (type a value) or "slider" (pick within the bounds). Clients without a slider fall back to an input showing the range.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

A number, with its bounds, step and widget hint.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """A number, with its bounds, step and widget hint."""
    schema: dict[str, Any] = {"type": "number"}
    if self.minimum is not None:
        schema["minimum"] = self.minimum
    if self.maximum is not None:
        schema["maximum"] = self.maximum
    if self.step is not None:
        schema["multipleOf"] = self.step
    if self.widget != "input":
        schema["x-widget"] = self.widget
    return schema

validate_answer

validate_answer(value: Any) -> float

Accepts a number or numeric text within the bounds; an empty answer falls back to the default.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> float:
    """Accepts a number or numeric text within the bounds; an empty answer falls back to the default."""
    if value in ("", None) and self.default is not None:
        return self.default
    if isinstance(value, bool):
        raise AnswerRejected("Please enter a valid number.")
    try:
        number = float(value)
    except (TypeError, ValueError):
        raise AnswerRejected("Please enter a valid number.") from None
    if self.minimum is not None and number < self.minimum:
        raise AnswerRejected(f"Must be ≥ {self.minimum:g}.")
    if self.maximum is not None and number > self.maximum:
        raise AnswerRejected(f"Must be ≤ {self.maximum:g}.")
    if self.step is not None and not _is_multiple(number, self.step):
        raise AnswerRejected(f"Must be a multiple of {self.step:g}.")
    return number

PathRequest dataclass

PathRequest(
    label: str,
    start: str | PathLike | None = None,
    default: str | None = None,
    must_exist: bool = True,
    kind: Literal["file", "dir", "any"] = "file",
    extensions: Sequence[str] | None = None,
    field: str | None = None,
    help: str | None = None,
)

Bases: Request

A declarative request to choose a filesystem path.

Frontends render this as whatever browsing UI is appropriate (a live, filesystem-aware browser on a console; a modal file-browser dialog on a TUI/GUI). Application code only describes what it needs — a file or a directory, which extensions are acceptable, whether the target must already exist — never how to browse for it.

Attributes:

Name Type Description
label str

The prompt shown to the user.

start str | PathLike | None

Directory (or partial path) to open the browser in. Defaults to the current working directory.

default str | None

Value returned when the user submits an empty answer.

must_exist bool

Whether the chosen path must already exist on disk. For kind="dir", only honored on frontends whose picker supports navigating to a not-yet-created directory; the Textual frontend's directory dialog only ever lists existing directories, so a new one can't be named there regardless of this flag.

kind Literal['file', 'dir', 'any']

Restricts the selectable target: "file", "dir", or "any". "any" is more expensive to render (frontends that need a dedicated file-vs-folder dialog, e.g. the Textual one, ask an extra up-front question to disambiguate) — prefer "file"/ "dir" whenever the field's intent is known.

extensions Sequence[str] | None

When set, only files with one of these suffixes (e.g. [".json"]) are selectable. Ignored when kind="dir". Matching is case-insensitive and tolerates a missing leading dot.

field str | None

Logical field name used in the persisted transcript.

help str | None

Optional supplementary help text.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

normalized_extensions

normalized_extensions() -> set[str] | None

Returns extensions as lowercase, dot-prefixed suffixes, or None if unset.

See normalize_extensions — every frontend must compare against this (or the free function directly) rather than re-deriving its own normalized set, so a file offered by a picker is never subsequently rejected by validation over a case or leading-dot mismatch.

Source code in src/clabe/ui/_requests.py
def normalized_extensions(self) -> set[str] | None:
    """Returns ``extensions`` as lowercase, dot-prefixed suffixes, or ``None`` if unset.

    See `normalize_extensions` — every frontend must compare against
    this (or the free function directly) rather than re-deriving its own
    normalized set, so a file offered by a picker is never subsequently
    rejected by validation over a case or leading-dot mismatch.
    """
    return normalize_extensions(self.extensions)

answer_schema

answer_schema() -> dict[str, Any]

A path string, or null (cancelled).

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """A path string, or ``null`` (cancelled)."""
    return {"type": ["string", "null"]}

validate_answer

validate_answer(value: Any) -> Path | None

Accepts None (cancelled) or a path satisfying the request; an empty answer falls back to the default.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> Path | None:
    """Accepts ``None`` (cancelled) or a path satisfying the request; an empty answer falls back to the default."""
    if value == "":
        value = self.default
    if value is None:
        return None
    path = Path(value)
    error = validate_path(self, path)
    if error is not None:
        raise AnswerRejected(error)
    return path

PickRequest dataclass

PickRequest(
    label: str,
    options: Sequence[str | Choice],
    default: str | None = None,
    allow_none: bool = True,
    none_label: str = "None",
    field: str | None = None,
    help: str | None = None,
)

Bases: Request

A declarative request to pick one option from a list.

Frontends render this however is appropriate (a numbered list on a console, a dropdown/option-list in a TUI/GUI, a <select> on the web). Application code only describes what it needs, never how to ask.

Attributes:

Name Type Description
label str

The prompt shown to the user.

options Sequence[str | Choice]

The available options (plain strings or Choice).

default str | None

Value selected by default when the frontend supports it.

allow_none bool

Whether a "none" sentinel option is offered.

none_label str

Label for the "none" option when allow_none is set.

field str | None

Logical field name used in the persisted transcript.

help str | None

Optional supplementary help text.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

choices

choices() -> list[Choice]

Normalize options into a list of Choice.

Source code in src/clabe/ui/_requests.py
def choices(self) -> list[Choice]:
    """Normalize ``options`` into a list of `Choice`."""
    return [opt if isinstance(opt, Choice) else Choice(value=opt) for opt in self.options]

answer_schema

answer_schema() -> dict[str, Any]

One of the option values, or null when the request allows it.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """One of the option values, or ``null`` when the request allows it."""
    values: list[Any] = [c.value for c in self.choices()]
    return {"enum": values + [None] if self.allow_none else values}

validate_answer

validate_answer(value: Any) -> Any

Accepts one of the option values, or None when the request allows it.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> Any:
    """Accepts one of the option values, or ``None`` when the request allows it."""
    if value is None:
        if self.allow_none:
            return None
        raise AnswerRejected("Please choose one of the options.")
    if value not in [c.value for c in self.choices()]:
        raise AnswerRejected(f"{value!r} is not one of the options.")
    return value

ReadOnlyTable dataclass

ReadOnlyTable(
    columns: Sequence[str],
    rows: Sequence[Sequence[Any]],
    title: str | None = None,
    prompt: str | None = None,
    confirm_label: str = "OK",
    cancel_label: str = "Cancel",
    field: str | None = None,
)

Bases: Request

A declarative request to display tabular data read-only and collect a yes/no.

The table is never editable; it exists to show the user a set of values and gather a single confirmation. The affirmative button returns True and the negative button returns False (as does dismissing the dialog).

Prefer the constructors over populating columns and rows by hand:

  • from_records — a sequence of mappings, one row each; columns are inferred from the keys (first-seen order) unless given explicitly.
  • from_object — a Pydantic model instance or a plain mapping rendered as a two-column Parameter | Value table, one row per field/key.

Attributes:

Name Type Description
columns Sequence[str]

Column headers, left to right.

rows Sequence[Sequence[Any]]

Row values; each inner sequence aligns positionally to columns.

title str | None

Optional title shown above the table.

prompt str | None

Optional question shown near the buttons (e.g. "Is this correct?").

confirm_label str

Label on the affirmative button. Defaults to "OK".

cancel_label str

Label on the negative button. Defaults to "Cancel".

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

A boolean.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """A boolean."""
    return {"type": "boolean"}

validate_answer

validate_answer(value: Any) -> bool

Accepts a strict boolean.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> bool:
    """Accepts a strict boolean."""
    return _boolean(value)

from_records classmethod

from_records(
    records: Sequence[Mapping[str, Any]],
    *,
    columns: Sequence[str] | None = None,
    **kwargs: Any,
) -> ReadOnlyTable

Build a table from a sequence of mappings (one row per mapping).

When columns is omitted it is inferred from the union of the record keys, preserving first-seen order. Keys absent from a given record render as empty cells.

Source code in src/clabe/ui/_requests.py
@classmethod
def from_records(
    cls,
    records: Sequence[Mapping[str, Any]],
    *,
    columns: Sequence[str] | None = None,
    **kwargs: Any,
) -> "ReadOnlyTable":
    """
    Build a table from a sequence of mappings (one row per mapping).

    When ``columns`` is omitted it is inferred from the union of the record
    keys, preserving first-seen order. Keys absent from a given record render
    as empty cells.
    """
    records = list(records)
    if columns is None:
        seen: dict = {}
        for record in records:
            for key in record:
                seen.setdefault(key, None)
        columns = list(seen)
    else:
        columns = list(columns)
    rows = [[record.get(column, "") for column in columns] for record in records]
    return cls(columns=columns, rows=rows, **kwargs)

from_object classmethod

from_object(
    obj: Mapping[str, Any] | BaseModel,
    *,
    key_header: str = "Parameter",
    value_header: str = "Value",
    **kwargs: Any,
) -> ReadOnlyTable

Build a two-column Parameter | Value table from a model or mapping.

Accepts a Pydantic model instance or a plain mapping; each field/key becomes one row.

Source code in src/clabe/ui/_requests.py
@classmethod
def from_object(
    cls,
    obj: Mapping[str, Any] | BaseModel,
    *,
    key_header: str = "Parameter",
    value_header: str = "Value",
    **kwargs: Any,
) -> "ReadOnlyTable":
    """
    Build a two-column ``Parameter | Value`` table from a model or mapping.

    Accepts a Pydantic model instance or a plain mapping; each field/key
    becomes one row.
    """
    if isinstance(obj, BaseModel):
        data = obj.model_dump()
    elif isinstance(obj, Mapping):
        data = dict(obj)
    else:
        raise TypeError(f"from_object expects a Pydantic model or mapping, got {type(obj).__name__}.")
    rows = [[str(key), value] for key, value in data.items()]
    return cls(columns=[key_header, value_header], rows=rows, **kwargs)

Request dataclass

Request()

Base of every declarative prompt request.

A request describes what to ask; it never asks. It knows its prompt kind, how to describe itself to any client as JSON (spec), the JSON Schema of a valid answer (answer_schema) and how to check and coerce an answer (validate_answer), so every client and the run apply the same rules.

Attributes:

Name Type Description
prompt_kind str

The prompt kind ("text", "pick", ...), shared by every instance of a request class. (Not kind: PathRequest already has a kind field.)

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

Returns the JSON Schema a valid answer must satisfy (no answer, by default).

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """Returns the JSON Schema a valid answer must satisfy (no answer, by default)."""
    return {"type": "null"}

validate_answer

validate_answer(value: Any) -> Any

Validates value and returns it coerced to the type the asker expects.

Raises:

Type Description
AnswerRejected

The answer is not acceptable; the prompt should stay open.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> Any:
    """Validates ``value`` and returns it coerced to the type the asker expects.

    Raises:
        AnswerRejected: The answer is not acceptable; the prompt should stay open.
    """
    raise NotImplementedError(f"{type(self).__name__} does not validate answers.")

TextRequest dataclass

TextRequest(
    label: str,
    default: str | None = None,
    multiline: bool = False,
    validators: list[Validator] = list(),
    field: str | None = None,
)

Bases: Request

A declarative request for free-form text.

Attributes:

Name Type Description
label str

The prompt shown to the user.

default str | None

Value returned when the user submits an empty answer.

multiline bool

Hint that a multi-line editor is appropriate.

validators list[Validator]

Validators applied to the answer; the frontend re-prompts and surfaces the returned error until they all pass.

field str | None

Logical field name used in the persisted transcript.

spec

spec() -> dict[str, Any]

Returns a JSON-safe description of what to show (callables dropped, models named).

Source code in src/clabe/ui/_requests.py
def spec(self) -> dict[str, Any]:
    """Returns a JSON-safe description of what to show (callables dropped, models named)."""
    return pydantic_core.to_jsonable_python(self._spec_fields(), fallback=_jsonable_fallback, bytes_mode="base64")

answer_schema

answer_schema() -> dict[str, Any]

A string.

Source code in src/clabe/ui/_requests.py
def answer_schema(self) -> dict[str, Any]:
    """A string."""
    return {"type": "string"}

validate_answer

validate_answer(value: Any) -> str

Accepts a string, falling back to the default when empty, then runs the validators.

Source code in src/clabe/ui/_requests.py
def validate_answer(self, value: Any) -> str:
    """Accepts a string, falling back to the default when empty, then runs the validators."""
    return _text(self, value)

NavigationRequested

NavigationRequested(action: Literal['back', 'forward'])

Bases: Exception

Raised by a client's ask when the user asks to navigate instead of answering (e.g. Alt+← in the TUI).

Whoever drives the client handles it: during a run, LocalClient goes back ("back") or forward ("forward") and asks again if the run refuses; outside a run it is ignored.

Parameters:

Name Type Description Default
action Literal['back', 'forward']

"back" or "forward".

required
Source code in src/clabe/ui/_session.py
def __init__(self, action: Literal["back", "forward"]) -> None:
    super().__init__(action)
    self.action = action

NoSessionError

Bases: RuntimeError

Raised by ask when nothing can ask the user.

PromptCancelledError

Bases: Exception

Raised by a prompt that was cancelled before it was answered (e.g. the run went back or aborted).

Session

Bases: Protocol

Something that can ask the user and tell them things: a run, or a local client outside a run.

ask

ask(request: Request) -> Any

Asks request and blocks until it is answered; returns the validated answer.

Source code in src/clabe/ui/_session.py
def ask(self, request: Request) -> Any:
    """Asks ``request`` and blocks until it is answered; returns the validated answer."""
    ...

notify

notify(message: str, level: MessageLevel = INFO) -> None

Tells the user something, without expecting an answer.

Source code in src/clabe/ui/_session.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Tells the user something, without expecting an answer."""
    ...

header

header(text: str) -> None

Shows the user a prominent header.

Source code in src/clabe/ui/_session.py
def header(self, text: str) -> None:
    """Shows the user a prominent header."""
    ...

TextualClient

TextualClient()

A Client backed by a single persistent Textual app.

The app is started lazily on first use and runs on a background thread for the remainder of the session. Messages, answered prompts, and live activity all render inside the one app; console logging is muted for the app's lifetime so nothing corrupts the display.

Like every client it never validates: ask returns the raw answer and whoever drives the client (a run, or a ClientSession) validates it and asks again if needed.

Source code in src/clabe/ui/_textual.py
def __init__(self) -> None:
    self._app: _LauncherApp | None = None
    self._thread: threading.Thread | None = None
    self._log_handler: _TuiLogHandler | None = None
    self._prev_console_level: int | None = None
    self._reporter: Callable[[str], str] | None = None

set_context

set_context(context: Any) -> None

Shows what the run is about (a RunContext) in the bar under the header.

Source code in src/clabe/ui/_textual.py
def set_context(self, context: Any) -> None:
    """Shows what the run is about (a [`RunContext`][clabe.workflow.RunContext]) in the bar under the header."""
    app = self._ensure()
    app.call_from_thread(app.set_context, context)

set_reporter

set_reporter(reporter: Callable[[str], str] | None) -> None

Lets the user report an issue (F3): reporter files a report with the user's comment and returns its id. None turns reporting off.

Source code in src/clabe/ui/_textual.py
def set_reporter(self, reporter: Callable[[str], str] | None) -> None:
    """Lets the user report an issue (F3): ``reporter`` files a report with the user's comment and returns its
    id. ``None`` turns reporting off."""
    self._reporter = reporter
    if self._app is not None:
        self._app.reporter = reporter

close

close() -> None

Tear down the TUI and restore console logging.

Source code in src/clabe/ui/_textual.py
def close(self) -> None:
    """Tear down the TUI and restore console logging."""
    if self._app is None:
        return
    from ..logging import set_console_level
    from ..runnable import get_activity_indicator

    get_activity_indicator().set_sink(None)
    if self._log_handler is not None:
        logging.getLogger().removeHandler(self._log_handler)
        self._log_handler = None
    if self._prev_console_level is not None:
        set_console_level(self._prev_console_level)
        self._prev_console_level = None
    try:
        self._app.call_from_thread(self._app.exit)
    except Exception as exc:  # noqa: BLE001 -- best-effort teardown; the thread join below still runs either way
        logger.debug("Ignoring error while exiting the TUI app during close(): %s", exc)
    if self._thread is not None:
        self._thread.join(timeout=5)
    self._app = None
    self._thread = None

ask

ask(request: Request) -> Any

Shows request in the TUI and returns the raw answer, echoing it in the Session pane.

Raises:

Type Description
PromptCancelledError

cancel was called while the prompt was shown.

ValueError

request is not a primitive prompt (e.g. an unresolved field request).

Source code in src/clabe/ui/_textual.py
def ask(self, request: Request) -> Any:
    """Shows ``request`` in the TUI and returns the raw answer, echoing it in the Session pane.

    Raises:
        PromptCancelledError: `cancel` was called while the prompt was shown.
        ValueError: ``request`` is not a primitive prompt (e.g. an unresolved field request).
    """
    handler = self._HANDLERS.get(request.prompt_kind)
    if handler is None:
        raise ValueError(f"Clients cannot ask {request.prompt_kind!r} prompts; resolve the request first.")
    answer = getattr(self, handler)(request)
    self._echo_answer(request, answer)
    return answer

notify

notify(message: str, level: MessageLevel = INFO) -> None

Writes a timestamped, level-styled message to the Session pane.

Source code in src/clabe/ui/_textual.py
def notify(self, message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Writes a timestamped, level-styled message to the Session pane."""
    self._ensure()
    line = Text(f"[{_local_time()}] ", style="dim")
    line.append_text(_linkify(message, _RICH_STYLES[level]))
    self._write_user(line)

header

header(text: str) -> None

Shows the banner as the empty-state logo in the Session pane.

Source code in src/clabe/ui/_textual.py
def header(self, text: str) -> None:
    """Shows the banner as the empty-state logo in the Session pane."""
    app = self._ensure()
    app.call_from_thread(app.set_logo, text)

cancel

cancel() -> None

Abort the waiting prompt from any thread; it raises PromptCancelledError.

Source code in src/clabe/ui/_textual.py
def cancel(self) -> None:
    """Abort the waiting prompt from any thread; it raises `PromptCancelledError`."""
    app = self._app
    if app is None:
        return
    try:
        app.call_from_thread(app.cancel_pending)
    except RuntimeError as exc:  # the app is shutting down or this is the app's own thread
        logger.debug("Could not cancel the TUI prompt: %s", exc)

set_experiment

set_experiment(name: str) -> None

Show the running experiment name in the TUI header.

Source code in src/clabe/ui/_textual.py
def set_experiment(self, name: str) -> None:
    """Show the running experiment name in the TUI header."""
    app = self._ensure()
    app.call_from_thread(app.set_experiment, name)

make_client

make_client(backend: str = 'auto') -> Client

Builds a client for the requested backend.

Parameters:

Name Type Description Default
backend str

"auto" (TUI on a terminal when the frontend extra is installed, else console), "tui", "console" or "headless" (no screen: prompts are answered from the web UI).

'auto'

Raises:

Type Description
ValueError

backend is not a recognized option.

ImportError

"tui" without the frontend extra.

Source code in src/clabe/ui/_client.py
def make_client(backend: str = "auto") -> Client:
    """Builds a client for the requested backend.

    Args:
        backend: ``"auto"`` (TUI on a terminal when the ``frontend`` extra is installed, else console), ``"tui"``,
            ``"console"`` or ``"headless"`` (no screen: prompts are answered from the web UI).

    Raises:
        ValueError: ``backend`` is not a recognized option.
        ImportError: ``"tui"`` without the ``frontend`` extra.
    """
    from .._extras import has_tui, require_tui
    from ..logging import clabe_console
    from ._console import ConsoleClient

    choice = (backend or "auto").lower()
    if choice == "auto":
        choice = "tui" if clabe_console.is_terminal and has_tui() else "console"
    if choice == "tui":
        require_tui()
        from ._textual import TextualClient

        return TextualClient()
    if choice == "console":
        return ConsoleClient()
    if choice == "headless":
        return HeadlessClient()
    raise ValueError(f"Unknown UI backend: {backend!r}")

acknowledge

acknowledge(
    message: str,
    *,
    title: str = "Notice",
    button_label: str = "OK",
    field: str | None = None,
) -> None

Shows message and blocks until the user dismisses it (see AcknowledgeRequest).

Source code in src/clabe/ui/_session.py
def acknowledge(message: str, *, title: str = "Notice", button_label: str = "OK", field: str | None = None) -> None:
    """Shows ``message`` and blocks until the user dismisses it (see [`AcknowledgeRequest`][clabe.ui.AcknowledgeRequest])."""
    ask(AcknowledgeRequest(message=message, title=title, button_label=button_label, field=field))

activity

activity(description: str) -> AbstractContextManager[None]

Shows live work (e.g. a running app) for the duration of a block; a run records it as activity events.

Parameters:

Name Type Description Default
description str

What the work is, as shown to the user.

required
Source code in src/clabe/ui/_session.py
def activity(description: str) -> contextlib.AbstractContextManager[None]:
    """Shows live work (e.g. a running app) for the duration of a block; a run records it as activity events.

    Args:
        description: What the work is, as shown to the user.
    """
    from ..runnable import get_activity_indicator  # lazily: clabe.runnable imports clabe.ui

    return get_activity_indicator().activity(description)

ask

ask(request: Request) -> Any

Asks request through the bound session and returns its validated answer.

Parameters:

Name Type Description Default
request Request

What to ask (e.g. a TextRequest).

required

Returns:

Type Description
Any

The answer, validated and coerced by the request (a FieldRequest gives the typed field

Any

value).

Raises:

Type Description
NoSessionError

Nothing is bound that can ask the user.

PromptCancelledError

The prompt was cancelled before it was answered.

Source code in src/clabe/ui/_session.py
def ask(request: Request) -> Any:
    """Asks ``request`` through the bound session and returns its validated answer.

    Args:
        request: What to ask (e.g. a [`TextRequest`][clabe.ui.TextRequest]).

    Returns:
        The answer, validated and coerced by the request (a [`FieldRequest`][clabe.ui.FieldRequest] gives the typed field
        value).

    Raises:
        NoSessionError: Nothing is bound that can ask the user.
        PromptCancelledError: The prompt was cancelled before it was answered.
    """
    session = current_session()
    if session is None:
        raise NoSessionError("No session is bound. User interaction is not possible.")
    return session.ask(request)

autocomplete

autocomplete(
    label: str,
    options: Sequence[str] | OptionsFunction,
    *,
    default: str | None = None,
    strict: bool = False,
    validators: Sequence[Validator] = (),
    field: str | None = None,
    help: str | None = None,
) -> str

Asks for text completed against options, a list or a function of the typed text returning the options (see AutoCompleteRequest).

Source code in src/clabe/ui/_session.py
def autocomplete(
    label: str,
    options: Sequence[str] | OptionsFunction,
    *,
    default: str | None = None,
    strict: bool = False,
    validators: Sequence[Validator] = (),
    field: str | None = None,
    help: str | None = None,
) -> str:
    """Asks for text completed against ``options``, a list or a function of the typed text returning the options (see
    [`AutoCompleteRequest`][clabe.ui.AutoCompleteRequest])."""
    return ask(
        AutoCompleteRequest(
            label=label,
            options=options,
            default=default,
            strict=strict,
            validators=list(validators),
            field=field,
            help=help,
        )
    )

bind

bind(
    session: Session | None,
) -> Generator[None, None, None]

Binds session as the process' session for the block, then removes that binding.

Process-wide: every thread sees the binding. Bindings form an ordered list and the latest one is current, so blocks may end in any order (e.g. on different threads): ending a block removes its own binding wherever it is, and never brings back a binding whose block has already ended.

Parameters:

Name Type Description Default
session Session | None

The session to bind, or None for "no session" while this binding is the latest.

required
Source code in src/clabe/ui/_session.py
@contextlib.contextmanager
def bind(session: Session | None) -> Generator[None, None, None]:
    """Binds ``session`` as the process' session for the block, then removes that binding.

    Process-wide: every thread sees the binding. Bindings form an ordered list and the latest one is current, so
    blocks may end in any order (e.g. on different threads): ending a block removes its own binding wherever it is,
    and never brings back a binding whose block has already ended.

    Args:
        session: The session to bind, or ``None`` for "no session" while this binding is the latest.
    """
    binding = _Binding(session)
    with _bindings_lock:
        _bindings.append(binding)
    try:
        yield
    finally:
        with _bindings_lock:
            if binding in _bindings:  # by identity: _Binding does not define equality
                _bindings.remove(binding)

confirm

confirm(
    label: str,
    *,
    default: bool = False,
    field: str | None = None,
) -> bool

Asks a yes/no question (see ConfirmRequest).

Source code in src/clabe/ui/_session.py
def confirm(label: str, *, default: bool = False, field: str | None = None) -> bool:
    """Asks a yes/no question (see [`ConfirmRequest`][clabe.ui.ConfirmRequest])."""
    return ask(ConfirmRequest(label=label, default=default, field=field))

current_session

current_session() -> Session | None

Returns the session of the latest binding, or None if nothing is bound.

Source code in src/clabe/ui/_session.py
def current_session() -> Session | None:
    """Returns the session of the latest binding, or ``None`` if nothing is bound."""
    with _bindings_lock:
        return _bindings[-1].session if _bindings else None

field

field(
    model: type,
    field_name: str,
    *,
    initial: object | None = None,
) -> Any

Asks for one field of model and returns the typed value (see FieldRequest).

The session resolves the field to the prompt its type calls for (e.g. yes/no for a bool).

Source code in src/clabe/ui/_session.py
def field(model: type, field_name: str, *, initial: object | None = None) -> Any:
    """Asks for one field of ``model`` and returns the typed value (see [`FieldRequest`][clabe.ui.FieldRequest]).

    The session resolves the field to the prompt its type calls for (e.g. yes/no for a ``bool``).
    """
    return ask(FieldRequest(model=model, field_name=field_name, initial=initial))

form

form(
    model: type,
    *,
    title: str | None = None,
    initial: object | None = None,
    field: str | None = None,
) -> Any

Asks to fill in model as a form; the model instance, or None when cancelled (see FormRequest).

Source code in src/clabe/ui/_session.py
def form(model: type, *, title: str | None = None, initial: object | None = None, field: str | None = None) -> Any:
    """Asks to fill in ``model`` as a form; the model instance, or ``None`` when cancelled (see
    [`FormRequest`][clabe.ui.FormRequest])."""
    return ask(FormRequest(model=model, title=title, initial=initial, field=field))

group

group(
    title: str | None = None, /, **items: Request
) -> dict[str, Any]

Asks several prompts together as one (e.g. a text input and a slider) and returns their answers by name.

Parameters:

Name Type Description Default
title str | None

Optional title shown above the group.

None
**items Request

The prompts, by name: text, number, confirm, pick, autocomplete, path or field requests.

{}

Returns:

Type Description
dict[str, Any]

Each item's validated value, by name.

Source code in src/clabe/ui/_session.py
def group(title: str | None = None, /, **items: Request) -> dict[str, Any]:
    """Asks several prompts together as one (e.g. a text input and a slider) and returns their answers by name.

    Args:
        title: Optional title shown above the group.
        **items: The prompts, by name: text, number, confirm, pick, autocomplete, path or field requests.

    Returns:
        Each item's validated value, by name.
    """
    return ask(GroupRequest(items=items, title=title))

header

header(text: str) -> None

Shows the user a header through the bound session; logs it when nothing can show it.

Parameters:

Name Type Description Default
text str

The header text.

required
Source code in src/clabe/ui/_session.py
def header(text: str) -> None:
    """Shows the user a header through the bound session; logs it when nothing can show it.

    Args:
        text: The header text.
    """
    session = current_session()
    if session is not None:
        session.header(text)
        return
    logger.info("%s", text)

html

html(
    source: str | Path,
    *,
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None

Shows an HTML page (a local file, a URL, or the HTML itself) and blocks until the user continues.

The page is sandboxed. Clients that cannot show HTML log a warning instead (see MediaRequest).

Source code in src/clabe/ui/_session.py
def html(
    source: str | Path,
    *,
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None:
    """Shows an HTML page (a local file, a URL, or the HTML itself) and blocks until the user continues.

    The page is sandboxed. Clients that cannot show HTML log a warning instead (see [`MediaRequest`][clabe.ui.MediaRequest]).
    """
    ask(MediaRequest(source, "html", title=title, caption=caption, button_label=button_label, field=field))

image

image(
    source: str | Path,
    *,
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None

Shows an image (a local file or a URL) and blocks until the user continues.

Clients that cannot show images log a warning with the file instead (see MediaRequest).

Source code in src/clabe/ui/_session.py
def image(
    source: str | Path,
    *,
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None:
    """Shows an image (a local file or a URL) and blocks until the user continues.

    Clients that cannot show images log a warning with the file instead (see [`MediaRequest`][clabe.ui.MediaRequest]).
    """
    ask(MediaRequest(source, "image", title=title, caption=caption, button_label=button_label, field=field))

markdown

markdown(
    text: str,
    *,
    title: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None

Shows a Markdown document and blocks until the user continues (see MarkdownRequest).

Source code in src/clabe/ui/_session.py
def markdown(text: str, *, title: str | None = None, button_label: str = "Continue", field: str | None = None) -> None:
    """Shows a Markdown document and blocks until the user continues (see [`MarkdownRequest`][clabe.ui.MarkdownRequest])."""
    ask(MarkdownRequest(markdown=text, title=title, button_label=button_label, field=field))

notify

notify(message: str, level: MessageLevel = INFO) -> None

Tells the user something through the bound session; logs it (at level) when nothing can show it.

Parameters:

Name Type Description Default
message str

The text to show.

required
level MessageLevel

How prominently to show it.

INFO
Source code in src/clabe/ui/_session.py
def notify(message: str, level: MessageLevel = MessageLevel.INFO) -> None:
    """Tells the user something through the bound session; logs it (at ``level``) when nothing can show it.

    Args:
        message: The text to show.
        level: How prominently to show it.
    """
    session = current_session()
    if session is not None:
        session.notify(message, level)
        return
    logger.log(level.logging_level, "%s", message)

number

number(
    label: str,
    *,
    default: float | None = None,
    field: str | None = None,
    minimum: float | None = None,
    maximum: float | None = None,
    step: float | None = None,
    widget: Literal["input", "slider"] = "input",
) -> float

Asks for a number, optionally bounded (see NumberRequest).

Source code in src/clabe/ui/_session.py
def number(
    label: str,
    *,
    default: float | None = None,
    field: str | None = None,
    minimum: float | None = None,
    maximum: float | None = None,
    step: float | None = None,
    widget: Literal["input", "slider"] = "input",
) -> float:
    """Asks for a number, optionally bounded (see [`NumberRequest`][clabe.ui.NumberRequest])."""
    request = NumberRequest(
        label=label, default=default, field=field, minimum=minimum, maximum=maximum, step=step, widget=widget
    )
    return ask(request)

path

path(
    label: str,
    *,
    start: str | PathLike | None = None,
    default: str | None = None,
    must_exist: bool = True,
    kind: Literal["file", "dir", "any"] = "file",
    extensions: Sequence[str] | None = None,
    field: str | None = None,
    help: str | None = None,
) -> Path | None

Asks for a filesystem path; None when cancelled (see PathRequest).

Source code in src/clabe/ui/_session.py
def path(
    label: str,
    *,
    start: str | os.PathLike | None = None,
    default: str | None = None,
    must_exist: bool = True,
    kind: Literal["file", "dir", "any"] = "file",
    extensions: Sequence[str] | None = None,
    field: str | None = None,
    help: str | None = None,
) -> Path | None:
    """Asks for a filesystem path; ``None`` when cancelled (see [`PathRequest`][clabe.ui.PathRequest])."""
    return ask(
        PathRequest(
            label=label,
            start=start,
            default=default,
            must_exist=must_exist,
            kind=kind,
            extensions=extensions,
            field=field,
            help=help,
        )
    )

pick

pick(
    label: str,
    options: Sequence[str | Choice],
    *,
    default: str | None = None,
    allow_none: bool = True,
    none_label: str = "None",
    field: str | None = None,
    help: str | None = None,
) -> str | None

Asks to pick one option; None when the "none" option is picked (see PickRequest).

Source code in src/clabe/ui/_session.py
def pick(
    label: str,
    options: Sequence[str | Choice],
    *,
    default: str | None = None,
    allow_none: bool = True,
    none_label: str = "None",
    field: str | None = None,
    help: str | None = None,
) -> str | None:
    """Asks to pick one option; ``None`` when the "none" option is picked (see [`PickRequest`][clabe.ui.PickRequest])."""
    return ask(
        PickRequest(
            label=label,
            options=options,
            default=default,
            allow_none=allow_none,
            none_label=none_label,
            field=field,
            help=help,
        )
    )

table

table(
    columns: Sequence[str],
    rows: Sequence[Sequence[Any]],
    *,
    title: str | None = None,
    prompt: str | None = None,
    confirm_label: str = "OK",
    cancel_label: str = "Cancel",
    field: str | None = None,
) -> bool

Shows a read-only table and asks yes/no (see ReadOnlyTable).

Source code in src/clabe/ui/_session.py
def table(
    columns: Sequence[str],
    rows: Sequence[Sequence[Any]],
    *,
    title: str | None = None,
    prompt: str | None = None,
    confirm_label: str = "OK",
    cancel_label: str = "Cancel",
    field: str | None = None,
) -> bool:
    """Shows a read-only table and asks yes/no (see [`ReadOnlyTable`][clabe.ui.ReadOnlyTable])."""
    return ask(
        ReadOnlyTable(
            columns=columns,
            rows=rows,
            title=title,
            prompt=prompt,
            confirm_label=confirm_label,
            cancel_label=cancel_label,
            field=field,
        )
    )

text

text(
    label: str,
    *,
    default: str | None = None,
    multiline: bool = False,
    validators: Sequence[Validator] = (),
    field: str | None = None,
) -> str

Asks for free-form text (see TextRequest).

Source code in src/clabe/ui/_session.py
def text(
    label: str,
    *,
    default: str | None = None,
    multiline: bool = False,
    validators: Sequence[Validator] = (),
    field: str | None = None,
) -> str:
    """Asks for free-form text (see [`TextRequest`][clabe.ui.TextRequest])."""
    return ask(TextRequest(label=label, default=default, multiline=multiline, validators=list(validators), field=field))

url

url(
    address: str,
    *,
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None

Shows a web page and blocks until the user continues.

Sites that refuse to be framed still get a link to open them. Clients that cannot show web pages log a warning with the URL instead (see MediaRequest).

Source code in src/clabe/ui/_session.py
def url(
    address: str,
    *,
    title: str | None = None,
    caption: str | None = None,
    button_label: str = "Continue",
    field: str | None = None,
) -> None:
    """Shows a web page and blocks until the user continues.

    Sites that refuse to be framed still get a link to open them. Clients that cannot show web pages log a warning
    with the URL instead (see [`MediaRequest`][clabe.ui.MediaRequest]).
    """
    ask(MediaRequest(address, "url", title=title, caption=caption, button_label=button_label, field=field))