Hooks
This page lists the complete interface of all 27 hooks. A hook is an extension point through which plugins participate in framework flows: the same hook can be implemented by multiple plugins, the framework calls them in the order described below, and it decides what happens next based on their return values.
For concrete plugin examples, see Plugins and hooks; to learn which stages a message passes through, see Turn.
Dispatch modes and base types
Section titled “Dispatch modes and base types”Every hook specifies a dispatch mode that defines how HookRuntime calls multiple plugin implementations and handles their return values:
| Dispatch mode | Meaning |
|---|---|
| First result | Calls implementations from highest to lowest priority and returns the first non-None value, skipping remaining plugins (False, "", and [] count as non-None values) |
| Run all | Calls every registered implementation and collects the results |
| Sequential | Calls implementations in priority order, passing each plugin’s modified request to the next; stops early if a plugin returns a termination or denial decision (used by Agent interception hooks) |
Common type aliases in hook signatures:
| Type | Meaning |
|---|---|
Envelope |
Alias for Any representing an inbound or outbound message (dict, dataclass, Pydantic model, or object with attributes) |
TurnState |
Alias for dict[str, Any] shared across hooks, tools, and event handlers within a single Turn |
All signatures below come from bub.hooks.specs.BubHookSpecs. When implementing a hook with @hookimpl, declare only the parameter names you need; Bub injects arguments by name.
Execution priority
Section titled “Execution priority”Bub uses pluggy to register hook implementations, and HookRuntime to invoke them uniformly.
| Rule | Meaning |
|---|---|
| Registration order | Builtin implementations (builtin) are registered first, then plugins from bub entry points |
| Priority | @hookimpl(tryfirst=True) runs first; trylast=True runs last |
| Same priority | Implementations registered later run first |
| Runtime order | Calls the list returned by get_hookimpls() in reverse order, one item at a time |
| Argument passing | Passes arguments according to the argnames declared by an implementation; declare only the parameters you actually use |
| Unsupported arguments | wrapper=True, hookwrapper=True |
If you call HookRuntime directly, the two result-collection methods differ as follows:
| Method | Behavior |
|---|---|
call_first / call_first_sync |
Returns the first non-None result; empty containers and False also count as results |
call_many / call_many_sync |
Runs every implementation and collects results that were not skipped; whether it continues after a failure depends on the specific call site |
The plugin list printed by bub hooks follows pluggy’s registration order, not the actual execution order. When diagnosing hook order, rely on the priority rules and the logs.
Turn Hooks
Section titled “Turn Hooks”A single message-processing flow is called a Turn. The following nine hooks are triggered by BubFramework.process_inbound() and cover the whole process from determining the session to sending the reply.
| Hook | What it does | Dispatch |
|---|---|---|
resolve_session |
Determines which session a message belongs to | First result |
load_state |
Restores the state needed for this Turn | Run all and merge results |
build_prompt |
Builds the prompt sent to the model | First result |
run_model |
Calls the model and returns the complete text | First result |
run_model_stream |
Calls the model and returns streaming events | First result |
continue_prompt |
Optionally appends a user message when the Agent continues running | First result |
save_state |
Saves application state after the model stage ends | Run all |
render_outbound |
Converts model output into messages to be sent | Run all and concatenate messages |
dispatch_outbound |
Hands messages to be sent to external channels | Run all, once per message |
Exceptions from this group of hooks are ultimately caught by process_inbound(): it first calls on_error(stage="turn", ...) and then re-raises the original exception. When no implementation is found in the model stage, or when an error is reported in streaming output, stage="run_model" is used.
resolve_session
Section titled “resolve_session”Determines the session_id for a new message so the framework knows which session it belongs to.
def resolve_session(self, message: Envelope) -> str:| Parameter / Return | Type | Description |
|---|---|---|
message |
Envelope |
Incoming raw message |
| Returns | str |
Session ID; falls back to <channel>:<chat_id> when empty |
- Dispatch: First result.
load_state
Section titled “load_state”Restores the application state needed for this Turn from the session store.
def load_state(self, message: Envelope, session_id: str) -> TurnState:| Parameter / Return | Type | Description |
|---|---|---|
message |
Envelope |
Incoming message |
session_id |
str |
Session ID resolved by resolve_session |
| Returns | TurnState |
Turn state dictionary (non-dictionary return values are ignored) |
- Dispatch: Run all; lower-priority results are merged first, higher-priority results after.
build_prompt
Section titled “build_prompt”Builds the prompt sent to the model based on the original message and the restored state.
def build_prompt(self, message: Envelope, session_id: str, state: TurnState) -> list[UserContent] | LegacyPrompt:| Parameter / Return | Type | Description |
|---|---|---|
message |
Envelope |
Incoming message |
session_id |
str |
Current session ID |
state |
TurnState |
Shared Turn state dictionary (write _command_output to skip the model stage for internal commands) |
| Returns | list[UserContent] | LegacyPrompt |
Model prompt content; falls back to the raw message text if the first non-None result is "" or [] |
- Dispatch: First result.
Prompt content
Section titled “Prompt content”build_prompt returns list[UserContent]; list elements can be constructed as follows:
| Content | Construction |
|---|---|
| Text | str |
| Image | republic.image(url, media_type=...) |
| Audio | republic.audio(url, media_type=...) |
| Video | republic.video(url, media_type=...) |
Hooks that use the legacy prompt format (run_model, run_model_stream, continue_prompt, and system_prompt) receive:
| Situation | Format received |
|---|---|
| No media | str |
| Contains media | A list of [{"type", "media_type", "url"}] content blocks |
to_content() still accepts legacy strings and content-block lists, and handles the format conversion. To convert back to the legacy format, use bub.prompt.to_legacy_prompt().
run_model
Section titled “run_model”Calls the model and returns the complete text output directly.
def run_model(self, prompt: str | list[dict], session_id: str, state: TurnState) -> str:| Parameter / Return | Type | Description |
|---|---|---|
prompt |
str | list[dict] |
Legacy prompt input (see Prompt content) |
session_id |
str |
Current session ID |
state |
TurnState |
Shared Turn state dictionary |
| Returns | str |
Complete assistant response text |
- Dispatch: First result.
run_model_stream
Section titled “run_model_stream”Calls the model and returns streaming events that can be consumed one at a time.
def run_model_stream(self, prompt: str | list[dict], session_id: str, state: TurnState) -> AsyncStreamEvents:| Parameter / Return | Type | Description |
|---|---|---|
prompt |
str | list[dict] |
Legacy prompt input (see Prompt content) |
session_id |
str |
Current session ID |
state |
TurnState |
Shared Turn state dictionary |
| Returns | AsyncStreamEvents |
Async stream yielding StreamEvent items |
- Dispatch: First result.
- Relationship with
run_model: You only need to implement one of the two. Plain text can be converted into streaming output, and streaming output can be aggregated into plain text. - After replacing the builtin model stage: The builtin Agent’s interception hooks do not run automatically unless wired in by your implementation.
continue_prompt
Section titled “continue_prompt”Optionally adds a user message when the Agent needs to continue running.
def continue_prompt(self, prompt: str | list[dict] | None, tape: Tape, state: StreamState) -> str | None:| Parameter / Return | Type | Description |
|---|---|---|
prompt |
str | list[dict] | None |
Legacy prompt input for the current step |
tape |
Tape |
Active session Tape |
state |
StreamState |
Active stream state (note: StreamState, not TurnState) |
| Returns | str | None |
Extra user prompt for the next step, or None to continue without adding a user message |
- Dispatch: First result (called only when
StepFinished.status == "continue").
save_state
Section titled “save_state”Saves application state after the model stage ends.
def save_state( self, session_id: str, state: TurnState, message: Envelope, model_output: str,) -> None:| Parameter | Type | Description |
|---|---|---|
session_id |
str |
Current session ID |
state |
TurnState |
Shared Turn state dictionary |
message |
Envelope |
Incoming message |
model_output |
str |
Final text produced by the model stage (empty string on error) |
- Dispatch: Run all (called in the
finallyblock of the model stage; only saves application state, not runtime resources).
render_outbound
Section titled “render_outbound”Converts model output into one or more messages to be sent.
def render_outbound( self, message: Envelope, session_id: str, state: TurnState, model_output: str,) -> list[Envelope]:| Parameter / Return | Type | Description |
|---|---|---|
message |
Envelope |
Original incoming message |
session_id |
str |
Current session ID |
state |
TurnState |
Shared Turn state dictionary |
model_output |
str |
Final text produced by the model stage or internal command |
| Returns | list[Envelope] |
List of outbound messages to dispatch |
- Dispatch: Run all; concatenates returned lists in execution order. Falls back to one default reply from
model_outputreusingchannelandchat_idif no implementation produces messages.
dispatch_outbound
Section titled “dispatch_outbound”Hands a message to be sent to an external channel.
def dispatch_outbound(self, message: Envelope) -> bool:| Parameter / Return | Type | Description |
|---|---|---|
message |
Envelope |
Single outbound message to deliver |
| Returns | bool |
Delivery indicator (does not stop other implementations from running; filter messages in render_outbound instead) |
- Dispatch: Run all; called once per outbound message.
App Hooks
Section titled “App Hooks”The following 14 hooks manage configuration, resources, channels, and tools. They serve the whole application rather than handling a single message.
| Hook | What it does | Dispatch |
|---|---|---|
register_cli_commands |
Registers commands with the root CLI app | Run all |
onboard_config |
Supplements or modifies onboarding configuration | Run all |
provide_model_options |
Provides models to choose from | Run all and merge results |
provide_environment |
Provides the environment for tool execution and file access | First result |
on_error |
Observes exceptions from framework stages | Run all |
system_prompt |
Provides system prompts | Run all and concatenate results |
provide_tape_store |
Provides storage for conversation Tapes | First result |
provide_lifespan |
Manages resources for the application runtime | Run all |
provide_tape_sidecar |
Attaches a Sidecar to each session Tape | Run all and deduplicate by name |
provide_channels |
Provides channels for receiving messages | Run all and deduplicate by name |
build_tape_context |
Builds the Tape context for the current session | First result |
admit_message |
Decides how to handle a new message | First result |
provide_steering_inbox |
Provides the inbox for messages that steer the current task | First result |
provide_tools |
Provides tools to the Agent | Run all and deduplicate by name |
register_cli_commands
Section titled “register_cli_commands”Registers custom CLI commands with Bub’s root Typer app.
def register_cli_commands(self, app: Any) -> None:| Parameter | Type | Description |
|---|---|---|
app |
typer.Typer |
Root Typer CLI application instance |
- Dispatch: Run all.
onboard_config
Section titled “onboard_config”Supplements or modifies configuration during onboarding.
def onboard_config(self, current_config: dict[str, Any]) -> dict[str, Any] | None:| Parameter / Return | Type | Description |
|---|---|---|
current_config |
dict[str, Any] |
Currently loaded configuration plus modifications from earlier hooks |
| Returns | dict[str, Any] | None |
Dictionary recursively merged into the configuration (non-dictionary non-None values raise TypeError) |
- Dispatch: Run all.
provide_model_options
Section titled “provide_model_options”Provides models for the session to choose from.
def provide_model_options( self, session_id: str, workspace: Path | None,) -> ModelOptions | None:| Parameter / Return | Type | Description |
|---|---|---|
session_id |
str |
Current session ID |
workspace |
Path | None |
Active workspace directory |
| Returns | ModelOptions | None |
Candidate models and current_model |
- Dispatch: Run all; merges model lists and keeps the highest-priority
current_model.
provide_environment
Section titled “provide_environment”Provides the runtime environment for bash, file tools, and code execution.
def provide_environment(self, session_id: str, workspace: Path) -> Environment | None:| Parameter / Return | Type | Description |
|---|---|---|
session_id |
str |
Current session ID |
workspace |
Path |
Active workspace directory |
| Returns | Environment | None |
Session execution environment (defaults to LocalEnvironment(workspace)) |
- Dispatch: First result; one instance is cached per session and closed when
running()exits.
on_error
Section titled “on_error”Observes exceptions from framework stages; useful for logging and error reporting.
def on_error(self, stage: str, error: Exception, message: Envelope | None) -> None:| Parameter | Type | Description |
|---|---|---|
stage |
str |
Stage identifier ("turn", "run_model", "resolve_session", "admit_message") |
error |
Exception |
Raised exception instance |
message |
Envelope | None |
Associated inbound message, or None when outside a message context |
- Dispatch: Run all; when an implementation fails, it logs
hook.on_error_failedand is skipped. Only observes errors and cannot suppress exceptions.
system_prompt
Section titled “system_prompt”Provides a system prompt block that is prepended to the model prompt.
def system_prompt(self, prompt: str | list[dict], state: TurnState) -> str:| Parameter / Return | Type | Description |
|---|---|---|
prompt |
str | list[dict] |
Legacy prompt input for the current Turn |
state |
TurnState |
Shared Turn state dictionary |
| Returns | str |
System prompt block to append |
- Dispatch: Run all; joins non-empty results with blank lines from low to high priority.
provide_tape_store
Section titled “provide_tape_store”Provides the Tape store used to record conversations.
def provide_tape_store(self) -> TapeStore | AsyncTapeStore | None:| Return | Type | Description |
|---|---|---|
| Returns | TapeStore | AsyncTapeStore | None |
Tape store instance, or a single-yield generator (do not wrap with @contextmanager / @asynccontextmanager) |
- Dispatch: First result (resolved once on entering
framework.running()).
provide_lifespan
Section titled “provide_lifespan”Holds resources that need to be started and cleaned up during framework.running().
def provide_lifespan(self) -> AsyncIterator[None] | Iterator[None] | None:| Return | Type | Description |
|---|---|---|
| Returns | AsyncIterator[None] | Iterator[None] | None |
Sync or async generator that yields once (do not wrap with @contextmanager / @asynccontextmanager) |
- Dispatch: Run all; each generator is entered on startup and cleaned up in reverse order on exit.
provide_tape_sidecar
Section titled “provide_tape_sidecar”Provides a Sidecar for each session Tape, used to store data or capabilities attached to the main Tape.
def provide_tape_sidecar(self) -> TapeSidecar:| Return | Type | Description |
|---|---|---|
| Returns | TapeSidecar |
Sidecar paired with the main Tape (<main tape>__sidecar__<sidecar>) |
- Dispatch: Run all; deduplicates by
name, keeping the highest-priority implementation.
provide_channels
Section titled “provide_channels”Provides channels for receiving messages.
def provide_channels(self, message_handler: MessageHandler) -> list[Channel]:| Parameter / Return | Type | Description |
|---|---|---|
message_handler |
MessageHandler |
Async callback async (message: Envelope) -> None invoked by the channel on incoming messages |
| Returns | list[Channel] |
List of Channel / Lifecycle instances |
- Dispatch: Run all; deduplicates by
name, keeping the highest-priority implementation.
build_tape_context
Section titled “build_tape_context”Builds the Tape context for the current session, used to generate context messages.
def build_tape_context(self) -> TapeContext:| Return | Type | Description |
|---|---|---|
| Returns | TapeContext |
Context projection strategy (non-TapeContext values raise TypeError) |
- Dispatch: First result.
admit_message
Section titled “admit_message”Decides, when a new message arrives, whether to process it immediately, drop it, queue it, or use it to steer the current task.
def admit_message( self, session_id: str, message: Envelope, turn: TurnSnapshot,) -> AdmitDecision | None:| Parameter / Return | Type | Description |
|---|---|---|
session_id |
str |
Target session ID |
message |
Envelope |
Newly arrived inbound message |
turn |
TurnSnapshot |
Snapshot of the active Turn for this session |
| Returns | AdmitDecision | None |
Admission decision (None falls back to the channel’s default policy) |
- Dispatch: First result.
When it returns an AdmitDecision, ChannelManager handles the new message according to action:
action |
Session is currently processing a message | Session is idle |
|---|---|---|
process |
Creates a new Turn immediately, in parallel with the current Turn | Creates a Turn immediately |
drop |
Drops the new message | Drops the new message |
follow_up |
Queues it; processes it in arrival order after the current Turn completes | Creates a Turn immediately |
steer |
Sends the new message to the current Turn to steer the running task; if it cannot be injected or is not handled in time, it is queued instead | Creates a Turn immediately |
provide_steering_inbox
Section titled “provide_steering_inbox”Provides an inbox for holding steer messages temporarily; MessagesPending then delivers those messages to the Agent.
def provide_steering_inbox(self) -> SteeringInbox | None:| Return | Type | Description |
|---|---|---|
| Returns | SteeringInbox | None |
Steering inbox instance, or a single-yield generator (do not wrap with @contextmanager) |
- Dispatch: First result.
provide_tools
Section titled “provide_tools”Provides custom tools to the Agent.
def provide_tools(self) -> list[Tool]:| Return | Type | Description |
|---|---|---|
| Returns | list[Tool] |
List of custom Tool instances |
- Dispatch: Run all; deduplicates by
name, keeping the highest-priority implementation.
When resources are created and released
Section titled “When resources are created and released”framework.running() acquires resources in the following order:
- Starts all generators returned by
provide_lifespan. - Acquires the result of
provide_tape_store. - Acquires the result of
provide_steering_inbox.
On exit, the framework shuts down session execution environments and then releases the resources above in reverse order; cleanup runs even if an exception occurs partway through.
| Scenario | How long resources last |
|---|---|
bub run |
While processing one message |
bub chat / bub gateway |
For the entire application runtime |
| Embedded in another program | Determined by the host; should usually cover the whole service lifecycle |
- Do not let multiple
running()scopes overlap on the same Framework. - Background shell process-tree termination: on POSIX,
SIGTERMis sent first and thenSIGKILL; on Windows, only the direct shell is terminated. Even if the host forcibly kills the process, you still need to complete cleanup yourself.
Errors during the runtime
Section titled “Errors during the runtime”on_error can observe framework errors that occur during the runtime above, but it cannot recover the task and does not change how exceptions propagate. When embedding in another program, the host should catch exceptions raised by process_inbound() itself. Unhandled CLI exceptions usually exit with a non-zero status; however, for some model-stage errors, bub run only logs them and returns fallback text, so it may still exit with 0.
Agent Hooks
Section titled “Agent Hooks”These four hooks run before and after model or tool calls. AgentPlugins triggers them by subscribing to Agent events, and they can also be connected directly through PluginAgentHooks.
| Hook | What it does | Dispatch |
|---|---|---|
before_llm_call |
Observes, modifies, or terminates the request before calling the model | Sequential |
after_llm_call |
Observes the final result of one model call | Run all |
before_tool_call |
Modifies arguments, replaces the result, or denies the call before executing a tool | Sequential |
after_tool_call |
Observes or modifies the final result of one tool call | Run all |
When an implementation in this group raises an exception, the framework logs hook.agent_hook_failed and skips it; when the return type is incorrect, it logs hook.agent_hook_bad_return and skips it. Raising an exception does not block tool execution; to intercept a tool you must return a decision.
before_llm_call
Section titled “before_llm_call”Observes or modifies the request, or supplies the final text directly, before the request is sent to the model provider.
def before_llm_call(self, request: LLMCallRequest, state: TurnState) -> LLMCallRequest | LLMCallDecision | None:| Parameter / Return | Type | Description |
|---|---|---|
request |
LLMCallRequest |
Immutable request snapshot about to be sent to the model provider |
state |
TurnState |
Shared Turn state dictionary |
| Returns | LLMCallRequest | LLMCallDecision | None |
Return dataclasses.replace(request, ...) to modify request parameters, LLMCallDecision.finish(text) to skip the model call, or None to proceed unchanged |
- Dispatch: Sequential.
after_llm_call
Section titled “after_llm_call”Observes the final result of one model call.
def after_llm_call(self, request: LLMCallRequest, result: LLMCallResult, state: TurnState) -> None:| Parameter | Type | Description |
|---|---|---|
request |
LLMCallRequest |
Final request sent to the model provider |
result |
LLMCallResult |
Aggregated model call result (text, tool calls, usage, error, duration) |
state |
TurnState |
Shared Turn state dictionary |
- Dispatch: Run all (runs on success or ordinary failure; skipped when cancelled, when the stream is closed early, or when
before_llm_callfinishes early).
before_tool_call
Section titled “before_tool_call”Modifies arguments, directly replaces the result, or denies the call before the tool executes.
def before_tool_call(self, call: ToolCall, state: TurnState) -> ToolCallDecision | None:| Parameter / Return | Type | Description |
|---|---|---|
call |
ToolCall |
Tool call about to be executed |
state |
TurnState |
Shared Turn state dictionary |
| Returns | ToolCallDecision | None |
Return None or proceed(arguments) to continue, replace(result) to skip the tool and supply a result, or deny(message) to reject the call |
- Dispatch: Sequential.
after_tool_call
Section titled “after_tool_call”Observes the final result of one tool call, and can also modify the result the model actually sees.
def after_tool_call(self, call: ToolCall, result: ToolCallResult, state: TurnState) -> None:| Parameter | Type | Description |
|---|---|---|
call |
ToolCall |
Executed tool call |
result |
ToolCallResult |
Mutable tool result (assigning to result.result changes the output the model sees) |
state |
TurnState |
Shared Turn state dictionary |
- Dispatch: Run all (runs on success, failure, denial, or replacement; skipped only on cancellation or early stream closure).
Interception payload definitions
Section titled “Interception payload definitions”The following field definitions are taken directly from bub.core.events and match the Agent hook signatures. To focus on the interface, the code omits docstrings and convenience constructors.
LLMCallRequest
Section titled “LLMCallRequest”A request about to be sent to the model provider. The object is immutable; create a copy with dataclasses.replace().
@dataclass(frozen=True)class LLMCallRequest: run_id: str model: str messages: list[republic.Message] tool_names: tuple[str, ...] = () max_tokens: int | None = None| Field | Type | Description |
|---|---|---|
run_id |
str |
Current Agent run ID |
model |
str |
Target model identifier (provider:model) |
messages |
list[republic.Message] |
Context messages about to be sent to the model |
tool_names |
tuple[str, ...] |
Read-only tuple of tool names visible in this model call |
max_tokens |
int | None |
Maximum output tokens for this response |
LLMCallResult
Section titled “LLMCallResult”The final result of one model call. For streaming calls, the complete result is aggregated first, and then after_llm_call is triggered.
@dataclass(frozen=True)class LLMCallResult: run_id: str text: str | None = None tool_calls: list[dict[str, Any]] = field(default_factory=list) usage: dict[str, Any] | None = None error: Exception | None = None duration_ms: int = 0| Field | Type | Description |
|---|---|---|
run_id |
str |
Current Agent run ID |
text |
str | None |
Aggregated assistant text output |
tool_calls |
list[dict[str, Any]] |
Tool calls requested by the model |
usage |
dict[str, Any] | None |
Token usage dictionary |
error |
Exception | None |
Exception raised during the call, or None on success |
duration_ms |
int |
Elapsed call time in milliseconds |
LLMCallDecision
Section titled “LLMCallDecision”The early-termination decision returned by before_llm_call, constructed with LLMCallDecision.finish(text).
@dataclass(frozen=True)class LLMCallDecision: action: Literal["finish"] = "finish" text: str = ""
@classmethod def finish(cls, text: str) -> LLMCallDecision: ...| Field / Method | Type | Description |
|---|---|---|
action |
Literal["finish"] |
Decision action ("finish") |
text |
str |
Text used directly as the model output |
finish(text) |
LLMCallDecision |
Skip the model provider call and finish with text |
ToolCall
Section titled “ToolCall”A tool call about to be executed. context is the tool runtime’s context; it is None when no context is available.
@dataclass(frozen=True)class ToolCall: run_id: str tool: str arguments: dict[str, Any] context: ToolContext | None = field(default=None, repr=False, compare=False)| Field | Type | Description |
|---|---|---|
run_id |
str |
Current Agent run ID |
tool |
str |
Tool name |
arguments |
dict[str, Any] |
Keyword arguments passed to the tool |
context |
ToolContext | None |
Tool execution context (tape, run_id, state, call_id) |
ToolCallDecision
Section titled “ToolCallDecision”The handling decision returned by before_tool_call, constructed with proceed(), replace(), and deny() respectively.
@dataclass(frozen=True)class ToolCallDecision: action: Literal["proceed", "replace", "deny"] = "proceed" arguments: dict[str, Any] | None = None result: Any = None message: str | None = None
@classmethod def proceed(cls, arguments: dict[str, Any] | None = None) -> ToolCallDecision: ...
@classmethod def replace(cls, result: Any) -> ToolCallDecision: ...
@classmethod def deny(cls, message: str) -> ToolCallDecision: ...| Field / Method | Type | Description |
|---|---|---|
action |
Literal["proceed", "replace", "deny"] |
Decision action |
arguments |
dict[str, Any] | None |
Replacement argument dictionary when action == "proceed" |
result |
Any |
Replacement tool output when action == "replace" |
message |
str | None |
Denial message when action == "deny" |
proceed(arguments=None) |
ToolCallDecision |
Allow execution (optionally replacing arguments) |
replace(result) |
ToolCallDecision |
Skip the tool function and return result directly |
deny(message) |
ToolCallDecision |
Block execution and report message as a tool error |
ToolCallResult
Section titled “ToolCallResult”The final result of one tool call. This dataclass is not frozen=True, so after_tool_call can assign directly to result.result.
@dataclassclass ToolCallResult: run_id: str tool: str arguments: dict[str, Any] result: Any = None error: Exception | None = None duration_ms: int = 0| Field | Type | Description |
|---|---|---|
run_id |
str |
Current Agent run ID |
tool |
str |
Tool name |
arguments |
dict[str, Any] |
Final arguments used for the call |
result |
Any |
Tool output (mutable in after_tool_call) |
error |
Exception | None |
Exception raised or denial error, or None on success |
duration_ms |
int |
Elapsed execution time in milliseconds |
App hooks and Agent events
Section titled “App hooks and Agent events”The concept page explains who intervenes in which direction; this section covers the adapter details. For the relationship between the three kinds of data and the decision semantics, see Agent events.
Event mapping
Section titled “Event mapping”PluginAgentHooks connects app hooks to Agent events:
| App hook | Agent event | Notes |
|---|---|---|
before_llm_call |
LLMCallStarted |
Before every model call; may return a rewritten LLMCallRequest or an LLMCallDecision |
after_llm_call |
LLMCallFinished |
Once after success or ordinary failure |
before_tool_call |
ToolCallStarted |
Before every tool call; may proceed(arguments), replace(result), or deny(message) |
after_tool_call |
ToolCallFinished |
Fires on success, failure, denial, and replacement |
continue_prompt |
StepFinished |
Called only when status == "continue"; the result becomes next_prompt |
provide_steering_inbox |
MessagesPending |
Drains steering messages into the next step of the current Run |
Model-visible tool calls, including built-in tools such as .tape.handoff, also pass through ToolCallStarted / ToolCallFinished.
How the two differ
Section titled “How the two differ”| Aspect | Handling Agent events directly | App interception hooks |
|---|---|---|
| Registration | agent.events.on(Type, handler) |
@hookimpl in a plugin |
| Order | Registration order | pluggy priority |
| Argument changes | Replace event.call / event.request in place |
Return ToolCallDecision.proceed(arguments=...) or a new LLMCallRequest |
| Control | Set event.decision |
Return a decision object |
| Exceptions | Propagate to the emit() caller and may fail the Run |
Logged and skipped; the Run continues |
| Bad return type | Not applicable | Logged as a warning and skipped |
A security policy written as a hook therefore cannot block a call by raising; it must return deny(...).
How to subscribe
Section titled “How to subscribe”PluginAgentHooks(runtime).subscribe(events) attaches the four interception hooks to an existing or new event bus; AgentPlugins.attach(agent) subscribes automatically and also wires continue_prompt, the steering inbox, and the system prompt. For embedding and lifecycle requirements, see Reusing Bub.
PluginAgentHooks
Section titled “PluginAgentHooks”class PluginAgentHooks: def __init__(self, runtime: HookRuntime) -> None: ...
def subscribe(self, events: EventBus | None = None) -> EventBus: ...
async def before_llm_call( self, request: LLMCallRequest, state: TurnState, ) -> tuple[LLMCallRequest, LLMCallDecision | None]: ...
async def after_llm_call( self, request: LLMCallRequest, result: LLMCallResult, state: TurnState, ) -> None: ...
async def before_tool_call( self, call: ToolCall, state: TurnState, ) -> tuple[ToolCall, ToolCallDecision]: ...
async def after_tool_call( self, call: ToolCall, result: ToolCallResult, state: TurnState, ) -> None: ...| Method | Description |
|---|---|
__init__(runtime) |
Bind to a HookRuntime instance |
subscribe(events=None) |
Register the four interception hooks on events (or a new EventBus) and return the bus |
before_llm_call(request, state) |
Run before_llm_call hooks sequentially and return (request, decision) |
after_llm_call(request, result, state) |
Run all after_llm_call hooks |
before_tool_call(call, state) |
Run before_tool_call hooks sequentially and return (call, decision) |
after_tool_call(call, result, state) |
Run all after_tool_call hooks |
AgentPlugins
Section titled “AgentPlugins”AgentComponents
Section titled “AgentComponents”class AgentComponents(TypedDict, total=False): store: TapeStore | AsyncTapeStore context: TapeContext sidecars: Sequence[TapeSidecar]| Key | Type | Description |
|---|---|---|
store |
TapeStore | AsyncTapeStore |
Store resolved from provide_tape_store (omitted when none is provided) |
context |
TapeContext |
Context strategy resolved from build_tape_context |
sidecars |
Sequence[TapeSidecar] |
Sidecars resolved from provide_tape_sidecar |
AgentPlugins
Section titled “AgentPlugins”class AgentPlugins: def __init__( self, framework: BubFramework | None = None, *, plugins: Iterable[object] | None = None, ) -> None: ...
def running(self) -> AbstractAsyncContextManager[AsyncExitStack]: ...
def components(self) -> AgentComponents: ...
def attach(self, agent: Agent, *, tools: bool = True) -> Agent: ...
async def build_state( self, session_id: str, *, message: Envelope | None = None, agent: Agent | None = None, ) -> TurnState: ...| Parameter / Method | Description |
|---|---|
framework |
Existing BubFramework to reuse (mutually exclusive with plugins; when both are omitted, installed entry-point plugins are loaded) |
plugins |
Explicit collection of plugin objects to register without loading other entry points |
running() |
Async context manager managing provide_lifespan, provide_tape_store, and provide_steering_inbox |
components() |
Return AgentComponents suitable for Agent(**plugins.components()) |
attach(agent, *, tools=True) |
Wire interception hooks, continue_prompt, steering inbox, system_prompt, and plugin tools onto agent |
build_state(session_id, *, message=None, agent=None) |
Call load_state and populate runtime keys (_session_id, _runtime_agent, _steering_inbox) |