# Reuse Bub in a service

When embedding Bub in an existing Python service, you can use the minimal [`bub.core.Agent`](/docs/sdk/) kernel or reuse capabilities from the Bub app layer — including configuration loading, skill discovery, plugin hooks, built-in tools, and the full Turn message pipeline.

The key question is not which entry point has the most features, but **which assembly and lifecycle responsibilities remain with your host service**.

App-layer entry points require the [`app` optional dependencies](/docs/getting-started/install/#app-install) and configured model credentials (such as `REPUBLIC_OPENAI_API_KEY`):

```bash
uv add "bub[app]"
```

If you only need the core model–tool–Tape loop without app configuration, skills, or plugins, start with the [core SDK](/docs/sdk/).

<a id="choose-a-depth"></a>

## Choose a reuse layer {#choose-a-reuse-layer}

Bub offers five reuse entry points depending on which responsibilities remain with your host service. These are parallel entry points rather than a mandatory upgrade path—start at the smallest layer that meets your needs:

| Capability to reuse | Entry point | What the host service still owns |
| --- | --- | --- |
| **CLI or persistent gateway** | `bub run` / `bub chat` / `bub gateway`, or a custom CLI wrapper | Config, credentials, and deployment; no Python loop code needed |
| **Complete message Turn** (inbound message to outbound replies) | `BubFramework.process_inbound()` | Service lifetime, top-level error handling, per-session locking, and custom reply delivery |
| **App config, skills, tool allowlists, and commands** (host consumes the stream) | `BubAgent.run_stream()` | Consuming and closing the stream, delivering replies, cross-Turn state persistence, and per-session locking |
| **Plugin hooks for the `core.Agent` loop** | `AgentPlugins.attach()` | Driving `agent.run()`, inbound/outbound messages, and per-session locking |
| **Single tool function** | Import the tool and pass it to `core.Agent(tools=[...])` | Model connection, Tape store, Run loop, and all resource lifetimes |

:::note
Installing a plugin package only activates the extension points supported by the entry point you call. Lower layers (`AgentPlugins`, `BubAgent`) reuse tools and Agent loop hooks, whereas message channels, CLI commands, and outer Turn hooks run only in `BubFramework` or `bub gateway`.
:::

<a id="process-inbound"></a>

## Run a complete Turn: `BubFramework.process_inbound()` {#run-a-complete-turn}

If you want Bub to handle the entire flow—session resolution, prompt construction, model and tool execution, state saving, and outbound message assembly—start with `BubFramework.process_inbound()`.

Create `embedded.py`:

```python title="embedded.py" {12-17}
import asyncio

from bub import BubFramework
from bub.envelope import content_of

async def main() -> None:
    framework = BubFramework()
    framework.load_hooks()

    async with framework.running():
        result = await framework.process_inbound({
            "session_id": "embedded:customer-42",
            "channel": "embedded",
            "chat_id": "customer-42",
            "content": "What kinds of order questions can you help me with?",
        })

    print(result.session_id)
    for outbound in result.outbounds:
        print(content_of(outbound))

if __name__ == "__main__":
    asyncio.run(main())
```

Run it:

```bash
uv run python embedded.py
```

Key usage rules:

- **Call `load_hooks()` once at startup**: loads built-in implementations and installed entry-point plugins.
- **Keep `framework.running()` open for the service lifetime**: this async context manager holds plugin lifespans, the Tape store, and the `SteeringInbox`. Enter it at service startup/shutdown (e.g., FastAPI `lifespan`), not per request.
- **Read replies from `result.outbounds`**: `process_inbound()` returns an aggregated `TurnResult`. If an installed `dispatch_outbound` plugin also sends messages, avoid sending duplicates from your host code.
- **Enable the streaming model path**: passing `stream_output=True` runs `run_model_stream` internally and still returns a `TurnResult` (a bound `ChannelRouter` can also observe incremental events via `wrap_stream()`; **`stream_output=True` works with or without a Router**).

<a id="reuse-bubagent"></a>

## Reuse only the model stage: `BubAgent.run_stream()` {#model-stage}

Use `BubAgent.run_stream()` when you want Bub's app configuration, skill discovery, tool filtering, and comma commands, but want to iterate the event stream yourself (for example, to stream SSE frames to a frontend).

`run_stream()` returns an `AsyncStreamEvents` async iterator (not a context manager). **Always wrap it with `contextlib.aclosing()`** so the stream closes cleanly on early exit or exceptions:

```python collapse={1-7} {14-19,21}
import asyncio
import contextlib

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

async def main() -> None:
    framework = BubFramework()
    framework.load_hooks()

    async with framework.running():
        agent = BubAgent(framework)
        stream = await agent.run_stream(
            session_id="customer-42",
            prompt="Answer directly in plain text: what order questions can you handle?",
            allowed_tools=[],
            allowed_skills=[],
        )

        async with contextlib.aclosing(stream):
            async for event in stream:
                if event.kind == "text":
                    print(event.data["delta"], end="", flush=True)
        print()

if __name__ == "__main__":
    asyncio.run(main())
```

Instantiate `BubAgent` inside `async with framework.running():` so it picks up the active Tape store, and reuse the same `BubAgent` instance across sessions.

Compared with `process_inbound()`, `BubAgent.run_stream()`:

- **Still runs**: resolves `session_id` to a session Tape, binds the runtime Agent, runs `load_state` hooks when `state=None`, and executes comma commands;
- **Skips**: initial `build_prompt`, `save_state`, `render_outbound`, `dispatch_outbound`, and per-session concurrency locking;
- **Stream rules**: close the stream with `aclosing()`; a `final` event ends only one Step, while the full run finishes when the `async for` loop ends.

:::tip[System prompt note]
Default system instructions do not ask the model to reply via channel skills (such as `telegram`); that instruction is added only by `ChannelManager` in `bub gateway` and `bub chat`. When calling `run_stream()` or `process_inbound()` in your own service, the model replies with normal text. Do not overwrite `agent.system_prompt` directly, as that removes prompt sections for plugins, skills, deferred tools, and code mode.
:::

<a id="run-stream-options"></a>

### Limit tools and skills per request {#narrow-tools-and-skills}

Pass `allowed_tools` and `allowed_skills` to `BubAgent.run_stream()` to restrict which tools and skills the model can use on a given call:

```python collapse={1-12} ins={27-28}
import asyncio
import contextlib

from bub import BubFramework
from bub.builtin.agent import BubAgent
from bub.core.tools import Tool

def lookup_order(order_id: str) -> str:
    return f"Order {order_id}: processing."

async def main() -> None:
    framework = BubFramework()
    framework.load_hooks()

    async with framework.running():
        order_tool = Tool.from_callable(
            lookup_order,
            name="orders.get",
            description="Look up a sample order by ID.",
        )
        agent = BubAgent(framework, tools=[order_tool])
        stream = await agent.run_stream(
            session_id="customer-42",
            prompt="Look up order A123.",
            allowed_tools={"orders.get"},
            allowed_skills=[],
        )
        async with contextlib.aclosing(stream):
            async for event in stream:
                if event.kind == "text":
                    print(event.data["delta"], end="", flush=True)

if __name__ == "__main__":
    asyncio.run(main())
```

| Parameter | `None` (default) | Empty collection (`[]` or `set()`) |
| --- | --- | --- |
| `allowed_tools` | All tools on the Agent instance | Disable all tools for this call |
| `allowed_skills` | All discovered skills | Disable all skills for this call |

Passing an unknown tool name raises `ValueError`. Keep three rules in mind:

1. `allowed_tools` restricts model tool calls and code mode, but **does not restrict direct comma commands** (such as `,fs.read`). Enforce permissions in `before_tool_call` if every execution path must be gated.
2. Allowlists are reliable only when set by **host code**; letting the model generate a subagent's `allowed_tools` in chat is not a security boundary.
3. Passing `state` explicitly to `run_stream(state=...)` skips `load_state` hooks. To combine normal state loading with custom request fields, call `await framework.build_state(message, session_id)` first and add your keys to the returned dict (see [Python API](/docs/reference/python-api/#framework)).

<a id="components"></a>

## Reuse only tools or Agent loop hooks {#reuse-tools-or-hooks}

### 1. Reuse plugin tools directly in `core.Agent` {#tool-implementations}

If your service uses the core `bub.core.Agent` but you want a tool from a Bub plugin, you can import that tool directly and pass it to `Agent(tools=[...])` without starting `BubFramework`.

The example below reuses only `web.search` from `bub-web-search`. Install the dependencies and set your credentials first:

```bash
uv add "bub[app]" \
  "bub-web-search @ git+https://github.com/bubbuild/bub-contrib.git@main#subdirectory=packages/bub-web-search"

export BUB_SEARCH_PROVIDER=jina
export BUB_SEARCH_JINA_API_KEY=jina_...
export REPUBLIC_OPENAI_API_KEY=sk-...
```

Save as `search_agent.py`:

```python title="search_agent.py" collapse={1-10} {13,19}
import asyncio
from pathlib import Path

import republic
from bub_web_search.tools import build_tools

from bub.core import Agent
from bub.core.store import FileTapeStore

async def main() -> None:
    search_tools = build_tools()
    search = search_tools.get("web.search")
    if search is None:
        raise RuntimeError("Configure BUB_SEARCH_PROVIDER and BUB_SEARCH_JINA_API_KEY first.")

    agent = Agent(
        store=FileTapeStore(Path("sessions")),
        tools=[search],
        system_prompt="Search reliable sources before answering. Include source links.",
    )
    async with republic.get_model("openai:gpt-5-mini") as model:
        async with agent.run(
            "Find the official Python asyncio documentation.",
            model=model,
            tape="research-42",
            options={"max_tokens": 4096},
        ) as stream:
            async for event in stream:
                if event.kind == "text":
                    print(event.data.get("delta", ""), end="", flush=True)
                elif event.kind == "error":
                    raise RuntimeError(str(event.data.get("message", "Agent failed")))
    print()

if __name__ == "__main__":
    asyncio.run(main())
```

Run `uv run python search_agent.py` to record the session in `sessions/`. Here only the tool function is reused; the host still owns the model, Tape store, and event stream. See [`bub-web-search`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-web-search) for more details.

<a id="other-hooks"></a>

### 2. Attach plugin hooks to `core.Agent` with `AgentPlugins` {#agent-loop-hooks}

If you want to reuse not only tools but also loop-related plugin hooks (`system_prompt`, `provide_tools`, `before_llm_call`, `before_tool_call`, etc.) on a `core.Agent`, use `AgentPlugins` (see [Hooks reference: Event mapping](/docs/reference/hooks/#event-mapping)).

Save the minimal example below as `agent_hooks.py`:

```python title="agent_hooks.py" wrap collapse={1-10} {21-25}
import asyncio

import republic

from bub.core import Agent
from bub.core.store import InMemoryTapeStore
from bub.hooks import hookimpl
from bub.hooks.agent import AgentPlugins
from bub.turn import TurnState

class PlainTextPlugin:
    """Add a system prompt to the Agent."""

    @hookimpl
    def system_prompt(self, prompt: str, state: TurnState) -> str:
        return "Answer briefly and clearly."

async def main() -> None:
    plugins = AgentPlugins(plugins=[PlainTextPlugin()])
    async with plugins.running():
        components = {**plugins.components(), "store": InMemoryTapeStore()}
        agent = plugins.attach(Agent(system_prompt="Answer the user's question.", **components))
        state = await plugins.build_state("customer-42", agent=agent)

        async with republic.get_model("openai:gpt-5-mini") as model:
            async with agent.run("What can you do?", model=model, tape="customer-42", state=state) as stream:
                async for event in stream:
                    if event.kind == "text":
                        print(event.data.get("delta", ""), end="", flush=True)
        print()

if __name__ == "__main__":
    asyncio.run(main())
```

Run it with `uv run python agent_hooks.py`.

Key rules for `AgentPlugins`:

- **Explicit plugin list vs. auto-discovery**: `AgentPlugins(plugins=[...])` registers only the listed plugin instances. To load all installed entry-point plugins and built-in hooks, create `framework = BubFramework()`, call `framework.load_hooks()`, and pass `AgentPlugins(framework)`.
- **Merge `components()`**: `plugins.components()` returns a dict with `store`, `context`, and `sidecars`. Merge overrides with `{**plugins.components(), "store": ...}` before passing to `Agent()`.
- **Run inside `plugins.running()`**: call `plugins.attach(agent)` before registering your own `agent.events.on(...)` handlers so your handlers see hook modifications.
- **Covers loop hooks only**: `attach()` does not run outer Turn stages (`build_prompt`, `save_state`, `render_outbound`, `dispatch_outbound`). If a plugin requires companion tools (e.g., `bub-context-budget` requires the `tape.handoff` tool) or persistent connections (e.g., [`bub-mcp`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-mcp#embedding)), wire those components explicitly.

## Bind a `ChannelRouter` for channel delivery {#bind-a-router}

If your host service already handles reply delivery (for example, returning an HTTP response), reading `TurnResult.outbounds` is all you need—no Router required.

Implement `ChannelRouter` and call `framework.bind_channel_router(router)` only when Bub channels should own outbound delivery and stream wrapping:

- `dispatch_output()`: delivers outbound messages; returning `False` does not trigger an automatic retry, and `process_inbound()` still returns `outbounds`.
- `wrap_stream()`: wraps the event stream and yields the model events Bub aggregates into `model_output`.
- `admit_channel_message()`: used by `ChannelManager` admission; calling `process_inbound()` directly does not run admission or queueing automatically.

See the [Python API](/docs/reference/python-api/#framework) and [Turn concepts](/docs/concepts/turn/) for contracts.

<a id="lifecycle-and-concurrency"></a>

## Production checklist {#lifecycle-failure-concurrency}

Whichever app-layer entry point you choose, verify these seven boundaries before deploying to production:

1. **Call `load_hooks()` once at startup**: do not re-register plugins on every request.
2. **Use a single `running()` scope**: do not overlap `running()` scopes on the same `BubFramework` (`ChannelManager.listen_and_run()` enters `running()` internally).
3. **Settings are cached process-wide**: multiple `BubFramework` instances isolate plugin sets, but `Settings` instances are cached per process.
4. **Catch exceptions in the host**: `run_stream()` and `process_inbound()` raise exceptions on failure; `on_error` hooks only log errors and do not suppress exceptions.
5. **Serialize same-session concurrency**: lock per `session_id` in your host (e.g., `asyncio.Lock`), or use `ChannelManager` with `follow_up` admission.
6. **Close event streams**: wrap streams with `contextlib.aclosing()`. Except for `temp/` sessions, ordinary sessions write their records to the main Tape as the run goes; closing the stream retries any that failed to write and lets other runs on the same Tape read them.
7. **External side effects do not roll back**: model errors, cancellation, or discarding a Tape fork do not undo file edits, HTTP calls, or database writes already performed by tools.

<a id="cli"></a>

## Run or package the CLI {#run-or-publish-cli}

If you do not need to embed Bub inside another Python service, run `bub run`, `bub chat`, or `bub gateway` directly. To package it under your own command name (such as `my-bub`) bundled with custom plugins and skills for your team, see [Packaging and distribution](/docs/app/distribution/).