Extension API: Events
Part of the Extension API Guide. Complete references for broadcast
BookEventtypes andInterceptableEventtypes.
Broadcast Event Reference (BookEvent)
Broadcast events are fire-and-forget notifications. Register a handler with registerEventHandler. The return value of the handler is ignored. Exceptions are caught and logged; other handlers for the same event still fire.
BookEvent.ResourcesDiscover
Fires at startup when Book scans the project directory.
| Field | Type | Description |
|---|---|---|
|
|
Current working directory |
|
|
Always |
registerEventHandler(BookEvent.ResourcesDiscover::class) { event, ctx ->
ctx.displayMessage("[Init] Scanning resources in: ${event.cwd}")
}
BookEvent.SessionStart
Fires when a session begins (new session or resumed session).
| Field | Type | Description |
|---|---|---|
|
|
|
|
|
Path of the previous session file, or null |
registerEventHandler(BookEvent.SessionStart::class) { event, ctx ->
ctx.displayMessage("[Session] Started (${event.reason})")
}
BookEvent.SessionCompact
Fires after a session compaction (summarisation of older entries).
| Field | Type | Description |
|---|---|---|
|
|
The compaction entry written to the session |
|
|
True if triggered by an extension, false if by the agent |
registerEventHandler(BookEvent.SessionCompact::class) { event, ctx ->
ctx.displayMessage("[Session] Compacted (fromExt=${event.fromExt})")
}
BookEvent.SessionTree
Fires after a branch (tree fork) is created.
| Field | Type | Description |
|---|---|---|
|
|
Session file path of the new branch |
|
|
Session file path of the parent branch |
|
|
Summary text stored at the branch point |
|
|
True if triggered by an extension |
registerEventHandler(BookEvent.SessionTree::class) { event, ctx ->
ctx.displayMessage("[Session] Branched: ${event.newLeaf}")
}
BookEvent.SessionShutdown
Fires when the session is ending (Ctrl+C, Ctrl+D, or normal exit).
| Field | Type | Description |
|---|---|---|
|
|
|
registerEventHandler(BookEvent.SessionShutdown::class) { event, ctx ->
ctx.displayMessage("[Session] Ending: ${event.reason}")
}
BookEvent.AgentStart
Fires when the agent begins processing a user input. No payload fields.
registerEventHandler(BookEvent.AgentStart::class) { _, ctx ->
ctx.displayMessage("[Agent] Startingβ¦")
}
BookEvent.AgentEnd
Fires when the agent finishes processing (after all turns complete).
| Field | Type | Description |
|---|---|---|
|
|
Full conversation history at end of run |
Assistant messages in messages carry a fully-populated usage field (see BookEvent.TurnEnd for the field reference). You can iterate the list and filter for AssistantMessage instances to aggregate token or cost totals across the run.
registerEventHandler(BookEvent.AgentEnd::class) { event, ctx ->
val assistants = event.messages.filterIsInstance<AssistantMessage>()
val totalCost = assistants.sumOf { it.usage.cost.total }
val totalTokens = assistants.sumOf { it.usage.totalTokens }
ctx.displayMessage("[Agent] Done. turns=${assistants.size} tokens=$totalTokens cost=\$${"%.6f".format(totalCost)}")
}
BookEvent.TurnStart
Fires at the beginning of each agent turn (one LLM request/response cycle).
| Field | Type | Description |
|---|---|---|
|
|
0-based turn index within the current run |
|
|
Unix epoch milliseconds when the turn started |
registerEventHandler(BookEvent.TurnStart::class) { event, ctx ->
ctx.displayMessage("[Turn ${event.index}] Starting at ${event.timestamp}")
}
BookEvent.TurnEnd
Fires at the end of each agent turn.
| Field | Type | Description |
|---|---|---|
|
|
0-based turn index |
|
|
The assistant message produced this turn |
|
|
Tool results collected during this turn |
event.message.usage is a Usage value containing:
Usage field |
Type | Description |
|---|---|---|
|
|
Input tokens consumed this turn |
|
|
Output tokens produced this turn |
|
|
Tokens served from the provider cache |
|
|
Tokens written into the provider cache (serialized as |
|
|
Sum of all token fields |
|
|
Computed cost breakdown |
usage.cost is a Cost value containing:
Cost field |
Type | Description |
|---|---|---|
|
|
Cost for input tokens (USD) |
|
|
Cost for output tokens (USD) |
|
|
Cost for cache-read tokens (USD) |
|
|
Cost for cache-creation tokens (USD) |
|
|
Sum of all cost fields (USD) |
Cost values are computed from the model’s per-token pricing table when available. For unknown or zero-priced models all cost fields will be 0.0.
registerEventHandler(BookEvent.TurnEnd::class) { event, ctx ->
val usage = event.message.usage
ctx.displayMessage(
"[Turn ${event.index}] tokens=${usage.totalTokens} " +
"cost=\$${"%.6f".format(usage.cost.total)}"
)
}
BookEvent.MessageStart
Fires when the LLM begins streaming a new message.
| Field | Type | Description |
|---|---|---|
|
|
The (initially empty) message being built |
registerEventHandler(BookEvent.MessageStart::class) { event, ctx ->
ctx.displayMessage("[Stream] New message starting (role=${event.message.role})")
}
BookEvent.MessageUpdate
Fires for each streaming delta from the LLM.
| Field | Type | Description |
|---|---|---|
|
|
The partially-built message so far |
|
|
Either |
registerEventHandler(BookEvent.MessageUpdate::class) { event, ctx ->
if (event.streamEvent is StreamEvent.TextDelta) {
// Print each streaming delta as it arrives
print(event.streamEvent.delta)
}
}
BookEvent.ToolExecutionStart
Fires just before a tool begins executing.
| Field | Type | Description |
|---|---|---|
|
|
Unique tool call ID for this invocation |
|
|
Tool name (e.g., |
|
|
Full arguments passed to the tool |
registerEventHandler(BookEvent.ToolExecutionStart::class) { event, ctx ->
ctx.displayMessage("[Tool] Starting: ${event.name}(${event.args})")
}
BookEvent.ToolExecutionUpdate
Fires during tool execution with partial results (for long-running tools that stream output).
| Field | Type | Description |
|---|---|---|
|
|
Tool call ID |
|
|
Tool name |
|
|
Arguments |
|
|
Partial output so far |
BookEvent.ToolExecutionEnd
Fires when a tool finishes executing.
| Field | Type | Description |
|---|---|---|
|
|
Tool call ID |
|
|
Tool name |
|
|
Full output text |
|
|
True if the tool returned an error result |
registerEventHandler(BookEvent.ToolExecutionEnd::class) { event, ctx ->
if (event.isError) ctx.displayMessage("[Tool] ERROR in ${event.name}: ${event.result}")
}
BookEvent.AfterProviderResponse
Fires after the LLM provider HTTP response stream completes.
| Field | Type | Description |
|---|---|---|
|
|
HTTP status code (always |
|
|
Response headers (empty in current Koog abstraction) |
BookEvent.ModelSelected
Fires when the active LLM model is changed.
| Field | Type | Description |
|---|---|---|
|
|
The new model identifier |
|
|
The previous model identifier, or null if first selection |
|
|
Who changed the model: |
registerEventHandler(BookEvent.ModelSelected::class) { event, ctx ->
ctx.displayMessage("[Model] Switched to: ${event.modelId}")
}
BookEvent.ThinkingLevelSelected
Fires when the thinking/reasoning level is changed.
| Field | Type | Description |
|---|---|---|
|
|
New thinking level identifier |
|
|
Previous thinking level, or null |
Interceptable Event Reference (InterceptableEvent)
Interceptable events let your extension modify or cancel an operation before it proceeds. Register a handler with registerInterceptor. The handler must return a result object of the corresponding type. If no interceptor is registered, or all interceptors throw exceptions, the default behavior applies (fail-open).
Only the first non-throwing interceptor result is used β subsequent registered interceptors are not called once one returns a result.
BeforeSwitch
Fires before switching to a different session.
| Payload Field | Type | Description |
|---|---|---|
|
|
Why the switch was requested |
|
|
Target session path, or null for a new session |
| Result Field | Default | Controls |
|---|---|---|
|
|
Set |
registerInterceptor(BeforeSwitch::class) { event, ctx ->
SwitchResult(cancel = false) // allow
}
BeforeFork
Fires before creating a branch (fork) in the session tree.
| Payload Field | Type | Description |
|---|---|---|
|
|
ID of the session entry being forked from |
|
|
Position in the session at which to fork |
| Result Field | Default | Controls |
|---|---|---|
|
|
Set |
BeforeCompact
Fires before a session compaction.
| Payload Field | Type | Description |
|---|---|---|
|
|
|
| Result Field | Default | Controls |
|---|---|---|
|
|
Set |
BeforeTree
Fires before the tree selector UI is displayed.
| Payload Field | Type | Description |
|---|---|---|
|
|
|
| Result Field | Default | Controls |
|---|---|---|
|
|
Set |
BeforeAgentStart
Fires before the agent begins processing user input. Lets you modify the system prompt or inject a custom first message.
| Payload Field | Type | Description |
|---|---|---|
|
|
The user’s input text |
|
|
Current system prompt (merged from SYSTEM.md files and CLI flags) |
|
|
Additional system prompt options |
| Result Field | Default | Controls |
|---|---|---|
|
|
If non-null, inject a custom |
|
|
If non-null, replace the system prompt entirely |
System Prompt Loading Order: The systemPrompt field you receive in this event is the result of Book’s multi-stage loading process:
-
~/.bk/SYSTEM.mdcontent (if exists, auto-discovered) -
.bk/SYSTEM.mdcontent (if exists, auto-discovered) -
--system-prompt FILECLI flag (if provided, replaces steps 1-2) -
--system-prompt-append FILECLI flag (if provided, appends to previous steps) -
Your extension (receives the merged result, can override or append)
Extensions can still override the entire prompt or append additional context. The event.systemPrompt field contains the fully-merged result of all file-based and CLI-based loading.
Use Cases:
-
Appending project-specific rules: Add context or constraints to the existing prompt
-
Overriding with extension logic: Replace the entire prompt based on runtime conditions
-
Inspecting loaded prompts: Log or validate the merged prompt before the agent starts
registerInterceptor(BeforeAgentStart::class) { event, ctx ->
// Log the merged prompt for debugging
ctx.displayMessage("[Prompt] Using system prompt: ${event.systemPrompt.take(100)}...")
// Append extension-specific rules
AgentStartResult(
systemPrompt = event.systemPrompt + """
## Custom Rules (injected by extension)
- Always respond in bullet points.
- Prefer concise answers under 3 paragraphs.
""".trimIndent()
)
}
Note: If your extension returns systemPrompt = null, the original merged prompt is used unchanged.
MessageEnd
Fires after the LLM finishes streaming a complete message. Lets you rewrite the message content.
| Payload Field | Type | Description |
|---|---|---|
|
|
The completed message |
| Result Field | Default | Controls |
|---|---|---|
|
|
If non-null, replace the message object used downstream |
registerInterceptor(MessageEnd::class) { event, ctx ->
// Strip any accidental leakage of API keys from the assistant message
MessageResult(message = null) // null = use original
}
ToolCall
Fires before a tool call is executed. Lets you block or allow it.
| Payload Field | Type | Description |
|---|---|---|
|
|
Name of the tool being called |
|
|
Unique call ID |
|
|
Arguments provided to the tool |
| Result Field | Default | Controls |
|---|---|---|
|
|
Set |
|
|
Human-readable reason shown when blocked |
registerInterceptor(ToolCall::class) { event, ctx ->
if (event.toolName == "write_file") {
ToolCallResult(block = true, reason = "write_file is disabled by policy")
} else {
ToolCallResult(block = false)
}
}
ToolResultEvent
Fires after a tool executes. Lets you rewrite the content or error flag.
| Payload Field | Type | Description |
|---|---|---|
|
|
Name of the tool |
|
|
Unique call ID |
|
|
Raw output from the tool |
|
|
Extra structured output, or null |
|
|
Whether the tool reported an error |
| Result Field | Default | Controls |
|---|---|---|
|
|
Override the content string (null = keep original) |
|
|
Override the error flag (null = keep original) |
ContextEvent
Fires before the current message list is sent to the LLM. Lets you filter or reorder messages.
| Payload Field | Type | Description |
|---|---|---|
|
|
The full message list to be sent |
| Result Field | Default | Controls |
|---|---|---|
|
|
Replacement message list (null = use original) |
registerInterceptor(ContextEvent::class) { event, ctx ->
// Drop system messages older than the first 2
val filtered = event.messages.take(2) + event.messages.drop(2).filter { it.role != "system" }
ContextResult(messages = filtered)
}
BeforeProviderRequest
Fires just before the raw JSON payload is sent to the LLM provider API. Lets you modify the request body.
| Payload Field | Type | Description |
|---|---|---|
|
|
The raw provider API request payload |
| Result Field | Default | Controls |
|---|---|---|
|
|
Replacement payload (null = use original) |
UserBash
Fires before BashTool executes a shell command. Lets you block or modify the command.
| Payload Field | Type | Description |
|---|---|---|
|
|
The command string to execute |
|
|
Excluded patterns (from config) |
|
|
Working directory for the command |
| Result Field | Default | Controls |
|---|---|---|
|
|
Set |
|
|
Reason string logged and returned as error output |
|
|
Override the command string (null = use original) |
registerInterceptor(UserBash::class) { event, ctx ->
if (event.command.startsWith("sudo")) {
UserBashResult(block = true, reason = "sudo commands are not permitted")
} else {
UserBashResult(block = false)
}
}
InputReceived
Fires when the user submits text in the TUI (before the agent processes it). Slash commands bypass this intercept.
| Payload Field | Type | Description |
|---|---|---|
|
|
The raw input text |
|
|
Always |
| Result Field | Default | Controls |
|---|---|---|
|
|
Override the input text (null = use original) |
|
|
Set |
registerInterceptor(InputReceived::class) { event, ctx ->
// Auto-expand shorthand
val expanded = event.text.replace("!fix", "Please fix the last error.")
InputResult(text = expanded)
}