# Python API

This page lists the public Python classes and function signatures exposed by Bub, followed by tables explaining their parameters, fields, and methods. For step-by-step usage guides, see the [SDK guide](/docs/sdk/), [Tape](/docs/concepts/tape/), [Events](/docs/concepts/events/), and [Turn](/docs/concepts/turn/).

- **`bub.core`**: Core layer containing the `Agent` loop, model client protocols, tools, Tape, and the event bus. Importing only `bub.core` never reads YAML files or `BUB_*` environment variables and does not load the CLI or plugins.
- **`bub`**: Application layer containing `BubFramework`, `BubAgent`, channels, and configuration loading. Requires [installing](/docs/getting-started/install/) the `bub[app]` optional dependency.

`republic.*` types appearing in signatures come from the underlying Republic library and are not expanded separately on this page.

---

## Core {#core}

### `Agent` {#agent}

```python
from bub.core import Agent

class Agent:
    tools: dict[str, Tool]
    builtin_tools: list[BuiltinTool]
    system_prompt: SystemPrompt
    events: EventBus

    def __init__(
        self,
        *,
        model: Model | None = None,
        store: TapeStore | AsyncTapeStore | None = None,
        tools: Iterable[Tool | BuiltinTool] = (),
        system_prompt: SystemPrompt | PromptSection | Iterable[PromptSection] = (),
        context: TapeContext | None = None,
        sidecars: Sequence[TapeSidecar] = (),
        max_steps: int = sys.maxsize,
        max_tool_concurrency: int | None = None,
        name: str = "agent",
        command_prefix: str | None = None,
    ) -> None: ...

    def tape(self, name: str, *, state: TurnState | None = None) -> Tape: ...

    @asynccontextmanager
    async def session(
        self,
        name: str,
        *,
        state: TurnState | None = None,
        merge_back: bool = True,
    ) -> AsyncGenerator[Tape]: ...

    @asynccontextmanager
    async def run(
        self,
        prompt: str | list[UserContent],
        *,
        model: Model | None = None,
        options: Mapping[str, Any] | None = None,
        tape: str,
        state: TurnState | None = None,
        merge_back: bool = True,
        metadata: dict[str, Any] | None = None,
    ) -> AsyncGenerator[AsyncStreamEvents]: ...

    async def start(
        self,
        prompt: str | list[UserContent],
        *,
        model: Model | None = None,
        options: Mapping[str, Any] | None = None,
        tape: str,
        state: TurnState | None = None,
        merge_back: bool = True,
        metadata: dict[str, Any] | None = None,
    ) -> AsyncStreamEvents: ...

    async def run_on(
        self,
        tape: Tape,
        prompt: list[UserContent],
        *,
        model: Model | None = None,
        options: Mapping[str, Any] | None = None,
        metadata: dict[str, Any] | None = None,
        span: Span | None = None,
        on_close: Callable[[], Awaitable[None]] | None = None,
    ) -> AsyncStreamEvents: ...

    async def run_once(
        self,
        prompt: list[UserContent] | None,
        *,
        model: Model | None = None,
        options: Mapping[str, Any] | None = None,
        tape: Tape,
        state: StreamState | None = None,
        pending: Sequence[list[UserContent]] = (),
    ) -> AsyncGenerator[StreamEvent, None]: ...

    async def run_command(self, tape: Tape, line: str) -> str: ...

    async def prepare_tools(
        self,
        tape: Tape,
        prompt: list[UserContent] | None,
    ) -> list[Tool]: ...
```

**Constructor parameters** (`Agent.__init__`):

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `model` | `Model \| None` | `None` | Default model (`republic.ChatModel` or `ModelClient`); can also be passed per `run()` call |
| `store` | `TapeStore \| AsyncTapeStore \| None` | New `InMemoryTapeStore()` | Synchronous or asynchronous session history store |
| `tools` | `Iterable[Tool \| BuiltinTool]` | `()` | Local `Tool` objects (stored in `agent.tools`) and provider-executed tools such as `republic.tools.WebSearch()` (stored in `agent.builtin_tools`); later entries override earlier ones with the same name |
| `system_prompt` | `SystemPrompt \| PromptSection \| Iterable[PromptSection]` | `()` | System prompt; rendered once per Run before the first model Step and reused by later Steps |
| `context` | `TapeContext \| None` | `default_tape_context()` | Strategy for projecting Tape entries into model context messages |
| `sidecars` | `Sequence[TapeSidecar]` | `()` | Sibling `TapeSidecar` instances mounted alongside the main Tape |
| `max_steps` | `int` | `sys.maxsize` | Maximum model Steps per Run |
| `max_tool_concurrency` | `int \| None` | `None` | Maximum concurrent local tool calls within one model response (`1` runs tools sequentially; does not coordinate concurrency across separate Runs) |
| `name` | `str` | `"agent"` | Name used for the Agent's OpenTelemetry trace span |
| `command_prefix` | `str \| None` | `None` | Direct command prefix (`None` disables commands; when enabled, must be a non-empty string with no whitespace, such as `","`) |

**Run parameters** (`Agent.run` / `Agent.start`):

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `prompt` | `str \| list[UserContent]` | Required | User prompt text or multimodal content blocks for this Run |
| `model` | `Model \| None` | `self.model` | Model connection overriding the Agent's default model for this Run |
| `options` | `Mapping[str, Any] \| None` | `None` | Generation options passed to the underlying model call (`republic.ChatOptions`, such as `max_tokens` or `reasoning_effort`) |
| `tape` | `str` | Required | Name of the conversation Tape used by this Run |
| `state` | `TurnState \| None` | `None` | Request-scoped dictionary shared by tools and event handlers during this Run |
| `merge_back` | `bool` | `True` | Whether entries recorded on the Run's Tape fork are also written to the main Tape, each as it is appended (see [forks and merges](/docs/sdk/tape/#forks-and-merges)) |
| `metadata` | `dict[str, Any] \| None` | `None` | Run metadata emitted on `RunStarted`; never enters model context |

**Methods**:

| Method | Description |
| --- | --- |
| `run(...)` | Async context manager: runs on a fork of the named Tape, automatically closing the stream on exit; entries reach the main Tape according to `merge_back` |
| `start(...)` | Same parameters as `run(...)`, but returns `AsyncStreamEvents` directly; the caller must call `await stream.aclose()` |
| `tape(name, *, state=None)` | Returns a read-write `Tape` view for the given name without automatically writing an initial `session/start` anchor |
| `session(name, *, state=None, merge_back=True)` | Async context manager: opens a fork of the named Tape, whose entries reach the main Tape according to `merge_back` |
| `run_on(tape, prompt, ...)` | Executes a Run on an already opened `Tape` instance |
| `run_once(...)` | Executes a single model Step and all tool calls requested by that response |
| `run_command(tape, line)` | Executes a direct command line without calling the model |
| `prepare_tools(tape, prompt)` | Overridable hook called once at the start of each Run to select active tools; calls outside the prepared set trigger a fresh `prepare_tools(tape, None)` lookup |

---

### `Model`, `ModelClient`, and `ChatModelClient` {#model}

```python
from bub.core import ChatModelClient, Model, ModelClient

type Model = republic.ChatModel | ModelClient

class ModelClient(Protocol):
    max_tokens: int | None

    @property
    def spec(self) -> str: ...

    def open_stream(
        self,
        messages: list[republic.Message],
        *,
        spec: str,
        options: Mapping[str, Any],
    ) -> AbstractAsyncContextManager[tuple[str, republic.Stream[Any]]]: ...

class ChatModelClient:
    max_tokens: int | None = None

    def __init__(self, model: republic.ChatModel) -> None: ...

    @property
    def spec(self) -> str: ...

    @asynccontextmanager
    async def open_stream(
        self,
        messages: list[republic.Message],
        *,
        spec: str,
        options: Mapping[str, Any],
    ) -> AsyncIterator[tuple[str, republic.Stream[Any]]]: ...
```

| Member / Parameter | Type | Description |
| --- | --- | --- |
| `spec` | `str` | Model identifier string (`provider:model`) |
| `max_tokens` | `int \| None` | Default maximum output tokens; overridden by call-level `options["max_tokens"]` |
| `open_stream(messages, *, spec, options)` | Async context manager | Opens a streaming model call and yields `(resolved_spec, republic_stream)` |
| `ChatModelClient(model)` | `republic.ChatModel` | Adapts a `republic.ChatModel` to `ModelClient`; the caller still owns the underlying model lifecycle |

---

### `Tool`, `ToolContext`, and `@tool` {#tools}

```python
from bub.core import Tool, ToolContext, tool
from bub.core.tools import ToolExposure, content_result, result_content

type ToolExposure = Literal["auto", "direct", "code", "command"]

@dataclass(frozen=True)
class ToolContext:
    tape: Tape
    run_id: str | None = None
    state: dict[str, Any] = field(default_factory=dict)
    code_mode: bool = False
    command: bool = False
    events: EventBus | None = field(default=None, repr=False, compare=False)
    step_messages: list[republic.Message] = field(default_factory=list, repr=False, compare=False)
    call_id: str | None = None

@dataclass(frozen=True)
class Tool:
    name: str
    handler: Callable[..., Any]
    description: str = ""
    parameters: dict[str, Any] = field(default_factory=dict)
    context: bool = False
    exposure: ToolExposure = "auto"
    renderer: Callable[[Any], str] | None = None
    output_schema: dict[str, Any] | None = None
    deferred: bool = False

    async def run(self, *args: Any, **kwargs: Any) -> Any: ...
    def render(self, result: Any) -> str: ...
    def to_schema(self) -> dict[str, Any]: ...

    @classmethod
    def from_callable(
        cls,
        func: Callable[..., Any],
        *,
        name: str | None = None,
        description: str | None = None,
        context: bool = False,
        exposure: ToolExposure = "auto",
        renderer: Callable[[Any], str] | None = None,
        deferred: bool = False,
    ) -> Tool: ...

def tool(
    func: Callable | None = None,
    *,
    name: str | None = None,
    model: type[BaseModel] | None = None,
    description: str | None = None,
    context: bool = False,
    exposure: ToolExposure = "auto",
    renderer: Callable[[Any], str] | None = None,
    deferred: bool = False,
) -> Tool | Callable[[Callable], Tool]: ...

def content_result(content: Sequence[UserContent]) -> dict[str, Any]: ...
def result_content(result: Any) -> list[UserContent]: ...
```

**`@tool` / `Tool` parameters and fields**:

| Parameter / Field | Type | Default | Description |
| --- | --- | --- | --- |
| `func` / `handler` | `Callable[..., Any]` | Required | Synchronous or asynchronous Python callable implementing the tool |
| `name` | `str \| None` | `func.__name__` | Tool name (dots are converted to underscores in model-facing schemas) |
| `model` | `type[BaseModel] \| None` | `None` | Optional Pydantic parameter model (used with `@tool(model=...)`) |
| `description` | `str \| None` | Function docstring | Description shown to the model |
| `parameters` | `dict[str, Any]` | Derived from type annotations | JSON Schema dictionary of the tool's input parameters |
| `context` | `bool` | `False` | When `True`, Bub injects `context: ToolContext` as a keyword argument (excluded from the model-facing schema) |
| `exposure` | `ToolExposure` | `"auto"` | Where the tool is callable: `"auto"` (model, code mode, and commands), `"direct"` (model only), `"code"` (`run_code` only), or `"command"` (text commands only) |
| `renderer` | `Callable[[Any], str] \| None` | `None` | Custom serializer converting the tool return value to a string |
| `output_schema` | `dict[str, Any] \| None` | Derived from return annotation | Output JSON Schema used when generating code mode type stubs |
| `deferred` | `bool` | `False` | When `True`, only the tool name and description are shown initially; the model loads the full schema on demand via `tool.describe` |

**`ToolContext` fields**:

| Field | Type | Description |
| --- | --- | --- |
| `tape` | `Tape` | Read-write `Tape` view for the current session |
| `run_id` | `str \| None` | Unique identifier of the current Run |
| `state` | `dict[str, Any]` | Request-scoped `TurnState` dictionary |
| `code_mode` | `bool` | Whether the call originated inside code mode (`run_code`) |
| `command` | `bool` | Whether the call originated from a direct command |
| `events` | `EventBus \| None` | The Agent's `EventBus` |
| `step_messages` | `list[republic.Message]` | User messages sent by the calling model Step (recorded onto the Tape after the Step's tool calls finish) |
| `call_id` | `str \| None` | Call ID assigned by the model (calls inside code mode share the outer `run_code` call's ID) |

Use `content_result(content)` to return text together with images, audio, or video from a tool; `result_content(result)` reconstructs the multimodal content blocks during context projection (see [Media storage boundaries](/docs/sdk/tape/#media)).

---

### `SystemPrompt`, `PromptSection`, and `PromptContext` {#system-prompt}

```python
from bub.core import PromptContext, PromptSection, SystemPrompt

@dataclass(frozen=True)
class PromptContext:
    agent: Agent
    tape: Tape
    prompt: list[UserContent]
    tools: list[Tool]
    model: str

    @property
    def state(self) -> TurnState: ...

    @property
    def available_tools(self) -> list[Tool]: ...

type PromptSection = str | Callable[[PromptContext], str | Awaitable[str | None] | None]

class SystemPrompt:
    def __init__(self, sections: Iterable[PromptSection] = ()) -> None: ...

    @classmethod
    def of(
        cls,
        value: SystemPrompt | PromptSection | Iterable[PromptSection],
    ) -> SystemPrompt: ...

    @property
    def sections(self) -> tuple[PromptSection, ...]: ...

    def add(self, section: S) -> S: ...
    def remove(self, section: PromptSection) -> None: ...
    async def render(self, context: PromptContext) -> str: ...
```

| Class / Member | Description |
| --- | --- |
| `PromptSection` | Fixed string, or a sync/async callable `(PromptContext) -> str \| None` |
| `SystemPrompt.add(section)` / `remove(section)` | Add or remove a prompt section in order |
| `await SystemPrompt.render(context)` | Evaluates all sections and joins non-empty results with newlines |
| `PromptContext` | Context passed during rendering, exposing `agent`, `tape`, `prompt`, `tools`, `model`, `state`, and `available_tools` |

---

### `bub.prompt` {#prompt}

```python
from bub.prompt import LegacyPrompt, UserContent, prompt_text, to_content, to_legacy_prompt

type UserContent = str | republic.Image | republic.Audio | republic.Video
type LegacyPrompt = str | list[dict[str, Any]]

def to_content(prompt: list[UserContent] | LegacyPrompt) -> list[UserContent]: ...
def to_legacy_prompt(content: list[UserContent]) -> LegacyPrompt: ...
def prompt_text(content: list[UserContent]) -> str: ...
```

| Type / Function | Description |
| --- | --- |
| `UserContent` | Single user input block: plain text or a Republic media object |
| `LegacyPrompt` | Legacy hook prompt format (`str` when text-only, or a list of content-block dicts when media is present; see [prompt content](/docs/reference/hooks/#prompt-content)) |
| `to_content(prompt)` | Normalizes a string, content-block list, or `list[UserContent]` into `list[UserContent]` |
| `to_legacy_prompt(content)` | Converts `list[UserContent]` back into `LegacyPrompt` |
| `prompt_text(content)` | Extracts and joins the plain-text portions of `list[UserContent]` |

---

### `Tape`, `TapeContext`, and Stores {#tape}

```python
from bub.core import Tape, TapeContext, default_tape_context, session_tape_name
from bub.core.tape import AnchorSummary, TapeEntry, TapeInfo

@dataclass(frozen=True)
class TapeContext:
    anchor: AnchorSelector = LAST_ANCHOR
    select: ContextSelector | None = None
    state: dict[str, Any] = field(default_factory=dict)

    def build_query(self, query: TapeQuery) -> TapeQuery: ...

def default_tape_context() -> TapeContext: ...
def session_tape_name(session_id: str, workspace: Path) -> str: ...

@dataclass(frozen=True)
class TapeInfo:
    name: str
    entries: int
    anchors: int
    last_anchor: str | None
    entries_since_last_anchor: int
    last_token_usage: int | None
    last_token_cache_hit_rate: float | None

@dataclass(frozen=True)
class AnchorSummary:
    name: str
    state: dict[str, object]

@dataclass(frozen=True)
class Tape:
    store: AsyncTapeStore
    context: TapeContext
    sidecars: tuple[TapeSidecar, ...] = field(default=(), repr=False)

    @property
    def name(self) -> str: ...

    def with_context(self, context: TapeContext) -> Tape: ...
    def scoped(self, name: str, context: TapeContext | None = None) -> Tape: ...
    def query(self) -> TapeQuery[AsyncTapeStore]: ...
    async def info(self) -> TapeInfo: ...
    async def anchors(self, limit: int = 20) -> list[AnchorSummary]: ...
    async def search(self, query: TapeQuery[AsyncTapeStore]) -> list[TapeEntry]: ...
    async def append_event(self, name: str, payload: dict[str, Any], **meta: Any) -> None: ...
    async def read_messages(self) -> list[republic.Message]: ...

    async def handoff(
        self,
        *,
        name: str,
        state: dict[str, Any] | None = None,
        **meta: Any,
    ) -> list[TapeEntry]: ...

    async def reset(
        self,
        *,
        state: dict[str, Any] | None = None,
        keep_sidecars: Iterable[str] = (),
    ) -> None: ...

    @asynccontextmanager
    async def fork_tape(self, merge_back: bool = True) -> AsyncGenerator[Tape, None]: ...
```

**`TapeContext` fields**:

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `anchor` | `AnchorSelector` | `LAST_ANCHOR` | Anchor filter: read entries after the latest anchor (`LAST_ANCHOR`), after a named anchor string, or pass `None` to disable anchor filtering |
| `select` | `ContextSelector \| None` | `None` | Custom projection selector `(Iterable[TapeEntry], TapeContext) -> list[republic.Message]`. Use `default_tape_context()` to replay full multi-turn conversations and tool round-trips |
| `state` | `dict[str, Any]` | `{}` | Request-scoped `TurnState` dictionary bound to this context |

**`Tape` properties and methods**:

| Property / Method | Description |
| --- | --- |
| `name` | The Tape's bound name; accessing it before calling `scoped(name)` raises `ValueError` |
| `scoped(name, context=None)` | Returns a new `Tape` bound to `name` (and an optional replacement `context`) |
| `with_context(context)` | Returns a new `Tape` with a replaced `TapeContext` |
| `query()` | Returns a `TapeQuery` bound to this Tape and store |
| `await read_messages()` | Selects entries through `TapeContext` and projects them into `list[republic.Message]` (skipping entries with `meta["context"] is False`) |
| `await handoff(*, name, state=None, **meta)` | Appends an `anchor` entry and a `handoff` event, moving the default context start forward |
| `await reset(*, state=None, keep_sidecars=())` | Clears the Tape and writes a new `session/start` anchor; resets mounted sidecars by default |
| `await info()` / `await anchors(limit=20)` | Returns `TapeInfo` statistics or a list of `AnchorSummary(name, state)` |
| `await search(query)` | Runs the given `TapeQuery` and returns matching entries |
| `await append_event(name, payload, **meta)` | Appends an `event` entry to the Tape |
| `fork_tape(merge_back=True)` | Async context manager: reads and writes on a fork; by default each new entry is also written to the main Tape at once |

`session_tape_name(session_id, workspace)` returns a physical Tape name of the form `<workspace hash>__<session hash>`.

#### `TapeSidecar` {#tapesidecar}

```python
from bub.core.sidecars import TapeSidecar, sidecar_tape_name

class TapeSidecar(Protocol):
    @property
    def name(self) -> str: ...

def sidecar_tape_name(owner: str, sidecar: str) -> str: ...
```

A sidecar is backed by the sibling Tape `<owner>__sidecar__<name>`: it forks, merges, and resets with the main Tape, and its entries never enter the main context. See [Sidecars](/docs/sdk/tape/#sidecars) and [`provide_tape_sidecar`](/docs/reference/hooks/#provide_tape_sidecar).

#### `TapeEntry` {#tapeentry}

```python
@dataclass(frozen=True)
class TapeEntry:
    id: int
    kind: str
    payload: dict[str, Any]
    meta: dict[str, Any] = field(default_factory=dict)
    date: str = field(default_factory=utc_now)

    def copy(self) -> TapeEntry: ...

    @classmethod
    def message(cls, message: dict[str, Any], **meta: Any) -> TapeEntry: ...
    @classmethod
    def system(cls, content: str, **meta: Any) -> TapeEntry: ...
    @classmethod
    def anchor(cls, name: str, state: dict[str, Any] | None = None, **meta: Any) -> TapeEntry: ...
    @classmethod
    def tool_call(cls, calls: list[dict[str, Any]], *, content: str = "", **meta: Any) -> TapeEntry: ...
    @classmethod
    def tool_result(cls, results: list[Any], **meta: Any) -> TapeEntry: ...
    @classmethod
    def error(cls, error: BubError, **meta: Any) -> TapeEntry: ...
    @classmethod
    def event(cls, name: str, data: dict[str, Any] | None = None, **meta: Any) -> TapeEntry: ...
```

| Field | Type | Description |
| --- | --- | --- |
| `id` | `int` | Sequential ID assigned by the store (new entries start at `0` and are rewritten on `append`) |
| `kind` | `str` | Entry kind: `message`, `system`, `anchor`, `tool_call`, `tool_result`, `error`, or `event` |
| `payload` | `dict[str, Any]` | Entry payload dictionary |
| `meta` | `dict[str, Any]` | Run metadata; setting `context=False` keeps the entry out of model context |
| `date` | `str` | ISO 8601 timestamp string, defaulting to current UTC time |

#### `TapeStore` and `AsyncTapeStore` {#tape-store}

```python
from bub.core.store import AsyncTapeStore, TapeStore, is_async_tape_store

class TapeStore(Protocol):
    def list_tapes(self) -> list[str]: ...
    def reset(self, tape: str) -> None: ...
    def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ...
    def append(self, tape: str, entry: TapeEntry) -> None: ...

class AsyncTapeStore(Protocol):
    async def list_tapes(self) -> list[str]: ...
    async def reset(self, tape: str) -> None: ...
    async def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ...
    async def append(self, tape: str, entry: TapeEntry) -> None: ...

def is_async_tape_store(store: TapeStore | AsyncTapeStore) -> TypeIs[AsyncTapeStore]: ...
```

| Method | Contract |
| --- | --- |
| `list_tapes()` | Returns existing session Tape names (internal physical tapes such as sidecars need not be listed) |
| `append(tape, entry)` | Appends an entry and assigns an `id` starting at `1` and increasing monotonically within that Tape |
| `fetch_all(query)` | Returns entries matching `TapeQuery` in recording order (the async version is `async def` returning `Iterable`, not an async generator) |
| `reset(tape)` | Clears the Tape's records and resets its ID counter so the next `append` starts at `1` |

#### `TapeQuery` {#tapequery}

```python
@dataclass(frozen=True)
class TapeQuery[T: TapeStore | AsyncTapeStore]:
    tape: str
    store: T

    def query(self, value: str) -> Self: ...
    def after_anchor(self, name: str) -> Self: ...
    def last_anchor(self) -> Self: ...
    def between_anchors(self, start: str, end: str) -> Self: ...
    def between_dates(self, start: str | date_type, end: str | date_type) -> Self: ...
    def kinds(self, *kinds: str) -> Self: ...
    def limit(self, value: int) -> Self: ...

    @overload
    def all(self: TapeQuery[TapeStore]) -> Iterable[TapeEntry]: ...
    @overload
    async def all(self: TapeQuery[AsyncTapeStore]) -> Iterable[TapeEntry]: ...
```

| Method | Filter semantics |
| --- | --- |
| `query(value)` | Case-insensitive substring match against the JSON text of entry `kind`, `date`, `payload`, and `meta` |
| `after_anchor(name)` / `last_anchor()` | Entries strictly after the named or latest anchor (excluding the boundary anchor itself); raises `BubError(kind=NOT_FOUND)` if missing |
| `between_anchors(start, end)` | Entries between two anchors, excluding both boundaries; raises `BubError(kind=NOT_FOUND)` if either is missing |
| `between_dates(start, end)` | Inclusive ISO date or time range; a date-only upper bound covers the full day |
| `kinds(*kinds)` | Entries matching the specified kinds |
| `limit(value)` | Maximum number of entries returned (applied after all other filters) |
| `all()` | Executes the query (returns `Iterable` for sync stores; must be awaited for async stores) |

#### Built-in Stores {#builtin-stores}

```python
from bub.core.store import (
    AsyncTapeStoreAdapter,
    FileTapeStore,
    InMemoryQueryMixin,
    InMemoryTapeStore,
)

class InMemoryQueryMixin:
    def read(self, tape: str) -> list[TapeEntry] | None: ...
    def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ...

class InMemoryTapeStore(InMemoryQueryMixin):
    def __init__(self) -> None: ...
    def list_tapes(self) -> list[str]: ...
    def reset(self, tape: str) -> None: ...
    def read(self, tape: str) -> list[TapeEntry] | None: ...
    def append(self, tape: str, entry: TapeEntry) -> None: ...

class FileTapeStore(InMemoryQueryMixin):
    def __init__(self, directory: Path) -> None: ...
    def list_tapes(self) -> list[str]: ...
    def reset(self, tape: str) -> None: ...
    def append(self, tape: str, entry: TapeEntry) -> None: ...
    def read(self, tape: str) -> list[TapeEntry] | None: ...

class AsyncTapeStoreAdapter:
    def __init__(self, store: TapeStore) -> None: ...
    async def list_tapes(self) -> list[str]: ...
    async def reset(self, tape: str) -> None: ...
    async def fetch_all(self, query: TapeQuery) -> Iterable[TapeEntry]: ...
    async def append(self, tape: str, entry: TapeEntry) -> None: ...
```

| Class | Description |
| --- | --- |
| `InMemoryTapeStore` | In-process dictionary; `read()` returns copies of entries; cleared when the process exits |
| `FileTapeStore(directory)` | One `<tape>.jsonl` file per Tape with a per-file thread lock (no cross-process lock); `list_tapes()` returns only files containing exactly one `__`. Validate user-supplied Tape names before use (see [Tape and memory](/docs/sdk/tape/#storage)) |
| `AsyncTapeStoreAdapter(store)` | Wraps a synchronous `TapeStore` with `asyncio.to_thread()` to satisfy `AsyncTapeStore` |
| `InMemoryQueryMixin` | Provides in-memory `fetch_all(query)` filtering for stores that implement `read(tape)` |

---

### `EventBus` and Event Classes {#events}

```python
from bub.core.events import (
    AgentEvent,
    ChatFinished,
    CommandFinished,
    Event,
    EventBus,
    LLMCallFinished,
    LLMCallStarted,
    MessagesPending,
    RunFinished,
    RunStarted,
    StepFinished,
    StepStarted,
    TapeEvent,
    ToolCallFinished,
    ToolCallStarted,
)

class Event:
    @property
    def stopped(self) -> bool: ...

class EventBus:
    @overload
    def on(self, event_type: type[E]) -> Callable[[EventHandler[E]], EventHandler[E]]: ...
    @overload
    def on(self, event_type: type[E], handler: EventHandler[E]) -> EventHandler[E]: ...

    def off(self, event_type: type[E], handler: EventHandler[E]) -> None: ...
    async def emit(self, event: E) -> E: ...

@dataclass(kw_only=True)
class AgentEvent(Event):
    state: TurnState

@dataclass(kw_only=True)
class TapeEvent(AgentEvent):
    tape: Tape

@dataclass(kw_only=True)
class RunStarted(TapeEvent):
    model: str
    prompt: list[UserContent]
    metadata: dict[str, Any] = field(default_factory=dict)

@dataclass(kw_only=True)
class RunFinished(TapeEvent):
    status: str
    steps: int
    elapsed_ms: int
    error: str | None = None

@dataclass(kw_only=True)
class StepStarted(TapeEvent):
    step: int
    prompt: list[UserContent] | None

@dataclass(kw_only=True)
class StepFinished(TapeEvent):
    step: int
    status: str
    elapsed_ms: int
    error: str | None = None
    prompt: list[UserContent] | None = None
    stream: StreamState = field(default_factory=StreamState)
    next_prompt: list[UserContent] | None = None

@dataclass(kw_only=True)
class MessagesPending(TapeEvent):
    prompt: list[UserContent] | None
    messages: list[list[UserContent]] = field(default_factory=list)

@dataclass(kw_only=True)
class CommandFinished(TapeEvent):
    line: str
    name: str
    status: str
    elapsed_ms: int
    output: str

@dataclass(kw_only=True)
class LLMCallStarted(TapeEvent):
    request: LLMCallRequest
    decision: LLMCallDecision | None = None

    @property
    def stopped(self) -> bool: ...

@dataclass(kw_only=True)
class LLMCallFinished(TapeEvent):
    request: LLMCallRequest
    result: LLMCallResult

@dataclass(kw_only=True)
class ToolCallStarted(AgentEvent):
    call: ToolCall
    decision: ToolCallDecision = field(default_factory=lambda: ToolCallDecision.proceed())

    @property
    def stopped(self) -> bool: ...

@dataclass(kw_only=True)
class ToolCallFinished(AgentEvent):
    call: ToolCall
    result: ToolCallResult

@dataclass(kw_only=True)
class ChatFinished(TapeEvent):
    run_id: str
    model: str
    system_prompt: str | None
    new_messages: list[republic.Message]
    response_text: str | None
    tool_calls: list[dict[str, Any]] = field(default_factory=list)
    tool_results: list[Any] | None = None
    usage: dict[str, Any] | None = None
    provider: str | None = None
    assistant_fields: dict[str, Any] = field(default_factory=dict)
    error: BubError | None = None
    context_error: BubError | None = None
```

#### Events at a glance {#event-reference}

| Event | When it fires | What a handler can read or change |
| --- | --- | --- |
| `RunStarted` | A model Run begins | `model`, `prompt`, `metadata`, `tape`, `state` |
| `RunFinished` | The Run's stream closes | `status` (`ok` / `error` / `cancelled`), `steps`, `elapsed_ms`, `error` |
| `StepStarted` | A Step begins | `step`, optional `prompt` |
| `StepFinished` | A Step ends | `step`, `status`, `elapsed_ms`, `stream`; set `next_prompt` when continuing |
| `MessagesPending` | Before building a request, or when a Step ends without tool calls | Append user content to `messages`; at Step end, appended messages continue the Run |
| `LLMCallStarted` | Before calling the model provider | Replace `request`; set `LLMCallDecision.finish(text)` |
| `LLMCallFinished` | After success or an ordinary provider failure | `request` and the aggregated `result` (`LLMCallResult`) |
| `ToolCallStarted` | Before a local tool runs | Replace `call`; set `decision` (`proceed` / `deny` / `replace`) |
| `ToolCallFinished` | Tool success, failure, denial, or replacement | `call` and `result` (assign `event.result.result` to change the model-facing result) |
| `ChatFinished` | When a Step's exchange is ready to be recorded | `new_messages`, `response_text`, `tool_calls`, `tool_results`, `usage`, `error` |
| `CommandFinished` | A direct command succeeds or fails | `line`, `name`, `status`, `elapsed_ms`, `output` |

- `RunFinished` fires when the stream closes; a Run closed before iterating ends as `cancelled` with zero steps. `LLMCallFinished` and `ToolCallFinished` do not cover every cancellation path.
- Exceeding `max_steps` (set by `BUB_MAX_STEPS` in the app) raises `max_steps_reached`.
- Direct commands emit tool events and `CommandFinished`, but no `RunStarted` or `RunFinished`.
- See [Agent events](/docs/concepts/events/#call-control) for decision semantics and [Hooks reference](/docs/reference/hooks/#event-mapping) for app-hook mapping.

---

### `bub.streaming` {#streams}

```python
from bub.streaming import AsyncStreamEvents, StreamEvent, StreamState

@dataclass
class StreamState:
    error: BubError | None = None
    usage: dict[str, Any] | None = None
    system_prompt: str | None = None
    tools: list[Tool] = field(default_factory=list)

@dataclass(frozen=True)
class StreamEvent:
    kind: Literal["text", "reasoning", "tool_call", "tool_result", "usage", "error", "final"]
    data: dict[str, Any]

class AsyncStreamEvents:
    def __init__(
        self,
        iterator: AsyncIterator[StreamEvent],
        *,
        state: StreamState | None = None,
        on_close: Callable[[], Awaitable[None]] | None = None,
        span: Span | None = None,
    ) -> None: ...

    def __aiter__(self) -> AsyncIterator[StreamEvent]: ...
    async def __anext__(self) -> StreamEvent: ...
    async def aclose(self) -> None: ...

    @property
    def error(self) -> BubError | None: ...
    @property
    def usage(self) -> dict[str, Any] | None: ...
```

| Class / Member | Description |
| --- | --- |
| `StreamEvent.kind` | Event kind: `"text"`, `"reasoning"`, `"tool_call"`, `"tool_result"`, `"usage"`, `"error"`, or `"final"` (see [SDK output streams](/docs/sdk/#consume-the-stream)) |
| `StreamEvent.data` | Event payload dictionary; for `tool_result`, `data["tool_results"]` aligns with the Step's tool calls and holds a `BubError` for failed calls |
| `await AsyncStreamEvents.aclose()` | Explicitly closes the stream and runs `on_close` cleanup and Tape fork merging |
| `AsyncStreamEvents.error` / `usage` | Latest recorded `BubError` or token usage dictionary |

---

### `bub.errors` {#errors}

```python
from bub.errors import BubError, ErrorKind

class ErrorKind(StrEnum):
    INVALID_INPUT = "invalid_input"
    CONFIG = "config"
    PROVIDER = "provider"
    TOOL = "tool"
    TEMPORARY = "temporary"
    NOT_FOUND = "not_found"
    UNKNOWN = "unknown"

@dataclass
class BubError(Exception):
    kind: ErrorKind
    message: str
    details: dict[str, Any] | None = None

    def as_dict(self) -> dict[str, Any]: ...
```

| Field / Method | Type | Description |
| --- | --- | --- |
| `kind` | `ErrorKind` | Error category enum |
| `message` | `str` | Human-readable error message |
| `details` | `dict[str, Any] \| None` | Optional structured error context |
| `as_dict()` | `dict[str, Any]` | Converts the error into a JSON-serializable dictionary |

---

### `CodeMode` {#code-mode}

```python
from bub.core.codemode import CodeMode

type CodeTools = Iterable[Tool] | Callable[[TurnState], Iterable[Tool] | None]
type ModelResolver = Callable[[str | None, ToolContext], tuple[str, Mapping[str, Any]]]

class CodeMode:
    run_code: Tool

    def __init__(
        self,
        tools: CodeTools = (),
        *,
        environment: Environment | Callable[[TurnState], Environment] | None = None,
        models: str | ModelResolver | None = None,
        stub_dir: Path | Callable[[TurnState], Path] | None = None,
        media_tools: bool = True,
        name: str = "run_code",
    ) -> None: ...

    def code_tools(self, state: TurnState) -> list[Tool] | None: ...
    def environment(self, state: TurnState) -> Environment: ...
    def prompt(self, context: PromptContext) -> str | None: ...
```

| Parameter / Member | Type | Default | Description |
| --- | --- | --- | --- |
| `tools` | `CodeTools` | `()` | Tools callable inside `run_code` via `await tools.<name>(...)` (or a callable returning tools per `TurnState`) |
| `environment` | `Environment \| Callable \| None` | `LocalEnvironment()` in cwd | Execution environment (or factory) used to run Python code |
| `models` | `str \| ModelResolver \| None` | `None` | Model spec or resolver exposed inside code mode |
| `stub_dir` | `Path \| Callable \| None` | `None` | Directory where generated tool type stubs are written |
| `media_tools` | `bool` | `True` | Whether to expose `attach_image`, `attach_audio`, and `attach_video` inside `run_code` |
| `name` | `str` | `"run_code"` | Name of the model-facing tool |
| `code_mode.run_code` | `Tool` | — | Generated `Tool` instance to pass to `Agent(tools=[code_mode.run_code])` |
| `code_mode.prompt` | `PromptSection` | — | Prompt section describing callable tools for `Agent(system_prompt=[..., code_mode.prompt])` |

See [Custom tools and code mode](/docs/sdk/tools/#compose-tools-with-codemode) for usage.

---

### `Environment`, `Process`, and `LocalEnvironment` {#environment}

```python
from bub.environment import (
    ENVIRONMENT_STATE_KEY,
    CallTool,
    CodeFailed,
    Environment,
    LocalEnvironment,
    Process,
)

ENVIRONMENT_STATE_KEY = "_runtime_environment"
type CallTool = Callable[[str, dict[str, Any]], Awaitable[Any]]

class Environment(abc.ABC):
    workspace: str | None = None
    python: str = "python3"

    @abc.abstractmethod
    async def spawn(
        self,
        command: str | Sequence[str],
        *,
        cwd: str | None = None,
        env: Mapping[str, str] | None = None,
    ) -> Process: ...

    @abc.abstractmethod
    async def read_text(self, path: str) -> str: ...
    async def read_bytes(self, path: str) -> bytes: ...

    @abc.abstractmethod
    async def write_text(self, path: str, content: str) -> None: ...
    def resolve_path(self, path: str) -> str: ...

    @abc.abstractmethod
    async def run_code(
        self,
        code: str,
        *,
        tools: Sequence[str],
        call_tool: CallTool,
        write: Callable[[str], None],
    ) -> None: ...

    async def close(self) -> None: ...

class LocalEnvironment(Environment):
    def __init__(self, workspace: str | Path | None = None) -> None: ...
```

#### `Environment` members {#environment-members}

| Member | Signature | Description |
| --- | --- | --- |
| `workspace` | `str \| None` | Working directory inside the environment; relative paths are rejected when `None` |
| `python` | `str` | Python executable inside the environment, `"python3"` by default (`LocalEnvironment` uses `sys.executable`) |
| `spawn` | `async (command, *, cwd=None, env=None) -> Process` | **Abstract**. Runs a string through the shell or a sequence as an argument vector; `cwd` defaults to `workspace` |
| `read_text` | `async (path) -> str` | **Abstract**. Reads a UTF-8 text file |
| `read_bytes` | `async (path) -> bytes` | Reads raw bytes (defaults to reading via `python` inside the environment; override when direct filesystem access is available) |
| `write_text` | `async (path, content) -> None` | **Abstract**. Writes a UTF-8 text file, creating missing parent directories |
| `resolve_path` | `(path) -> str` | Resolves a relative path against `workspace`; raises `ValueError` without a workspace |
| `run_code` | `async (code, *, tools, call_tool, write) -> None` | **Abstract**. Executes model-written Python code |
| `close` | `async () -> None` | Releases environment resources; called when `framework.running()` exits |

#### `Process` {#process}

```python
class Process(abc.ABC):
    @property
    @abc.abstractmethod
    def stdout(self) -> asyncio.StreamReader: ...
    @property
    @abc.abstractmethod
    def stderr(self) -> asyncio.StreamReader: ...
    @property
    @abc.abstractmethod
    def returncode(self) -> int | None: ...

    @abc.abstractmethod
    async def wait(self) -> int: ...
    @abc.abstractmethod
    async def write_stdin(self, data: bytes) -> None: ...
    @abc.abstractmethod
    def close_stdin(self) -> None: ...
    @abc.abstractmethod
    def signal(self, *, kill: bool) -> None: ...
    def is_running(self) -> bool: ...
```

| Member | Description |
| --- | --- |
| `stdout` / `stderr` | `asyncio.StreamReader` streams |
| `returncode` | Process exit code, or `None` while running |
| `await wait()` | Waits for exit and returns the exit code |
| `await write_stdin(data)` / `close_stdin()` | Writes and flushes standard input, or closes standard input |
| `signal(*, kill)` | Requests termination of the process and its descendants (or forces termination when `kill=True`); must not raise once exited |
| `is_running()` | Whether the process or its descendants are still alive |

#### `run_code` contract {#run-code-contract}

- `code` may use top-level `await`; each tool in `tools` is exposed as `await tools.<name>(**kwargs)` forwarding to `await call_tool(name, kwargs)` (and `republic.` prefixed names are forwarded for media and model helpers).
- Standard output must be passed to `write(chunk)` immediately as produced so output survives timeouts.
- Raise `CodeFailed(error, traceback)` when the code itself raises; custom environments with a Python interpreter can reuse `bub.core.codemode.runner.run_code_in_subprocess(self, ...)`.

#### `CodeFailed` {#codefailed}

```python
class CodeFailed(Exception):
    def __init__(self, error: str, traceback: str = "") -> None: ...
```

`error` is `"<Type>: <message>"`, and `traceback` contains only the model code's own stack frames.

#### Where the environment comes from {#provide-an-environment}

The application layer caches one `Environment` per session via the `provide_environment(session_id, workspace)` hook (defaulting to `LocalEnvironment(workspace)`), stores it in `TurnState[ENVIRONMENT_STATE_KEY]`, and calls `close()` when `framework.running()` exits.

:::caution
`LocalEnvironment` executes directly on the host, and **a separate subprocess is not a security sandbox**. Implement an isolated `Environment` when running untrusted code.
:::

---

## Application (`bub`) {#application}

### `BubFramework` and `BubAgent` {#framework}

```python
from bub import BubFramework
from bub.builtin.agent import BubAgent

class BubFramework:
    workspace: Path
    config_file: Path
    default_command: str | None
    events: EventBus

    def __init__(self, config_file: Path = DEFAULT_CONFIG_FILE) -> None: ...

    @property
    def plugin_manager(self) -> pluggy.PluginManager: ...

    def load_builtin_hooks(self) -> None: ...
    def load_hooks(self) -> None: ...
    def create_cli_app(self) -> typer.Typer: ...

    async def build_prompt(
        self,
        message: Envelope,
        session_id: str,
        state: dict[str, Any],
    ) -> list[UserContent]: ...

    async def continue_prompt(
        self,
        prompt: list[UserContent] | None,
        tape: Tape,
        state: StreamState,
    ) -> str | None: ...

    async def build_state(self, message: Envelope, session_id: str) -> TurnState: ...
    async def process_inbound(self, inbound: Envelope, stream_output: bool = False) -> TurnResult: ...
    async def resolve_session(self, message: Envelope) -> str: ...
    def plugin_report(self) -> dict[str, PluginStatus]: ...
    def hook_report(self) -> dict[str, list[str]]: ...
    def bind_channel_router(self, router: ChannelRouter | None) -> None: ...
    async def dispatch_via_channel_router(self, message: Envelope) -> bool: ...
    async def quit_via_channel_router(self, session_id: str) -> None: ...

    async def admit_message(
        self,
        *,
        session_id: str,
        message: Envelope,
        turn: TurnSnapshot,
    ) -> AdmitDecision | None: ...

    async def get_model_options(
        self,
        *,
        session_id: str,
        workspace: str | Path | None = None,
    ) -> ModelOptions: ...

    async def steer_message(
        self,
        *,
        message: Envelope,
        session_id: str,
        state: TurnState,
        reason: str | None = None,
    ) -> bool: ...

    def get_channels(self, message_handler: MessageHandler) -> dict[str, Channel]: ...

    @asynccontextmanager
    async def running(self) -> AsyncGenerator[contextlib.AsyncExitStack, None]: ...

    async def get_environment(self, session_id: str) -> Environment | None: ...
    def get_tape_store(self) -> TapeStore | AsyncTapeStore | None: ...
    def get_tape_sidecars(self) -> tuple[TapeSidecar, ...]: ...
    def get_tools(self) -> tuple[Tool, ...]: ...
    def get_steering_inbox(self) -> SteeringInbox | None: ...
    def get_agent_hooks(self) -> PluginAgentHooks: ...
    def get_system_prompt(self, prompt: list[UserContent], state: dict[str, Any]) -> str: ...
    def build_tape_context(self) -> TapeContext: ...
    def collect_onboard_config(self, plugin_name: str | None = None) -> dict[str, Any]: ...

class BubAgent(core.Agent):
    command_prefix: str

    def __init__(
        self,
        framework: BubFramework,
        *,
        tools: Collection[Tool] | None = None,
        tape_store: TapeStore | AsyncTapeStore | None = None,
        skill_dirs: Collection[Path] | None = None,
        command_prefix: str | None = None,
    ) -> None: ...

    async def run_stream(
        self,
        *,
        session_id: str,
        prompt: list[UserContent] | LegacyPrompt,
        state: TurnState | None = None,
        model: str | None = None,
        allowed_skills: Collection[str] | None = None,
        allowed_tools: Collection[str] | None = None,
        reasoning_effort: str | None = None,
    ) -> AsyncStreamEvents: ...

    async def prepare_tools(
        self,
        tape: Tape,
        prompt: list[UserContent] | None,
    ) -> list[Tool]: ...
```

**`BubFramework` key methods**:

| Method | Description |
| --- | --- |
| `BubFramework(config_file=...)` | Loads application configuration; `workspace` defaults to the current working directory |
| `load_hooks()` / `load_builtin_hooks()` | Registers builtin hooks and all installed entry-point plugins (or builtin hooks only) |
| `running()` | Async context manager managing `provide_lifespan`, `TapeStore`, session `Environment` instances, and `SteeringInbox` |
| `await process_inbound(inbound, stream_output=False)` | Executes a complete 7-stage Turn and returns `TurnResult` |
| `await build_state(message, session_id)` | Runs `load_state` hooks and populates `_runtime_*` keys to build `TurnState` |
| `get_tools()` / `get_channels(handler)` / `get_tape_store()` | Collects registered tools, channels, or the active Tape store |
| `bind_channel_router(router)` | Binds a `ChannelRouter` for outbound delivery, stream wrapping, and session cancellation |

**`BubAgent` constructor and `run_stream()` parameters**:

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `framework` | `BubFramework` | Required | Associated `BubFramework` (construct `BubAgent` inside `async with framework.running():` to use the active store) |
| `tools` | `Collection[Tool] \| None` | `framework.get_tools()` | Overrides the base tool collection for this Agent instance |
| `tape_store` | `TapeStore \| AsyncTapeStore \| None` | `framework.get_tape_store()` | Explicit store taking precedence over the framework's store |
| `session_id` | `str` | Required (`run_stream`) | Session ID (a `temp/` prefix prevents the Tape fork from merging back on close) |
| `prompt` | `list[UserContent] \| LegacyPrompt` | Required (`run_stream`) | User input sent to the model |
| `state` | `TurnState \| None` | `None` | Loaded via `framework.build_state()` when `None`; passing a dict skips `load_state` hooks |
| `model` | `str \| None` | Session or configured model | Overrides `provider:model` for this call |
| `allowed_tools` / `allowed_skills` | `Collection[str] \| None` | `None` | Limits allowed tools or skills for this call (`[]` disables all; unknown names raise `ValueError`) |
| `reasoning_effort` | `str \| None` | Session or configured effort | Overrides reasoning effort for this call |

See [Reuse Bub in a service](/docs/integrations/reuse-app/) for embedding patterns and [Turn](/docs/concepts/turn/#stages) for the differences from a complete Turn.

---

### `bub.envelope` and `bub.turn` {#messages}

```python
from bub.envelope import Envelope, content_of, field_of, normalize_envelope, unpack_batch
from bub.turn import TurnResult, TurnState

type Envelope = Any
type TurnState = dict[str, Any]

def field_of(message: Envelope, key: str, default: Any = None) -> Any: ...
def content_of(message: Envelope) -> str: ...
def normalize_envelope(message: Envelope) -> dict[str, Any]: ...
def unpack_batch(batch: Any) -> list[Envelope]: ...

@dataclass(frozen=True)
class TurnResult:
    session_id: str
    prompt: list[UserContent]
    model_output: str
    outbounds: list[Envelope] = field(default_factory=list)
    state: TurnState = field(default_factory=dict)
```

| Function / Field | Description |
| --- | --- |
| `field_of(message, key, default=None)` | Reads a key or attribute from a mapping, dataclass, Pydantic model, or object |
| `content_of(message)` | Reads the `"content"` string field from a message (returns `""` if absent) |
| `normalize_envelope(message)` | Converts any `Envelope` into a mutable Python dictionary |
| `unpack_batch(batch)` | Expands a single outbound message or list returned by `render_outbound` into `list[Envelope]` |
| `TurnResult` | Result of `process_inbound()`, containing `session_id`, `prompt`, `model_output`, rendered `outbounds`, and final `state` |

---

### `bub.model_selection` {#model-options}

```python
from bub.model_selection import ModelChoice, ModelOptions

@dataclass(frozen=True)
class ModelChoice:
    id: str
    name: str | None = None
    description: str | None = None
    meta: dict[str, Any] | None = None

@dataclass(frozen=True)
class ModelOptions:
    models: list[ModelChoice] = field(default_factory=list)
    current_model: str | None = None
```

| Class / Field | Type | Description |
| --- | --- | --- |
| `ModelChoice.id` | `str` | Required model identifier (e.g. `"openai:gpt-5-mini"`) |
| `ModelChoice.name` / `description` / `meta` | Optional | Display name, description, and metadata dictionary |
| `ModelOptions.models` | `list[ModelChoice]` | Candidate models merged across `provide_model_options` hooks |
| `ModelOptions.current_model` | `str \| None` | Currently active model ID |

---

### `bub.channels` {#channels}

```python
from bub.channels import Channel, ChannelManager, ChannelMessage, Interface, Lifecycle
from bub.channels.admission import AdmitDecision, SteeringInbox, TurnAdmissionAction, TurnSnapshot
from bub.channels.contracts import ChannelRouter, MessageHandler
from bub.channels.message import MediaItem, MediaType, MessageKind

type MediaType = Literal["image", "audio", "video", "document"]
type MessageKind = Literal["error", "normal", "command"]
type MessageHandler = Callable[[Envelope], Coroutine[Any, Any, None]]
type TurnAdmissionAction = Literal["process", "drop", "follow_up", "steer"]

@dataclass
class MediaItem:
    type: MediaType
    mime_type: str
    filename: str | None = None
    url: str | None = None
    data_fetcher: Callable[[], Awaitable[bytes | None]] | None = None

    async def get_url(self) -> str | None: ...

@dataclass
class ChannelMessage:
    session_id: str
    channel: str
    content: str
    chat_id: str = "default"
    is_active: bool = False
    kind: MessageKind = "normal"
    context: dict[str, Any] = field(default_factory=dict)
    media: list[MediaItem] = field(default_factory=list)
    lifespan: contextlib.AbstractAsyncContextManager | None = None
    output_channel: str = ""

    @property
    def context_str(self) -> str: ...

    @classmethod
    def from_batch(cls, batch: list[ChannelMessage]) -> ChannelMessage: ...

class Channel(ABC):
    name: ClassVar[str] = "base"

    @abstractmethod
    async def start(self, stop_event: asyncio.Event) -> None: ...
    @abstractmethod
    async def stop(self) -> None: ...

    @property
    def needs_debounce(self) -> bool: ...
    @property
    def enabled(self) -> bool: ...

    async def send(self, message: ChannelMessage) -> None: ...

    def stream_events(
        self,
        message: ChannelMessage,
        stream: AsyncIterable[StreamEvent],
    ) -> AsyncIterable[StreamEvent]: ...

    async def admit_message(
        self,
        session_id: str,
        message: Envelope,
        turn: TurnSnapshot,
    ) -> AdmitDecision | None: ...

class Interface(Channel): ...
class Lifecycle(Channel): ...

class ChannelRouter(Protocol):
    async def dispatch_output(self, message: Envelope) -> bool: ...
    def wrap_stream(
        self,
        message: Envelope,
        stream: AsyncIterable[StreamEvent],
    ) -> AsyncIterable[StreamEvent]: ...
    async def quit(self, session_id: str) -> None: ...
    async def admit_channel_message(
        self,
        session_id: str,
        message: Envelope,
        turn: TurnSnapshot,
    ) -> AdmitDecision | None: ...

class ChannelManager:
    def __init__(
        self,
        framework: BubFramework,
        enabled_channels: Collection[str] | None = None,
        stream_output: bool | None = None,
        system_prompt: str | None = CHANNEL_SYSTEM_PROMPT,
    ) -> None: ...

    async def on_receive(self, message: ChannelMessage) -> None: ...
    def get_channel(self, name: str) -> Channel | None: ...
    async def dispatch_output(self, message: Envelope) -> bool: ...
    def wrap_stream(
        self,
        message: Envelope,
        stream: AsyncIterable[StreamEvent],
    ) -> AsyncIterable[StreamEvent]: ...
    async def quit(self, session_id: str) -> None: ...
    def enabled_channels(self) -> list[Channel]: ...
    async def listen_and_run(self) -> None: ...
    async def shutdown(self) -> None: ...
    async def admit_channel_message(
        self,
        session_id: str,
        message: Envelope,
        turn: TurnSnapshot,
    ) -> AdmitDecision | None: ...

@dataclass(frozen=True)
class AdmitDecision:
    action: TurnAdmissionAction
    reason: str | None = None

@dataclass(frozen=True)
class TurnSnapshot:
    session_id: str
    is_running: bool
    running_count: int
    pending_count: int
    steering_count: int = 0

class SteeringInbox(Protocol):
    async def enqueue_message(self, message: Envelope, state: TurnState) -> None: ...
    async def drain_messages(self, state: TurnState) -> list[Envelope]: ...
    def message_count(self, state: TurnState) -> int: ...
```

| Class | Description |
| --- | --- |
| `ChannelMessage` | Standard channel message object; `media` holds `MediaItem` objects (providing image, audio, or video bytes via `url` or async `data_fetcher`). See [Gateway: Custom channels](/docs/app/gateway/#custom-channels) |
| `Channel` / `Interface` / `Lifecycle` | `Channel` subclasses implement at least `start(stop_event)` and `stop()`; `Interface` marks an explicit user surface (such as `cli`), while `Lifecycle` marks a background service attached to the gateway (such as `mcp.lifecycle`) |
| `ChannelManager` | Implements `ChannelRouter` and manages channel lifecycles, debounce batching, message admission, and outbound delivery |
| `AdmitDecision` / `TurnSnapshot` / `SteeringInbox` | Message admission decision (`process` / `drop` / `follow_up` / `steer`), session activity snapshot, and steering inbox protocol (see [Hooks reference: `admit_message`](/docs/reference/hooks/#admit_message)) |

---

### `bub.hooks` {#hooks}

```python
from bub.hooks import BubHookSpecs, hookimpl, hookspec
```

See the [Hooks reference](/docs/reference/hooks/) for all 27 hook signatures, dispatch modes, and return contracts.

---

### `bub.application` and `bub.program_status` {#application-events}

```python
from bub.application import CommandChanged, Outcome, PromptChanged, PromptKind, WorkChanged
from bub.program_status import ProgramStatus

type Outcome = Literal["succeeded", "failed", "cancelled"]
type PromptKind = Literal["question", "permission", "auth"]

@dataclass(frozen=True)
class CommandChanged(Event):
    outcome: Outcome | None = None

@dataclass(frozen=True)
class WorkChanged(Event):
    busy: bool
    completed: Outcome | None = None

@dataclass(frozen=True)
class PromptChanged(Event):
    kind: PromptKind | None

class ProgramStatus:
    def __init__(self, output: TextIO | None) -> None: ...
    def __call__(self, event: Event) -> None: ...
```

These events are published on `framework.events` (independently of `agent.events`) to drive status bars and external UIs:

| Class | Fields | Description |
| --- | --- | --- |
| `CommandChanged` | `outcome` | `None` when a CLI command starts; `"succeeded"` / `"failed"` / `"cancelled"` when it ends |
| `WorkChanged` | `busy`, `completed` | Channel busy-state changes; may carry the outcome of a completed message |
| `PromptChanged` | `kind` | `"question"` / `"permission"` / `"auth"` when a modal prompt opens; `None` when it closes |
| `ProgramStatus` | `output` | Builtin terminal status handler: emits OSC 7501 states (`idle`, `working`, `blocked`, `done`, `error`) on a TTY and clears with `state=clear` when a command ends |

---

### `bub.inquirer` {#inquirer}

```python
from bub.inquirer import (
    CheckboxValidator,
    ask_checkbox,
    ask_confirm,
    ask_fuzzy,
    ask_prompt,
    ask_secret,
    ask_select,
    ask_text,
)

type CheckboxValidator = Callable[[list[str]], bool | str]

def ask_prompt(
    prompt: Callable[..., InquirerResult[Any]],
    message: str,
    *,
    kind: PromptKind = "question",
    **kwargs: Any,
) -> Any: ...

def ask_text(message: str, default: str = "") -> str: ...
def ask_secret(message: str) -> str: ...
def ask_confirm(message: str, default: bool = False, *, kind: PromptKind = "question") -> bool: ...
def ask_select(message: str, choices: list[str], default: str = "") -> str: ...
def ask_fuzzy(message: str, choices: list[str], default: str | None = None) -> str: ...
def ask_checkbox(
    message: str,
    choices: list[str],
    enabled: list[str] | None = None,
    validate: CheckboxValidator | None = None,
) -> list[str]: ...
```

| Function | Parameters | Return type | Description |
| --- | --- | --- | --- |
| `ask_text` | `message`, `default=""` | `str` | Single-line text input |
| `ask_secret` | `message` | `str` | Masked password or token input |
| `ask_confirm` | `message`, `default=False`, `*, kind="question"` | `bool` | Yes/no confirmation prompt |
| `ask_select` | `message`, `choices`, `default=""` | `str` | Single-choice selection list |
| `ask_fuzzy` | `message`, `choices`, `default=None` | `str` | Fuzzy-filtered single-choice selection |
| `ask_checkbox` | `message`, `choices`, `enabled=None`, `validate=None` | `list[str]` | Multi-select checkbox list with optional `validate` callback |

When called through the Bub CLI, these synchronous helpers emit `PromptChanged` on `framework.events`; user cancellation raises `typer.Abort`. See [Collect interactive input](/docs/app/plugins/#prompt-for-input).