# Plugins and Hooks

Bub discovers plugins automatically via standard [Python Entry Points](https://packaging.python.org/en/latest/specifications/entry-points/) and uses hooks to inject custom logic into each stage of the runtime.

Plugins can extend Bub in three ways:
- **Custom tools**: register tool functions via `provide_tools`;
- **Background services**: mount long-running services (such as MCP clients or message channels) via `Lifecycle`;
- **Pipeline hooks**: rewrite prompts, approve or block tool calls, and persist state across Turns.

## Create a minimal plugin {#create-a-plugin}

Before diving into advanced hooks, let's build a minimal offline echo plugin that needs no model API key so you can walk through the full workflow end to end.

### 1. Initialize the project {#initialize-project}

Scaffold a Python library with `uv`:

```bash
uv init --lib bub-echo-plugin
cd bub-echo-plugin
```

Create `src/bub_echo_plugin/plugin.py`:

- bub-echo-plugin/
  - pyproject.toml
  - src/
    - bub_echo_plugin/
      - \_\_init\_\_.py
      - **plugin.py** # Plugin and hook implementations

### 2. Declare the entry point {#declare-entry-point}

Expose the plugin under `[project.entry-points."bub"]` in `pyproject.toml`:

```toml title="pyproject.toml" mark={11-12}
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "bub-echo-plugin"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["bub[app]"]

[project.entry-points."bub"]
echo = "bub_echo_plugin.plugin:echo_plugin"
```

- The entry-point group name must be `"bub"`.
- The key (`echo`) is the plugin identifier; the value points to the module, instance, or class to load.

### 3. Implement a hook {#implement-hooks}

Mark hook methods with `@hookimpl`:

```python title="src/bub_echo_plugin/plugin.py" "@hookimpl"
from bub import hookimpl

class EchoPlugin:
    @hookimpl
    def run_model(self, prompt, session_id, state):
        return f"[echo:{session_id}] {prompt}"

echo_plugin = EchoPlugin()
```

Implementing `run_model` replaces the default model call and returns the echoed prompt with the session ID.

### Entry-point target forms {#entry-point-forms}

An entry point can reference a module, an instance, or a class/factory:

| Target syntax | Registered object | When to use |
| --- | --- | --- |
| `bub_myplugin.plugin` | Module | Hooks are stateless functions |
| `bub_myplugin.plugin:plugin` | Instance | Hooks share state via `self` |
| `bub_myplugin.plugin:MyPlugin` | Class or factory function | Plugin needs access to the `BubFramework` instance |

When targeting a class or factory function, Bub passes the `BubFramework` instance as the first argument:

```python
from bub import BubFramework, hookimpl

class MyPlugin:
    def __init__(self, framework: BubFramework) -> None:
        self.framework = framework

    @hookimpl
    def build_prompt(self, message, session_id, state):
        return f"Workspace: {self.framework.workspace}\n{message}"
```

## Install and verify {#install-and-run}

Once your plugin is written, install it into the environment where Bub runs and verify that its hooks are discovered and executed.

### Install in editable mode {#local-install}

```bash
uv sync
```

### Verify hook registration {#check-hook-registration}

```bash
uv run bub hooks
```

Confirm `echo` appears under `run_model`.

### Run a test {#run-tests}

Now send a test prompt to verify that your plugin is active:

```bash
uv run bub run "hello from my plugin"
```

You should see the echoed output intercepted by your plugin:

```text
[echo:cli:local] hello from my plugin
```

### Troubleshooting and execution order {#troubleshooting-and-dispatch}

1. **Matching Python environment**: ensure `bub` runs in the same virtual environment where the plugin was installed.
2. **Refresh entry-point metadata**: re-run `uv sync` (or `pip install -e .`) after editing `entry-points` in `pyproject.toml`.
3. **Hook priority**: Bub registers `builtin` hooks first, then entry-point plugins. At equal priority, **plugins registered later run first** (LIFO). Use `@hookimpl(tryfirst=True)` or `@hookimpl(trylast=True)` to adjust ordering explicitly (see [Hooks reference: Priority and dispatch](/docs/reference/hooks/#priority-and-dispatch)).

## Common hook patterns {#advanced-hooks}

Bub provides extension points across the entire runtime lifecycle (see the [Hooks reference](/docs/reference/hooks/) for all 27 signatures). Most real-world customizations fall into four common patterns:

### 1. Provide tools {#provide-tools}

Register `@tool` functions with `provide_tools`:

```python
from bub import hookimpl, tool
from bub.core.tools import Tool

@tool(name="orders.get")
def get_order(order_id: str) -> dict[str, str]:
    """Look up an order's shipping status by order ID."""
    return {"id": order_id, "status": "shipped"}

class OrdersPlugin:
    @hookimpl
    def provide_tools(self) -> list[Tool]:
        return [get_order]
```

#### Deferred tool schemas {#deferred-loading}

When a plugin registers many tools, injecting every full schema into the system prompt consumes context tokens. Set `deferred=True` to load schemas on demand:

```python "deferred=True"
@tool(name="orders.export", deferred=True)
def export_orders(format: str) -> str:
    """Export a report of historical orders."""
    ...
```

Deferred tools initially expose only their name and short description; the model calls `tool.describe` to load the full schema when needed.

### 2. Rewrite prompts, intercept calls, and persist state {#rewrite-and-intercept}

#### Rewrite prompts {#change-the-prompt}

- **Rewrite user input** (`build_prompt`):
  ```python
  from bub import hookimpl
  from bub.envelope import content_of

  @hookimpl
  def build_prompt(message, session_id, state):
      text = content_of(message)
      return [f"Answer using project terminology:\n\n{text}"]
  ```

- **Append system instructions** (`system_prompt`, joined with blank lines by priority):
  ```python
  @hookimpl
  def system_prompt(prompt, state):
      return "Include referenced file paths at the end of your reply."
  ```

#### Intercept model or tool calls {#control-a-model-or-tool-call}

Interception hooks run before a call executes. Note: raising an exception in an interception hook is logged and skipped — **it does not block execution**. Return a decision object to modify or block a call:

- **Cap model parameters** (`before_llm_call`):
  ```python
  from dataclasses import replace
  from bub import hookimpl
  from bub.hooks.interception import LLMCallRequest

  @hookimpl
  def before_llm_call(request: LLMCallRequest, state):
      max_tokens = min(request.max_tokens or 512, 512)
      return replace(request, max_tokens=max_tokens)
  ```

- **Approve or deny tool calls** (`before_tool_call`):
  ```python
  from bub import hookimpl
  from bub.hooks.interception import ToolCall, ToolCallDecision

  @hookimpl
  def before_tool_call(call: ToolCall, state):
      if call.tool == "orders.cancel" and not state.get("can_cancel_orders", False):
          return ToolCallDecision.deny("This session is not permitted to cancel orders.")
      return None
  ```

See [Pre-call interception and decisions](/docs/concepts/events/#call-control) and [`ToolCallDecision`](/docs/reference/hooks/#toolcalldecision).

#### Audit completed calls {#observe-completed-calls}

Completion hooks run after a call finishes, making them handy for measuring latency, reporting metrics, or writing audit logs:

```python
from bub import hookimpl

@hookimpl
def after_llm_call(request, result, state):
    print(f"model={request.model} error={result.error!r} elapsed={result.duration_ms}ms")

@hookimpl
def after_tool_call(call, result, state):
    print(f"tool={call.tool} error={result.error!r} elapsed={result.duration_ms}ms")
```

#### Persist state across Turns {#keep-application-state-across-turns}

Use `load_state` and `save_state` to persist application state across Turns (see [TurnState](/docs/concepts/turn/#state)):

```python
import asyncio
from bub import hookimpl

class TurnCounter:
    def __init__(self) -> None:
        self.counts: dict[str, int] = {}
        self.lock = asyncio.Lock()

    @hookimpl
    async def load_state(self, message, session_id):
        async with self.lock:
            return {"completed_turns": self.counts.get(session_id, 0)}

    @hookimpl
    async def save_state(self, session_id, state, message, model_output):
        async with self.lock:
            self.counts[session_id] = state.get("completed_turns", 0) + 1

turn_counter = TurnCounter()
```

### 3. Mount services and storage {#services-and-resources}

#### Background services (`Lifecycle`) {#lifecycle}

Components that stay running alongside `bub chat` or `bub gateway` (such as MCP clients or schedulers) subclass `Lifecycle` and register via `provide_channels`:

```python
from bub.channels.base import Lifecycle

class MyRuntime(Lifecycle):
    name = "myapp.lifecycle"

    async def start(self, stop_event) -> None:
        await self._connect(stop_event)

    async def stop(self) -> None:
        await self._close()
```

- `Lifecycle` services start automatically in `bub chat` and `bub gateway`, and are skipped in one-off `bub run` calls.
- Exclude a service at startup with `--enable-channel '!myapp.lifecycle'`.

#### Process-wide lifespan resources {#runtime-resources}

Use `provide_lifespan` with an async generator to manage database pools or HTTP clients across `framework.running()`:

```python
from bub import hookimpl

@hookimpl
async def provide_lifespan():
    client = await connect_database()
    try:
        yield
    finally:
        await client.close()
```

#### Custom Tape store {#provide-a-tape-store}

Replace the default file store via `provide_tape_store` (see [Store conversation history in a database](/docs/integrations/storage/)):

```python
from pathlib import Path
from bub import hookimpl
from bub.core.store import FileTapeStore

@hookimpl
def provide_tape_store():
    return FileTapeStore(Path("./application-tapes"))
```

### 4. Add CLI subcommands {#add-an-application-command}

Register custom Typer subcommands on the root `bub` CLI via `register_cli_commands`:

```python
import typer
from bub import hookimpl

@hookimpl
def register_cli_commands(app: typer.Typer):
    @app.command()
    def my_cmd(name: str = "world") -> None:
        typer.echo(f"Executed: {name}")
```

#### Interactive terminal prompts {#prompt-for-input}

Use `bub.inquirer` to prompt for input or confirmation inside custom CLI commands:

```python
from bub.inquirer import ask_confirm, ask_text

token = ask_text("Enter verification token")
if ask_confirm("Continue execution?", kind="permission"):
    pass
```

## Distribution and WASM extensions {#share-a-plugin}

### Package as a Python wheel {#package-and-distribute}

Package plugins, skills, and custom CLI commands into a standard Python wheel. See [Packaging and distribution](/docs/app/distribution/) for build configuration, or [Load portable Agent Plugins](/docs/integrations/agent-plugins/) for declarative cross-platform packages.

### WASM plugins (experimental) {#wasm-plugins}

With [`bub-extism`](https://github.com/bubbuild/bub-contrib/tree/main/packages/bub-extism), WebAssembly modules compiled from Go, Rust, or other languages can run as Bub hooks:

```json title="extism.json"
{
  "plugins": {
    "prompt": {
      "manifest": { "wasm": [{ "path": "go-build-prompt.wasm" }] },
      "wasi": true,
      "hooks": { "build_prompt": "build_prompt" }
    }
  }
}
```

```bash
export BUB_EXTISM_CONFIG_PATH=./extism.json
bub run "Say hello from a prompt built outside Python."
```